branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>const gulp = require('gulp'); const sass = require('gulp-sass'); const browserify = require("browserify"); const source = require('vinyl-source-stream'); const tsify = require("tsify"); const gulpShell = require("gulp-shell"); const gulpUtil = require('gulp-util'); const sources = { html: ['src/html/*'], typescript: ['src/typescript/app.ts'], typescriptFolder: ['src/typescript/**'], sass: ['src/sass/style.sass', 'node_modules/bootstrap/scss/bootstrap.scss'], copyjs: getJsNoMinifiedFiles('node_modules/angular/').concat( getJsNoMinifiedFiles('node_modules/angular-route/')).concat( getJsNoMinifiedFiles('node_modules/bootstrap/dist/js/')).concat( getJsNoMinifiedFiles('node_modules/jquery/dist/')).concat( getJsNoMinifiedFiles('node_modules/tether/dist/js/')).concat( getJsNoMinifiedFiles('node_modules/underscore/')), }; const publicFolder = "build"; const destinations = { html: publicFolder + '/html', typescript: publicFolder + "/js", sass: publicFolder + '/css', copyjs: publicFolder + '/js' }; /** * Functions * @param folder Folder to append to * @returns {*[]} */ function getJsNoMinifiedFiles(folder) { return [ "!" + folder + "*min.js", folder + "*.js" ]; } gulp.task("copy", function () { return gulp.src(sources.copyjs) .pipe(gulp.dest(destinations.copyjs)); }); gulp.task("html", function () { return gulp.src(sources.html) .pipe(gulp.dest(destinations.html)); }); gulp.task("typescript", function () { return browserify({ basedir: '.', debug: true, entries: sources.typescript, cache: {}, packageCache: {} }) .plugin(tsify) .bundle() .pipe(source('bundle.js')) .pipe(gulp.dest(destinations.typescript)); }); gulp.task('webserver', gulpShell.task([ 'lite-server' ])); gulp.task("sass", function () { return gulp.src(sources.sass) .pipe(sass()) .pipe(gulp.dest(destinations.sass)); }); gulp.task("dev", function () { gulp.watch(sources.sass, ['sass']); gulp.watch(sources.typescriptFolder, ['typescript']); gulp.watch(sources.html, ['html']); }); gulp.task("build", ["html", "typescript", "sass", "copy"], function () { }); <file_sep>export interface Phone { id: string; ownerEmail: string; }<file_sep><ul class="list-group" ng-controller="mobileAuthController"> <li class="list-group-item" ng-repeat="desktop in desktops | filter: {signInExpiry: '!!'} | orderBy: 'signInExpiry'"> {{ desktop.id }}: {{ desktop.name }} - {{ desktop.signInTime.toDateString() }}<br/> <a ng-click="desktop.confirmSignIn()" class="btn btn-info"> Sign in</a> <div class="text-xs-center" id="progress-caption-{{ desktop.name }}"> {{ desktop.WaitTimeLeft }} seconds left to login </div> <progress class="progress" ng-value="desktop.WaitTimeLeft" max="15" aria-describedby="progress-caption-{{ desktop.name }}"> </progress> </li> </ul> <file_sep>import {MobileAuthController} from "./controllers/MobileAuthController"; import {Router} from "./Router"; import {DesktopListController} from "./controllers/DesktopListController"; import {DesktopService} from "./services/Desktop.service"; const app = angular .module('prodriveAltAuth', ['ngRoute']) .config(Router) .controller("mobileAuthController", MobileAuthController) .controller('desktopListController', DesktopListController) .service('desktopService', DesktopService); console.log('Registered app');<file_sep>import IScope = angular.IScope; import {DesktopService} from "../services/Desktop.service"; import {Desktop} from "../classes/Desktop"; export interface IDesktopListScope extends IScope { desktops: Desktop[]; requestLogin(desktop: Desktop); } export class DesktopListController { static $inject = ["$scope", "desktopService"]; constructor(protected $scope: IDesktopListScope, protected desktopService: DesktopService) { desktopService.getDesktops().then((desktops: Desktop[]) => { $scope.desktops = desktops; }); $scope.requestLogin = (desktop: Desktop) => { console.log('Requesting sign in for ' + desktop.name); desktopService.requestSignIn(desktop); }; } }<file_sep># Authentication demo project This is a demo project to demonstrate a login method. ## Installation * Clone this repository with the following command `git clone https://gitlab.prodrive.nl/teuwil/authentication_list_demo.git` * Install the current version of [NodeJS](https://nodejs.org/en/) (Not LTS). * Then run the batch scripts included in the repository to install all of the dependencies. * Use the command "gulp webserver" to run the application locally. * Close the command line to stop the server.<file_sep>import IRouteProvider = angular.route.IRouteProvider; import ILocationProvider = angular.ILocationProvider; import IRoute = angular.route.IRoute; export class Router { static $inject = ["$routeProvider", "$locationProvider"]; constructor($routeProvider: IRouteProvider, $locationProvider: ILocationProvider) { console.log("Registered router"); $routeProvider .when('/mobile', <IRoute> { templateUrl: './dist/html/mobile.html', controller: 'mobileAuthController', }) .when('/desktop', <IRoute> { templateUrl: './dist/html/desktop.html', }).otherwise({redirectTo: '/desktop'}); $locationProvider.html5Mode(true); } }<file_sep>import IPromise = angular.IPromise; import {Desktop} from "../classes/Desktop"; import IQService = angular.IQService; import IQResolveReject = angular.IQResolveReject; import IIntervalService = angular.IIntervalService; export class DesktopService { static $inject = ["$q", "$interval"]; private desktops: Desktop[]; constructor(private $q: IQService, private $interval: IIntervalService) { this.desktops = [ new Desktop(1, "CLIENT1"), new Desktop(2, "CLIENT2"), new Desktop(3, "CLIENT3"), new Desktop(4, "CLIENT4"), new Desktop(5, "CLIENT5"), ]; $interval(() => { this.desktops.forEach((d: Desktop) => { d.updateWaitTime(); }); }, 250); } signOut(desktop: Desktop) { desktop.signOut(); } requestSignIn(desktop: Desktop) { desktop.signIn(); console.log(desktop.updateWaitTime() + "ms to sign in"); } getDesktops(): IPromise<Desktop[]> { return this.$q((resolve: IQResolveReject<Desktop[]>) => { resolve(this.desktops); }); } }<file_sep>export const DesktopWaitTime = 15; export class Desktop { public id: number = null; public name: string = null; public signInConfirmed: Date = null; public signInExpiry: Date = null; public WaitTimeLeft: number = null; constructor(id: number, name: string) { this.id = id; this.name = name; } signIn = (): void => { console.info("Signed in " + this.name); this.signInExpiry = new Date(); this.signInExpiry.setSeconds(this.signInExpiry.getSeconds() + DesktopWaitTime); this.updateWaitTime(); }; confirmSignIn = (): void => { console.info("Confirmed sign in " + this.name); this.signInConfirmed = new Date(); this.signInExpiry = null; this.updateWaitTime(); }; signOut = (): void => { console.info("Signed out " + this.name); this.signInConfirmed = null; this.signInExpiry = null; this.updateWaitTime(); }; isSignedIn = (): boolean => { return this.signInConfirmed != null || this.signInExpiry != null; }; /** * Returns the time left for the user * @returns {number} Time left in seconds */ updateWaitTime = (): number => { if (this.signInExpiry == null) { this.WaitTimeLeft = null; return null; } // Get the time when login is invalid var now: Date = new Date(); // Calculate seconds left before logout let timeLeft: Date = new Date(this.signInExpiry.getTime() - now.getTime()); this.WaitTimeLeft = timeLeft.getSeconds(); if (this.WaitTimeLeft <= 0) { this.signOut(); } return this.WaitTimeLeft; } }<file_sep>import {DesktopService} from "../services/Desktop.service"; import {Desktop, DesktopWaitTime} from "../classes/Desktop"; import IScope = angular.IScope; export interface MobileAuthControllerScope extends IScope { desktops: Desktop[]; desktopWaitTime: number; } export class MobileAuthController { static $inject = ["$scope", "desktopService"]; constructor(protected $scope: MobileAuthControllerScope, protected desktopService: DesktopService) { desktopService.getDesktops().then((desktops: Desktop[]) => { this.$scope.desktops = desktops; }); $scope.desktopWaitTime = DesktopWaitTime; } }
8842b572b3c593e2a7617f179fae4f537b21091c
[ "JavaScript", "TypeScript", "HTML", "Markdown" ]
10
JavaScript
teunw/Authentication_method_list
f5c13181f08e5ddf5adfb6fc961705278793d540
cc99da50320e71e756f88a9dad4f7570f267d693
refs/heads/master
<repo_name>PascalReinhardt-dev/DailyCoding<file_sep>/readme.md #README ##DailyCoding<file_sep>/code/372.py # Good morning! Here's your coding interview problem for today. # This problem was asked by Amazon. # Write a function that takes a natural number as input and returns the number of digits the input has. # Constraint: don't use any loops. import re def getDigits(number): SNumber = str(number) pattern = re.compile("^[1-9][0-9]*") if pattern.fullmatch(SNumber): return len(SNumber) else: return print(getDigits(42)) <file_sep>/code/359.py # Good morning! Here's your coding interview problem for today. # This problem was asked by Slack. # You are given a string formed by concatenating several words corresponding to the integers zero through nine and then anagramming. # For example, the input could be 'niesevehrtfeev', which is an anagram of 'threefiveseven'. Note that there can be multiple instances of each integer. # Given this string, return the original integers in sorted order. In the example above, this would be 357. import re def removeLettersFromString(Sstring,Sletters): for char in Sletters: Sstring = Sstring.replace(char,'',1) return Sstring def anagrammToNumber(anagram): counter = 0 realNumber = "" DOne = { "SNumber": "one", "INumber": 1, "ILen": 3 } DTwo = { "SNumber": "two", "INumber": 2, "ILen": 3 } DThree = { "SNumber": "three", "INumber": 3, "ILen": 5 } DFour = { "SNumber": "four", "INumber": 4, "ILen": 4 } Dfive = { "SNumber": "five", "INumber": 5, "ILen": 4 } DSix = { "SNumber": "six", "INumber": 6, "ILen": 3 } Dseven = { "SNumber": "seven", "INumber": 7, "ILen": 5 } DEight = { "SNumber": "eight", "INumber": 8, "ILen": 5 } DNine = { "SNumber": "nine", "INumber": 9, "ILen": 4 } DZero = { "SNumber": "zero", "INumber": 0, "ILen": 4 } numbers = [DZero, DOne, DTwo, DThree, DFour, Dfive, DSix, Dseven, DEight, DNine] oldAnagram = "" for number in numbers: condition = True while condition: for char in number.get("SNumber"): if char in anagram: counter += 1 condition = False if counter == number.get("ILen"): realNumber += str(number.get("INumber")) anagram = removeLettersFromString(anagram,number.get("SNumber")) condition = True counter = 0 if len(anagram) == 0: return realNumber else: print(anagram) anagram = "niesevehrtfeevfive" anagram = "oentrheeisxevenseerthinenzero" print(anagrammToNumber(anagram)) <file_sep>/code/340.py # Good morning! Here's your coding interview problem for today. # This problem was asked by Google. # Given a set of points (x, y) on a 2D cartesian plane, find the two closest points. For example, given the points [(1, 1), (-1, -1), (3, 4), (6, 1), (-1, -6), (-4, -3)], return [(-1, -1), (1, 1)]. def getClosestPoints2D(points): smallestDistance = float("inf") closetPoints = [] for apoint in points: for bpoint in points: distance = abs(apoint[0] - bpoint[0]) + abs(apoint[1] - bpoint[1]) if distance < smallestDistance and apoint != bpoint: closetPoints = [apoint,bpoint] smallestDistance = distance return closetPoints points = [(1, 1), (-1, -1), (3, 4), (6, 1), (-1, -6), (-4, -3)] for point in getClosestPoints2D(points): print(str(point[0]) + "," + str(point[1]))
14004e5501320de43c3e4aeb7aa22d35981f2ee8
[ "Markdown", "Python" ]
4
Markdown
PascalReinhardt-dev/DailyCoding
310a8b83607cabb49d8c24a0c5da6354f3d337df
1d91d52f9960e30981a11cc3e82937a857a4fcf0
refs/heads/master
<repo_name>gragib/Adafruit_IS31FL3731<file_sep>/examples/swirldemo/swirldemo.ino #include <Wire.h> #include <Adafruit_GFX.h> #include <Adafruit_IS31FL3731.h> Adafruit_IS31FL3731 ledmatrix = Adafruit_IS31FL3731(); // The lookup table to make the brightness changes be more visible uint8_t sweep[] = {1, 2, 3, 4, 6, 8, 10, 15, 20, 30, 40, 60, 60, 40, 30, 20, 15, 10, 8, 6, 4, 3, 2, 1}; void setup() { Serial.begin(9600); Serial.println("ISSI swirl test"); if (! ledmatrix.begin()) { Serial.println("IS31 not found"); while (1); } Serial.println("IS31 found!"); } uint8_t incr =0; void loop() { // animate over all the pixels, and set the brightness from the sweep table for (uint8_t x=0; x<16; x++) { for (uint8_t y=0; y<9; y++) { ledmatrix.drawPixel(x, y, sweep[(x+y+incr)%24]); } } incr++; delay(20); }
2b7acafce7345be9e475023e15fa2ebe83aebb56
[ "C++" ]
1
C++
gragib/Adafruit_IS31FL3731
090a0fa54036922278933ebc1ed7a16046942b3b
872f9acb65d1cd80540d430fcaf605979376b8b1
refs/heads/master
<file_sep>#include "APScan.h" APScan::APScan() { } bool APScan::start() { if (debug) { Serial.println("starting AP scan..."); Serial.println("MAC - Ch - RSSI - Encrypt. - SSID - Hidden");// - Vendor"); } aps._clear(); results = 0; for (int i = 0; i < maxAPScanResults; i++){ selected[i] = false; String("").toCharArray(names[i], 33); } // Scan Networks/Wifi and return the number of AP founds results = WiFi.scanNetworks( false, true //settings.apScanHidden - Scan including hidden? ); // lets scanNetworks return hidden APs. (async = false & show_hidden = true) // Max AP to search if(results > maxAPScanResults) results = maxAPScanResults; if (debug) Serial.println("Scan results: "+(String)results); for (int i = 0; i < results; i++) { Mac _ap; _ap.set(WiFi.BSSID(i)[0], WiFi.BSSID(i)[1], WiFi.BSSID(i)[2], WiFi.BSSID(i)[3], WiFi.BSSID(i)[4], WiFi.BSSID(i)[5]); aps.add(_ap); // Save the search AP channels[i] = WiFi.channel(i); rssi[i] = WiFi.RSSI(i); encryption[i] = WiFi.encryptionType(i); hidden[i] = WiFi.isHidden(i); String _ssid = WiFi.SSID(i); _ssid.replace("\"", "\\\""); _ssid.toCharArray(names[i], 33); //data_getVendor(WiFi.BSSID(i)[0],WiFi.BSSID(i)[1],WiFi.BSSID(i)[2]).toCharArray(vendors[i],9); if (debug) { Serial.print((String)i); Serial.print(" - "); _ap._print(); Serial.print(" - "); Serial.print(channels[i]); Serial.print(" - "); Serial.print(rssi[i]); Serial.print(" - "); Serial.print(getEncryption(encryption[i])); Serial.print(" - "); Serial.print(names[i]); Serial.print(" - "); Serial.print(hidden[i]); //Serial.print(" - "); //Serial.print(vendors[i]); Serial.println(); } } //for debugging the APScan crash bug /* if(debug){ for(int i=results;i<maxAPScanResults;i++){ Mac _ap; _ap.set(random(255),random(255),random(255),random(255),random(255),random(255)); aps.add(_ap); channels[i] = random(1,12); rssi[i] = random(-30,-90); encryption[i] = ENC_TYPE_NONE; String _ssid = "test_dbeJwq3tPtJsuWtgULgShD9dxXV"; _ssid.toCharArray(names[i],33); Serial.print((String)i); Serial.print(" - "); _ap._print(); Serial.print(" - "); Serial.print(channels[i]); Serial.print(" - "); Serial.print(rssi[i]); Serial.print(" - "); Serial.print(getEncryption(encryption[i])); Serial.print(" - "); Serial.print(names[i]); Serial.println(); results++; } } */ if (debug) Serial.println("scan done"); return true; } String APScan::getEncryption(int code) { switch (code) { case ENC_TYPE_NONE: return "none"; break; case ENC_TYPE_WEP: return "WEP"; break; case ENC_TYPE_TKIP: return "WPA"; break; case ENC_TYPE_CCMP: return "WPA2"; break; case ENC_TYPE_AUTO: return "WPA*"; break; } return "?"; } String APScan::getAPName(int num) { if (isHidden(num)) return "* Hidden SSID *"; return names[num]; } String APScan::getAPEncryption(int num) { return getEncryption(encryption[num]); } //String APScan::getAPVendor(int num){ return vendors[num]; } String APScan::getAPMac(int num) { return aps._get(num).toString(); } bool APScan::isHidden(int num) { return hidden[num]; } int APScan::getAPRSSI(int num) { return rssi[num]; } int APScan::getAPChannel(int num) { return channels[num]; } <file_sep>/* * This will deauthenticate some users from the network * Pin 13 Port B * My modified version of deauthenticate */ #include <Arduino.h> #include <ESP8266WiFi.h> #include "APScan.h" #include "ClientScan.h" //#include <ESP8266WebServer.h> //ESP8266WebServer server(80); #define BUILTIN_LED 2 // Scan in 15 sec #define CLIENT_SCAN_TIME 15 #define ATTACK_TIME /** * Constant Declaration */ /** * List Of client to deauthenticate */ const String clientList = { }; /** * List of AP to authenticate */ const String apList = { }; const bool debug = true; /** * scan time on idel */ const int clientScanTime = 15; int clientScanCounter = 0; bool is_found = false; /** * Attac */ const int attackTime = 20; // Attacking time int attackTimeCounter = 0; const int attackCount = 3; // after this will go to idle again int attackCountCounter = 0; // after this will go to idle again const int attackIdle = 10; // after this will go to idle again int attackIdleCounter = 0; // after this will go to idle again /** * Object Initialization */ APScan apScan; ClientScan clientScan; void ledOFF(){ digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH } void ledON(){ digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level } void setup() { pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output ////EEPROM.begin(4096); Serial.begin(115200); //WiFi.mode(WIFI_STA); //wifi_set_promiscuous_rx_cb(sniffer); //WiFi.begin(ssid, password); // WiFi.softAP( // ssid, // (const char*)settings.ssid.c_str(), // password, // (const char*)settings.password.c_str(), // 1, // settings.apChannel, // false // settings.ssidHidden // ); //for an open network without a password change to: WiFi.softAP(ssid); delay(1000); apScan.start(); // Working Already digitalWrite(BUILTIN_LED, LOW); delay(2000); // Delay 2 secs //clientScan.start(clientScanTime); digitalWrite(BUILTIN_LED, HIGH); } /** * The main process from */ void loop() { // Pure Attack Algirithm delay(1000); // delay for 1 sec int _time = millis(); Serial.println("LOOOOOOP:"+ (String)_time); if (is_found == true) { delay(1000); // delay for 1 sec _time = millis(); //Serial.println("SCAN STARt: " + (String)_time); //const int attackTime = 20; // Attacking time //int attackTimeCounter = 0; if (attackIdleCounter >= attackIdle){ // DO the attack here Start attack here Serial.println("Attack Idle count: " + (String) attackIdleCounter); if (attackTimeCounter >= attackTime){ Serial.println("Attack count: " + (String) attackTimeCounter); if (attackCountCounter >= attackCount){ Serial.println("RESET attack counter: "); attackCountCounter = 0; clientScanCounter = 0; is_found = false; // Back to scan again attackTimeCounter = 0; }else{ Serial.println("RESET attack counter: " + (String)attackCountCounter); } attackCountCounter++; attackTimeCounter=0; attackIdleCounter=0; }// if (attackTimeCounter >= attackTime){ attackTimeCounter++; } // if (attackIdleCounter >= attackIdle){ else{ Serial.println("\nIDLE Attack count: " + (String) attackIdleCounter); } attackIdleCounter++; //clientScanTime=0 }else{ if (clientScanCounter >= clientScanTime){ _time = millis(); //Serial.println("START SCAN Client(%i): %i");//, clientScanCounter, _time); // Dont Scan APs again since already scan in the boot. // START Scan Client in AP // Do The scan Client here is_found=true; if (is_found == true){ //Serial.println("Scan Found Cleint: %i");//, _time); }else{ //Serial.println("SCAN reset to idlea: %i");//, _time); clientScanCounter = 0; } } } clientScanCounter++; Serial.print("-"); Serial.println(clientScanCounter); } void startClientScan() { //if (server.hasArg("time") && apScan.getFirstTarget() > -1 && !clientScan.sniffing) { // server.send(200, "text/json", "true"); //clientScan.start(100000); //attack.stopAll(); //} else { // server.send( 200, "text/json", "Error: no selected access point"); //} }
9a1fcd93926e241940741b71a935583da7e94326
[ "C++" ]
2
C++
CJXABCJX/esp2866_wifi
b611e068742d8e878b821a9a4200f25466a293f0
0e3d2f289dcda4f7c38b8912fdbc561e4b6b5f6c
refs/heads/master
<file_sep>var click_count = 0; function swap_colour() { click_count+=1; console.log(click_count); var main_content = document.getElementById("main_content"); if (click_count == 13) { window.location.assign("arme001.html"); } else { main_content.classList.toggle("contentonclick"); } }
aaae646d6be6207ecdc7bc640a9ad57313138340
[ "JavaScript" ]
1
JavaScript
aritmie/aritmie.github.io
d648a13900c50f8deea56248764d0d95a06af7ec
93a3b3adfe662c0df83ec0fe433520dd9c58608a
refs/heads/master
<repo_name>ssw940521/STL<file_sep>/Friend/match.cpp #include "match.h" void Match::print_time(time & t) { } <file_sep>/Friend/match.h #pragma once #ifndef STUDENT_H #define STUDENT_H #include"time.h" class Match { public: void print_time(time &t); }; #endif // !STUDENT_H <file_sep>/Friend/demo.cpp #include<iostream> #include"time.h" #include"stdlib.h" using namespace std; void ptintTime(time &t); int main() { time t(6, 34, 25); printTime(t); system("pause"); return 0; } void printTime(time &t) { cout << t.m_iHour << ":" << t.m_iMinute << ":" << t.m_iSecond << endl; }
97adc36d986c757989ad1c8d424f32cbe12c3ce2
[ "C++" ]
3
C++
ssw940521/STL
7fbd16d1f39e13a525c0c0e6c69bfb4360e64895
aaeeb437365aa84f0548c45a9c70c58620e30197
refs/heads/main
<repo_name>rahulraj6026/Multithreading<file_sep>/src/com/threads/semaphore/App.java package com.threads.semaphore; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class App { public static void main(String[] args) throws InterruptedException { // Creates a thread pool that creates new threads as needed, but will reuse // previously constructed threads when they are available. These pools will // typically improve the performance of programs that execute many short-lived // asynchronous tasks.Calls to execute will reuse previously constructed threads // if available. If no existing thread is available, a new thread will be // created // and added to the pool. Threads that have not been used for sixty seconds are // terminated and removed from the cache. ExecutorService execute = Executors.newCachedThreadPool(); // create 200 threads for (int i = 0; i < 200; i++) { execute.submit(new Runnable() { @Override public void run() { Connection.getInstance().connect(); } }); } // Initiates an orderly shutdown in which previously submitted tasks are // executed, but no new tasks will be accepted.Invocation has no additional // effect if already shut down. execute.shutdown(); execute.awaitTermination(1, TimeUnit.DAYS); } } <file_sep>/src/com/threads/producerconsumer/SyncProducerConsumer.java package com.threads.producerconsumer; import java.util.LinkedList; import java.util.Random; class SyncProcessor { // LL to add Integers LinkedList<Integer> list = new LinkedList<Integer>(); // variable to store limit size Integer size = 10; // An object to handle the lock Object lock = new Object(); void produce() throws InterruptedException { int value = 0; while (true) { synchronized (lock) { // check if size is reached to limit while (list.size() == size) { // move into waiting state until item is consumed lock.wait(); System.out.println("Producer into waiting state... "); } // add the value to the list list.add(value++); System.out.println("List size after producing.. " + list.size()); // notify the consumer object to continue its execution lock.notify(); System.out.println("Consumer can continue it's execution... "); System.out.println(); } } } void consume() throws InterruptedException { while (true) { Random random = new Random(); synchronized (lock) { while (list.size() == 0) { // lock until there is an item to consume in the storage lock.wait(); System.out.println("Consumer into waiting state... "); } System.out.print("List size is: " + list.size()); int val = list.removeFirst(); System.out.println(" Value Removed is: " + val); // make the producer to execute as it is in waiting state lock.notify(); System.out.println("Producer can continue its execution... "); System.out.println(); } Thread.sleep(random.nextInt(1000)); } } } class SampleTest extends Thread { SyncProcessor p = new SyncProcessor(); Thread t1 = new Thread(new Runnable() { public void run() { try { p.produce(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); Thread t2 = new Thread(new Runnable() { public void run() { try { p.consume(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); } public class SyncProducerConsumer { public static void main(String[] args) throws InterruptedException { SampleTest sample = new SampleTest(); sample.t1.start(); sample.t2.start(); sample.t1.join(); sample.t2.join(); } } <file_sep>/src/com/threads/deadlock/Account.java package com.threads.deadlock; public class Account { private int amount = 0; public void deposit(int a) { amount += a; } public void withdraw(int a) { amount -= a; } public int getBalance() { return amount; } public void transfer(Account acc1, Account acc2, int amo) { acc1.deposit(amo); acc2.withdraw(amo); } } <file_sep>/src/com/threads/start/SampleThreadImplementExample.java package com.threads.start; /* * In this example we will look into one of the two implementations of thread * We need to implement Runnable to the class * While starting the Thread we need to pass the className to the Thread * and run() will execute the Thread. */ class TestThread implements Runnable{ @Override public void run() { System.out.println("This will execcute the thread! "); for(int i=0;i<10;i++) { Thread th = Thread.currentThread(); System.out.println(th.getName()+" "+(i+1)); try { Thread.sleep(100); }catch(Exception ex) { ex.printStackTrace(); } } } } public class SampleThreadImplementExample { public static void main(String[] args) { Thread t1 = new Thread(new TestThread()); t1.start(); Thread t2 = new Thread(new TestThread()); t2.start(); } } <file_sep>/src/com/threads/start/SampleThreadExample.java package com.threads.start; class Runner extends Thread{ @Override public void run() { System.out.println("This will execcute the thread! "); for(int i=0;i<10;i++) { System.out.println(this+" "+(i+1)); try { Thread.sleep(1000); }catch(Exception ex) { ex.printStackTrace(); } } } } public class SampleThreadExample { public static void main(String[] args) { Runner r = new Runner(); r.start(); Runner r1 = new Runner(); r1.start(); } } <file_sep>/src/com/threads/synchronization/ThreadMultipleLock.java package com.threads.synchronization; import java.util.ArrayList; import java.util.List; import java.util.Random; /* * In this example we see how to add multiple locks using the synchronized code blocks. * To achieve this we will create two lists and add random integer values in a given range. When we try to run the threads we see that the size of both the lists are not same the loop runs for 1000 times. * To fix this we make the methods of the respective threads synchronized which will fix the issue but will execute slow as the thread acquires the lock of the class and releases once it is done with its execution. * To fix the above issue we create separate synchronized blocks in both the method implementation. By doing so it will reduce the processing time as if one block acquires lock for execution then other thread has to wait for other thread to complete its execution. After the execution the first block releases the lock then the second block executes the code. By doing this no threads can run the blocks at the same time which will increase the execution time. * We make us of lock variable in order to lock both the synchronized block separately */ public class ThreadMultipleLock { //create objects for synchronized blocks private Object lock1 = new Object(); private Object lock2 = new Object(); // create two lists to store the variables List<Integer> list1 = new ArrayList<>(); List<Integer> list2 = new ArrayList<>(); // create a object to fetch random variables public Random random = new Random(); // execute thread one public void executeThreadOne() { synchronized (lock1) { try { Thread.sleep(1); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } int someNumber = random.nextInt(100); System.out.println("Thread Name: " + Thread.currentThread().getName()+" Number added: "+someNumber); list1.add(someNumber); } } // execute thread two public void executeThreadTwo() { synchronized (lock2) { try { Thread.sleep(1); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } int someNumber = random.nextInt(100); System.out.println("Thread Name: " + Thread.currentThread().getName()+" Number added: "+someNumber); list2.add(someNumber); } } // Implementation of Threads public void startProcess() { for (int i = 0; i < 1000; i++) { executeThreadOne(); executeThreadTwo(); } } public void main() { //Calculate start time long start = System.currentTimeMillis(); // create a method to run first thread Thread t1 = new Thread(new Runnable() { @Override public void run() { startProcess(); } }); // create a method to run second thread Thread t2 = new Thread(new Runnable() { @Override public void run() { startProcess(); } }); // start both the threads t1.start(); t2.start(); // to make this execute we need to join this to main thread. This will wait // until the thread dies try { t1.join(); t2.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } //calculate the end time long end = System.currentTimeMillis(); System.out.println("Time " + (end - start)); System.out.println(list1.size() + " " + list2.size()); } } <file_sep>/src/com/threads/synchronization/TestClass.java package com.threads.synchronization; public class TestClass { private static class Demo implements Runnable { @Override public void run() { for (int i = 0; i < 1000; i++) { System.out.println(i); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } public static void main(String[] args) { Thread d = new Thread(new Demo()); d.start(); } } <file_sep>/src/com/threads/latches/LatchesExample.java package com.threads.latches; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /* * This is a sample program for latches. Its used when a thread needs to wait for other threads before starting its work. */ class Processor implements Runnable { // create a temporary variable for latches CountDownLatch latches; // create a constructor and assign the result public Processor(CountDownLatch latches) { this.latches = latches; } // implement the run method public void run() { System.out.println("The process is started...."); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // decrease the latch count as processing is done latches.countDown(); System.out.println("Finished Process: " + Thread.currentThread().getName()); } } public class LatchesExample { public static void main(String[] args) { // create count down latches // count the number of times countDown must be invoked before threads can pass // through await CountDownLatch latches = new CountDownLatch(3); // create threads with latches say 3 in this case. ExecutorService executors = Executors.newFixedThreadPool(3); //created threads and start the execution by passing on the latches. for(int i=0; i<3; i++) { executors.submit(new Processor(latches)); } //Causes the current thread to wait until the latch has counted down to zero, unless the thread is interrupted. try { latches.await(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " has finished"); } } <file_sep>/src/com/threads/producerconsumer/ProducerConsumer.java package com.threads.producerconsumer; import java.util.Random; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; public class ProducerConsumer { // create a ArrayBlockingQueue for this scenario private static BlockingQueue<Integer> block = new ArrayBlockingQueue<Integer>(10); public static void main(String[] args) { // create two threads Thread t1 = new Thread(new Runnable() { @Override public void run() { // make a call to producer try { producer(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { try { consumer(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); // start the threads t1.start(); t2.start(); // wait till all the thread execution is completed try { t1.join(); t2.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Current Thread " + Thread.currentThread().getName()); } // create a method for producer private static void producer() throws InterruptedException { // generate random numbers Random random = new Random(); // run a loop to just add a item into the queue while (true) { System.out.println("Item is produced successfully..."); // produce a random number into the queue block.put(random.nextInt(100)); System.out.println("Size of storage... " + block.size()); } } // create a method for consumer private static void consumer() throws InterruptedException { // generate a random index Random random = new Random(); while (true) { Thread.sleep(10); // check if index is zero if yes then consume the item if (random.nextInt(10) == 0) { // consume the item from the queue Integer item = block.take(); System.out.println("Item is consumed..."); System.out.println("Consumer item is: " + item); System.out.println("Size of storage is: " + block.size()); } } } }
91ea5e688916d0f25ed1dc1210408b5e73004c05
[ "Java" ]
9
Java
rahulraj6026/Multithreading
1f4de45a96e9919f829fd89a719a8a65275ac70b
8335bc556e8f87b0d69fb3b6f80130ca6e601a4b
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class IceEventListener : MonoBehaviour { DryIcePlaceholder IcePalletsList; void Start() { IcePalletsList = GetComponentInParent<DryIcePlaceholder>(); } // Update is called once per frame void Update () { } public void ListenToEvent(GameObject go) { tag = "occupied"; go.GetComponent<DryIce>().OnIceGrasped += UpdateStatus; } private void UpdateStatus(GameObject go) { go.GetComponent<DryIce>().OnIceGrasped -= UpdateStatus; tag = "empty"; if (IcePalletsList.IceUsed.Count != 0) { foreach (var item in IcePalletsList.IceUsed) { if (item.CompareTag("empty")) { IcePalletsList.Ice.Insert(0, item); IcePalletsList.IceUsed.Remove(item); break; } } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using Leap.Unity.Interaction; [RequireComponent(typeof(InteractionBehaviour))] public class SnapToCloseDoor : MonoBehaviour { private InteractionBehaviour _intObj; private HingeJoint _joint; bool isClosing; Vector3 origPos; Vector3 origRot; float prAngle; bool snapped = true; // Use this for initialization void Start() { _joint = GetComponent<HingeJoint>(); prAngle = _joint.angle; StartCoroutine(RotationDirection()); } private void OnEnable() { _intObj = GetComponent<InteractionBehaviour>(); origPos = transform.position; origRot = transform.rotation.eulerAngles; } private void OnDisable() { } // Update is called once per frame void Update() { if (_intObj.isHovered && isClosing) { if (_joint.angle - _joint.limits.min < 10) { SnapToClose(); } } } void SnapToClose() { if (!snapped) { _intObj.rigidbody.transform.position = origPos; _intObj.rigidbody.rotation = Quaternion.Euler(origRot); _intObj.ignoreGrasping = true; _intObj.ignorePrimaryHover = true; _intObj.ignoreGrasping = false; _intObj.ignorePrimaryHover = false; Debug.Log("Snaped"); } } IEnumerator RotationDirection() { while (true) { prAngle = _joint.angle; yield return new WaitForSecondsRealtime(0.15f); if (_joint.angle < prAngle) isClosing = true; else isClosing = false; if ((transform.rotation.eulerAngles - origRot) == Vector3.zero) { snapped = true; } else { snapped = false; // Debug.Log(transform.rotation.eulerAngles); } } } //bool CheckAngle() //{ // crAngle = _joint.angle; // if (crAngle < prAngle) return true; // else if (crAngle > prAngle) return false; // else return false; //} } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using Leap.Unity.Interaction; using DG.Tweening; using FMODUnity; using TMPro; [RequireComponent(typeof(InteractionBehaviour))] [RequireComponent(typeof(HingeJoint))] public class ButtomPressEvent : MonoBehaviour { [EventRef] public string ButtonPressSound; public UnityEvent OnPress = new UnityEvent(); HingeJoint _joint; InteractionBehaviour _intBtn; private bool _buttonEnabled; private ButtonVisibilityTween _tween; Tween myTween; bool pressed; Material _mat; Color _color; public Color CoorToBlendTo; public TextMeshPro m_Text; private float offsetAngle; // Use this for initialization void Start() { _joint = GetComponent<HingeJoint>(); _intBtn = GetComponent<InteractionBehaviour>(); _tween = GetComponent<ButtonVisibilityTween>(); _mat = GetComponent<Renderer>().materials[2]; _color = _mat.color; // myTween = _mat.DOFade(_color.a, 0); AngleOffset(); } private bool CheckBtn() { if (_tween != null) { return _tween.isUsable; } else return true; } void AngleOffset() { offsetAngle = transform.localEulerAngles.z; } // Update is called once per frame void Update() { //m_Text.text = Mathf.Round((transform.localEulerAngles.z - offsetAngle)).ToString(); if (_intBtn.isHovered && CheckBtn()) CheckButtonAngle(); } private void CheckButtonAngle() { if (_joint.limits.max - (transform.localEulerAngles.z - offsetAngle) < 0.5f && !pressed) { OnPress.Invoke(); pressed = true; PlaySound(); ChangeButtonColorOnPress(); } if ((transform.localEulerAngles.z - offsetAngle) - _joint.limits.min < 3) { pressed = false; //ResetColorBack(); } //if (_joint.limits.max - _joint.angle < 1f) } private void ChangeButtonColorOnPress() { myTween = _mat.DOColor(CoorToBlendTo, 0.1f).SetLoops(2, LoopType.Yoyo); } private void ResetColorBack() { myTween = _mat.DOColor(_color, 0.2f); } private void PlaySound() { if (ButtonPressSound.Length > 1) RuntimeManager.PlayOneShot(ButtonPressSound, transform.position); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class DoorsOpenClose : MonoBehaviour, IDoor { public bool XRotate; public bool YRotate; public bool ZRotate; public float rotationAngle; public float speed; public float openDelay; [SerializeField] protected bool ON; protected bool rotate; protected Vector3 currentRotateVector; protected Quaternion ClosedRotation, OpenRotation, TargetRotation; protected Transform _transform; public GameObject OlderItemRestrictsOpen; public GameObject OlderItemRestrictsClose; public GameObject PairDoor; public MeshRenderer Mesh; public int MaterialNum; public Material TransparentMaterial; private Material OpaqueMaterial; public Collider[] cols; private Collider[] othersCols; private bool _openCommandComesOutside; private void Awake() { InitStartData(); if (Mesh != null) { Material[] mat = Mesh.materials; OpaqueMaterial = mat[MaterialNum]; } cols = GetComponentsInChildren<Collider>(); GetCollidersInOthers(); CheckRestriction(); } void OnEnable() { // DoorsLogo_Reset.ResetAction += Reset; } void OnDisable() { //DoorsLogo_Reset.ResetAction -= Reset; } private void InitStartData() { Vector3 rotateVector = Vector3.zero; _transform = transform; if (GetComponent<Collider>() == null) gameObject.AddComponent<BoxCollider>(); if (_transform.CompareTag("Untagged")) _transform.tag = Constant.TAGDOORS; speed = speed != 0 ? speed : 200f; if (!XRotate && !YRotate && !ZRotate) print("!!!!!!! set rotation axis for " + _transform.name + " !!!!!!"); ClosedRotation = _transform.localRotation; OpenRotation = _transform.localRotation; // openDelay = openDelay == 0 ? 0.2f : openDelay; if (XRotate) rotateVector = new Vector3(1, 0, 0); else if (YRotate) rotateVector = new Vector3(0, 1, 0); else if (ZRotate) rotateVector = new Vector3(0, 0, 1); Vector3 vector = OpenRotation.eulerAngles; vector += (rotateVector * rotationAngle); OpenRotation.eulerAngles = vector; rotateVector *= speed; } public void OpenCloseDoorsFromPaired() { _openCommandComesOutside = true; OpenCloseDoor(); } public void OpenCloseDoor() { if (ON && OlderItemRestrictsClose != null && OlderItemRestrictsClose.GetComponent<IDoor>().GetOpened()) { print(name + " !!!!!!!!! restrict open"); Debug.Break(); return; } if (!ON && OlderItemRestrictsOpen != null && !OlderItemRestrictsOpen.GetComponent<IDoor>().GetOpened()) { print(name + " !!!!!!!! restrict close"); Debug.Break(); return; } TargetRotation = ON ? ClosedRotation : OpenRotation; ON = !ON; CheckRestriction(); if (OnDoorOpen != null) // check for subscribers OnDoorOpen(gameObject, ON); // call the event OnDoorOpen Hide(); if (PairDoor != null && !_openCommandComesOutside) { DoorsOpenClose dr = PairDoor.GetComponent<DoorsOpenClose>(); if (dr != null) dr.OpenCloseDoorsFromPaired(); } _openCommandComesOutside = false; Invoke("StartMove", openDelay); } void Hide() { if (Mesh == null) return; Material[] mat = Mesh.materials; mat[MaterialNum] = ON ? TransparentMaterial : OpaqueMaterial; Mesh.materials = mat; } void StartMove() { rotate = true; } //---------------------------------------------------------- void Update() { if (rotate) { _transform.localRotation = Quaternion.RotateTowards(transform.localRotation, TargetRotation, Time.deltaTime * speed); //Time.deltaTime*speed); if (Quaternion.Angle(_transform.localRotation, TargetRotation) < .1f) { _transform.localRotation = TargetRotation; rotate = false; } } } public bool GetOpened() { return ON; } private void Reset() { if (!ON) return; ON = false; _openCommandComesOutside = false; Hide(); _transform.localRotation = ClosedRotation; rotate = false; } private IEnumerator CollidersOnOff (bool ON) { yield return new WaitForSecondsRealtime(0.5f); foreach (var col in othersCols) { col.enabled = ON; } } public void CheckRestriction() { if (OlderItemRestrictsClose != null && ON) { StartCoroutine("CollidersOnOff", ON); } if (OlderItemRestrictsClose != null && !ON) { StartCoroutine("CollidersOnOff", ON); } if (OlderItemRestrictsOpen != null && ON) { StartCoroutine("CollidersOnOff", !ON); } if (OlderItemRestrictsOpen != null && !ON) { StartCoroutine("CollidersOnOff", !ON); } } void GetCollidersInOthers() { if (OlderItemRestrictsClose != null) othersCols = OlderItemRestrictsClose.GetComponentsInChildren<Collider>(); if (OlderItemRestrictsOpen != null) othersCols = OlderItemRestrictsOpen.GetComponentsInChildren<Collider>(); } public Action<GameObject, bool> OnDoorOpen = delegate { }; } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using DG.Tweening; public class ObjectVisibilityTween : MonoBehaviour { public bool Move; public bool Rotate; public bool Scale; public bool ScaleOnOutOnly; public bool isUsable { get; private set; } public Transform HiddenTransform; public Transform TargetTransform; private Vector3 InitialPos; private Vector3 InitialRot; private Vector3 InitialScale; Tween myTween; public AnimationCurve curveIN; public AnimationCurve curveOUT; Task deactivatingRoutine; // controlls CoRoutine; Task activatingRoutine; // Use this for initialization void Start() { if (TargetTransform == null) TargetTransform = gameObject.transform; InitialPos = TargetTransform.localPosition; InitialRot = TargetTransform.localEulerAngles; InitialScale = TargetTransform.localScale; DoHideImmediately(); } // Update is called once per frame void Update() { } public void DoShowWithDelay(float delay) { activatingRoutine = new Task(ShowRoutine(0.35f, delay)); } public void DoShow(float duration) { activatingRoutine = new Task(ShowRoutine(duration, 0)); } IEnumerator ShowRoutine(float duration, float delay) { yield return new WaitForSecondsRealtime(delay); if (deactivatingRoutine != null && deactivatingRoutine.Running) deactivatingRoutine.Stop(); //if (myTween != null) myTween.TogglePause(); TargetTransform.gameObject.SetActive(true); if (Move) myTween = TargetTransform.DOLocalMove(InitialPos, duration).SetEase(curveIN); if (Scale || ScaleOnOutOnly) myTween = TargetTransform.DOScale(InitialScale, duration); if (Rotate) myTween = TargetTransform.DOLocalRotate(InitialRot, duration); myTween.OnComplete(MakeUsable); } void MakeUsable() { isUsable = true; } public void DoHide(float duration) { // if (deactivatingRoutine != null && deactivatingRoutine.Running) deactivatingRoutine.Stop(); deactivatingRoutine = new Task(HideRoutine(duration, 0)); } public void DoHideWithDelay(float delay) { deactivatingRoutine = new Task(HideRoutine(0.15f, delay)); } IEnumerator HideRoutine(float duration, float delay) { yield return new WaitForSecondsRealtime(delay); if (activatingRoutine != null && activatingRoutine.Running) activatingRoutine.Stop(); //yield return new WaitUntil(() => allowTween); if (myTween != null && myTween.IsPlaying()) myTween.Pause(); isUsable = false; if (Scale || ScaleOnOutOnly) myTween = TargetTransform.DOScale(Vector3.zero, duration); if (Move) myTween = TargetTransform.DOLocalMove(HiddenTransform.localPosition, duration).SetEase(curveOUT); if (Rotate) myTween = TargetTransform.DOLocalRotate(HiddenTransform.localEulerAngles, duration); myTween.OnComplete(DoFinal); } public void DoHideImmediately() { DoHide(0); } private void DoFinal() { TargetTransform.gameObject.SetActive(false); if (ScaleOnOutOnly) TargetTransform.DOScale(InitialScale, 0); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using Leap.Unity.Interaction; using Leap.Unity.Encoding; using System.Linq; using System; using TMPro; using Leap; public class ContactDetection : MonoBehaviour { Finger.FingerType MiddleFinger = Finger.FingerType.TYPE_MIDDLE; Finger.FingerType IndexFinger = Finger.FingerType.TYPE_INDEX; public TextMeshPro m_Text; public UnityEvent OnHoverBegin; public UnityEvent OnHoverEnd; public UnityEvent OnContactBegin; public UnityEvent OnContactEnd; public UnityEvent OnContactCenterBegin; public UnityEvent OnContactCenterEnd; private float distanceToCenter; public float activationDistance; public float deactivationDistance; bool contactPending; public Collider _collider; public List<Collider> _cols; IDoor parentIDoor; DoorsOpenClose parentDoorRotator; private InteractionBehaviour _intObj; // Use this for initialization void Start() { //MiddleFinger _intObj = GetComponent<InteractionBehaviour>(); _intObj.OnHoverBegin += ActivateHover; _intObj.OnHoverEnd += DeactivateHover; _intObj.OnContactBegin += OnContactBegin.Invoke; _intObj.OnContactEnd += OnContactEnd.Invoke; _collider = GetComponent<Collider>(); if (_intObj.manager.hoverActivationRadius < deactivationDistance) { Debug.LogWarning("!!!!!!!!!!!! Adjust min distance !!!!!!!!!!!!!!"); Debug.Break(); } } void ActivateHover() { OnHoverBegin.Invoke(); } void DeactivateHover() { OnHoverEnd.Invoke(); } // Update is called once per frame void Update() { if (_intObj.isHovered) { _cols = _intObj.primaryHoverColliders; distanceToCenter = Vector3.Distance(_collider.bounds.center, _intObj.primaryHoveringControllerPoint); if (distanceToCenter < activationDistance && !contactPending) { StartCoroutine(CheckContactDistance()); contactPending = true; } } } IEnumerator CheckContactDistance() { OnContactCenterBegin.Invoke(); yield return new WaitForSecondsRealtime(0.1f); while (distanceToCenter < deactivationDistance) { //m_Text.text = distanceToCenter.ToString(); contactPending = true; yield return null;// WaitForSecondsRealtime(0.1f); } contactPending = false; OnContactCenterEnd.Invoke(); yield return new WaitForSecondsRealtime(0.1f); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using Leap.Unity.Interaction; using Leap.Unity.Attributes; using Leap.Unity; using Leap; public class PitchManager : MonoBehaviour { Leap.Hand _hand; [SerializeField] protected HandModelBase _handModel; public HandModelBase HandModel { get { return _handModel; } set { _handModel = value; } } Controller controller = new Controller(); Vector3 pinchPos; public GameObject leapHand; protected PinchDetector pinchScript; protected Vector3 pinch_position; protected float pinch_distance; protected Vector3 new_position; protected bool pinching; protected bool startPinch; protected bool endPinch; // Vector3 pinch_pos; // Use this for initialization void Start () { pinching = false; pinchScript = leapHand.GetComponent<PinchDetector>(); } // Update is called once per frame void Update () { // Gets the state of your pinch startPinch = pinchScript.DidStartPinch; endPinch = pinchScript.DidEndPinch; pinching = pinchScript.IsPinching; // Does something once the state of the pinch changes //if (startPinch) //{ // Target.SetActive(true); // Debug.Log(startPinch); //} //else if (endPinch) //{ // Target.SetActive(false); // Target.transform.localScale = Vector3.one; //} if (pinching) { pinch_position = pinchScript.Position; //pinch_distance = pinchScript.Distance; //Target.transform.position = pinch_position;// + (Vector3.back * 0.01f); // Debug.Log(GetRelativeDistance()); //Target.transform.localScale = GetRelativeDistance() * Vector3.one; } } float GetRelativeDistance() { float minValue = pinchScript.ActivateDistance; float maxValue = pinchScript.DeactivateDistance; float actualValue = pinchScript.Distance; float persentage = actualValue / minValue;// 100; return persentage; } Hand ReturnHand() { Frame frame = controller.Frame(); // controller is a Controller object if (frame.Hands.Count > 0) { List<Hand> hands = frame.Hands; Hand firstHand = hands[0]; return firstHand; } else return null; } public void ShowPosition() { Hand _hand = ReturnHand(); Debug.Log(_hand.GrabStrength); //Vector3 pinchPos = _hand.GetPinchPosition(); } public void HidePos() { //Target.SetActive(false); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class ToggleColor : MonoBehaviour { private Material _mat; public Material toggRedleMaterial; public Color yellow; private Color _originalCol; // Use this for initialization void Start() { } private void Awake() { //_mat = GetComponent<Renderer>().material; //_originalCol = _mat.color; RetrieveOriginalColor(); } // Update is called once per frame void Update() { } public void Toggle_Color(bool activeColor) { if (activeColor) { ChangeMaterilaTo(_mat, _originalCol); //GetComponent<Renderer>().material = _mat; //_mat.color = _originalCol; } else { ChangeMaterilaTo(_mat, yellow); //GetComponent<Renderer>().material = _mat; //_mat.color = yellow; } } public void ToggleRedColor() { GetComponent<Renderer>().material = toggRedleMaterial; } private void ChangeMaterilaTo(Material _mat, Color _color) { if (GetComponent<Renderer>() == null) { Renderer[] _ren = GetComponentsInChildren<Renderer>(); foreach (var item in _ren) { item.material = _mat; _mat.color = _color; } } else { GetComponent<Renderer>().material = _mat; _mat.color = _color; } } private void RetrieveOriginalColor() { if (GetComponent<Renderer>() == null) { Renderer[] _ren = GetComponentsInChildren<Renderer>(); foreach (var item in _ren) { _mat = item.material; _originalCol = _mat.color; } } else { _mat = GetComponent<Renderer>().material; _originalCol = _mat.color; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class VRTeleporter : MonoBehaviour { public Vector3 Offset; private bool runNormal; private Task AnimatedArcRoutine; public float speed = 10; public Vector3 mvelocity = Vector3.one; public float smoothTime = 0.3F; public GameObject positionMarker; // marker for display ground position public Transform bodyTransforn; // target transferred by teleport public LayerMask excludeLayers; // excluding public LayerMask includeLayers; // including public float angle = 45f; // Arc take off angle public float strength = 10f; // Increasing this value will increase overall arc length int maxVertexcount = 35; // limitation of vertices for performance. [SerializeField] private float vertexDelta = 0.08f; // Delta between each Vertex on arc. Decresing this value may cause performance problem. 0.08f is a def value private LineRenderer arcRenderer; private Vector3 velocity; // Velocity of latest vertex private Vector3 groundPos; // detected ground position private Vector3 lastNormal; // detected surface normal private bool groundDetected = false; private List<Vector3> vertexList = new List<Vector3>(); // vertex on arc private bool displayActive = false; // don't update path when it's false. // Teleport target transform to ground position public void Teleport() { if (groundDetected && runNormal) { // bodyTransforn.position = groundPos + lastNormal * 0.01f; StartCoroutine(TeleportOverSpeed(bodyTransforn, (groundPos + lastNormal * 0.01f), speed)); ToggleDisplay(false); } else { Debug.Log("Ground wasn't detected"); } } // Active Teleporter Arc Path public void ToggleDisplay(bool active) { displayActive = active; StartCoroutine(EnableLineRendererOnNextFrame(active)); if (active && AnimatedArcRoutine == null) { runNormal = false; AnimatedArcRoutine = new Task(BeginAnimateArc()); } if (!active) positionMarker.SetActive(active); } private void Awake() { arcRenderer = GetComponent<LineRenderer>(); arcRenderer.enabled = false; positionMarker.SetActive(false); } private void Start() { } private void Update() { if (displayActive) { UpdatePath(); } } IEnumerator BeginAnimateArc() { //yield return new WaitForEndOfFrame(); arcRenderer.positionCount = 0; arcRenderer.enabled = true; while (arcRenderer.positionCount != vertexList.ToArray().Length -1) { for (int i = 1; i < vertexList.ToArray().Length; i++) { Vector3[] tempPos = vertexList.ToArray(); Array.Resize(ref tempPos, i ); // increments arch path every frame arcRenderer.positionCount = i; arcRenderer.SetPositions(tempPos); yield return new WaitForSeconds(0.015f); //WaitForEndOfFrame(); } } runNormal = true; // start render the arch nornally, every frame. AnimatedArcRoutine = null; } private void UpdatePath() { groundDetected = false; vertexList.Clear(); // delete all previouse vertices velocity = Quaternion.AngleAxis(-angle, transform.right) * transform.forward * strength; RaycastHit hit; Vector3 pos = transform.position; // take off position vertexList.Add(pos); while (!groundDetected && vertexList.Count < maxVertexcount) { Vector3 newPos = pos + velocity * vertexDelta + 0.5f * Physics.gravity * vertexDelta * vertexDelta; velocity += Physics.gravity * vertexDelta; vertexList.Add(newPos); // add new calculated vertex // linecast between last vertex and current vertex if (Physics.Linecast(pos, newPos, out hit, ~excludeLayers))// includeLayers)) { groundDetected = true; groundPos = hit.point; lastNormal = hit.normal; } pos = newPos; // update current vertex as last vertex } // positionMarker.SetActive(groundDetected); if (groundDetected) { //positionMarker.transform.position = Vector3.SmoothDamp(positionMarker.transform.position, groundPos + lastNormal * 0.01f, ref mvelocity, smoothTime); positionMarker.transform.position = groundPos + lastNormal * 0.01f; //original implementation positionMarker.transform.LookAt(groundPos); } // Update Line Renderer every frame (full path) if (runNormal) { positionMarker.SetActive(groundDetected); arcRenderer.enabled = groundDetected; arcRenderer.positionCount = vertexList.Count -1; // -1 to skipp rendering the end of the arch Vector3[] tempPos = vertexList.ToArray(); Array.Resize(ref tempPos, vertexList.Count -1); // -1 to skipp rendering the end of the arch arcRenderer.SetPositions(tempPos); } } public IEnumerator TeleportOverSpeed(Transform objectToMove, Vector3 end, float speed) //teleporter over time { // speed should be 1 unit per second while (objectToMove.transform.position != end + Offset) { objectToMove.transform.position = Vector3.MoveTowards(objectToMove.transform.position, end + Offset, speed * Time.deltaTime); yield return new WaitForEndOfFrame(); } } private IEnumerator EnableLineRendererOnNextFrame(bool active) { if (active) yield return new WaitForEndOfFrame(); // fixes jittering on enabling LineRenderer before moving its position; arcRenderer.enabled = active; } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class EventManager : MonoBehaviour { public bool IceTrayOpen; public bool GlovesOn; public bool AllIceLoaded; public GameObject IceTrayArrow; public GameObject GlovesArrow; public GameObject IcePalletsArrow; // Use this for initialization void Start() { } // Update is called once per frame void Update() { } private void Awake() { DoorsOpenClose[] doorsScript = FindObjectsOfType<DoorsOpenClose>(); ToggleHandsModel glovesScript = FindObjectOfType<ToggleHandsModel>(); DryIcePlaceholder icePlaceholderScript = FindObjectOfType<DryIcePlaceholder>(); icePlaceholderScript.OnCountChanged += ChechIceCount; glovesScript.OnGlovesOn += CheckGloves; foreach (var item in doorsScript) { item.OnDoorOpen += GetDoorStatus; } } private void CheckGloves(bool on) { GlovesOn = on; Debug.Log(GlovesOn); MakeUpdate(); } private void GetDoorStatus(GameObject go, bool status) { if (go.name == "DoorsIce") { IceTrayOpen = status; if (IceTrayOpen) { IceTrayArrow.SetActive(false); } } MakeUpdate(); } void MakeUpdate() { if (IceTrayOpen && !GlovesOn) { GlovesArrow.SetActive(true); } else GlovesArrow.SetActive(false); } void ChechIceCount(int count) { if (count == 0) AllIceLoaded = true; else AllIceLoaded = false; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using Leap.Unity.Interaction; using DG.Tweening; using System; public class DryIcePlaceholder : MonoBehaviour { public List<GameObject> Ice; public List<GameObject> IceUsed; IDryIce Iice; InteractionBehaviour _IntIce; bool shouldTween; bool icePalletInside; public Action<int> OnCountChanged = delegate { }; void Start() { //Debug.Log(Ice.Count); DryIce[] iceScript = FindObjectsOfType<DryIce>(); foreach (var item in iceScript) { item.OnIceReleased += UpdatePlaceholder; item.OnIceGrasped += OutlineEmptyIfGrasped; } } private void UpdatePlaceholder(GameObject go) { icePalletInside = true; StartCoroutine("PlaceIce", go.transform); } public IEnumerator PlaceIce(Transform ice) { _IntIce = ice.GetComponent<InteractionBehaviour>(); shouldTween = true; while (icePalletInside) //(Iice != null && _IntIce != null) { // Highlight LoopColor(Ice[0]); if (_IntIce == null) Debug.Log("int obj is null " + _IntIce.gameObject); if (!_IntIce.isGrasped) { ice.transform.DOMove(Ice[0].transform.position, 0.25f).OnComplete(MakeKinematic); ice.transform.DORotate(Ice[0].transform.rotation.eulerAngles, 0.1f);// // GetComponent<Rigidbody>().MovePosition(Ice[1].transform.position); IceUsed.Add(Ice[0]); Ice[0].GetComponent<IceEventListener>().ListenToEvent(ice.gameObject); Ice.RemoveAt(0); icePalletInside = false; break; } yield return new WaitForSecondsRealtime(0.1f); } OnCountChanged(Ice.Count); } void LoopColor(GameObject go) { if (shouldTween) { tempGO = go; //go.GetComponent<QuickOutline>().enabled = true; go.GetComponent<QuickOutline>().OutlineWidth = 4; go.GetComponent<MeshRenderer>().enabled = true; go.GetComponent<Renderer>().material.DOColor(Color.green, .25f).SetLoops(2, LoopType.Yoyo); go.GetComponent<Renderer>().material.DOFade(.001f, .25f).SetLoops(2, LoopType.Yoyo).OnComplete(DisableMeshRenderer); } shouldTween = false; } void MakeKinematic() { _IntIce.GetComponent<Rigidbody>().isKinematic = true; } GameObject tempGO; void DisableMeshRenderer() { tempGO.GetComponent<QuickOutline>().OutlineWidth = 0; tempGO.GetComponent<Renderer>().enabled = false; //tempGO.GetComponent<QuickOutline>().enabled = false; tempGO = null; } private void OnTriggerEnter(Collider other) { if (other.CompareTag("dryicepallet")) { StartCoroutine(OutlinePlaceholder()); } } void OutlineEmptyIfGrasped(GameObject go) { StartCoroutine(OutlinePlaceholder()); } IEnumerator OutlinePlaceholder() { yield return new WaitForSecondsRealtime(0.25f); GameObject[] IceArray = Ice.ToArray(); GameObject go = IceArray[0]; QuickOutline _outline = go.GetComponent<QuickOutline>(); go.GetComponent<MeshRenderer>().enabled = true; // _outline.enabled = true; while (_outline.OutlineWidth < 4) { _outline.OutlineWidth += 0.25f; yield return new WaitForSeconds(0.05f); } while (_outline.OutlineWidth == 0) { _outline.OutlineWidth -= 0.25f; yield return new WaitForSeconds(0.05f); } //_outline.enabled = false; go.GetComponent<MeshRenderer>().enabled = false; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using Leap.Unity; public class DetectorManager : MonoBehaviour { public HandModelBase[] CapsulHands; public HandModelBase[] RiggedHands; public GameObject PalmDetector; public GameObject PinchDetector; private int current = 1; // first element // Use this for initialization public void ToggleDetectors() { if (current == 2) // reached the last lement, toggle back { DoJob(CapsulHands[0]);// first element of Hands Array is a left hand current = 1; } else { DoJob(RiggedHands[0]); current = 2; } } void DoJob(HandModelBase model) { PalmDetector.GetComponent<PalmDirectionDetector>().HandModel = model; PinchDetector.GetComponent<PinchDetector>().HandModel = model; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using DG.Tweening; using Leap.Unity.Interaction; using System; public class DryIce : MonoBehaviour, IDryIce { private InteractionBehaviour intObj; public Action<GameObject> OnIceReleased; public Action<GameObject> OnIceGrasped; public void BePlaced() { } // Use this for initialization IEnumerator Start() { yield return new WaitForSeconds(1); intObj = GetComponent<InteractionBehaviour>(); intObj.OnGraspEnd += UpdateStatus; intObj.OnGraspBegin += UpdateStatus; } private Collider _collider; private void OnTriggerEnter(Collider other) { if (other.CompareTag("IcePlaceholder")) StartCoroutine(ReleaseIntObjAfterDelay(1)); } private void OnTriggerStay(Collider other) { if (other.CompareTag("IcePlaceholder")) { _collider = other; } } private void OnTriggerExit(Collider other) { if (other.CompareTag("IcePlaceholder")) { _collider = null; } } void UpdateStatus() { if (intObj == null) Debug.Log("int obj is null " + intObj.gameObject); if (_collider != null && !intObj.isGrasped) OnIceReleased(gameObject); else if (_collider != null && intObj.isGrasped) { if (OnIceGrasped != null) OnIceGrasped(gameObject); } } IEnumerator ReleaseIntObjAfterDelay(float delay) { yield return new WaitForSeconds(delay); intObj.ReleaseFromGrasp(); intObj.ignoreGrasping = true; yield return new WaitForSeconds(0.5f); intObj.ignoreGrasping = false; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class LazerPointer : MonoBehaviour { public LayerMask excludeLayers; // excluding public LayerMask includeLayers; // including public GameObject LaserRedPrefab; public GameObject LaserGreenPrefab; public RaycastHit hit; public bool Hidden { get; private set; } private Transform LaserRed; private Transform LaserGreen; public Transform laserEndPoint; public Transform laserstartPoint; public bool _enableLaser; private void Awake() { LaserRed = Instantiate(LaserRedPrefab).transform; LaserGreen = Instantiate(LaserGreenPrefab).transform; LaserRed.gameObject.SetActive(false); LaserGreen.gameObject.SetActive(false); //gameObject.SetActive(false); } // Use this for initialization void Start() { } // Update is called once per frame void Update() { //RaycastHit hit; if (Physics.Raycast(laserstartPoint.transform.position, transform.forward, out hit, 5, includeLayers)) { ShowLaser(hit); } else { HideLaser(); } } private void ShowLaser(RaycastHit hit) { //if (hit.transform.gameObject.layer == 18) // { Hidden = false; LaserGreen.gameObject.SetActive(true); LaserRed.gameObject.SetActive(false); LaserGreen.position = Vector3.Lerp(laserstartPoint.transform.position, hit.point, .5f); LaserGreen.LookAt(hit.point); LaserGreen.localScale = new Vector3(LaserGreen.localScale.x, LaserGreen.localScale.y, hit.distance); //iArrow arrow = hit.transform.GetComponentInChildren<iArrow>(); //if (arrow != null) //{ // arrow.ShowHideArrow(); //} // } //else //{ // LaserGreen.gameObject.SetActive(false); // LaserRed.gameObject.SetActive(true); // LaserRed.position = Vector3.Lerp(laserstartPoint.transform.position, hit.point, .5f); // LaserRed.LookAt(hit.point); // LaserRed.localScale = new Vector3(LaserRed.localScale.x, LaserRed.localScale.y, hit.distance); //} } private void HideLaser() { Hidden = true; LaserRed.gameObject.SetActive(false); LaserGreen.gameObject.SetActive(false); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using DG.Tweening; using System; using UnityEngine.Events; using Leap.Unity.Interaction; public class ButtonVisibilityTween : MonoBehaviour { bool allowTween = true; public bool Move; public bool Rotate; public bool Scale; public bool ScaleOnOutOnly; public bool isUsable { get; private set; } public Transform HiddenTransform; private Vector3 InitialPos; private Vector3 InitialRot; private Vector3 InitialScale; Rigidbody rb; Collider col; Tween myTween; public AnimationCurve curveIN; public AnimationCurve curveOUT; InteractionBehaviour _intObj; Task deactivatingRoutine; // controlls CoRoutine; HingeJoint myHinge; private void Awake() { _intObj = GetComponent<InteractionBehaviour>(); rb = GetComponent<Rigidbody>(); col = GetComponent<Collider>(); } void Start() { //yield return new WaitForSeconds(0.1f); InitialPos = transform.localPosition; InitialRot = transform.localEulerAngles; InitialScale = transform.localScale; myHinge = GetComponent<HingeJoint>(); myHinge.connectedBody = null; DoHideImmediately(); } private void Update() { } private void OnEnable() { // _intObj.OnContactStay -= AllowTween; // _intObj.OnContactEnd -= DisallowTween; _intObj.OnHoverBegin -= StartTrackingWhileOnHover; _intObj.OnHoverEnd -= EndTrackingAfterOnHover; //_intObj.OnContactStay += AllowTween; //_intObj.OnContactEnd += DisallowTween; _intObj.OnHoverBegin += StartTrackingWhileOnHover; _intObj.OnHoverEnd += EndTrackingAfterOnHover; } private void OnDisable() { _intObj.OnContactStay -= AllowTween; _intObj.OnContactEnd -= DisallowTween; _intObj.OnHoverBegin -= StartTrackingWhileOnHover; _intObj.OnHoverEnd -= EndTrackingAfterOnHover; } void StartTrackingWhileOnHover() { //StartCoroutine(PauseTween()); } void EndTrackingAfterOnHover() { //StopCoroutine(PauseTween()); } public void AllowTween() { allowTween = true; } public void DisallowTween() { //allowTween = false; } IEnumerator PauseTween() { while (!allowTween) { if (myTween != null) myTween.Pause(); yield return null; } } public void DoShow(float duration) { if (deactivatingRoutine.Running) { deactivatingRoutine.Stop(); } if (myTween != null) myTween.TogglePause(); gameObject.SetActive(true); rb.isKinematic = true; col.enabled = false; if (Move) myTween = gameObject.transform.DOLocalMove(InitialPos, duration).SetEase(curveIN); if (Scale || ScaleOnOutOnly) myTween = gameObject.transform.DOScale(InitialScale, duration); if (Rotate) myTween = gameObject.transform.DOLocalRotate(InitialRot, duration); myTween.OnComplete(AttachConnectedBody); } public void DoHide(float duration) { deactivatingRoutine = new Task(HideRoutine(duration, 0)); } public void DoHideWithDelay(float delay) { if (gameObject.activeInHierarchy) deactivatingRoutine = new Task(HideRoutine(0.15f, delay)); } IEnumerator HideRoutine(float duration, float delay) { yield return new WaitForSecondsRealtime(delay); //yield return new WaitUntil(() => allowTween); if (myTween != null) myTween.TogglePause(); isUsable = false; myHinge.connectedBody = null; rb.isKinematic = true; col.enabled = false; if (Scale || ScaleOnOutOnly) myTween = gameObject.transform.DOScale(Vector3.zero, duration); if (Move) myTween = gameObject.transform.DOLocalMove(HiddenTransform.localPosition, duration).SetEase(curveOUT); if (Rotate) myTween = gameObject.transform.DOLocalRotate(HiddenTransform.localEulerAngles, duration); myTween.OnComplete(DoFinal); } public void DoHideImmediately() { DoHide(0); } private void AttachConnectedBody() { myHinge.connectedBody = transform.root.GetComponent<Rigidbody>(); isUsable = true; rb.isKinematic = false; col.enabled = true; } private void DoFinal() { gameObject.SetActive(false); if (ScaleOnOutOnly) transform.DOScale(InitialScale, 0); } public void PauseDeactivatingRoutine() { if (deactivatingRoutine != null && deactivatingRoutine.Running) DoShow(0); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using DG.Tweening; public class LightController : MonoBehaviour { Light _light; Tween tween; // Use this for initialization void Start () { _light = GetComponent<Light>(); } // Update is called once per frame void Update () { } private void OnEnable() { } public void IncreaseIntensity(float value) { if (!gameObject.activeInHierarchy) gameObject.SetActive(true); tween = _light.DOIntensity(value, 1f); } public void DecreaseIntensity(float value) { if (tween != null && tween.IsPlaying()) tween.Kill(); tween = _light.DOIntensity(value, 0.15f); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using Leap.Unity; using Leap; using Leap.Unity.Interaction; using UnityEngine.Events; public class MagicCircleManager : MonoBehaviour { private Task hintHandler; public UnityEvent OnCircleShow; public UnityEvent OnCircleHide; public UnityEvent OnCircleHideButPalmEndFacingFloor; public UnityEvent OnCircleActiveAndPalmFacingFloor; public UnityEvent OnPalmAcriveButGrabBegin; public UnityEvent OnPalmEndFacingFloor; public UnityEvent TerminateAll; public AnimationClip _animation; private Animation _myAnim; public float speed = 1; public PinchDetector pinchScript; public PalmDirectionDetector palmScript; public InteractionController intController; public GameObject Target; protected bool pinching; protected bool startPinch; protected bool endPinch; protected bool objectHidden; protected bool palmFacingFloor; Leap.Hand _hand; Controller controller = new Controller(); private bool isGrabbing; private void Start() { if (Target == null) Target = gameObject; _myAnim = GetComponent<Animation>(); HideMagicCircle(); hintHandler = new Task(HintTimer()); hintHandler.Pause(); } private void Awake() { //if (Target == null) // Target = gameObject; //_myAnim = GetComponent<Animation>(); //HideMagicCircle(); } Hand ReturnHand() { Frame frame = controller.Frame(); // controller is a Controller object if (frame.Hands.Count > 0) { List<Hand> hands = frame.Hands; Hand firstHand = hands[0]; return firstHand; } else { return null; } } IEnumerator isGrabbingSmth() { //Debug.Log("Started to listen to Grab mechanic"); isGrabbing = false; while (pinching) { if (intController.isPrimaryHovering) { //Debug.Log("Hovering"); isGrabbing = true; break; } if (ReturnHand() == null) // skip empty frames { break; } float probability = ReturnHand().GrabStrength; if (probability > .9f) isGrabbing = true; else isGrabbing = false; yield return null; } //isGrabbing = false; } public void CheckGrabState() { Hand _hand = ReturnHand(); Debug.Log(_hand.GrabStrength); } public void ShowMagicCircle() { if (!isGrabbing) { OnCircleShow.Invoke(); hintHandler = new Task(HintTimer()); // start the hint timer objectHidden = false; StartCoroutine(CheckPlayingState()); StartCoroutine(CheckPalm()); _myAnim.AddClip(_animation, "Show"); _myAnim["Show"].speed = speed * -1; _myAnim["Show"].time = _myAnim["Show"].length; _myAnim.Play("Show"); } } public void HideMagicCircle() { if (!objectHidden) { objectHidden = true; StopCoroutine(CheckPlayingState()); StopCoroutine(CheckPalm()); if (palmScript.IsActive && !isGrabbing) OnCircleHide.Invoke(); // teleprot else if (isGrabbing) OnPalmAcriveButGrabBegin.Invoke(); // red color else { OnCircleHideButPalmEndFacingFloor.Invoke(); } TerminateAll.Invoke(); // just to make sure that nothing is missed. _myAnim.AddClip(_animation, "Hide"); _myAnim["Hide"].speed = speed * 1; _myAnim["Hide"].time = 0; // _myAnim["Hide"].length; _myAnim.Play("Hide"); } } IEnumerator CheckPlayingState() { while (_myAnim.isPlaying) { yield return new WaitForEndOfFrame(); } // if (!objectHidden) // OnCircleShow.Invoke(); } IEnumerator CheckPalm() { bool invoked = false; while (!objectHidden) { if (palmScript.IsActive && !invoked) { OnCircleActiveAndPalmFacingFloor.Invoke(); // green hintHandler.Stop(); invoked = true; //Debug.Log("Invoking"); } else if (!palmScript.IsActive && invoked) { OnPalmEndFacingFloor.Invoke(); // yellow hintHandler.Start(); invoked = false; } yield return null; } } private void Terminate() { } void Update() { pinching = pinchScript.IsPinching; startPinch = pinchScript.DidStartPinch; endPinch = pinchScript.DidEndPinch; if (startPinch) StartCoroutine(isGrabbingSmth()); if (endPinch) { StopCoroutine(isGrabbingSmth()); HideMagicCircle(); } if (isGrabbing && !objectHidden) HideMagicCircle(); if (pinching && objectHidden && !isGrabbing) ShowMagicCircle(); } private void FixedUpdate() { if (pinching) { Target.transform.position = pinchScript.Position; } } private IEnumerator HintTimer() { float duration = 3; float normalizedTime = 0; while (normalizedTime <= 1f) { normalizedTime += Time.deltaTime / duration; yield return null; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class MyDebugger : MonoBehaviour { public UnityEvent RunAtStart; // Use this for initialization IEnumerator Start() { yield return new WaitForSeconds(1); if (RunAtStart != null) { RunAtStart.Invoke(); } } // Update is called once per frame void Update() { } public void PrintDebug() { Debug.Log("DEtected"); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class LazerTeleport : MonoBehaviour { public GameObject Player; public LazerPointer lazer; public VRTeleporter teleporter; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public IEnumerator MoveOverSpeed(GameObject objectToMove, Vector3 end, float speed) { // speed should be 1 unit per second while (objectToMove.transform.position != end) { objectToMove.transform.position = Vector3.MoveTowards(objectToMove.transform.position, end, speed * Time.deltaTime); yield return new WaitForEndOfFrame(); } } public void TeleportMe(float speed) { // new implementation: // if (!lazer.Hidden) //StartCoroutine(MoveOverSpeed(Player, new Vector3(lazer.hit.point.x, Player.transform.position.y, lazer.hit.point.z), speed)); teleporter.Teleport(); teleporter.ToggleDisplay(false); //Vector3 pos = Player.transform.position; //pos.x = lazer.hit.point.x; //pos.z = lazer.hit.point.z; //Player.transform.position = pos; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using Leap.Unity; using Leap.Unity.Interaction; using System; public class ToggleHandsModel : MonoBehaviour { private InteractionBehaviour intGloves; public HandModelManager HandPool; public string[] HandGroups; [SerializeField] private int current; public DetectorManager _detectorManagerScript; public Material[] _material; Renderer[] _ren; void Start () { _ren = GetComponentsInChildren<Renderer>(); intGloves = gameObject.GetComponent<InteractionBehaviour>(); intGloves.OnHoverBegin += ToggleHands; // intGloves.OnHoverBegin(ToggleHands); } // Update is called once per frame void Update () { if (Input.GetKeyDown("space")) ToggleHands(); } public Action<bool> OnGlovesOn = delegate { }; public void ToggleHands() { //Debug.Log("shifting hands"); HandPool.DisableGroup(HandGroups[current]); if (current == HandGroups.Length - 1) // reached the last element { current = 0; // start with the first element OnGlovesOn(false); } else { current++; OnGlovesOn(true); } HandPool.EnableGroup(HandGroups[current]); foreach (var item in _ren) { item.material = _material[current]; } _detectorManagerScript.ToggleDetectors(); // toggle detectors for new hands } //private void OnTriggerEnter(Collider other) //{ // if (other.CompareTag("gloves")) // { // ToggleHands(); // } //} IEnumerator DisableCollider() { gameObject.GetComponent<Collider>().enabled = false; yield return new WaitForSeconds(1.5f); gameObject.GetComponent<Collider>().enabled = true; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnbDisInt : MonoBehaviour { DoorsOpenClose _doors; Collider _col; // Use this for initialization void Start() { _doors = GetComponent<DoorsOpenClose>(); if (_doors == null) gameObject.SetActive(false); _col = GetComponent<Collider>(); CheckRestriction(); } // Update is called once per frame void Update() { } public void CheckRestriction() { if (_doors.OlderItemRestrictsClose != null) _col.enabled = !_doors.OlderItemRestrictsClose.GetComponent<IDoor>().GetOpened(); if (_doors.OlderItemRestrictsOpen != null) _col.enabled = _doors.OlderItemRestrictsOpen.GetComponent<IDoor>().GetOpened(); } } <file_sep>public static class Constant { public static string TAGDOORS = "doors"; }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using Leap; using Leap.Unity; using Leap.Unity.Interaction; public class CustumTeleporter : MonoBehaviour { public VRTeleporter teleporter; public GameObject RightHandGO; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void ShowTeleport() { teleporter.ToggleDisplay(true); } public void TeleportMe() { if (RightHandGO.activeInHierarchy) { teleporter.Teleport(); teleporter.ToggleDisplay(false); } teleporter.ToggleDisplay(false); } } <file_sep>public interface IDoor { void OpenCloseDoor(); bool GetOpened(); }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public interface IDryIce { void BePlaced(); } <file_sep>using UnityEngine; using System.Collections; public class AnimatedUVs : MonoBehaviour { public int materialIndex = 0; public float speed; public Vector2 uvAnimationRate = new Vector2(1.0f, 0.0f); public string textureName = "_MainTex"; Renderer myRenderer; Vector2 uvOffset = Vector2.zero; private void Start() { myRenderer = GetComponent<Renderer>(); } void LateUpdate() { uvOffset -= (uvAnimationRate * Time.deltaTime * speed); if (myRenderer.enabled) { myRenderer.materials[materialIndex].SetTextureOffset(textureName, uvOffset); } } }
b1a68cdee892110e65f584dd293f23c9f4e75257
[ "C#" ]
26
C#
Gustorvo/Dry-Ice-Loading-Leap-Motion
80a42ed076b6c5b3dad0ed18b6691585f4c65008
45d4a28eb5c4b769569f1c9f253c64092bebfc52
refs/heads/master
<repo_name>DiscoveryInstitute/haplo<file_sep>/core/AncestralChromosomes.cpp #include <memory> #include <string> #include <utility> #include <vector> #include "AncestralChromosomes.h" #include "HaploBlockVariants.h" using namespace std; AncestralChromosomes& AncestralChromosomes::initialiseFoundingGeneration() { // Initialize founding generation. Each chromosome gets its own ref_id const long nGenerations = m_graph->getNumberOfGenerations(); const long foundingGeneration = nGenerations-1; const long gen = foundingGeneration; const auto& graphMaleFounders = m_graph->getMales(gen); const auto& graphFemaleFounders = m_graph->getFemales(gen); const long nMaleFounders = graphMaleFounders.size(); const long nFemaleFounders = graphFemaleFounders.size(); long ref = 0; vector<PersonNode> maleFounders; maleFounders.reserve(nMaleFounders); vector<PersonNode> femaleFounders; femaleFounders.reserve(nFemaleFounders); for (auto nodesPair : { make_pair(&graphMaleFounders, &maleFounders), make_pair(&graphFemaleFounders, &femaleFounders) }) for (auto& graphFounder : *nodesPair.first) { auto& founders = *nodesPair.second; auto chromosomeA = m_variants->getReferenceChromosome(ref++); auto chromosomeB = m_variants->getReferenceChromosome(ref++); chromosomeA = chromosomeA.filtered(graphFounder.chromosomeFromFatherExtancyPattern); chromosomeB = chromosomeB.filtered(graphFounder.chromosomeFromMotherExtancyPattern); founders.emplace_back(move(chromosomeA), move(chromosomeB)); } m_nodes.at(gen) = { move(maleFounders), move(femaleFounders) }; return *this; } AncestralChromosomes& AncestralChromosomes::forwardsDropAllGenerations( const double mu, mt19937_64& rng) { const long nGenerations = m_graph->getNumberOfGenerations(); const long extantGeneration = 0L; const long foundingGeneration = nGenerations-1; // Drop the genes to following generations. for (long gen=foundingGeneration-1; gen >= extantGeneration; --gen) { forwardsDropOneGeneration(gen, mu, rng); } return *this; } AncestralChromosomes& AncestralChromosomes::forwardsDropOneGeneration( const long gen, const double mu, mt19937_64& rng) { const long nGenerations = m_graph->getNumberOfGenerations(); const long lastGeneration = nGenerations-1; if (gen < 0L) throw invalid_argument("Gen must be >=0"); if (gen >= lastGeneration) throw invalid_argument("Gen id too big"); auto& maleParents = m_nodes.at(gen+1).first; auto& femaleParents = m_nodes.at(gen+1).second; const auto& graphMaleChildren = m_graph->getMales(gen); const auto& graphFemaleChildren = m_graph->getFemales(gen); long nMaleChildren = graphMaleChildren.size(); long nFemaleChildren = graphFemaleChildren.size(); vector<PersonNode> maleChildren; maleChildren.reserve(nMaleChildren); vector<PersonNode> femaleChildren; femaleChildren.reserve(nFemaleChildren); for (auto nodesPair : { make_pair(&graphMaleChildren, &maleChildren), make_pair(&graphFemaleChildren, &femaleChildren) }) for (auto& graphChild : *nodesPair.first) { auto& children = *nodesPair.second; Chromosome chromosomeFromFather; Chromosome chromosomeFromMother; if (graphChild.extantFather()) { auto& father = maleParents.at(graphChild.fatherId); chromosomeFromFather = Chromosome::combine(father.chromosomeFromFather, father.chromosomeFromMother, graphChild.chromosomeFromFatherRecombinationPattern); chromosomeFromFather = chromosomeFromFather.filtered(graphChild.chromosomeFromFatherExtancyPattern); chromosomeFromFather = m_variants->mutate(chromosomeFromFather, mu, gen, rng); } if (graphChild.extantMother()) { auto& mother = femaleParents.at(graphChild.motherId); chromosomeFromMother = Chromosome::combine(mother.chromosomeFromFather, mother.chromosomeFromMother, graphChild.chromosomeFromMotherRecombinationPattern); chromosomeFromMother = chromosomeFromMother.filtered(graphChild.chromosomeFromMotherExtancyPattern); chromosomeFromMother = m_variants->mutate(chromosomeFromMother, mu, gen, rng); } children.emplace_back(move(chromosomeFromFather), move(chromosomeFromMother)); } m_nodes.at(gen) = { move(maleChildren), move(femaleChildren) }; return *this; } size_t AncestralChromosomes::getSizeInMemory(long gen) const { size_t sum = sizeof(m_nodes.at(gen)); for (auto* persons : { &m_nodes.at(gen).first, &m_nodes.at(gen).second }) for (auto& person : *persons) for (auto* chromosome : { &person.chromosomeFromFather, &person.chromosomeFromMother }) { sum += chromosome->getSizeInMemory(); } return sum; } string AncestralChromosomes::toString(long gen) const { std::string s; s = "Generation: " + to_string(gen); s += "\nMales: " + to_string(getMales(gen).size()) + "\n"; for (const auto& m : getMales(gen)) { s += m.chromosomeFromFather.toString(); s += m.chromosomeFromMother.toString(); } s += "\nFemales: " + to_string(getFemales(gen).size()) + "\n"; for (const auto& f : getFemales(gen)) { s += f.chromosomeFromFather.toString(); s += f.chromosomeFromMother.toString(); } s+="\n"; return s; } bool AncestralChromosomes::operator==(const AncestralChromosomes& o) const { return ( m_graph == o.m_graph || ( m_graph != nullptr && o.m_graph != nullptr && *m_graph == *o.m_graph ) ) && ( m_variants == o.m_variants || ( m_variants != nullptr && o.m_variants != nullptr && *m_variants == *o.m_variants ) ) && m_nodes == o.m_nodes; } <file_sep>/hpc/FileOutputs.cpp #include "FileOutputs.h" #include <fstream> #include <string> #include "FileWriter.h" using namespace std; FileOutputs::FileOutputs(const string& pfx) : m_file_prefix(pfx) { ofstream ofs(pfx + "test"); if (!ofs) throw runtime_error("Directory not available to write files: " + pfx); } void FileOutputs::assertNoExistingOutputFiles() const { auto filenames = {m_file_prefix + "Q.txt", m_file_prefix + "S.txt", m_file_prefix + "Pi.txt", m_file_prefix + "Phi.txt", m_file_prefix + "snp_dist.txt", m_file_prefix + "r2.txt", m_file_prefix + "dprime.txt", m_file_prefix + "CLDP.txt", m_file_prefix + "aCLDP.txt", m_file_prefix + "nKLD.txt", m_file_prefix + "pair_spectrum.txt"}; for (string filename : filenames) { ifstream ifs(filename); if (ifs) throw runtime_error("Output file already exists: " + filename); } } void FileOutputs::writeOutputFiles(const Analysis& analysis) const { FileWriter::write(m_file_prefix + "Q.txt", to_string(analysis.total_blocks), "Q - total generated haploblocks"); FileWriter::write(m_file_prefix + "S.txt", to_string(analysis.total_snp_sites), "S - total number of SNPs (mutations)"); FileWriter::write(m_file_prefix + "Pi.txt", to_string(analysis.sn_diversity), "Pi - total diversity per SN site"); FileWriter::write(m_file_prefix + "Phi.txt", analysis.snp_freq_spectrum.toString(true), "Phi - SNP frequency spectrum"); FileWriter::write(m_file_prefix + "snp_dist.txt", analysis.snp_distribution.toString(true), "SNP distribution along chromosome"); FileWriter::write(m_file_prefix + "r2.txt", analysis.correlation_function.toString(true), "r2 - correlation vs genome distance"); FileWriter::write(m_file_prefix + "dprime.txt", analysis.dprime_function.toString(true), "D' - correlation vs genome distance"); FileWriter::write(m_file_prefix + "CLDP.txt", analysis.complete_linkage_function.toString(true), "CLDP - complete linkage-disequilibrium proportion vs genome distance"); FileWriter::write(m_file_prefix + "aCLDP.txt", analysis.almost_complete_linkage_function.toString(true), "aCLDP - almost-complete linkage-disequilibrium proportion vs genome distance"); FileWriter::write(m_file_prefix + "nKLD.txt", analysis.normalized_kullback_leibler_function.toString(true), "nKLD - normalised Kullback-Leibler function vs genome distance"); FileWriter::write(m_file_prefix + "sigma2.txt", analysis.sigma_squared_function.toString(true), "sigma2 - average(numerator(r2))/average(denominator(r2))"); FileWriter::write(m_file_prefix + "pair_spectrum.txt", analysis.freq_pair_spectrum.toString(true), "pair_spectrum - SNPs frequency pair spectrum"); } <file_sep>/hpc/FileReader.cpp #include "FileReader.h" #include <fstream> #include <map> #include <regex> #include <sstream> #include <stdexcept> #include <string> #include <vector> #include "core/Parser.h" using namespace std; inline long nearestLong(double x) { return (long)(x>0 ? x+0.5 : x-0.5); } /** * Reads a file using a very simple TOML-like format. * Returns a map/dictionary from string keys to string values. * Key/value pairs are given line by line: * keyA = valueA * keyB = valueB * ... * Except that * whitespace at the start of a line means it continues previous line * # means comment - it and the rest of the line will be ignored * other whitespace is condensed into single spaces */ map<string,string> FileReader::parseTOML(string input_filename) { ifstream ifs(input_filename, ifstream::in); if (ifs.fail()) throw invalid_argument("Cannot open " + input_filename); stringstream raw_ss; raw_ss << ifs.rdbuf(); string s = raw_ss.str(); s = regex_replace(s, regex(R"([\n\r]+)"), "\n"); // replace native line endings s = regex_replace(s, regex(R"(#[^\n]*\n)"), "\n"); // remove comments s = regex_replace(s, regex(R"(\s*\n)"), "\n"); // remove wspace before newline s = regex_replace(s, regex(R"(\n\s+)"), " "); // continue line if starts with space s = regex_replace(s, regex(R"([^\S\n]+)"), " "); // remove extra space (except newlines) s = regex_replace(s, regex(R"([^\S\n]*=[^\S\n]*)"), "="); // remove space around '=' map<string,string> kvmap; istringstream lines_ss(s); for (string line; getline(lines_ss,line); ) { if (line.length()==0) continue; istringstream tokens_ss(line); vector<string> tokens; for (string token; getline(tokens_ss,token,'='); ) { tokens.push_back(token); } if (tokens.size()==0 || tokens[0].empty()) throw invalid_argument("No key in this entry: " + line); if (tokens.size()==1) tokens.push_back(""); if (tokens.size()>2) throw invalid_argument("Extra values in this entry: " + line); kvmap.emplace(tokens[0], tokens[1]); } return kvmap; } /** * Read PopulationStructureHistory from a text file. * The format of each line is: 'gen nmales nfemales' . * Generations are generations before present, so the first line gives * the total number of generations to simulate back. * Generations must be in descending order (forward in time to present). * The first and last generation must be specified. * Any generations not explicitly specified, are interpolated * piecewise-linearly, and non-integer values are rounded down. * Example: * 4 4 4 * 3 1 1 * 0 4 4 * becomes: * 4 4 4 * 3 1 1 * 2 2 2 * 1 3 3 * 0 4 4 */ PopulationStructureHistory FileReader::readPopulationStructureHistory(string input_filename) { vector<pair<long,long>> history; long previousGen=-1L; // to keep stupid compilers happy ifstream ifs(input_filename, ifstream::in); if (ifs.fail()) throw invalid_argument("Cannot open " + input_filename); // For each line in the text file. for (string line; getline(ifs,line); ) { line = regex_replace(line, regex(R"([\s]*#.*)"), ""); // remove comments (and trim space) line = regex_replace(line, regex(R"([\s]+)"), " "); // trim whitespace to single space if (line.length()==0) continue; // Read the point. istringstream tokens_ss(line); vector<string> tokens; for (string token; getline(tokens_ss, token, ' '); ) { if (!token.empty()) tokens.push_back(token); } if (tokens.size() != 3) { throw invalid_argument("Need 3 args per line: gen nmales nfemales. " "Got: " + line); } long nextGen = (long)Parser::parseNonNegativeDouble(tokens[0]); long nextNMales = Parser::parsePositiveLong(tokens[1]); long nextNFemales = Parser::parsePositiveLong(tokens[2]); // If first point, create the vector and enter point. if (history.empty()) { const long ngens = nextGen+1; history = vector<pair<long,long>>(ngens); history[nextGen] = { nextNMales, nextNFemales }; previousGen = nextGen; } else { // Otherwise, interpolate from the last point. if (nextGen >= previousGen) throw invalid_argument( "Need descending generation numbers. Got" + line); auto& previousEntry = history[previousGen]; long previousNMales = previousEntry.first; long previousNFemales = previousEntry.second; double norm = 1.0 / (previousGen - nextGen); history[nextGen] = { nextNMales, nextNFemales }; for (long gen = nextGen+1; gen < previousGen; ++gen) { double t = (gen - nextGen) * norm; long nMales = nearestLong(t * previousNMales + (1-t) * nextNMales); long nFemales = nearestLong(t * previousNFemales + (1-t) * nextNFemales); history[gen] = { nMales, nFemales }; } previousGen = nextGen; } } // Check the history is not empty. auto& extantEntry = history[0]; if (extantEntry.first==0L && extantEntry.second==0L) throw invalid_argument("No extant generation!"); return PopulationStructureHistory(history); } /** * Read MutationRateHistory from a text file. * The format of each line is: 'gen rate'. * See readPopulationStructureHistory for details about interpolation. */ MutationRateHistory FileReader::readMutationRateHistory(string input_filename) { vector<double> history; long previousGen=-1L; // to keep stupid compilers happy ifstream ifs(input_filename, ifstream::in); if (ifs.fail()) throw invalid_argument("Cannot open " + input_filename); // For each line in the text file. for (string line; getline(ifs,line); ) { line = regex_replace(line, regex(R"([\s]*#.*)"), ""); // remove comments (and trim space) line = regex_replace(line, regex(R"([\s]+)"), " "); // trim whitespace to single space if (line.length()==0) continue; // Read the point. istringstream tokens_ss(line); vector<string> tokens; for (string token; getline(tokens_ss, token, ' '); ) { if (!token.empty()) tokens.push_back(token); } if (tokens.size() != 2) { throw invalid_argument("Need 2 args per line: gen rate. " "Got: " + line); } long nextGen = (long)Parser::parseNonNegativeDouble(tokens[0]); double nextRate = Parser::parseNonNegativeDouble(tokens[1]); // If first point, create the vector and enter point. if (history.empty()) { const long ngens = nextGen+1; history = vector<double>(ngens); history[nextGen] = nextRate; previousGen = nextGen; } else { // Otherwise, interpolate from the last point. if (nextGen >= previousGen) throw invalid_argument( "Need descending generation numbers. Got" + line); double previousRate = history[previousGen]; double norm = 1.0 / (previousGen - nextGen); history[nextGen] = nextRate; for (long gen = nextGen+1; gen < previousGen; ++gen) { double t = (gen - nextGen) * norm; double rate = t * previousRate + (1-t) * nextRate; history[gen] = rate; } previousGen = nextGen; } } return MutationRateHistory(history); } void FileReader::stopIfFindStopFile() { ifstream ifs("stop", ifstream::in); if (!ifs.fail()) { printf("Stopping because 'stop' file found\n"); exit(0); } } <file_sep>/hpc/FileOutputs.h #pragma once #include <string> #include "core/Analysis.h" class FileOutputs { const std::string m_file_prefix; public: FileOutputs(const std::string& pfx=""); void assertNoExistingOutputFiles() const; void writeOutputFiles(const Analysis& analysis) const; }; <file_sep>/hpc/FileMemorySaver.h #pragma once #include <string> #include <vector> #include "core/AncestralChromosomes.h" #include "core/AncestralRecombinationGraph.h" class FileMemorySaver { const std::string m_file_prefix; // can be or include a directory name std::vector<std::string> m_discard_list; // list of files to delete (at checkpoint) public: FileMemorySaver(const std::string& pfx=""); void unloadGenerationToFile(AncestralRecombinationGraph& arg, long gen) const; void reloadGenerationFromFile(AncestralRecombinationGraph& arg, long gen) const; void discardGeneration(AncestralRecombinationGraph& arg, long gen); void unloadGenerationToFile(AncestralChromosomes& ac, long gen) const; void reloadGenerationFromFile(AncestralChromosomes& ac, long gen) const; void discardGeneration(AncestralChromosomes& ac, long gen); void deleteDiscardedGenerations(); }; <file_sep>/core/Chromosome.h #pragma once #include "Blocks.h" using LocusId = long; using BlockId = long; using AlleleId = long; using Chromosome = Blocks<AlleleId>; using ChromosomeId = long; static constexpr AlleleId UNKNOWN_ALLELE{}; static constexpr long UNKNOWN_GENERATION = -1; enum ChromosomeType { AUTO, X, Y, MITO }; <file_sep>/README.md # Haplo Haplo is an implementation of the algorithm described here: http://dx.doi.org/10.5048/BIO-C.2016.4 It is partial in that population substructure has not yet been included, but all other features are included. Haplo performs a full backwards coalescent simulation of a chromosome or section of chromosome, for arbitrarily large populations and (almost) arbitrarily long timescales. It includes the possibility to simulate different numbers of males and females, different mating behaviours, different (or changing) mutation rates, different recombination rates. Full details of all the options are given below. ### COMPILE, SET-UP, AND RUN --- **Compile** using `hpc/build.sh` to create an executable `Haplo`. (Make sure you have the latest version of g++ and make). The script will tell you where to find the built executable. Copy the executable to wherever you will run it. **Edit** input files, for example named `inputs.txt`. Examples can be found in `hpc/sample_inputs`. Typically you will need to create a population-structure-history file, and add its name to the input file. You can also create a temporary (scratch) directory and/or an output directory and add them to the input file. **Run** with `./Haplo inputs.txt`. The code makes checkpoints periodically. If the program gets stopped by causes beyond its control (if it does not crash), restart it with `./Haplo inputs.txt --restart` Take care restarting with a changed input file. For example, if you change `temporary-file-prefix` input, it may not be able to find the saved data it needs. But restarting can sometimes be useful even if the run has completed. For example, one can rerun the final analysis with a different set of analysis parameters, without having to re-run the whole simulation. To stop a simulation cleanly before it has completed, create a file named `stop` (for example, type `touch stop`) in the working directory. If the stop file is present when the code next reaches a suitable stopping point, it will exit cleanly. ### INPUT FILE --- The input file uses a version of TOML composed of key-value pairs in the form `key = value`. The `#` character indicates that any following text on a line is a comment to be ignored. Lines may be continued onto the next line by beginning the next line with whitespace. ##### GENETICS `chromosome_type` - value can be `autosome` or `x` or `y` or `mito` `chromosome_length` - chromosome length in base pairs `recombination_rate` - per generation per nucleotide `mutation_rate` - per generation per nucleotide `mutation_rate_history_file` - if empty use constant mutation_rate, if file given see details below ##### PRIMORDIAL STRUCTURE (ID THEORY) `primordial_diversity` - the heterozygosity : probability that any given nucleotide is heterozygous `primordial_block_length` - length of primordial blocks in base pairs `primordial_probability_dimorphic` - the proportion of blocks that have two variants `primordial_probability_tetramorphic` - the proportion of blocks that have four variants ##### POPULATION / MATING `population_structure_history_file` - file containing demographic history - see below for details `fertility_parameter_alpha` - any number from 0 to infinity - infinity (or say 10^10) means mothers have random numbers of children - small numbers mean some mothers are more likely to have children - 0 means one mother has all children `mating_parameter_beta`- any number from 0 to infinity - infinity (or say 10^10) means mothers mate randomly with fathers - small numbers mean mothers are more likely to have children with same father - 0 means each mother has children with only one father ##### SAMPLING AND CULLING `random_seed` - change this to create a new sample history with the same parameters `population_sample` - the number of individuals to be sampled in extant generation `maximum_blocks` - the number of haplotype blocks that can be created (limit for compute efficiency) `use_mutation_loci` - `true`: store positions of mutations, `false`: approximate them for efficiency `cull_non_parents` - `true/false` remove non-parents from further consideration? `cull_nonancestral_parents` - `true/false` remove parents with no ancestral material? `hide_nonancestral_blocks` - `true/false` remove/hide blocks with no ancestral material? ##### IMPLEMENTATION `verbose_logging` - `true/false` extra logging comments `use_memory_unloading` - `true/false` unload memory contents to temporary files? `temporary_file_prefix` - prefix or path for naming or placing temporary files `output_file_prefix` - prefix or path for naming or placing output files ##### ANALYSIS / OUTPUT `analysis_datapoints_maximum` - maximum resolution for all output data distributions `analysis_linkage_distance_maximum` - maximum distance to calculate linkage `analysis_do_linkage_stats` - `true/false` option to do or not-do expensive linkage calculation `analysis_linkage_minimum_frequency` - value from 0 to 0.5 -exclude alleles with frequency smaller than this from linkage calculation `output_final_SNP_sites` - `true/false` option to create vcf like output of all SNPs (or not) ### POPULATION-STRUCTURE-HISTORY FILE --- This file contains a series of triples: a generation number, and then the number of males and the number of females. The size of each subpopulation is interpolated between each point. The generation numbers are counted back in time, but they are listed forwards in time from the founding generation to the present. Therefore the generation numbers must be decreasing. For example, for a simulation of 5000 generations with a constant population of 1000 men and 1500 women per generation: ``` 5000 1000 1500 0 1000 1500 ``` For a population that slowly grows from 2000 to 4000 and then plateaus at 4000: ``` 5000 1000 1000 4000 2000 2000 0 2000 2000 ``` ### MUTATION-RATE-HISTORY FILE --- If the filename is not set, the constant `mutation_rate` parameter (see above) is used instead. This file is very similar to the population-structure-history file except that it has a series of pairs: a generation number and the mutation rate at that generation. Mutation rates are again linearly interpolated between points. For example, for mutation rate that falls linearly from 2 x 10^-8 to 1 x 10^-8 over 2000 generations: ``` 2000 2e-8 0 1e-8 ``` --- --- <file_sep>/core/HaploBlockVariants.h #pragma once #include <map> #include <random> #include <utility> #include <vector> #include "Chromosome.h" #include "HaploBlockBoundaries.h" #include "MutationGraph.h" #include "PersonNode.h" /** HaploBlockVariants: Stores all the alleles / haplotype variants that exist on each haplotype block (non-recombining section of chromosome), and any tree-like relationship between them. Generates new alleles by mutation, recording which allele it mutated from. Also stores four reference chromosomes (the chromosomes of the founding pair). Also stores boundaries between blocks - copy of information in HaploBlockBoundaries. */ class HaploBlockVariants { friend class FileCheckpointer; private: long m_max_nodes_per_block; std::vector<Chromosome> m_reference_chromosomes; std::vector<MutationGraph> m_variants; std::vector<LocusId> m_boundaries; // map BlockId -> LocusId std::map<LocusId, BlockId> m_block_ids; // map LocusId -> BlockId public: HaploBlockVariants() : m_max_nodes_per_block(0L) {} // for creating unassigned variables bool unassigned() const { return m_reference_chromosomes.empty() && m_variants.empty() && m_boundaries.empty(); } HaploBlockVariants(const HaploBlockBoundaries& hbb, const long max_nodes_per_block, const long primordial_block_length, const double probability_dimorphic, const double probability_tetramorphic, const double primordial_diversity, const bool use_mutation_loci, std::mt19937_64& rng); LocusId getChromosomeLength() const { return m_boundaries.back(); } long getNumberBlocks() const { return m_boundaries.size()-1; } const std::vector<LocusId> getBlockBoundaries() const { return m_boundaries; } const Chromosome& getReferenceChromosome(long chromosomeIndex); Chromosome mutate(const Chromosome&, double mu, long gen, std::mt19937_64& rng); bool sampleChromosomesAndSimplify( const std::pair<std::vector<PersonNode>, std::vector<PersonNode>>& whole_gen, bool hard = false); Chromosome getFounderAlleleIdChromosome(const Chromosome& normal_id_chromosome) const; const MutationGraph& getMutationGraph(LocusId locus) const; void deleteMutationGraph(LocusId locus); bool operator==(const HaploBlockVariants&) const; }; <file_sep>/core/MutationGraph.cpp #include <iterator> #include <map> #include <vector> #include "Chromosome.h" #include "MutationGraph.h" using namespace std; MutationGraph::MutationGraph(vector<vector<LocusId>> founder_alleles, const bool use_mutation_loci) : m_use_mutation_loci(use_mutation_loci) { int n_founder_alleles = founder_alleles.size(); m_next_id = 1; for (AlleleId i = 0; i < n_founder_alleles; ++i) { vector<LocusId>& loci = founder_alleles.at(i); long n_mutations = loci.size(); vector<pair<BlockId, long>> mutations; if (m_use_mutation_loci) { mutations.reserve(loci.size()); for (auto locus : loci) mutations.emplace_back(locus, UNKNOWN_GENERATION); } m_nodes[m_next_id++] = Node { UNKNOWN_ALLELE, n_mutations, move(mutations), 0, 0 }; } } AlleleId MutationGraph::addAlleleMutation(AlleleId parent_id, long gen, const vector<LocusId>& loci) { if (parent_id == UNKNOWN_ALLELE) throw logic_error("Cannot mutate UNKNOWN_ALLELE"); long n_mutations = loci.size(); vector<pair<BlockId, long>> mutations; if (m_use_mutation_loci) { mutations.reserve(loci.size()); for (auto locus : loci) mutations.emplace_back(locus, gen); } m_nodes.at(parent_id).n_child_nodes++; AlleleId id = m_next_id++; m_nodes[id] = Node { parent_id, n_mutations, move(mutations), 0, 0 }; return id; } AlleleId MutationGraph::getFounderId(AlleleId id) const { while (m_nodes.at(id).parent_id) { id = m_nodes.at(id).parent_id; } return id; } bool MutationGraph::isDerivativeAllele(AlleleId parent_id, AlleleId id) const { while (true) { if (id == parent_id) return true; if (id == UNKNOWN_ALLELE) return false; id = m_nodes.at(id).parent_id; } } int MutationGraph::getMutationDistance(AlleleId id_a, AlleleId id_b) const { if (id_a == UNKNOWN_ALLELE || id_b == UNKNOWN_ALLELE) throw logic_error("Cannot get mutation distance of with UNKNOWN_ALLELE"); const Node* node_a; const Node* node_b; int distance_a, distance_b; int overlap_a, overlap_b; node_a = &m_nodes.at(id_a); distance_a = 0; node_b = &m_nodes.at(id_b); distance_b = 0; // Calculate distance to top while (node_a->parent_id) { distance_a += node_a->n_mutations; node_a = &m_nodes.at(node_a->parent_id); } while (node_b->parent_id) { distance_b += node_b->n_mutations; node_b = &m_nodes.at(node_b->parent_id); } if (node_a != node_b) { distance_a += node_a->n_mutations; distance_b += node_b->n_mutations; return distance_a + distance_b; } // Calculate distance of overlap node_a = &m_nodes.at(id_a); overlap_a = distance_a; node_b = &m_nodes.at(id_b); overlap_b = distance_b; while (node_a != node_b) { bool up_a = overlap_a >= overlap_b; bool up_b = overlap_a <= overlap_b; if (up_a) { overlap_a -= node_a->n_mutations; node_a = &m_nodes.at(node_a->parent_id); } if (up_b) { overlap_b -= node_b->n_mutations; node_b = &m_nodes.at(node_b->parent_id); } } return distance_a + distance_b - overlap_a - overlap_b; } void MutationGraph::simplify() { // Remove all nodes on dead branches. vector<AlleleId> dead_branch_ids; for (auto it = m_nodes.rbegin(); it != m_nodes.rend(); ++it) { auto* node = &it->second; if (node->n_child_nodes == 0 && node->frequency == 0) { AlleleId parent_id = node->parent_id; dead_branch_ids.push_back(it->first); if (parent_id) { auto* parent_node = &m_nodes.find(parent_id)->second; --parent_node->n_child_nodes; } } } for (AlleleId id : dead_branch_ids) m_nodes.erase(id); // Compress other unforked branches by removing empty nodes. vector<AlleleId> unforked_branch_empty_node_ids; string s = toString(); for (auto it = m_nodes.rbegin(); it != m_nodes.rend(); ++it) { auto* node = &it->second; while(node->parent_id) { auto parent_it = m_nodes.find(node->parent_id); auto* parent_node = &parent_it->second; if (parent_node->n_child_nodes==1 && parent_node->frequency==0) { if (parent_node->parent_id == UNKNOWN_ALLELE) break; // leave founder nodes alone node->parent_id = parent_node->parent_id; node->n_mutations += parent_node->n_mutations; if (m_use_mutation_loci) { copy(parent_node->mutations.begin(), parent_node->mutations.end(), back_inserter(node->mutations)); } unforked_branch_empty_node_ids.push_back(parent_it->first); } else { break; } } } for (AlleleId id : unforked_branch_empty_node_ids) m_nodes.erase(id); // Assign to a copy of itself (hopefully aligns the memory) auto copy_nodes = m_nodes; m_nodes = move(copy_nodes); // CHECK !!! for (auto& entry : m_nodes) { auto id = entry.first; auto* node = &entry.second; if (node->parent_id != UNKNOWN_ALLELE) { auto parent_it = m_nodes.find(node->parent_id); if (parent_it==m_nodes.end() || id <= node->parent_id || node->parent_id <0) { throw logic_error("invalid parent_id"); } } if (node->n_child_nodes == 0 && node->frequency == 0) { throw logic_error("dead nodes still present"); } } } vector<AlleleId> MutationGraph::getAlleleIds() const { vector<AlleleId> ret; for (auto& entry : m_nodes) ret.push_back(entry.first); return ret; } string MutationGraph::toString() const { string ret; ret += to_string(m_nodes.size()) + " "; for (auto entry : m_nodes) { auto& id = entry.first; auto& node = entry.second; long n_mutations = node.n_mutations; auto& mutations = node.mutations; long generation = (mutations.empty()) ? UNKNOWN_GENERATION : mutations.back().second; ret += "(" + to_string(id) + " " + to_string(getParentId(id)) + " " + to_string(getFounderId(id)) + " " + to_string(n_mutations) + " " + to_string(generation) + " " + to_string(node.frequency) + ") "; } return ret; } bool MutationGraph::Node::operator==(const Node& o) const { return parent_id == o.parent_id && n_mutations == o.n_mutations && mutations == o.mutations && n_child_nodes == o.n_child_nodes && frequency == o.frequency; } bool MutationGraph::operator==(const MutationGraph& o) const { return m_use_mutation_loci == o.m_use_mutation_loci && m_nodes == o.m_nodes && m_next_id == o.m_next_id; } <file_sep>/core/HaploBlockBoundaries.cpp #include "HaploBlockBoundaries.h" #include <algorithm> #include "BlocksRange.h" using namespace std; HaploBlockBoundaries::HaploBlockBoundaries(long chromosome_length, long maximum_blocks, mt19937_64& rng) { set<LocusId> boundary_set {0, chromosome_length}; auto nblocks = [&]() -> long { return boundary_set.size() - 1; }; const long first=1L; const long last=chromosome_length-1L; uniform_int_distribution<LocusId> randomLocus(first, last); // exclude first and last if (maximum_blocks > chromosome_length) maximum_blocks = chromosome_length; if (maximum_blocks < chromosome_length/2) { while (nblocks() < maximum_blocks) { boundary_set.insert(randomLocus(rng)); } } else { for(LocusId loc=first; loc<=last; ++loc) boundary_set.insert(loc); while (nblocks() > maximum_blocks) { boundary_set.erase(randomLocus(rng)); } } m_block_boundaries = vector<LocusId>(boundary_set.begin(), boundary_set.end()); for (LocusId locus : m_block_boundaries) m_block_boundary_used[locus] = 0L; m_block_boundary_used[0] = 1L; m_block_boundary_used[chromosome_length] = 1L; } BlocksRange HaploBlockBoundaries::createRandomRecombinationPattern( double nucleotide_rate, mt19937_64& rng) const { // If only one block (2 boundaries), there is no recombination. if (m_block_boundaries.size()==2) return BlocksRange(); // Generate how many random toggles there will be. long chromosome_length = m_block_boundaries.back() - 1; double total_rate = nucleotide_rate * (chromosome_length - 1); int n_random = poisson_distribution<int>(total_rate)(rng); vector<long> toggles; toggles.reserve(n_random+1); // Start true or false. if (bernoulli_distribution(0.5)(rng)) toggles.push_back(0); // Generate the toggles uniform_int_distribution<BlockId> randomBlock(1, m_block_boundaries.size()-2); // exclude first and last for (int i=0; i<n_random; i++) { toggles.push_back(randomBlock(rng)); // Add random toggles. } sort(toggles.begin(), toggles.end()); // Remove duplicate pairs (they cancel each other) size_t i=0, j=0; // start at second element for( ; i<toggles.size(); ++i, ++j) { toggles[j] = toggles[i]; if (j > 0 && toggles[j] == toggles[j-1]) j -= 2; } toggles.resize(j); for (auto& toggle : toggles) toggle = m_block_boundaries[toggle]; // Move the result into a new BlocksRange. return toggles.empty() ? BlocksRange() : BlocksRange(move(toggles)); } void HaploBlockBoundaries::recordBlockBoundaries(const BlocksRange& pattern) { for(LocusId locus : pattern.m_toggles) m_block_boundary_used[locus]++; } vector<LocusId> HaploBlockBoundaries::getRecordedBlockBoundaries() const { vector<LocusId> boundaries; for (const auto& entry : m_block_boundary_used) if (entry.second > 0) boundaries.push_back(entry.first); return boundaries; } vector<LocusId> HaploBlockBoundaries::getRandomBlockBoundaries(long nblocks, mt19937_64& rng) const { const LocusId maximum_blocks = m_block_boundaries.size()-1; set<long> block_set {0, maximum_blocks}; const long first = 1L; const long last = maximum_blocks - 1; uniform_int_distribution<BlockId> randomBlock(first, last); // exclude first and last auto out_nblocks = [&]() -> long { return block_set.size()-1; }; if (nblocks < maximum_blocks/2) { while (out_nblocks() < nblocks) { block_set.insert(randomBlock(rng)); } } else { for(LocusId loc=first; loc<=last; ++loc) block_set.insert(loc); while (out_nblocks() > nblocks) { block_set.erase(randomBlock(rng)); } } vector<LocusId> block_vec; block_vec.reserve(block_set.size()); for (const auto& blockid : block_set) { block_vec.push_back(m_block_boundaries[blockid]); } return block_vec; } string HaploBlockBoundaries::toString() const { string s = ""; for (auto& b : m_block_boundaries) { s += to_string(b) + " "; } return s; } bool HaploBlockBoundaries::operator==(const HaploBlockBoundaries& o) const { return m_block_boundaries == o.m_block_boundaries && m_block_boundary_used == o.m_block_boundary_used; } <file_sep>/core/ParentPairUrn.cpp #include "ParentPairUrn.h" #include <random> #include <utility> #include "PolyaUrn.h" /** * This method chooses mothers and fathers for children according to the scheme given in * http://bio-complexity.org/ojs/index.php/main/article/view/BIO-C.2016.4 eqn. 68. * * The variables have different names for readability in C++, but I have attempted to identify the * correspondence where possible. It uses a slightly more complex approach than described for * choosing fathers (in order to be more space-efficient) and so some of the variables do not map * one-to-one. * * const long nMaleAdults; <- M_{t+1} in paper * const long nFemaleAdults; <- F_{t+1} in paper * const double alpha; <- alpha in paper * const double beta; <- beta in paper * * PolyaUrn femalesPolyaUrn; * ^ Used to choose mothers for children. Records how many children each female has already had, * because these may influence probability of further children. * The urn returns an id of a mother, from 0 to f_{t+1}, * where f_{t+1} is the previous number of mothers. * NB: Variables f_{t+1} and C_{t+1},f from the paper are hidden in femalesPolyaUrn. * * std::vector<Mother> mothers; * ^ Represents information about mothers once they have been chosen. * * PolyaUrn Mother.partnersPolyaUrn; * ^ Used to choose fathers for children. For each female, records how many children she has * already had with each male, as may influence probability of further children with him. * The urn returns an id from 0 to m(f)_{t+1} where m(f) is the previous number of 'husbands' * this female has had, indicating whether he is her first, second, third, ... * std::vector<long> Mother.partnerIds; * ^ For each female, identify who the first, second, third, ..., 'husbands' are. * NB: Variables C_{t+1},mf are implictly hidden in malesPolyaUrnForFemale and malesForFemale. * * long nFathers=0; <- m_{t+1} in paper * ^ Records how many males have already become fathers. This is also the id for the next father. * */ using namespace std; uniform_real_distribution<double> ParentPairUrn::random(0.0, 1.0); ParentPairUrn::ParentPairUrn(long nM, long nF, double a, double b) : m_nMaleAdults(nM), m_nFemaleAdults(nF), m_alpha(a), m_beta(b), m_femalesPolyaUrn(m_nFemaleAdults, m_alpha, true), m_mothers(), m_nFathers(0) { m_mothers.reserve(nF); } pair<long,long> ParentPairUrn::pick(mt19937_64& rng) { // First choose a female mother. // Probability depends on how many children she has had (PolyaUrn remembers that). size_t f = m_femalesPolyaUrn.sample(rng); // If this is a new mother having the newest id, make some space for her data. if (f == m_mothers.size()) { m_mothers.push_back(Mother { PolyaUrn(m_nMaleAdults, m_beta, false), vector<long>{} }); } // Second, choose a male father. // Probability depends on who mother is and how many children they have had together. // First we choose a proxy: 0 means her first 'husband', 1 means her second 'husband' ... size_t mp = m_mothers[f].partnersUrn.sample(rng); size_t m; // Then convert the proxy into a reference to a particular male. if (mp == m_mothers[f].partnerIds.size()) { // If he didn't have a child with her before. long mc = (long)(random(rng) * m_nMaleAdults); // Choose who he via a random id. m = (mc < m_nFathers) // If this id has been used before, the male already has ? mc // children. If it has not been used before, this is a new Dad, : m_nFathers++; // so give him the next unused id and record we have extra Dad. m_mothers[f].partnerIds.push_back(m); // Record he was the latest father with this female. } else { // If he did have a child with her before. m = m_mothers[f].partnerIds[mp]; // Just look up his id. // NB: The PolyaUrn now remembers they had more than one child, but we don't need to. } return pair<long, long>(m,f); } <file_sep>/hpc/FileMemorySaver.cpp #include "FileMemorySaver.h" #include <cstddef> #include <fstream> #include <stdexcept> #include <vector> #include "core/Blocks.h" #include "core/BlocksRange.h" #include "FileDataPrimitiveIO.h" using namespace std; constexpr unsigned char FATHER_ID_DUMMY = 1<<0; constexpr unsigned char MOTHER_ID_DUMMY = 1<<1; constexpr unsigned char FATHER_REC_EMPTY = 1<<2; constexpr unsigned char FATHER_REC_FULL = 1<<3; constexpr unsigned char MOTHER_REC_EMPTY = 1<<4; constexpr unsigned char MOTHER_REC_FULL = 1<<5; constexpr unsigned char FATHER_EXT_EMPTY = 1<<6; constexpr unsigned char MOTHER_EXT_EMPTY = 1<<7; constexpr long DUMMY_ID = AncestralRecombinationGraph::DUMMY_ID; #define NOOP /* meaning: no-operation; do nothing */ FileMemorySaver::FileMemorySaver(const string& pfx) : m_file_prefix(pfx) { ofstream ofs(pfx + "test"); if (!ofs) throw runtime_error("Directory not available to write files: " + pfx); } void FileMemorySaver::unloadGenerationToFile(AncestralRecombinationGraph& arg, long gen) const { ofstream ofs(m_file_prefix+"ARG"+to_string(gen)+".bin", ios::out | ios::binary); auto& males = arg.m_nodes[gen].first; auto& females = arg.m_nodes[gen].second; auto nmales = males.size(); auto nfemales = females.size(); writePrimitive(ofs, nmales); writePrimitive(ofs, nfemales); for (auto* persons : { &males, &females } ) for (auto& person : *persons) { const auto& fatherId = person.fatherId; const auto& motherId = person.motherId; const auto& fatherRec = person.chromosomeFromFatherRecombinationPattern; const auto& motherRec = person.chromosomeFromMotherRecombinationPattern; const auto& fatherExt = person.chromosomeFromFatherExtancyPattern; const auto& motherExt = person.chromosomeFromMotherExtancyPattern; unsigned char flags = 0; if (fatherId==DUMMY_ID) flags |= FATHER_ID_DUMMY; if (motherId==DUMMY_ID) flags |= MOTHER_ID_DUMMY; if (fatherRec.empty()) flags |= FATHER_REC_EMPTY; if (fatherRec.full()) flags |= FATHER_REC_FULL; if (motherRec.empty()) flags |= MOTHER_REC_EMPTY; if (motherRec.full()) flags |= MOTHER_REC_FULL; if (fatherExt.empty()) flags |= FATHER_EXT_EMPTY; if (motherExt.empty()) flags |= MOTHER_EXT_EMPTY; writePrimitive(ofs, flags); if (flags & FATHER_ID_DUMMY) NOOP; else writePrimitive(ofs, fatherId); if (flags & MOTHER_ID_DUMMY) NOOP; else writePrimitive(ofs, motherId); if (flags & FATHER_REC_EMPTY) NOOP; else if (flags & FATHER_REC_FULL) NOOP; else writePrimitiveVector(ofs, fatherRec.m_toggles); if (flags & MOTHER_REC_EMPTY) NOOP; else if (flags & MOTHER_REC_FULL) NOOP; else writePrimitiveVector(ofs, motherRec.m_toggles); if (flags & FATHER_EXT_EMPTY) NOOP; else writePrimitiveVector(ofs, fatherExt.m_toggles); if (flags & MOTHER_EXT_EMPTY) NOOP; else writePrimitiveVector(ofs, motherExt.m_toggles); } ofs.close(); typedef AncestralRecombinationGraph::ChildNode T; males = vector<T>(); females = vector<T>(); } void FileMemorySaver::reloadGenerationFromFile(AncestralRecombinationGraph& arg, long gen) const { ifstream ifs(m_file_prefix+"ARG"+to_string(gen)+".bin", ios::in | ios::binary); long nmales, nfemales; readPrimitive(ifs, nmales); readPrimitive(ifs, nfemales); auto& males = arg.m_nodes[gen].first; auto& females = arg.m_nodes[gen].second; males.resize(nmales); females.resize(nfemales); for (auto* persons : { &males, &females } ) for (auto& person : *persons) { auto& fatherId = person.fatherId; auto& motherId = person.motherId; auto& fatherRec = person.chromosomeFromFatherRecombinationPattern; auto& motherRec = person.chromosomeFromMotherRecombinationPattern; auto& fatherExt = person.chromosomeFromFatherExtancyPattern; auto& motherExt = person.chromosomeFromMotherExtancyPattern; unsigned char flags; readPrimitive(ifs, flags); if (flags & FATHER_ID_DUMMY) fatherId = DUMMY_ID; else readPrimitive(ifs, person.fatherId); if (flags & MOTHER_ID_DUMMY) motherId = DUMMY_ID; else readPrimitive(ifs, person.motherId); if (flags & FATHER_REC_EMPTY) fatherRec = BlocksRange::createEmpty(); else if (flags & FATHER_REC_FULL) fatherRec = BlocksRange::createFull(); else readPrimitiveVector(ifs, fatherRec.m_toggles); if (flags & MOTHER_REC_EMPTY) motherRec = BlocksRange::createEmpty(); else if (flags & MOTHER_REC_FULL) motherRec = BlocksRange::createFull(); else readPrimitiveVector(ifs, motherRec.m_toggles); if (flags & FATHER_EXT_EMPTY) fatherExt = BlocksRange::createEmpty(); else readPrimitiveVector(ifs, fatherExt.m_toggles); if (flags & MOTHER_EXT_EMPTY) motherExt = BlocksRange::createEmpty(); else readPrimitiveVector(ifs, motherExt.m_toggles); } } void FileMemorySaver::discardGeneration(AncestralRecombinationGraph& arg, long gen) { typedef AncestralRecombinationGraph::ChildNode T; arg.m_nodes[gen] = make_pair(vector<T>(), vector<T>()); m_discard_list.push_back(m_file_prefix+"ARG"+to_string(gen)+".bin"); } void FileMemorySaver::unloadGenerationToFile(AncestralChromosomes& ac, long gen) const { ofstream ofs(m_file_prefix+"AC"+to_string(gen)+".bin", ios::out | ios::binary); auto& males = ac.m_nodes[gen].first; auto& females = ac.m_nodes[gen].second; auto nmales = males.size(); auto nfemales = females.size(); writePrimitive(ofs, nmales); writePrimitive(ofs, nfemales); for (auto* persons : { &males, &females } ) for (auto& person : *persons) { writePrimitiveVector(ofs, person.chromosomeFromFather.m_intervals); writePrimitiveVector(ofs, person.chromosomeFromMother.m_intervals); } ofs.close(); typedef PersonNode T; males = vector<T>(); females = vector<T>(); } void FileMemorySaver::reloadGenerationFromFile(AncestralChromosomes& ac, long gen) const { ifstream ifs(m_file_prefix+"AC"+to_string(gen)+".bin", ios::in | ios::binary); long nmales, nfemales; readPrimitive(ifs, nmales); readPrimitive(ifs, nfemales); auto& males = ac.m_nodes[gen].first; auto& females = ac.m_nodes[gen].second; males.resize(nmales); females.resize(nfemales); for (auto* persons : { &males, &females } ) for (auto& person : *persons) { readPrimitiveVector(ifs, person.chromosomeFromFather.m_intervals); readPrimitiveVector(ifs, person.chromosomeFromMother.m_intervals); } } void FileMemorySaver::discardGeneration(AncestralChromosomes& ac, long gen) { typedef PersonNode T; ac.m_nodes[gen] = make_pair(vector<T>(), vector<T>()); m_discard_list.push_back(m_file_prefix+"AC"+to_string(gen)+".bin"); } void FileMemorySaver::deleteDiscardedGenerations() { for (string& filename : m_discard_list) remove(filename.c_str()); m_discard_list.clear(); } <file_sep>/core/ParentPairUrn.h #pragma once #include <random> #include <utility> #include <vector> #include "PolyaUrn.h" // Class to choose mothers and fathers for children according to the scheme given in // http://bio-complexity.org/ojs/index.php/main/article/view/BIO-C.2016.4 eqn. 68. // See more notes in cpp file. class ParentPairUrn { private: const long m_nMaleAdults; const long m_nFemaleAdults; const double m_alpha; const double m_beta; struct Mother { PolyaUrn partnersUrn; std::vector<long> partnerIds; }; PolyaUrn m_femalesPolyaUrn; std::vector<Mother> m_mothers; long m_nFathers=0; static std::uniform_real_distribution<double> random; public: /** * Create a new ParentPairUrn containing 'nM' males (M_{t+1} in paper) * and 'nF' females (F_{t+1} in paper), with mother randomness parameter 'a' (alpha) * and father-per-mother randomness parameter 'b' (beta). * Large alpha makes child more likely to have a random mother. * Small alpha makes child more likely to have a mother who already has children. * Large beta makes child more likely to have a random father. * Small beta makes child more likely to have father who already has children with the mother. */ ParentPairUrn(long nM, long nF, double a, double b); /** * Choose a parent-pair using the supplied random number generator. Two ids is returned, first * for the father and second for the mother. The first pick is always labelled with ids=0,0. * Subsequent fathers are given monotonically-increasing ids if they have not been picked * before, and subsequent mothers are given monotonically-increasing ids from a separate * sequence. */ std::pair<long,long> pick(std::mt19937_64& rng); long getNumberOfFathers() { return m_nFathers; } long getNumberOfMothers() { return m_mothers.size(); } }; <file_sep>/core/AncestralRecombinationGraph.cpp #include "AncestralRecombinationGraph.h" #include <memory> #include <random> #include <utility> #include <vector> #include "BlocksRange.h" #include "ParentPairUrn.h" #include "PopulationStructureHistory.h" using namespace std; template<typename T> vector<T> trim(vector<T>& v, long n) { return vector<T>(make_move_iterator(v.begin()), make_move_iterator(v.begin() + n)); } static constexpr long DID = AncestralRecombinationGraph::DUMMY_ID; bool AncestralRecombinationGraph::ChildNode::extantFather() const { return !chromosomeFromFatherExtancyPattern.empty(); } bool AncestralRecombinationGraph::ChildNode::extantMother() const { return !chromosomeFromMotherExtancyPattern.empty(); } bool AncestralRecombinationGraph::ChildNode::extant() const { return extantFather() || extantMother(); } bool AncestralRecombinationGraph::ChildNode::operator==(const ChildNode& o) const { return fatherId == o.fatherId && motherId == o.motherId && chromosomeFromFatherRecombinationPattern == o.chromosomeFromFatherRecombinationPattern && chromosomeFromMotherRecombinationPattern == o.chromosomeFromMotherRecombinationPattern && chromosomeFromFatherExtancyPattern == o.chromosomeFromFatherExtancyPattern && chromosomeFromMotherExtancyPattern == o.chromosomeFromMotherExtancyPattern; } /** * Initialize children of the extant (final) generation. */ AncestralRecombinationGraph& AncestralRecombinationGraph::initialiseExtantGeneration( const pair<long,long> samples) { // First check the requested sample is consistent with population size. const long extantGeneration = 0L; long nMalesSample = samples.first; long nFemalesSample = samples.second; long nMalesPopn = m_history->getNumberOfMales(extantGeneration); long nFemalesPopn = m_history->getNumberOfFemales(extantGeneration); if (nMalesSample > nMalesPopn || nFemalesSample > nFemalesPopn) { throw invalid_argument("Sample must be no larger than extant population."); } // Specify which chromosomes are of interest or to be ignored for each type. // Relevant chromosomes are by definition wholly extant (ALL). // Ignored chromosomes are treated as if wholly non-extant (NONE). const BlocksRange ALL = BlocksRange::createFull(); const BlocksRange NONE = BlocksRange(); const BlocksRange& DRP = NONE; // DUMMY_RECOMBINATION_PATTERN ChildNode MALE_NODE; ChildNode FEMALE_NODE; switch (m_chromosome_type) { case AUTO: // Both male and female have autosome from both father and mother. MALE_NODE = { DID, DID, DRP, DRP, ALL, ALL }; FEMALE_NODE = { DID, DID, DRP, DRP, ALL, ALL }; break; case X: // Male has X chromosome from mother. Female has X from both father and mother. MALE_NODE = { DID, DID, DRP, DRP, NONE, ALL }; FEMALE_NODE = { DID, DID, DRP, DRP, ALL, ALL }; break; case Y: // Male has Y chromosome from father. Female has no Y chromosome. MALE_NODE = { DID, DID, DRP, DRP, ALL, NONE }; FEMALE_NODE = { DID, DID, DRP, DRP, NONE, NONE }; break; case MITO: // Both male and female have DNA from the mother only. MALE_NODE = { DID, DID, DRP, DRP, NONE, ALL }; FEMALE_NODE = { DID, DID, DRP, DRP, NONE, ALL }; break; } // Create the representation of the final/extant/sampled generation. auto maleChildNodes = vector<ChildNode>(nMalesSample, MALE_NODE); auto femaleChildNodes = vector<ChildNode>(nFemalesSample, FEMALE_NODE); m_nodes[extantGeneration] = { move(maleChildNodes), move(femaleChildNodes) }; return *this; } AncestralRecombinationGraph& AncestralRecombinationGraph::backwardsCoalesceAllGenerations( const double alpha, const double beta, const double rate, mt19937_64& rng, const bool cull_non_parents, const bool cull_non_ancestral, const bool hide_non_ancestral) { const long nGenerations = m_history->getNumberOfGenerations(); const long extantGeneration = 0L; const long foundingGeneration = nGenerations-1; for (long gen=extantGeneration; gen<foundingGeneration; ++gen) { backwardsCoalesceOneGeneration( gen, alpha, beta, rate, rng, cull_non_parents, cull_non_ancestral, hide_non_ancestral); } return *this; } AncestralRecombinationGraph& AncestralRecombinationGraph::backwardsCoalesceOneGeneration( const long gen, const double alpha, const double beta, const double rate, mt19937_64& rng, const bool cull_non_parents, const bool cull_non_ancestral, const bool hide_non_ancestral) { const BlocksRange ALL = BlocksRange::createFull(); const BlocksRange NONE = BlocksRange(); const BlocksRange& INHERIT_GRANDFATHER = ALL; // (all of father.chromosomeFromFather) const BlocksRange& INHERIT_GRANDMOTHER = NONE; // (none of father.chromosomeFromFather) const BlocksRange& DRP = NONE; // DUMMY_RECOMBINATION_PATTERN const ChildNode NON_EXTANT_NODE { DID, DID, DRP, DRP, NONE, NONE }; const long nGenerations = m_history->getNumberOfGenerations(); const long lastGeneration = nGenerations-1; HaploBlockBoundaries* hbb = m_haplo_block_boundaries; if (gen < 0L) throw invalid_argument("Gen must be >=0"); if (gen >= lastGeneration) throw invalid_argument("Gen must have children in ARG"); auto& maleChildNodes = m_nodes[gen].first; auto& femaleChildNodes = m_nodes[gen].second; // Adults are potential parents. Number of actual parents is generated in the parent urn. // All parent chromosomes are completely non-extant by default, // (unless they have children inherited extant blocks from them - see below). long nMaleAdults = m_history->getNumberOfMales(gen+1); long nFemaleAdults = m_history->getNumberOfFemales(gen+1); auto fatherNodes = vector<ChildNode>(nMaleAdults, NON_EXTANT_NODE); auto motherNodes = vector<ChildNode>(nFemaleAdults, NON_EXTANT_NODE); ParentPairUrn parentUrn(nMaleAdults, nFemaleAdults, alpha, beta); for (auto* childNodes : { &maleChildNodes, &femaleChildNodes }) for (auto& childNode : *childNodes) { auto parentIds = parentUrn.pick(rng); long fatherId = parentIds.first; long motherId = parentIds.second; auto& fatherEP = childNode.chromosomeFromFatherExtancyPattern; auto& motherEP = childNode.chromosomeFromMotherExtancyPattern; bool fatherCPE = !fatherEP.empty(); // father chromosome partially extant bool motherCPE = !motherEP.empty(); // mother chromosome partially extant BlocksRange fatherRecombinations; BlocksRange motherRecombinations; switch (m_chromosome_type) { case AUTO: // Recombination on chromosome from father and from mother if (fatherCPE) fatherRecombinations = hbb->createRandomRecombinationPattern(rate, rng); if (motherCPE) motherRecombinations = hbb->createRandomRecombinationPattern(rate, rng); break; case X: // Recombination from mother; from father is always from grandmother. if (fatherCPE) fatherRecombinations = INHERIT_GRANDMOTHER; if (motherCPE) motherRecombinations = hbb->createRandomRecombinationPattern(rate, rng); break; case Y: // From father is always from grandfather. No inheritance from mother. if (fatherCPE) fatherRecombinations = INHERIT_GRANDFATHER; if (motherCPE) motherRecombinations = DRP; break; case MITO: // From mother is always from grandmother. No inheritance from father. if (fatherCPE) fatherRecombinations = DRP; if (motherCPE) motherRecombinations = INHERIT_GRANDMOTHER; break; } if (fatherCPE) { auto& fathersFatherEP = fatherNodes[fatherId].chromosomeFromFatherExtancyPattern; auto& fathersMotherEP = fatherNodes[fatherId].chromosomeFromMotherExtancyPattern; auto fathersFatherPartialEP = fatherEP.intersectionWith(fatherRecombinations); auto fathersMotherPartialEP = fatherEP.intersectionWithInverse(fatherRecombinations); if (hide_non_ancestral) { if (fathersFatherPartialEP.empty()) fatherRecombinations = INHERIT_GRANDMOTHER; if (fathersMotherPartialEP.empty()) fatherRecombinations = INHERIT_GRANDFATHER; } fathersFatherEP = fathersFatherEP.unionWith(fathersFatherPartialEP); fathersMotherEP = fathersMotherEP.unionWith(fathersMotherPartialEP); hbb->recordBlockBoundaries(fatherRecombinations); } if (motherCPE) { auto& mothersFatherEP = motherNodes[motherId].chromosomeFromFatherExtancyPattern; auto& mothersMotherEP = motherNodes[motherId].chromosomeFromMotherExtancyPattern; auto mothersFatherPartialEP = motherEP.intersectionWith(motherRecombinations); auto mothersMotherPartialEP = motherEP.intersectionWithInverse(motherRecombinations); if (hide_non_ancestral) { if (mothersFatherPartialEP.empty()) motherRecombinations = INHERIT_GRANDMOTHER; if (mothersMotherPartialEP.empty()) motherRecombinations = INHERIT_GRANDFATHER; } mothersFatherEP = mothersFatherEP.unionWith(mothersFatherPartialEP); mothersMotherEP = mothersMotherEP.unionWith(mothersMotherPartialEP); hbb->recordBlockBoundaries(motherRecombinations); } childNode.fatherId = fatherId; childNode.motherId = motherId; childNode.chromosomeFromFatherRecombinationPattern = move(fatherRecombinations); childNode.chromosomeFromMotherRecombinationPattern = move(motherRecombinations); } // Clean-up long nFathers = parentUrn.getNumberOfFathers(); long nMothers = parentUrn.getNumberOfMothers(); if (cull_non_ancestral) { // Shift all the ancestral parents down the vector/array, // overwriting any non-ancestral parents; keep track of id changes. vector<long> fatherIdNew(nFathers); vector<long> motherIdNew(nMothers); long fidNew = 0, midNew = 0; for (long id=0; id<nFathers; id++) { if (fatherNodes[id].extant()) { fatherNodes[fidNew] = fatherNodes[id]; fatherIdNew[id] = fidNew++; } else { fatherIdNew[id] = DID; } } for (long id=0; id<nMothers; id++) { if (motherNodes[id].extant()) { motherNodes[midNew] = motherNodes[id]; motherIdNew[id] = midNew++; } else { motherIdNew[id] = DID; } } // Update the parent id changes in the children. for (auto* childNodes : { &maleChildNodes, &femaleChildNodes }) for (auto& childNode : *childNodes) { childNode.fatherId = fatherIdNew[childNode.fatherId]; childNode.motherId = motherIdNew[childNode.motherId]; } // Trim the vector/array. nFathers = fidNew; nMothers = midNew; fatherNodes = trim(fatherNodes, nFathers); motherNodes = trim(motherNodes, nMothers); } else if (cull_non_parents) { fatherNodes = trim(fatherNodes, nFathers); motherNodes = trim(motherNodes, nMothers); } if (!hide_non_ancestral) { for (auto* nodes : { &fatherNodes, &motherNodes }) for (auto& node : *nodes) { node.chromosomeFromFatherExtancyPattern = ALL; node.chromosomeFromMotherExtancyPattern = ALL; } } m_nodes[gen+1] = { fatherNodes, motherNodes }; return *this; } long AncestralRecombinationGraph::getNumberOfMalesWithAncestralHaploBlocks(long gen) const { auto& males = m_nodes[gen].first; long sum = 0L; for(auto& male : males) { if (male.extant()) ++sum; } return sum; } long AncestralRecombinationGraph::getNumberOfFemalesWithAncestralHaploBlocks(long gen) const { auto& females = m_nodes[gen].second; long sum = 0L; for(auto& female : females) { if (female.extant()) ++sum; } return sum; } long AncestralRecombinationGraph::getSizeOfAncestralHaploBlocks(long gen) const { const long max_range = m_haplo_block_boundaries->getChromosomeLength(); long sum = 0L; auto& males = m_nodes[gen].first; for(auto& male : males) { sum += male.chromosomeFromFatherExtancyPattern.getSizeOfRange(max_range); sum += male.chromosomeFromMotherExtancyPattern.getSizeOfRange(max_range); } auto& females = m_nodes[gen].second; for(auto& female : females) { sum += female.chromosomeFromFatherExtancyPattern.getSizeOfRange(max_range); sum += female.chromosomeFromMotherExtancyPattern.getSizeOfRange(max_range); } return sum; } long AncestralRecombinationGraph::getTotalNumberOfMales() const { const long ngens = getNumberOfGenerations(); long sum = 0L; for (long gen=0; gen<ngens; ++gen) sum += getMales(gen).size(); return sum; } long AncestralRecombinationGraph::getTotalNumberOfFemales() const { const long ngens = getNumberOfGenerations(); long sum = 0L; for (long gen=0; gen<ngens; ++gen) sum += getFemales(gen).size(); return sum; } long AncestralRecombinationGraph::getTotalNumberOfMalesWithAncestralHaploBlocks() const { const long ngens = getNumberOfGenerations(); long sum = 0L; for (long gen=0; gen<ngens; ++gen) sum += getNumberOfMalesWithAncestralHaploBlocks(gen); return sum; } long AncestralRecombinationGraph::getTotalNumberOfFemalesWithAncestralHaploBlocks() const { const long ngens = getNumberOfGenerations(); long sum = 0L; for (long gen=0; gen<ngens; ++gen) sum += getNumberOfFemalesWithAncestralHaploBlocks(gen); return sum; } long AncestralRecombinationGraph::getTotalSizeOfAncestralHaploBlocks() const { const long ngens = getNumberOfGenerations(); long sum = 0L; for (long gen=0; gen<ngens; ++gen) sum += getSizeOfAncestralHaploBlocks(gen); return sum; } size_t AncestralRecombinationGraph::getSizeInMemory(long gen) const { size_t sum = sizeof(m_nodes[gen]); for (auto* persons : { &m_nodes[gen].first, &m_nodes[gen].second }) for (auto& person : *persons) { sum += sizeof(person.fatherId); sum += sizeof(person.motherId); sum += person.chromosomeFromFatherRecombinationPattern.getSizeInMemory(); sum += person.chromosomeFromMotherRecombinationPattern.getSizeInMemory(); sum += person.chromosomeFromFatherExtancyPattern.getSizeInMemory(); sum += person.chromosomeFromMotherExtancyPattern.getSizeInMemory(); } return sum; } bool AncestralRecombinationGraph::operator==(const AncestralRecombinationGraph& o) const { return ( m_history == o.m_history || ( m_history != nullptr && o.m_history != nullptr && *m_history == *o.m_history) ) && ( m_haplo_block_boundaries == o.m_haplo_block_boundaries || ( m_haplo_block_boundaries != nullptr && o.m_haplo_block_boundaries != nullptr && *m_haplo_block_boundaries == *o.m_haplo_block_boundaries) ) && m_nodes == o.m_nodes && m_chromosome_type == o.m_chromosome_type; } <file_sep>/hpc/FileSNPsWriter.h #pragma once #include <random> #include <vector> #include <utility> #include "core/HaploBlockVariants.h" #include "core/PersonNode.h" class FileSNPsWriter { public: static void WriteSNPs( const std::string& output_filename, const HaploBlockVariants& variants, const std::pair<std::vector<PersonNode>, std::vector<PersonNode>>& whole_generation, std::mt19937_64& rng); }; <file_sep>/core/MutationGraph.h #pragma once #include <map> #include <utility> #include <vector> #include "Chromosome.h" /** MutationGraph: Stores a set of variants of a haplotype block, each variant referenced by an allele id. For each allele, stores the allele from which it was derived, plus the mutations that makes it different (or number of mutations if use_mutation_loci is not known), and the number of alleles that are further derived from itself, forming a tree graph. Can also be used to count the number of copies of each allele in the ancestral population, for summarizing statistics, or for culling the tree for efficiency reasons. */ class MutationGraph { friend class FileCheckpointer; private: // Represents an allele or a particular subset of mutations that appear together. struct Node { // The allele from which this one was derived. AlleleId parent_id; // The mutations (SNPs - Single Nucleotide Polymorphisms), represented by locations // on the chromosomes and age in generations since they occurred. long n_mutations; std::vector<std::pair<LocusId, long>> mutations; // The number of alleles that are (directly) derived from this one. // (and thus also have these SNPs). int n_child_nodes; // The number of copies of this particular allele / SNP group exist in the population. long frequency; bool operator==(const Node&) const; }; bool m_use_mutation_loci; std::map<AlleleId, Node> m_nodes; AlleleId m_next_id; public: MutationGraph() : m_use_mutation_loci(false), m_next_id(0L) {} // for creating unassigned variables MutationGraph(std::vector<std::vector<LocusId>> founder_alleles, const bool use_mutation_loci=true); AlleleId addAlleleMutation(AlleleId parent_id, long gen, const std::vector<LocusId>& loci); inline bool tooManyNodes(size_t nnodes) const { return m_nodes.size() > nnodes; } inline void incrementAlleleFrequency(AlleleId id) { m_nodes.at(id).frequency++; } void simplify(); inline void clearAlleleFrequencies() { for (auto& entry : m_nodes) entry.second.frequency = 0L; } std::vector<AlleleId> getAlleleIds() const; AlleleId getParentId(AlleleId id) const { return m_nodes.at(id).parent_id; } AlleleId getFounderId(AlleleId id) const; bool isDerivativeAllele(AlleleId parent_id, AlleleId id) const; const std::vector<std::pair<LocusId,long>>& getMutations(AlleleId id) const { return m_nodes.at(id).mutations; } int getNumberOfMutations(AlleleId id) const { return m_nodes.at(id).n_mutations; } int getMutationDistance(AlleleId ia, AlleleId ib) const; std::string toString() const; bool operator==(const MutationGraph&) const; }; <file_sep>/hpc/Haplo.cpp #include <cstdio> #include <cstdlib> #include <map> #include <random> #include <sstream> #include <stdexcept> #include <string> #include "core/Analysis.h" #include "core/AncestralChromosomes.h" #include "core/AncestralRecombinationGraph.h" #include "core/Chromosome.h" #include "core/Parser.h" #include "core/PopulationStructureHistory.h" #include "hpc/FileCheckpointer.h" #include "hpc/FileMemorySaver.h" #include "hpc/FileOutputs.h" #include "hpc/FileReader.h" #include "hpc/FileSNPsWriter.h" #include "hpc/FileWriter.h" #include "hpc/LoggerSmart.h" using namespace std; constexpr bool BACKWARDS = false; constexpr bool FORWARDS = true; int main(int argc, char** argv) { //-------------------------------------------------------------------- // State. mt19937_64 rng; PopulationStructureHistory population_history; MutationRateHistory mutation_history; HaploBlockBoundaries boundaries; AncestralRecombinationGraph graph; HaploBlockVariants variants; AncestralChromosomes chromosomes; long gen; long nGenerations; long extantGeneration; long foundingGeneration; try { //-------------------------------------------------------------------- // Read command line arguments. bool restart_at_checkpoint = false; string input_filename; for (int iarg=1; iarg<argc; ++iarg) { string argstr(argv[iarg]); if (argstr=="--restart") restart_at_checkpoint = true; else { if(input_filename=="") input_filename = argstr; else throw invalid_argument("Need one input filename"); } } //-------------------------------------------------------------------- // Read input file. Parser inputs(FileReader::parseTOML(input_filename)); // Set up logger. const bool verbose = inputs.getBool("verbose_logging"); LoggerSmart logger(verbose, 10); // log progress every 10s logger.logEvent("Inputs read:\n" + inputs.toString()); // Set up memory unloader. const bool use_memory_unloading = inputs.getBool("use_memory_unloading"); FileMemorySaver memory_saver(inputs.getString("temporary_file_prefix")); logger.logEvent("Memory saver created."); // Set up memory unloader. FileCheckpointer checkpointer("checkpoint.bin", 60); // checkpoint every 60s logger.logEvent("Checkpointer created."); // Before we start, check that there are no output files already there. // Don't want to overwrite results that were expensive to compute! const FileOutputs file_outputs(inputs.getString("output_file_prefix")); file_outputs.assertNoExistingOutputFiles(); logger.logEvent("Checked no output files."); const double alpha = inputs.getNonNegativeDouble("fertility_parameter_alpha"); const double beta = inputs.getNonNegativeDouble("mating_parameter_beta"); const double recombination_rate = inputs.getNonNegativeDouble("recombination_rate"); const bool cull_non_parents = inputs.getBool("cull_non_parents"); const bool cull_na_parents = inputs.getBool("cull_nonancestral_parents"); const bool hide_na_blocks = inputs.getBool("hide_nonancestral_blocks"); if (restart_at_checkpoint) { bool direction; checkpointer.load(direction, gen, rng, population_history, mutation_history, boundaries, graph, variants, chromosomes); nGenerations = population_history.getNumberOfGenerations(); extantGeneration = 0L; foundingGeneration = nGenerations - 1L; if (direction==BACKWARDS) goto continue_backwards; if (direction==FORWARDS) goto continue_forwards; } //-------------------------------------------------------------------- // Set Random Seed. { const string random_seed = inputs.getString("random_seed"); seed_seq seed(random_seed.begin(), random_seed.end()); rng = mt19937_64(seed); } //-------------------------------------------------------------------- // Read or construct PopulationStructureHistory. { const string population_history_filename = inputs.getString("population_structure_history_file"); population_history = PopulationStructureHistory( (population_history_filename != "") ? FileReader::readPopulationStructureHistory(population_history_filename) : PopulationStructureHistory::create( inputs.getString("population_growth_type"), inputs.getPositiveLong("population_number_of_generations"), inputs.getPositiveLong("population_initial"), inputs.getPositiveLong("population_final"), inputs.getPositiveLong("population_change_parameter"))); nGenerations = population_history.getNumberOfGenerations(); extantGeneration = 0L; foundingGeneration = nGenerations - 1L; if (logger.verbose()) { string s = (population_history_filename != "") ? "Population History was read from file:\n" : "Population History was constructed:\n"; for (long gen = nGenerations-1; gen >= 0L; --gen) { long nmales = population_history.getNumberOfMales(gen); long nfemales = population_history.getNumberOfFemales(gen); s += to_string(gen) + " " + to_string(nmales) + " " + to_string(nfemales) + "\n"; } logger.logEvent(s); } } //-------------------------------------------------------------------- // Read or construct MutationRateHistory. { const string mutation_history_filename = inputs.getString("mutation_rate_history_file"); mutation_history = MutationRateHistory( (mutation_history_filename != "") ? FileReader::readMutationRateHistory(mutation_history_filename) : MutationRateHistory::Constant(nGenerations, inputs.getNonNegativeDouble("mutation_rate"))); } //-------------------------------------------------------------------- // Generate AncestralRecombinationGraph. { boundaries = HaploBlockBoundaries( inputs.getPositiveLong("chromosome_length"), inputs.getPositiveLong("maximum_blocks"), rng); graph = AncestralRecombinationGraph(&population_history, &boundaries, inputs.getChromosomeType("chromosome_type")) .initialiseExtantGeneration(inputs.getPositiveLong("population_sample")); logger.logEvent("HBB and ARG initialised.\n"); FileWriter::write("log_ancestral.txt","# gen size_of_ancestral_haploblocks"); } for (gen = extantGeneration; gen<foundingGeneration; ++gen) { { graph.backwardsCoalesceOneGeneration( gen, alpha, beta, recombination_rate, rng, cull_non_parents, cull_na_parents, hide_na_blocks); } logger.logProgress("Generation " + to_string(gen) + " of ARG done."); FileWriter::append("log_ancestral.txt", to_string(gen) + " " + to_string(graph.getSizeOfAncestralHaploBlocks(gen)) + "\n"); if (use_memory_unloading) memory_saver.unloadGenerationToFile(graph, gen); if (checkpointer.timeDue()) { checkpointer.save(BACKWARDS, gen, rng, population_history, mutation_history, boundaries, graph, variants, chromosomes); memory_saver.deleteDiscardedGenerations(); } continue_backwards: FileReader::stopIfFindStopFile(); } //-------------------------------------------------------------------- // Propagate AncestralRecombinationGraph and generate mutations // to create AncestralChromosomes. { const long max_nodes_per_block = inputs.getPositiveLong("population_sample") * 6; // 2x haploid samples -> 4x nodes + leeway = 6x ^ variants = HaploBlockVariants( boundaries, max_nodes_per_block, inputs.getPositiveLong("primordial_block_length"), inputs.getNonNegativeDouble("primordial_probability_dimorphic"), inputs.getNonNegativeDouble("primordial_probability_tetramorphic"), inputs.getNonNegativeDouble("primordial_diversity"), inputs.getBool("use_mutation_loci"), rng); chromosomes = AncestralChromosomes(&graph, &variants) .initialiseFoundingGeneration(); logger.logEvent("\nHBV and AC initialised.\n"); } for (gen = foundingGeneration-1; gen>=extantGeneration; --gen) { if (use_memory_unloading) memory_saver.reloadGenerationFromFile(graph, gen); { const double mutation_rate = mutation_history.getMutationRate(gen); chromosomes.forwardsDropOneGeneration(gen, mutation_rate, rng); } logger.logProgress("Generation " + to_string(gen) + " of AC done."); if (use_memory_unloading) memory_saver.discardGeneration(chromosomes, gen+1); if (use_memory_unloading) memory_saver.discardGeneration(graph, gen); if (variants.sampleChromosomesAndSimplify(chromosomes.getGeneration(gen))) logger.logEvent("HaploBlockVariants simplified."); if (checkpointer.timeDue() || gen == extantGeneration) { checkpointer.save(FORWARDS, gen, rng, population_history, mutation_history, boundaries, graph, variants, chromosomes); memory_saver.deleteDiscardedGenerations(); } continue_forwards: FileReader::stopIfFindStopFile(); } logger.logEvent("\nSimulation complete."); //-------------------------------------------------------------------- // Write SNPs if (inputs.getBool("output_final_SNP_sites")) { logger.logEvent("Writing SNPs."); FileSNPsWriter::WriteSNPs(inputs.getString("output_file_prefix")+"SNPs.sites", variants, chromosomes.getExtantGeneration(), rng); logger.logEvent("Wrote SNPs."); } //-------------------------------------------------------------------- // Calculate final output statistics. auto analysis = Analysis::Calculate(logger, inputs, variants, chromosomes.getExtantGeneration()); file_outputs.writeOutputFiles(analysis); logger.logEvent("Results written to files."); const string unused_inputs = inputs.getUnusedKeysAsString(); if (unused_inputs != "") { printf("There were unused inputs. See log_unused.txt.\n"); FileWriter::write("log_unused.txt", unused_inputs.c_str(), "Keys from the input file that were not used.\n"); } return EXIT_SUCCESS; //-------------------------------------------------------------------- } catch(const exception& e) { fprintf(stderr, "%s\n", e.what()); return EXIT_FAILURE; } } <file_sep>/core/Analysis.h #pragma once #include <utility> #include <vector> #include "GraphDataBinned.h" #include "GraphDataBinned2D.h" #include "HaploBlockVariants.h" #include "Logger.h" #include "Parser.h" #include "PersonNode.h" class Analysis { public: long total_blocks; // Q in the paper long total_snp_sites; // S in the paper double sn_diversity; // Pi in the paper GraphDataBinned snp_freq_spectrum; // Phi in the paper GraphDataBinned snp_distribution; // Not in paper GraphDataBinned correlation_function; // r^2 in the paper GraphDataBinned dprime_function; // D' in the paper GraphDataBinned complete_linkage_function; // CLDP in the paper GraphDataBinned almost_complete_linkage_function; // Not in paper GraphDataBinned normalized_kullback_leibler_function; // Not in paper GraphDataBinned sigma_squared_function; // Not in paper GraphDataBinned2D freq_pair_spectrum; // Not in paper static Analysis Calculate( Logger& logger, Parser& inputs, HaploBlockVariants& variants, std::pair<std::vector<PersonNode>, std::vector<PersonNode>>& whole_gen); }; <file_sep>/hpc/FileDataPrimitiveIO.h #pragma once #include <fstream> #include <string> #include <utility> #include <vector> template<typename V> inline void writePrimitive(std::ofstream& ofs, const V& p) { ofs.write((char*)&p, sizeof(p)); } template<typename V> inline void readPrimitive(std::ifstream& ifs, V& p) { ifs.read((char*)&p, sizeof(p)); } inline void writeString(std::ofstream& ofs, const std::string& s) { writePrimitive(ofs, s.size()); ofs.write(s.c_str(),s.size()); } inline void readString(std::ifstream& ifs, std::string& s) { size_t sz; readPrimitive(ifs,sz); s.resize(sz); ifs.read(&s[0],s.size()); } /** VECTOR */ template<typename V> inline void writePrimitiveVector(std::ofstream& ofs, const std::vector<V>& v) { long n_units = v.size(); writePrimitive(ofs, n_units); char* ptr = (char*)&v[0]; ofs.write(ptr, n_units * sizeof(V)); } template<typename V> inline void readPrimitiveVector(std::ifstream& ifs, std::vector<V>& v) { long n_units; readPrimitive(ifs, n_units); v.resize(n_units); char* ptr = (char*)&v[0]; ifs.read(ptr, n_units * sizeof(V)); } /** MAP */ template<typename U, typename V> inline void writePrimitiveMap(std::ofstream& ofs, const std::map<U,V>& m) { long n_units = m.size(); writePrimitive(ofs, n_units); for (const auto& e : m) { writePrimitive(ofs, e); } } template<typename U, typename V> inline void readPrimitiveMap(std::ifstream& ifs, std::map<U,V>& m) { long n_units; readPrimitive(ifs, n_units); for (int i=0; i<n_units; ++i) { std::pair<U,V> e; readPrimitive(ifs, e); m.emplace(e.first, e.second); } } <file_sep>/core/AncestralRecombinationGraph.h #pragma once #include <cstddef> #include <utility> #include <vector> #include "BlocksRange.h" #include "HaploBlockBoundaries.h" #include "PopulationStructureHistory.h" /** AncestralRecombinationGraph: Stores the Ancestral Recombination Graph for the whole population by storing, for each ancestral individual, the ids of their parents in the previous generation, the recombination pattern by which the chromosome inherited from the father was recombined from the father's two chromosomes, and a mask showing which parts of that chromosome are *ancestral*: that is, which haplotype blocks have direct direct descendants in any chromosomes of any person in the final sample, and the corresponding recombination pattern and mask for the chromosome inherited from the mother. The ARG is built backwards in time from the final generation (this is possible because the recombination process is symmetric in time, unlike a mutation or selection process). It can also be used to query how much genetic information present at a given timepoint is ancestral to the final sample. */ class AncestralRecombinationGraph { friend class FileCheckpointer; friend class FileMemorySaver; public: /** * ChildNode contains the minimum information required to generate the chromosomes of a * child from the previous generation. * * The final AncestralRecombinationGraph is a directed network of ChildNodes. */ struct ChildNode { long fatherId; long motherId; BlocksRange chromosomeFromFatherRecombinationPattern; BlocksRange chromosomeFromMotherRecombinationPattern; BlocksRange chromosomeFromFatherExtancyPattern; BlocksRange chromosomeFromMotherExtancyPattern; bool extantFather() const; bool extantMother() const; bool extant() const; bool operator==(const ChildNode&) const; }; private: /** The sizes and structures of populations through time. */ PopulationStructureHistory* m_history; /** The actual haplotype boundaries observed (randomly created). */ HaploBlockBoundaries* m_haplo_block_boundaries; /** The nodes of the graph. */ std::vector<std::pair<std::vector<ChildNode>, std::vector<ChildNode>>> m_nodes; /** Autosome, X, Y or mitochondrial. */ ChromosomeType m_chromosome_type; public: AncestralRecombinationGraph() // for creating unassigned variables : m_history(nullptr), m_haplo_block_boundaries(nullptr), m_chromosome_type(AUTO) {} /** * Constructor for AncestralRecombinationGraph with given inputs: * population size history, and maximum number of haplotype blocks. */ AncestralRecombinationGraph( PopulationStructureHistory* history, HaploBlockBoundaries* boundaries, ChromosomeType chromosome_type = AUTO) : m_history(history), m_haplo_block_boundaries(boundaries), m_nodes(history->getNumberOfGenerations()), m_chromosome_type(chromosome_type) {} AncestralRecombinationGraph& initialiseExtantGeneration(const std::pair<long,long> samples); AncestralRecombinationGraph& initialiseExtantGeneration(const long samples) { return initialiseExtantGeneration({samples/2, samples/2}); } /** * Randomly generate the AncestralRecombinationGraph given these additional * input parameters which can be specified per generation: * 'alpha' influences the number of females that become mothers. * 'beta' influences the number of males that become fathers. * 'recombination_rate' is the expected number of recombinations per copied chromosome. */ AncestralRecombinationGraph& backwardsCoalesceAllGenerations( const double alpha, const double beta, const double recombination_rate, std::mt19937_64& rng, const bool cull_non_parents = true, const bool cull_non_ancesral = true, const bool hide_non_ancestral = true); AncestralRecombinationGraph& backwardsCoalesceOneGeneration( const long gen, const double alpha, const double beta, const double recombination_rate, std::mt19937_64& rng, const bool cull_non_parents = true, const bool cull_non_ancesral = true, const bool hide_non_ancestral = true); long getNumberOfGenerations() const { return m_nodes.size(); } const std::vector<ChildNode>& getMales(long gen) const { return m_nodes[gen].first; } const std::vector<ChildNode>& getFemales(long gen) const { return m_nodes[gen].second; } // Statistics methods long getNumberOfMalesWithAncestralHaploBlocks(long gen) const; long getNumberOfFemalesWithAncestralHaploBlocks(long gen) const; long getSizeOfAncestralHaploBlocks(long gen) const; long getTotalNumberOfMales() const; long getTotalNumberOfFemales() const; long getTotalNumberOfMalesWithAncestralHaploBlocks() const; long getTotalNumberOfFemalesWithAncestralHaploBlocks() const; long getTotalSizeOfAncestralHaploBlocks() const; size_t getSizeInMemory(long gen) const; bool operator==(const AncestralRecombinationGraph&) const; static constexpr long DUMMY_ID = -1L; }; <file_sep>/core/GraphDataBinned2D.cpp #include "GraphDataBinned2D.h" #include <cstddef> #include <stdexcept> #include <string> using namespace std; string GraphDataBinned2D::toString(bool bar_end) const { string s; size_t n = m_weight_bins.size(); double delta_x = (m_range_x.second - m_range_x.first) / n; double delta_y = (m_range_y.second - m_range_y.first) / n; for(size_t ix = 0; ix < n; ++ix) { double bin_min_x = m_range_x.first + ix * delta_x; double bin_max_x = ix+1==n ? m_range_x.second : bin_min_x + delta_x; for(size_t iy = 0; iy < n; ++iy) { double bin_min_y = m_range_y.first + iy * delta_y; double bin_max_y = iy+1==n ? m_range_y.second : bin_min_y + delta_y; double bin_weight = m_weight_bins.at(ix).at(iy); double bin_value = m_value_bins.at(ix).at(iy); double bin_average = bin_weight ? bin_value / bin_weight : 0.0; s += to_string(bin_min_x) + " " + to_string(bin_min_y) + " "; if (bar_end) s += to_string(bin_max_x) + " " + to_string(bin_max_y) + " "; s += to_string(bin_weight) + " " + to_string(bin_average) + "\n"; } } return s; } GraphDataBinned2D& GraphDataBinned2D::merge(GraphDataBinned2D& other) { if (this->m_weight_bins.size() != other.m_weight_bins.size() || this->m_value_bins.size() != other.m_value_bins.size() || this->m_range_x != other.m_range_x || this->m_range_y != other.m_range_y || this->m_delta_inv_x != other.m_delta_inv_x || this->m_delta_inv_y != other.m_delta_inv_y || this->m_bin_includes_upper_bound != other.m_bin_includes_upper_bound) throw invalid_argument("Attempt to merge data with different bins"); size_t n = m_weight_bins.size(); for (size_t ix = 0; ix < n; ++ix) { for (size_t iy = 0; iy < n; ++iy) { this->m_weight_bins[ix][iy] += other.m_weight_bins[ix][iy]; this->m_value_bins[ix][iy] += other.m_value_bins[ix][iy]; } } return *this; } <file_sep>/hpc/Makefile VPATH := ../../../core ../../../hpc . #GPP := g++ -std=c++11 -O3 GPP := g++ -std=c++11 -I../../.. -g -pg -O3 -Wall -Wno-unknown-pragmas -fdiagnostics-color all: # default target #========================================== # Specific targets #========================================== Haplo: Haplo.o \ Analysis.o \ AncestralChromosomes.o \ AncestralRecombinationGraph.o \ Blocks.o \ BlocksRange.o \ FileCheckpointer.o \ FileMemorySaver.o \ FileOutputs.o \ FileReader.o \ FileSNPsWriter.o \ FileWriter.o \ GraphDataBinned.o \ GraphDataBinned2D.o \ HaploBlockBoundaries.o \ HaploBlockVariants.o \ MutationGraph.o \ ParentPairUrn.o \ Parser.o \ PolyaUrn.o \ PopulationStructureHistory.o \ EXECS := Haplo #========================================== # Generic targets #========================================== -include *.d %.o: %.cpp @ echo making $*.o @ $(GPP) -MMD -c $< -o $@ $(EXECS): @ echo making $@ @ $(GPP) $^ -o $@ @ chmod +x $@ @ echo #========================================== # Declare 'phony' (non-file) targets #========================================== .PHONY: clean all clean: @ rm -f *.o *.d *.exe* all: $(EXECS) #========================================== <file_sep>/core/PersonNode.h #pragma once #include "Chromosome.h" struct PersonNode { Chromosome chromosomeFromFather; Chromosome chromosomeFromMother; PersonNode() {} PersonNode(Chromosome&& f, Chromosome&& m) : chromosomeFromFather(f), chromosomeFromMother(m) {} bool operator==(const PersonNode& o) const { return chromosomeFromFather == o.chromosomeFromFather && chromosomeFromMother == o.chromosomeFromMother; } }; <file_sep>/core/PopulationStructureHistory.cpp #include "PopulationStructureHistory.h" #include <stdexcept> #include <string> #include <utility> #include <vector> #include <cmath> using namespace std; PopulationStructureHistory PopulationStructureHistory::create( string type, long initial_gen, long init_popn, long final_popn, double growth_rate) { if (type == "Constant") return Constant(initial_gen, final_popn); if (type == "Linear") return Linear(initial_gen, init_popn, final_popn); if (type == "Exponential") return Exponential(initial_gen, init_popn, final_popn); if (type == "Logistic") return Logistic(initial_gen, init_popn, final_popn, growth_rate); if (type == "Sinusoidal") return Sinusoidal(initial_gen, init_popn, final_popn, growth_rate); throw invalid_argument("Unknown type argument to PSH"); } inline pair<long, long> evenSplit(long popn) { return pair<long, long> { popn/2, popn/2 + popn%2}; } inline long nearestLong(double x) { return (long)(x>0 ? x+0.5 : x-0.5); } PopulationStructureHistory PopulationStructureHistory::Constant( long initial_gen, long males, long females) { pair<long, long> nMaleFemale(males, females); return PopulationStructureHistory(vector<pair<long,long>>(initial_gen+1, nMaleFemale)); } PopulationStructureHistory PopulationStructureHistory::Constant(long initial_gen, long popn) { return PopulationStructureHistory(vector<pair<long,long>>(initial_gen+1, evenSplit(popn))); } PopulationStructureHistory PopulationStructureHistory::Linear( long initial_gen, long initial_popn, long final_popn) { vector<pair<long,long>> vec; vec.reserve(initial_gen+1); double step = (initial_popn - final_popn) / (double) initial_gen; for(int i=0; i<initial_gen; ++i) { long popn = nearestLong(final_popn + i*step); vec.emplace_back(evenSplit(popn)); } vec.emplace_back(evenSplit(initial_popn)); return PopulationStructureHistory(vec); } PopulationStructureHistory PopulationStructureHistory::Exponential( long initial_gen, long initial_popn, long final_popn) { vector<pair<long,long>> vec; vec.reserve(initial_gen+1); double popn = final_popn; double factor = exp( (log(initial_popn) - log(final_popn)) / initial_gen ); for(int i=0; i<initial_gen; ++i) { vec.emplace_back(evenSplit(nearestLong(popn))); popn *= factor; } vec.emplace_back(evenSplit(initial_popn)); return PopulationStructureHistory(vec); } PopulationStructureHistory PopulationStructureHistory::Logistic( long initial_gen, long initial_popn, long final_popn, double growth_rate) { vector<pair<long,long>> vec; vec.reserve(initial_gen+1); double popn = final_popn; for(int i=0; i<initial_gen; ++i) { vec.emplace_back(evenSplit(nearestLong(popn))); popn += growth_rate * popn * (initial_popn - popn) / initial_popn; if (popn > final_popn) popn = final_popn; } vec.emplace_back(evenSplit(initial_popn)); return PopulationStructureHistory(vec); } PopulationStructureHistory PopulationStructureHistory::Sinusoidal( long initial_gen, long initial_popn, long final_popn, double growth_rate) { vector<pair<long,long>> vec; vec.reserve(initial_gen+1); constexpr double pi = 3.14159265; double base = final_popn; double amplitude = 0.5 * (initial_popn - final_popn); double k = 2 * pi * growth_rate / initial_gen; for(int i=0; i<initial_gen; ++i) { long popn = nearestLong(base + amplitude * (1 - cos(k*i))); vec.emplace_back(evenSplit(popn)); } return PopulationStructureHistory(vec); } long PopulationStructureHistory::getTotalNumberOfMales() const { long sum = 0L; for (auto& popn : m_populations) sum += popn.first; return sum; } long PopulationStructureHistory::getTotalNumberOfFemales() const { long sum = 0L; for (auto& popn : m_populations) sum += popn.second; return sum; } bool PopulationStructureHistory::operator==(const PopulationStructureHistory& o) const { return m_populations == o.m_populations; } <file_sep>/hpc/FileWriter.h #pragma once #include <string> class FileWriter { public: static void write(const std::string& output_filename, const std::string& content, const std::string& comment=""); static void append(const std::string& output_filename, const std::string& content, const std::string& comment=""); }; <file_sep>/core/HaploBlockVariants.cpp #include <algorithm> #include <iterator> #include <random> #include <vector> #include "Chromosome.h" #include "HaploBlockBoundaries.h" #include "HaploBlockVariants.h" using namespace std; vector<LocusId> generateMutations(int nmuts, LocusId start_locus, LocusId end_locus, mt19937_64& rng) { uniform_int_distribution<long> distribution(start_locus, end_locus-1); vector<LocusId> mutations; mutations.reserve(nmuts); for (long i=0; i<nmuts; i++) mutations.push_back(distribution(rng)); sort(mutations.begin(), mutations.end()); // sort return mutations; } /** * Each original allele is represented by a set of single nucleotide changes from some * (unspecified) reference sequence. * Each original allele may be placed on more than one original chromosome. * */ struct OriginalAllele { vector<LocusId> single_nucleotide_differences; vector<int> chromosome_placements; }; HaploBlockVariants::HaploBlockVariants( const HaploBlockBoundaries& hbb, const long max_nodes_per_block, const long primordial_block_length, const double probability_dimorphic, const double probability_tetramorphic, const double primordial_diversity, const bool use_mutation_loci, mt19937_64& rng) { m_max_nodes_per_block = max_nodes_per_block; LocusId chromosome_length = hbb.getChromosomeLength(); long n_primordial_blocks = chromosome_length / primordial_block_length + (chromosome_length % primordial_block_length ? 1 : 0); double primordial_snp_rate = // primordial mutation-like SNPs primordial_diversity / (2 * probability_dimorphic + 4 * probability_tetramorphic); vector<LocusId> primordial_block_boundaries = hbb.getRandomBlockBoundaries(n_primordial_blocks, rng); vector<vector<OriginalAllele>> primordial_blocks(n_primordial_blocks); for (long ipb=0; ipb<n_primordial_blocks; ++ipb) { LocusId block_start = primordial_block_boundaries.at(ipb); LocusId block_end = primordial_block_boundaries.at(ipb+1); double r = uniform_real_distribution<double>(0,1.0)(rng); int n_original_alleles = (r-=probability_tetramorphic) < 0 ? 4 : (r-=probability_dimorphic) < 0 ? 2 : 1; int n_copies_per_original_allele = 4 / n_original_alleles; vector<int> placements{0,1,2,3}; swap(placements.at(0), placements.at(uniform_int_distribution<int>(0,3)(rng))); swap(placements.at(1), placements.at(uniform_int_distribution<int>(1,3)(rng))); swap(placements.at(2), placements.at(uniform_int_distribution<int>(2,3)(rng))); auto it = placements.begin(); for (int ioa=0; ioa<n_original_alleles; ++ioa) { vector<LocusId> snps; vector<int> plcs; if (n_original_alleles > 1) { double expected_n_snps = primordial_snp_rate * (block_end - block_start); long n_snps = poisson_distribution<long>(expected_n_snps)(rng); snps = generateMutations(n_snps, block_start, block_end, rng); } for (int i=0; i<n_copies_per_original_allele; ++i) plcs.push_back(*it++); OriginalAllele original_allele { snps, plcs }; primordial_blocks.at(ipb).push_back(original_allele); } } const auto& recombination_block_boundaries = hbb.getRecordedBlockBoundaries(); set<LocusId> all_blocks; for (LocusId boundary : primordial_block_boundaries) all_blocks.insert(boundary); for (LocusId boundary : recombination_block_boundaries) all_blocks.insert(boundary); m_boundaries = vector<LocusId>(all_blocks.begin(), all_blocks.end()); long n_all_blocks = m_boundaries.size() - 1; m_variants.reserve(n_all_blocks); vector<vector<pair<LocusId,AlleleId>>> reference_chromosomes(4); for (long ib=0; ib<n_all_blocks; ++ib) { LocusId block_start = m_boundaries.at(ib); LocusId block_end = m_boundaries.at(ib+1); const auto& pbb = primordial_block_boundaries; long ipb = distance(pbb.begin(), upper_bound(pbb.begin(), pbb.end(), block_start)) - 1L; // index of primordial block vector<vector<LocusId>> observed_block_founding_snd_sets; AlleleId allele_id = 1; for (const auto& original_allele : primordial_blocks.at(ipb)) { vector<LocusId> snd_set; for (LocusId snd : original_allele.single_nucleotide_differences) { if (block_start <= snd && snd < block_end) snd_set.push_back(snd); } observed_block_founding_snd_sets.push_back(snd_set); for (int iref : original_allele.chromosome_placements) { reference_chromosomes.at(iref).emplace_back(block_start, allele_id); } ++allele_id; } m_variants.emplace_back(observed_block_founding_snd_sets); m_block_ids.emplace(block_start, ib); // maps locus_id -> block_id } m_block_ids.emplace(chromosome_length, n_all_blocks); for (auto& reference_chromosome : reference_chromosomes) { Chromosome new_chromosome; new_chromosome.m_intervals = move(reference_chromosome); new_chromosome = new_chromosome.compressed(); m_reference_chromosomes.push_back(new_chromosome); } } const Chromosome& HaploBlockVariants::getReferenceChromosome(long i) { long n = m_reference_chromosomes.size(); return m_reference_chromosomes.at(i % n); } Chromosome HaploBlockVariants::mutate( const Chromosome &chromosome_in, double nucleotide_mutation_rate, long generation, mt19937_64 &rng) { LocusId chromosome_length = m_boundaries.back(); double total_mutation_rate = nucleotide_mutation_rate * chromosome_length; int n_mutations = poisson_distribution<int>(total_mutation_rate)(rng); if (n_mutations == 0) return chromosome_in; const long end_locus = m_boundaries.back(); vector<LocusId> mutationLoci = generateMutations(n_mutations, 0, end_locus, rng); map<BlockId, vector<LocusId>> mutatedBlocks; for (LocusId locus : mutationLoci) { BlockId block = prev(m_block_ids.upper_bound(locus))->second; mutatedBlocks[block].push_back(locus); } Chromosome chromosome_out; auto& out = chromosome_out.m_intervals; auto begin_it = chromosome_in.m_intervals.cbegin(); auto end_it = chromosome_in.m_intervals.cend(); auto it = begin_it; AlleleId allele = UNKNOWN_ALLELE; for (auto block_it = mutatedBlocks.begin(); block_it != mutatedBlocks.end(); ++block_it) { BlockId block = block_it->first; auto& muts = block_it->second; LocusId block_begin = m_boundaries.at(block); LocusId block_end = m_boundaries.at(block+1); // Include interval boundaries that occur before the start of the mutation block. for ( ; it != end_it && it->first <= block_begin; ++it) { if (it->second != allele) out.push_back(*it); allele = it->second; } if (allele == UNKNOWN_ALLELE) continue; // Ignore unknown/non-ancestral // Create a mutated allele. AlleleId mutated_allele = m_variants.at(block).addAlleleMutation(allele, generation, muts); // Add the boundary for the start of the mutated block // (or if there is an existing boundary, update it, or even remove it). if (out.back().first < block_begin) { out.emplace_back(block_begin, mutated_allele); // add entry } else { out.back().second = mutated_allele; // update last entry if (out.size() >= 2 && out.end()[-2].second == mutated_allele) { out.pop_back(); // remove last entry } } // Add a boundary for the end of the mutated block, if necessary. auto interval_end = it != end_it ? it->first : end_locus; if (block_end < interval_end) { out.emplace_back(block_end, allele); } else { allele = mutated_allele; } } // Include interval boundaries that occur after the last mutated block. for ( ; it != end_it; ++it) { if (it->second != allele) out.push_back(*it); allele = it->second; } return chromosome_out; } bool HaploBlockVariants::sampleChromosomesAndSimplify( const pair<vector<PersonNode>, vector<PersonNode>>& whole_generation, bool hard) { bool simplified = false; const long end_locus = m_boundaries.back(); for (LocusId locus : m_boundaries) { if (locus == end_locus) break; auto bi = m_block_ids.at(locus); MutationGraph& mut_graph = m_variants.at(bi); if (!hard && !mut_graph.tooManyNodes(m_max_nodes_per_block)) continue; mut_graph.clearAlleleFrequencies(); for (auto* persons : { &whole_generation.first, &whole_generation.second }) for (auto& person : *persons) for (auto* chromosome : { &person.chromosomeFromFather, &person.chromosomeFromMother }) { AlleleId allele = chromosome->getValue(locus); if (allele == UNKNOWN_ALLELE) continue; mut_graph.incrementAlleleFrequency(allele); } mut_graph.simplify(); simplified = true; } return simplified; } Chromosome HaploBlockVariants::getFounderAlleleIdChromosome( const Chromosome& normal_id_chromosome) const { Chromosome new_chromosome; new_chromosome.m_intervals = normal_id_chromosome.m_intervals; for (auto& interval : new_chromosome.m_intervals) { LocusId locus = interval.first; AlleleId& allele = interval.second; if (allele==UNKNOWN_ALLELE) continue; BlockId block = prev(m_block_ids.upper_bound(locus))->second; AlleleId founder_allele = m_variants.at(block).getFounderId(allele); allele = (allele==founder_allele) ? founder_allele : -founder_allele; } return new_chromosome; } const MutationGraph& HaploBlockVariants::getMutationGraph(LocusId locus) const { return m_variants.at(m_block_ids.at(locus)); } void HaploBlockVariants::deleteMutationGraph(LocusId locus) { m_variants.at(m_block_ids.at(locus)) = MutationGraph(); } bool HaploBlockVariants::operator==(const HaploBlockVariants& o) const { return m_max_nodes_per_block == o.m_max_nodes_per_block && m_reference_chromosomes == o.m_reference_chromosomes && m_variants == o.m_variants && m_boundaries == o.m_boundaries && m_block_ids == o.m_block_ids; } <file_sep>/core/GraphDataBinned.h #pragma once #include <cmath> #include <string> #include <vector> class GraphDataBinned { public: std::vector<double> m_weight_bins; std::vector<double> m_value_bins; double m_min; double m_max; double m_delta_inv; bool m_bin_includes_upper_bound; /** Create a data-structure for summarising data in bins for graphs. */ GraphDataBinned(double mn, double mx, std::size_t nbins, bool bin_includes_upper_bound = false) : m_weight_bins(nbins), m_value_bins(nbins), m_min(mn), m_max(mx), m_delta_inv(nbins / (mx-mn)), m_bin_includes_upper_bound(bin_includes_upper_bound) {} // For making copies, but with data zeroed, for use in omp parallel for loops. GraphDataBinned zeroedCopy() { return GraphDataBinned(m_min, m_max, m_value_bins.size(),m_bin_includes_upper_bound); } /** Sample the value (y-position) at a particular x-position (for line graphs). */ inline void sampleValue(double x, double y, double multiplier = 1.0) { double iflt = m_delta_inv * (x - m_min); long i = m_bin_includes_upper_bound ? ceil(iflt) - 1 : iflt; if (i < 0 || i >= (long)m_weight_bins.size()) return; m_weight_bins.at(i) += multiplier; m_value_bins.at(i) += y * multiplier; } /** Sample weight at a particular x-position (for histograms). */ inline void sampleWeight(double x, double multiplier = 1.0) { sampleValue(x, 0.0, multiplier); } std::string toString(bool endbar=false) const; // For reduction in omp parallel for loops. GraphDataBinned& merge(const GraphDataBinned& other); GraphDataBinned& divide(const GraphDataBinned& other); }; <file_sep>/core/Analysis.cpp #include "Analysis.h" #include <map> #include <utility> #include <vector> #include "Chromosome.h" #include "GraphDataBinned.h" #include "GraphDataBinned2D.h" #include "Parser.h" using namespace std; #pragma omp declare reduction (merge : GraphDataBinned : omp_out.merge(omp_in) ) initializer (omp_priv = omp_orig.zeroedCopy()) #pragma omp declare reduction (merge2D : GraphDataBinned2D : omp_out.merge(omp_in) ) initializer (omp_priv = omp_orig.zeroedCopy()) /** * Calculate the output parameters listed in table 4, page 14 of * http://bio-complexity.org/ojs/index.php/main/article/view/BIO-C.2016.4 * The method assumes that all mutation_graphs have already been pruned. */ Analysis Analysis::Calculate( Logger& logger, Parser& inputs, HaploBlockVariants& variants, pair<vector<PersonNode>, vector<PersonNode>>& whole_generation) { logger.logEvent("Analysis begins."); const long max_bins = inputs.getPositiveLong("analysis_datapoints_maximum"); const long max_distance = inputs.getPositiveLong("analysis_linkage_distance_maximum"); const bool do_linkage_stats = inputs.getBool("analysis_do_linkage_stats"); const bool use_mutation_loci = inputs.getBool("use_mutation_loci"); const double min_freq = inputs.getNonNegativeDouble("analysis_linkage_minimum_frequency"); const long total_sn_loci = variants.getChromosomeLength(); const long total_blocks = variants.getNumberBlocks(); const auto& boundary_loci = variants.getBlockBoundaries(); const LocusId chromosome_length = boundary_loci.back(); const auto block_loci = vector<LocusId>(boundary_loci.begin(),boundary_loci.end()-1); const long total_males = whole_generation.first.size(); const long total_females = whole_generation.second.size(); const long total_chromosomes = 2 * (total_males + total_females); const AlleleId NO_PARENT = -1; const Chromosome EMPTY = Chromosome(); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Sample and Simplify Mutation Graphs variants.sampleChromosomesAndSimplify(whole_generation, true); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Transform the data into a more cache-friendly shape to make processing faster. logger.logEvent(" Data Transform begins."); vector<vector<AlleleId>> allele_data(total_blocks); // [BlockId][ChromosomeId] vector<vector<AlleleId>> parent_data(total_blocks); // [BlockId][AlleleId] vector<vector<long>> nsnp_data(total_blocks); // [BlockId][AlleleId]; vector<vector<vector<LocusId>>> snp_data; // [BlockId][AlleleId][int] if (use_mutation_loci) snp_data.resize(total_blocks); // Extract and transpose the chromosome data. bool empty_chromosomes = false; for (BlockId ib=0; ib<total_blocks; ++ib) allele_data[ib].reserve(total_chromosomes); for (auto* persons : { &whole_generation.first, &whole_generation.second }) for (auto& person : *persons) for (auto* chromosome : { &person.chromosomeFromFather, &person.chromosomeFromMother }) { if (*chromosome == EMPTY) { empty_chromosomes = true; continue; } #pragma omp parallel for for (BlockId bi=0; bi<total_blocks; ++bi) { LocusId block_locus = block_loci[bi]; AlleleId allele = chromosome->getValue(block_locus); if (allele==UNKNOWN_ALLELE) throw logic_error("Unknown allele in non-empty chromosome."); allele_data[bi].push_back(allele); } *chromosome = EMPTY; // delete/free memory } whole_generation.first = {}; // delete/free memory whole_generation.second = {}; // delete/free memory if (empty_chromosomes) logger.logEvent(" There were empty chromosomes in sample."); logger.logEvent(" Data Transposed."); // Next, map the non-contiguous allele ids in MutationGraph to a set of contiguous allele ids. #pragma omp parallel for for (BlockId bi=0; bi<total_blocks; ++bi) { const MutationGraph& graph = variants.getMutationGraph(block_loci[bi]); // Get old ids. Map to new ids. vector<AlleleId> old_allele_ids = graph.getAlleleIds(); map<AlleleId, AlleleId> new_allele_id_map; new_allele_id_map[UNKNOWN_ALLELE] = NO_PARENT; AlleleId new_allele_id = 0; for (const auto& old_allele_id : old_allele_ids) { new_allele_id_map[old_allele_id] = new_allele_id++; } // Copy the (old) parent_ids and mutation-locus groups into a contiguous vector structure. int n_alleles = old_allele_ids.size(); parent_data[bi] = vector<AlleleId>(n_alleles); nsnp_data[bi] = vector<long>(n_alleles); if (use_mutation_loci) snp_data[bi] = vector<vector<LocusId>>(n_alleles); for (const auto& old_allele_id : old_allele_ids) { AlleleId new_allele_id = new_allele_id_map.at(old_allele_id); parent_data[bi][new_allele_id] = graph.getParentId(old_allele_id); // important that the graph was pruned first ^ nsnp_data[bi][new_allele_id] = graph.getNumberOfMutations(old_allele_id); if (use_mutation_loci) { const auto& mutations = graph.getMutations(old_allele_id); snp_data[bi][new_allele_id].reserve(mutations.size()); for (auto& entry : mutations) snp_data[bi][new_allele_id].push_back(entry.first); } } // Finally update all the copied allele ids from old to new. for (AlleleId& allele_id : allele_data[bi]) allele_id = new_allele_id_map.at(allele_id); for (AlleleId& parent_id : parent_data[bi]) parent_id = new_allele_id_map.at(parent_id); variants.deleteMutationGraph(block_loci[bi]); // delete/free memory } variants = HaploBlockVariants(); // delete/free memory logger.logEvent(" Data Transform complete."); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Process the data to get statistics. const double total_freq = (double)allele_data[0].size(); logger.logEvent("Total samples: " + to_string(total_freq)); const double freq_max = 0.5; const size_t freq_nbins = min(max_bins, (long)ceil(freq_max * total_freq)); const double link_max = min(total_sn_loci, max_distance); const size_t link_nbins = min(max_bins, max_distance); long total_snp_sites = 0L; double sn_diversity = 0.0; GraphDataBinned snp_freq_spectrum(0, freq_max, freq_nbins, true); GraphDataBinned snp_distribution(0, chromosome_length, min(chromosome_length,max_bins)); GraphDataBinned correlation_function(0, link_max, link_nbins); GraphDataBinned dprime_function(0, link_max, link_nbins); GraphDataBinned complete_linkage_function(0, link_max, link_nbins); GraphDataBinned almost_complete_linkage_function(0, link_max, link_nbins); GraphDataBinned normalized_kullback_leibler_function(0, link_max, link_nbins); GraphDataBinned sigma_squared_numerator(0, link_max, link_nbins); GraphDataBinned sigma_squared_denominator(0, link_max, link_nbins); GraphDataBinned2D freq_pair_spectrum({0.0,0.5},{0.0,0.5}, 20, true); // First, the single-locus statistics. logger.logEvent(" Single Nucleotides statistics begin."); long n_alleles_fixed=0; #pragma omp parallel for reduction(+: total_snp_sites, sn_diversity) \ reduction(merge: snp_freq_spectrum) for (BlockId bi=0; bi<total_blocks; ++bi) { const int n_alleles = nsnp_data[bi].size(); double freqs[n_alleles]; // Roughly corresponds to pi in the paper. for (AlleleId ai=0; ai<n_alleles; ++ai) freqs[ai] = 0.0; // First, the frequencies for all alleles (unique combinations of single nucleotides). for (AlleleId ai : allele_data[bi]) { ++freqs[ai]; } // Second, transform these into frequencies for the single nucleotides. for (AlleleId ai=n_alleles-1; ai>=0; --ai) { AlleleId pai = parent_data[bi][ai]; if (pai == NO_PARENT) continue; freqs[pai] += freqs[ai]; } // Finally, update the single nucleotide stats. double norm_sn_diversity = 2.0 / total_sn_loci; for (AlleleId ai=0; ai<n_alleles; ++ai) { double fa = freqs[ai] / total_freq; if (fa==0.0) throw logic_error("freqs elements should not be empty"); if (fa>=1.0) { ++n_alleles_fixed; continue; } fa = fa < 0.5 ? fa : (1.0-fa); long n_snps = nsnp_data[bi][ai]; total_snp_sites += n_snps; sn_diversity += norm_sn_diversity * n_snps * fa * (1.0 - fa); snp_freq_spectrum.sampleWeight(fa, n_snps); if (use_mutation_loci) { for (auto snp : snp_data[bi][ai]) snp_distribution.sampleWeight(snp,1); } } } logger.logEvent(" Fixed Alleles: " + to_string(n_alleles_fixed)); logger.logEvent(" Single Nucleotides statistics complete."); if (do_linkage_stats) { // Second, the two-locus statistics. const size_t nblocks = block_loci.size(); const double f1 = 1.0 / total_freq; logger.logEvent(" Pair Nucleotide statistics begin."); logger.logEvent(" Total blocks: " + to_string(nblocks) + "."); #pragma omp parallel for schedule(dynamic) \ reduction(merge: correlation_function, \ dprime_function, \ complete_linkage_function, \ almost_complete_linkage_function, \ normalized_kullback_leibler_function, \ sigma_squared_numerator, \ sigma_squared_denominator) \ reduction(merge2D: freq_pair_spectrum) for (size_t bi=0; bi<nblocks; ++bi) { for (size_t bj=bi; bj<nblocks; ++bj) { const LocusId block_locus_i = block_loci[bi]; const LocusId block_locus_j = block_loci[bj]; const LocusId block_end_locus_i = (bi+1)==nblocks ? total_sn_loci : block_loci[bi+1]; const long block_distance = block_locus_j - block_end_locus_i; if (block_distance > max_distance) break; // goto next bi const int n_alleles_i = nsnp_data[bi].size(); const int n_alleles_j = nsnp_data[bj].size(); double freqs_i[n_alleles_i]; double freqs_j[n_alleles_j]; double freqs_ij[n_alleles_i][n_alleles_j]; for (AlleleId ai=0; ai<n_alleles_i; ++ai) freqs_i[ai] = 0.0; for (AlleleId aj=0; aj<n_alleles_j; ++aj) freqs_j[aj] = 0.0; for (AlleleId ai=0; ai<n_alleles_i; ++ai) for (AlleleId aj=0; aj<n_alleles_j; ++aj) freqs_ij[ai][aj] = 0.0; // First, the frequencies for all pairs of alleles in block i and block j. for (ChromosomeId ci=0; ci<total_freq; ++ci) { AlleleId ai = allele_data[bi][ci]; AlleleId aj = allele_data[bj][ci]; ++freqs_i[ai]; ++freqs_j[aj]; ++freqs_ij[ai][aj]; } // Second, transform these into frequencies for the single nucleotides, for block i ... for (AlleleId ai=n_alleles_i-1; ai>=0; --ai) { AlleleId pai = parent_data[bi][ai]; if (pai == NO_PARENT) continue; freqs_i[pai] += freqs_i[ai]; for (AlleleId aj=0; aj<n_alleles_j; ++aj) { freqs_ij[pai][aj] += freqs_ij[ai][aj]; } } // ... then for block j for (AlleleId aj=n_alleles_j-1; aj>=0; --aj) { AlleleId paj = parent_data[bj][aj]; if (paj == NO_PARENT) continue; freqs_j[paj] += freqs_j[aj]; for (AlleleId ai=0; ai<n_alleles_i; ++ai) { freqs_ij[ai][paj] += freqs_ij[ai][aj]; } } // Calculate correlations for this pair of blocks double kl_numerator = 0.0; double kl_denom_sqrd = 0.0; for (AlleleId ai=0; ai<n_alleles_i; ++ai) { double fa = freqs_i[ai] / total_freq; if (fa==0.0) throw logic_error("freqs elements should not be empty"); if (fa==1.0) continue; if (fa<min_freq || fa>1.0-min_freq) continue; for (AlleleId aj=(bi==bj?ai:0); aj<n_alleles_j; ++aj) { double fb = freqs_j[aj] / total_freq; if (fb==0.0) throw logic_error("freqs elements should not be empty"); if (fb==1.0) continue; if (fb<min_freq || fb>1.0-min_freq) continue; double fab = freqs_ij[ai][aj] / total_freq; double fA = 1 - fa; double fB = 1 - fb; double faB = fa - fab; double fAb = fb - fab; double fAB = 1 - fab - faB - fAb; double delta = fab * fAB - faB * fAb; double sig2_numerator = delta * delta; double sig2_denominator = (fa * fA * fb * fB); double correlation = sig2_numerator / sig2_denominator; // eqn 47a: r^2 double dprime = delta / (delta > 0 ? min(fa*fB,fA*fb) : -min(fa*fb,fA*fB)); double complete_linkage = (fab==0 || faB==0 || fAb==0 || fAB == 0) ? 1.0 : 0.0; double almost_complete_linkage = (fab<=f1 || faB<=f1 || fAb<=f1 || fAB <=f1) ? 1.0 : 0.0; double mafA = min(fa,fA); double mafB = min(fb,fB); if (use_mutation_loci) { for (LocusId locus_i : snp_data[bi][ai]) for (LocusId locus_j : snp_data[bj][aj]) { double locus_distance = fabs(locus_i - locus_j); correlation_function.sampleValue(locus_distance, correlation); dprime_function.sampleValue(locus_distance, dprime); complete_linkage_function.sampleValue(locus_distance, complete_linkage); almost_complete_linkage_function.sampleValue(locus_distance, almost_complete_linkage); sigma_squared_numerator.sampleValue(locus_distance, sig2_numerator); sigma_squared_denominator.sampleValue(locus_distance, sig2_denominator); if (0<locus_distance && locus_distance < 1e4) { freq_pair_spectrum.sampleWeight(mafA, mafB); freq_pair_spectrum.sampleWeight(mafB, mafA); } } } else { double distance = fabs(block_locus_j-block_locus_i); long nlocuspairs = nsnp_data[bi][ai] * nsnp_data[bj][aj]; correlation_function.sampleValue( distance, correlation, nlocuspairs ); dprime_function.sampleValue( distance, dprime, nlocuspairs ); complete_linkage_function.sampleValue( distance, complete_linkage, nlocuspairs ); almost_complete_linkage_function.sampleValue( distance, almost_complete_linkage, nlocuspairs ); sigma_squared_numerator.sampleValue( distance, sig2_numerator, nlocuspairs ); sigma_squared_denominator.sampleValue( distance, sig2_denominator, nlocuspairs ); if (0 < distance && distance < 1e4) { freq_pair_spectrum.sampleWeight(mafA, mafB, nlocuspairs); freq_pair_spectrum.sampleWeight(mafB, mafA, nlocuspairs); } } bool ai_is_founder = parent_data[bi][ai] == NO_PARENT; bool aj_is_founder = parent_data[bj][aj] == NO_PARENT; if (ai_is_founder && aj_is_founder) { double weight = (bi==bj && ai!=aj) ? 2.0 : 1.0; kl_numerator += weight * (fab ? fab * log(fab / (fa * fb)) : 0.0); kl_denom_sqrd += weight * (fa * fb * log(fa) * log(fb)); } } } if (kl_denom_sqrd) { double kl_distance = block_locus_j - block_locus_i; double kl_value = kl_numerator / sqrt(kl_denom_sqrd); normalized_kullback_leibler_function.sampleValue(kl_distance, kl_value); } logger.logProgress(" Pair " + to_string(bi) + ", " + to_string(bj) + " done."); } // end for block bj } // end for block bj logger.logEvent(" Pair Nucleotide statistics complete."); sigma_squared_numerator.divide(sigma_squared_denominator); } // end if do_linkage logger.logEvent("Analysis complete."); return Analysis { total_blocks, total_snp_sites, sn_diversity, move(snp_freq_spectrum), move(snp_distribution), move(correlation_function), move(dprime_function), move(complete_linkage_function), move(almost_complete_linkage_function), move(normalized_kullback_leibler_function), move(sigma_squared_numerator), move(freq_pair_spectrum) }; } <file_sep>/hpc/build_omp.sh #----------------------------------------------------------------------------- # # Compile the code # #----------------------------------------------------------------------------- ROOTPATH=$( cd $(dirname $0)"/.." ; pwd -P) SCRIPTPATH=$ROOTPATH"/hpc" COMPILEPATH=$ROOTPATH"/scratch/hpc/omp" mkdir -p $COMPILEPATH cd $COMPILEPATH #make -s -f $SCRIPTPATH/Makefile clean make -s -j $(nproc) -k -f $SCRIPTPATH/Makefile_omp $1 2> err head -n 25 err # -s do not echo everything # -j use multiple procs # -f name of makefile (default: Makefile) # -k says keep going after errors #----------------- echo Compiled to: $COMPILEPATH cd - > /dev/null #----------------- <file_sep>/core/PopulationStructureHistory.h #pragma once #include <string> #include <utility> #include <vector> /** PopulationStructureHistory: Stores the population structure over history. Currently stored as a simple list of pairs: the number of males and number of females at each generation. Generation 0 is the extant generation from which we take the sample, last in time. Other generations are listed in order backwards in time. */ class PopulationStructureHistory { friend class FileCheckpointer; friend class FileReader; private: std::vector<std::pair<long,long>> m_populations; PopulationStructureHistory(std::vector<std::pair<long,long>> popns) : m_populations(popns) {} public: PopulationStructureHistory() // for creating unassigned variables : m_populations() {} static PopulationStructureHistory Constant( long initial_gen, long final_males, long final_females); static PopulationStructureHistory Constant(long initial_gen, long final_popn); static PopulationStructureHistory Linear( long initial_gen, long initial_popn, long final_popn); static PopulationStructureHistory Exponential( long initial_gen, long initial_popn, long final_popn); static PopulationStructureHistory Logistic( long initial_gen, long initial_popn, long final_popn, double growth_rate); static PopulationStructureHistory Sinusoidal( long initial_gen, long initial_popn, long final_popn, double growth_rate); static PopulationStructureHistory create( std::string type, long initial_gen, long initial_popn, long final_popn, double growth_rate); long getNumberOfGenerations() const { return m_populations.size(); } long getNumberOfMales(long gen) const { return m_populations[gen].first; } long getNumberOfFemales(long gen) const { return m_populations[gen].second; } long getTotalNumberOfMales() const; long getTotalNumberOfFemales() const; bool operator==(const PopulationStructureHistory&) const; }; <file_sep>/core/GraphDataBinned.cpp #include "GraphDataBinned.h" #include <cstddef> #include <limits> #include <stdexcept> #include <string> using namespace std; string GraphDataBinned::toString(bool bar_end) const { string s; size_t n = m_weight_bins.size(); double delta = (m_max - m_min) / n; for(size_t i = 0; i < n; i++) { double bin_min = m_min + i * delta; double bin_max = i+1==n ? m_max : bin_min + delta; double bin_weight = m_weight_bins.at(i); double bin_value = m_value_bins.at(i); double bin_average = bin_weight ? bin_value / bin_weight : 0.0; s += to_string(bin_min); s += " "; if (bar_end) { s += to_string(bin_max); s += " "; } s += to_string(bin_weight); s += " "; s += to_string(bin_average); s += "\n"; } return s; } void assertBinsIdentical(const GraphDataBinned& a, const GraphDataBinned& b) { if (a.m_weight_bins.size() != b.m_weight_bins.size() || a.m_value_bins.size() != b.m_value_bins.size() || a.m_min != b.m_min || a.m_max != b.m_max || a.m_delta_inv != b.m_delta_inv || a.m_bin_includes_upper_bound != b.m_bin_includes_upper_bound) throw invalid_argument("Attempt to combine data with different bins"); } GraphDataBinned& GraphDataBinned::merge(const GraphDataBinned& other) { assertBinsIdentical(*this, other); size_t n = m_weight_bins.size(); for (size_t i = 0; i < n; ++i) { this->m_weight_bins[i] += other.m_weight_bins[i]; this->m_value_bins[i] += other.m_value_bins[i]; } return *this; } GraphDataBinned& GraphDataBinned::divide(const GraphDataBinned& divisor) { assertBinsIdentical(*this, divisor); size_t n = m_weight_bins.size(); for (size_t i = 0; i < n; ++i) { double weight = divisor.m_weight_bins[i]; double value = divisor.m_value_bins[i]; if (weight == 0.0) continue; if (value == 0.0) this->m_value_bins[i] = numeric_limits<double>::max(); else this->m_value_bins[i] *= weight / value; } return *this; } <file_sep>/core/Blocks.h #pragma once #include <cstddef> #include <functional> #include <random> #include <set> #include <string> #include <utility> #include <vector> #include "BlocksRange.h" template<typename V> class Blocks { friend class FileCheckpointer; friend class FileMemorySaver; friend class HaploBlockVariants; private: std::vector<std::pair<long, V>> m_intervals; public: /** Default constructor */ Blocks<V>() {} /** Create Blocks where the whole range is one value. */ Blocks<V>(V value) : m_intervals({std::pair<long,V>(0,value)}) {} /** Combine two Blocks according to 'combinePattern'. */ static Blocks<V> combine(const Blocks<V>& a, const Blocks<V>& b, const BlocksRange& combinePattern); /** Filter Blocks according to 'filterPattern'. */ Blocks<V> filtered(const BlocksRange& filterPattern) const; Blocks<V> compressed(); bool operator==(const Blocks<V>& other) const; V getValue(long position) const; std::string toString() const; size_t getSizeInMemory() const; }; <file_sep>/core/PolyaUrn.h #pragma once #include <random> #include <vector> class PolyaUrn { // Parameters (see notes on constructor) const long m_total_options; const double m_alpha; const bool m_reserve; // State long m_current_options; long m_current_picks; std::vector<std::vector<long>> m_nodes; static std::uniform_real_distribution<double> random; long pick_by_existing_index(const long index); long pick_new_index(); long pick_by_ic(long ic); public: /** * Create a new Polya Urn where the user can choose from a population of size 'total_options', * with randomness parameter 'alpha' (larger -> more random, smaller -> more concentrated). * The optional parameter 'reserve' can be used to preallocate memory when a large memory * need is anticipated. */ PolyaUrn(long total_options, double alpha, bool reserve = false) : m_total_options(total_options), m_alpha(alpha), m_reserve(reserve), m_current_options(0L), m_current_picks(0L) {} /** * Choose from the population using the supplied random number generator. An id is returned. * The first pick is always labelled id=0. Subsequent picks are given monotonically-increasing * ids if they have not been picked before. */ long sample(std::mt19937_64& rng); }; <file_sep>/core/MutationRateHistory.h #pragma once #include <string> #include <utility> #include <vector> /** MutationRateHistory: Stores the mutation rate over history. Currently stored as a simple list of values: the mutation rate at each generation. Generation 0 is the extant generation from which we take the sample, last in time. Other generations are listed in order backwards in time. */ class MutationRateHistory { friend class FileCheckpointer; friend class FileReader; private: std::vector<double> m_rates; MutationRateHistory(std::vector<double> rates) : m_rates(rates) {} public: MutationRateHistory() {}// for creating unassigned variables static MutationRateHistory Constant(long ngens, double rate) { return MutationRateHistory(std::vector<double>(ngens,rate)); } long getNumberOfGenerations() const { return m_rates.size(); } double getMutationRate(long gen) const { return m_rates[gen]; } bool operator==(const MutationRateHistory& o) { return m_rates == o.m_rates; } }; <file_sep>/hpc/FileCheckpointer.h #pragma once #include <ctime> #include <random> #include <string> #include "core/AncestralChromosomes.h" #include "core/AncestralRecombinationGraph.h" #include "core/HaploBlockBoundaries.h" #include "core/HaploBlockVariants.h" #include "core/MutationRateHistory.h" #include "core/Parser.h" #include "core/PopulationStructureHistory.h" class FileCheckpointer { private: const std::string m_filename; const long minimum_interval; long previous_time; public: FileCheckpointer(const std::string& filename, long min_int) : m_filename(filename), minimum_interval(min_int*CLOCKS_PER_SEC), previous_time(-min_int*CLOCKS_PER_SEC) {} bool timeDue(); void save( const bool& forwards, const long& step, const std::mt19937_64& rng, const PopulationStructureHistory& psh, const MutationRateHistory& mrh, const HaploBlockBoundaries& hbb, const AncestralRecombinationGraph& arg, const HaploBlockVariants& hbv, const AncestralChromosomes& ac); void load( bool& forwards, long& step, std::mt19937_64& rng, PopulationStructureHistory& psh, MutationRateHistory& mrh, HaploBlockBoundaries& hbb, AncestralRecombinationGraph& arg, HaploBlockVariants& hbv, AncestralChromosomes& ac); }; <file_sep>/hpc/FileCheckpointer.cpp #include "FileCheckpointer.h" #include <algorithm> #include <type_traits> #define typeof(x) std::remove_reference<decltype((x))>::type #include "FileDataPrimitiveIO.h" using namespace std; bool FileCheckpointer::timeDue() { long current_time = clock(); return (current_time >= previous_time + minimum_interval); } void FileCheckpointer::save(const bool& forwards, const long& step, const mt19937_64& rng, const PopulationStructureHistory& psh, const MutationRateHistory& mrh, const HaploBlockBoundaries& hbb, const AncestralRecombinationGraph& arg, const HaploBlockVariants& hbv, const AncestralChromosomes& ac) { long current_time = clock(); previous_time = current_time; ofstream ofs(m_filename, ios::out | ios::binary); writePrimitive(ofs, forwards); writePrimitive(ofs, step); ofs << rng; /** Parser writePrimitive(ofs, parser.m_map.size()); for (auto& entry : parser.m_map) { writeString(ofs, entry.first); writeString(ofs, entry.second); } writePrimitive(ofs, parser.m_used.size()); for (auto& entry : parser.m_used) { writeString(ofs, entry); } */ /** PopulationStructureHistory */ writePrimitiveVector(ofs, psh.m_populations); /** MutationRateHistory */ writePrimitiveVector(ofs, mrh.m_rates); /** HaploBlockBoundaries */ writePrimitiveVector(ofs, hbb.m_block_boundaries); writePrimitiveMap(ofs, hbb.m_block_boundary_used); /** Ancestral Recombination Graph */ { writePrimitive(ofs, arg.m_chromosome_type); const auto& gens = arg.m_nodes; const decltype(arg.m_nodes)::value_type nullgen; size_t ngens = gens.size(); writePrimitive(ofs, ngens); //size_t n2write = count_if(gens.begin(), gens.end(), [](const typeof(gens)::value_type& g){ return !g.first.empty() || !g.second.empty();}); size_t n2write = ngens - count(gens.begin(), gens.end(), nullgen); writePrimitive(ofs, n2write); for (size_t igen=0; igen<ngens; ++igen) { const auto& gen = gens[igen]; if (n2write<ngens/2) { if(gen == nullgen) continue; writePrimitive(ofs, igen); } auto& males = gen.first; auto& females = gen.second; auto nmales = males.size(); auto nfemales = females.size(); writePrimitive(ofs, nmales); writePrimitive(ofs, nfemales); for (auto* persons : { &males, &females } ) for (auto& person : *persons) { writePrimitive(ofs, person.fatherId); writePrimitive(ofs, person.motherId); writePrimitiveVector(ofs, person.chromosomeFromFatherRecombinationPattern.m_toggles); writePrimitiveVector(ofs, person.chromosomeFromMotherRecombinationPattern.m_toggles); writePrimitiveVector(ofs, person.chromosomeFromFatherExtancyPattern.m_toggles); writePrimitiveVector(ofs, person.chromosomeFromMotherExtancyPattern.m_toggles); } } } /** HaploBlockVariants */ const bool have_hbv = !hbv.unassigned(); writePrimitive(ofs, have_hbv); writePrimitive(ofs, hbv.m_max_nodes_per_block); if (have_hbv) { writePrimitive(ofs, hbv.m_reference_chromosomes.size()); for (const auto& refc : hbv.m_reference_chromosomes) { writePrimitiveVector(ofs, refc.m_intervals); } writePrimitive(ofs, hbv.m_variants.size()); for (const auto& mutg : hbv.m_variants) { writePrimitive(ofs, mutg.m_use_mutation_loci); writePrimitive(ofs, mutg.m_next_id); writePrimitive(ofs, mutg.m_nodes.size()); for (const auto& entry : mutg.m_nodes) { const auto& id = entry.first; const auto& node = entry.second; writePrimitive(ofs, id); writePrimitive(ofs, node.parent_id); writePrimitive(ofs, node.n_mutations); writePrimitiveVector(ofs, node.mutations); writePrimitive(ofs, node.n_child_nodes); writePrimitive(ofs, node.frequency); } } writePrimitiveVector(ofs, hbv.m_boundaries); writePrimitiveMap(ofs, hbv.m_block_ids); } /** Ancestral Chromosomes */ const bool have_ac = !ac.unassigned(); writePrimitive(ofs, have_ac); if (have_ac) { const auto& gens = ac.m_nodes; const decltype(ac.m_nodes)::value_type nullgen; size_t ngens = gens.size(); writePrimitive(ofs, ngens); size_t n2write = ngens - count(gens.begin(), gens.end(), nullgen); writePrimitive(ofs, n2write); for (size_t igen=0; igen<ngens; ++igen) { const auto& gen = gens[igen]; if (n2write<ngens/2) { if(gen == nullgen) continue; writePrimitive(ofs, igen); } auto& males = gen.first; auto& females = gen.second; auto nmales = males.size(); auto nfemales = females.size(); writePrimitive(ofs, nmales); writePrimitive(ofs, nfemales); for (auto* persons : { &males, &females } ) for (auto& person : *persons) { writePrimitiveVector(ofs, person.chromosomeFromFather.m_intervals); writePrimitiveVector(ofs, person.chromosomeFromMother.m_intervals); } } } } void FileCheckpointer::load(bool& forwards, long& step, mt19937_64& rng, PopulationStructureHistory& psh, MutationRateHistory& mrh, HaploBlockBoundaries& hbb, AncestralRecombinationGraph& arg, HaploBlockVariants& hbv, AncestralChromosomes& ac) { ifstream ifs(m_filename, ios::in | ios::binary); readPrimitive(ifs, forwards); readPrimitive(ifs, step); ifs >> rng; /** Parser size_t ninputs; readPrimitive(ifs, ninputs); for (size_t i=0; i<ninputs; ++i) { string key; string value; readString(ifs, key); readString(ifs, value); parser.m_map[key] = value; } size_t nused; readPrimitive(ifs, nused); for (size_t i=0; i<nused; ++i) { string key; readString(ifs, key); parser.m_used.insert(key); } */ /** PopulationStructureHistory */ readPrimitiveVector(ifs, psh.m_populations); /** MutationRateHistory */ readPrimitiveVector(ifs, mrh.m_rates); /** HaploBlockBoundaries */ readPrimitiveVector(ifs, hbb.m_block_boundaries); readPrimitiveMap(ifs, hbb.m_block_boundary_used); /** Ancestral Recombination Graph */ { arg.m_history = &psh; arg.m_haplo_block_boundaries = &hbb; readPrimitive(ifs, arg.m_chromosome_type); auto& gens = arg.m_nodes; size_t ngens; readPrimitive(ifs, ngens); gens.resize(ngens); size_t n2read; readPrimitive(ifs, n2read); for (size_t i=0; i<n2read; ++i) { size_t igen; if (n2read<ngens/2) readPrimitive(ifs, igen); else igen = i; auto& gen = gens.at(igen); auto& males = gen.first; auto& females = gen.second; size_t nmales; size_t nfemales; readPrimitive(ifs, nmales); readPrimitive(ifs, nfemales); males.resize(nmales); females.resize(nfemales); for (auto* persons : { &males, &females } ) for (auto& person : *persons) { readPrimitive(ifs, person.fatherId); readPrimitive(ifs, person.motherId); readPrimitiveVector(ifs, person.chromosomeFromFatherRecombinationPattern.m_toggles); readPrimitiveVector(ifs, person.chromosomeFromMotherRecombinationPattern.m_toggles); readPrimitiveVector(ifs, person.chromosomeFromFatherExtancyPattern.m_toggles); readPrimitiveVector(ifs, person.chromosomeFromMotherExtancyPattern.m_toggles); } } } /** HaploBlockVariants */ bool have_hbv; readPrimitive(ifs, have_hbv); readPrimitive(ifs, hbv.m_max_nodes_per_block); if (have_hbv) { size_t nrefc; readPrimitive(ifs, nrefc); hbv.m_reference_chromosomes.resize(nrefc); for (auto& refc : hbv.m_reference_chromosomes) { readPrimitiveVector(ifs, refc.m_intervals); } size_t nvar; readPrimitive(ifs, nvar); hbv.m_variants.resize(nvar); for (auto& mutg : hbv.m_variants) { readPrimitive(ifs, mutg.m_use_mutation_loci); readPrimitive(ifs, mutg.m_next_id); size_t nnodes; readPrimitive(ifs, nnodes); for (size_t i=0; i<nnodes; ++i) { typeof(mutg.m_nodes)::key_type id; readPrimitive(ifs, id); auto& node = mutg.m_nodes[id]; readPrimitive(ifs, node.parent_id); readPrimitive(ifs, node.n_mutations); readPrimitiveVector(ifs, node.mutations); readPrimitive(ifs, node.n_child_nodes); readPrimitive(ifs, node.frequency); } } readPrimitiveVector(ifs, hbv.m_boundaries); readPrimitiveMap(ifs, hbv.m_block_ids); } /** Ancestral Chromosomes */ bool have_ac; readPrimitive(ifs, have_ac); if (have_ac) { ac.m_graph = &arg; ac.m_variants = &hbv; auto& gens = ac.m_nodes; size_t ngens; readPrimitive(ifs, ngens); gens.resize(ngens); size_t n2read; readPrimitive(ifs, n2read); for (size_t i=0; i<n2read; ++i) { size_t igen; if (n2read<ngens/2) readPrimitive(ifs, igen); else igen = i; auto& gen = gens.at(igen); auto& males = gen.first; auto& females = gen.second; size_t nmales; size_t nfemales; readPrimitive(ifs, nmales); readPrimitive(ifs, nfemales); males.resize(nmales); females.resize(nfemales); for (auto* persons : { &males, &females } ) for (auto& person : *persons) { readPrimitiveVector(ifs, person.chromosomeFromFather.m_intervals); readPrimitiveVector(ifs, person.chromosomeFromMother.m_intervals); } } } } <file_sep>/core/Blocks.cpp #include <algorithm> #include <string> #include "Blocks.h" #include "BlocksRange.h" using namespace std; template<typename V> Blocks<V> Blocks<V>::combine( const Blocks<V>& blocks_A, const Blocks<V>& blocks_B, const BlocksRange& pattern) { auto it0 = blocks_A.m_intervals.cbegin(); // 0 for off/unselected auto it1 = blocks_B.m_intervals.cbegin(); // 1 for on/selected auto end0 = blocks_A.m_intervals.cend(); auto end1 = blocks_B.m_intervals.cend(); auto tog_it = pattern.m_toggles.cbegin(); auto tog_end = pattern.m_toggles.cend(); V current0 = V(); V current1 = V(); Blocks<V> blocks_C; auto& intervals_C = blocks_C.m_intervals; for ( ; tog_it != tog_end; ++tog_it) { for ( ; it1 != end1 && it1->first < *tog_it; ++it1) { intervals_C.push_back(*it1); current1 = it1->second; } swap(it0, it1); swap(end0, end1); swap(current0, current1); for ( ; it1 != end1 && it1->first <= *tog_it; ++it1) { current1 = it1->second; } if (current1 != current0) { intervals_C.emplace_back(*tog_it, current1); } } for ( ; it1 != end1; ++it1) { intervals_C.push_back(*it1); current1 = it1->second; } return blocks_C; } template<typename V> Blocks<V> Blocks<V>::filtered(const BlocksRange& filterPattern) const { return combine(*this, Blocks<V>(), filterPattern); } template<typename V> Blocks<V> Blocks<V>::compressed() { const auto& old_intervals = this->m_intervals; Blocks<V> new_blocks; auto& new_intervals = new_blocks.m_intervals; auto it = old_intervals.begin(); auto end_it = old_intervals.end(); new_intervals.emplace_back(*it); for ( ; it != end_it; ++it) { if (new_intervals.back().second != it->second) { new_intervals.emplace_back(*it); } } return new_blocks; } template<typename V> bool Blocks<V>::operator==(const Blocks<V>& other) const { return (this->m_intervals.size() == other.m_intervals.size()) && equal(this->m_intervals.cbegin(), this->m_intervals.cend(), other.m_intervals.cbegin()); } template<typename V> V Blocks<V>::getValue(long position) const { auto itBegin = m_intervals.cbegin(); auto itEnd = m_intervals.cend(); typedef pair<long,V> P; auto it = upper_bound( itBegin, itEnd, make_pair(position, V()), [](const P& a, const P& b) { return a.first < b.first; }); return it==itBegin ? V() : prev(it)->second; } template<typename V> string Blocks<V>::toString() const { string s = ""; const auto& v = m_intervals; long n = v.size(); if (n==0) return "[0,end): " + to_string(V()) + ", "; long last = n-1; if (v[0].first != 0) { s += "[0," + to_string(v[0].first) + "):" + to_string(V()) + ", "; } for(int i=0; i<last; i++) { s += "[" + to_string(v[i].first) + "," + to_string(v[i+1].first) + "):" + to_string(v[i].second) + ", "; } s += "[" + to_string(v[last].first) + ",end):" + to_string(v[last].second) + ", "; return s; } template<typename V> size_t Blocks<V>::getSizeInMemory() const { return sizeof(vector<pair<long,V>>) + m_intervals.size() * sizeof(pair<long,V>); } // Specify which class(es) we want to pre-compile. template class Blocks<int>; template class Blocks<long>; <file_sep>/hpc/FileWriter.cpp #include "FileWriter.h" #include <fstream> #include <stdexcept> #include <string> using namespace std; void FileWriter::write( const string &output_filename, const string &content, const string &comment) { ofstream ofs(output_filename, ofstream::out | ofstream::trunc); if (ofs.fail()) throw invalid_argument("Cannot open " + output_filename); if (comment != "") ofs << "# " << comment << endl; ofs << content << endl; } void FileWriter::append( const string &output_filename, const string &content, const string &comment) { ofstream ofs(output_filename, ofstream::out | ofstream::app); if (ofs.fail()) throw invalid_argument("Cannot open " + output_filename); if (comment != "") ofs << "# " << comment << endl; ofs << content << endl; } <file_sep>/core/Parser.cpp #include "Parser.h" #include <algorithm> #include <limits> #include <stdexcept> #include <string> using namespace std; string msg(const string& type, const string& value, const string& key) { return "Not a " + type + ": " + value + " (key: " + key + ")"; } // Static methods. bool Parser::parseBool(const string& value, const string& key) { string s = value; transform(s.begin(), s.end(), s.begin(), ::tolower); if (s == "true") return true; if (s == "false") return false; throw invalid_argument(msg("boolean", value, key)); } double Parser::parseDouble(const string& value, const string& key) { try { return stod(value); } catch (const exception& e) { throw invalid_argument(msg("double", value, key)); } } long Parser::parseLong(const string& value, const string& key) { try { double dval = stod(value); if (fabs(dval) > (double)numeric_limits<long>::max()) throw invalid_argument("Number too large: " + value + " (key: " + key + ")"); return (long) dval; } catch (const exception& e) { throw invalid_argument(msg("long", value, key)); } } ChromosomeType Parser::parseChromosomeType( const string& value, const string& key) { string s = value; transform(s.begin(), s.end(), s.begin(), ::tolower); if (s == "autosome") return AUTO; if (s == "x chromosome") return X; if (s == "y chromosome") return Y; if (s == "mitochondrial dna") return MITO; throw invalid_argument(msg("ChromosomeType", value, key)); } double Parser::parseNonNegativeDouble( const string& value, const string& key) { double dval = parseDouble(value); if (0.0 <= dval) return dval; throw invalid_argument(msg("non-negative double", value, key)); } long Parser::parsePositiveLong( const string& value, const string& key) { long lval = parseLong(value); if (0 < lval) return lval; throw invalid_argument(msg("positive long", value, key)); } // Member methods. const string& Parser::getString(const string& key) { try { m_used.emplace(key); return m_map.at(key); } catch (const out_of_range& oor) { throw out_of_range("Key not found: " + key); } } bool Parser::getBool(const string& key) { return parseBool(getString(key), key); } double Parser::getDouble(const string& key) { return parseDouble(getString(key), key); } long Parser::getLong(const string& key) { return parseLong(getString(key), key); } ChromosomeType Parser::getChromosomeType(const string& key) { return parseChromosomeType(getString(key), key); } double Parser::getNonNegativeDouble(const string& key) { return parseNonNegativeDouble(getString(key), key); } long Parser::getPositiveLong(const string& key) { return parsePositiveLong(getString(key), key); } string Parser::getUnusedKeysAsString() const { string s; for (const auto& entry : m_map) { const string& key = entry.first; if (m_used.count(key)==0) { s += key + "\n"; } } return s; } string Parser::toString() const { string s; for (const auto& entry : m_map) { s += entry.first + " : " + entry.second + "\n"; } return s; } <file_sep>/core/PolyaUrn.cpp #include "PolyaUrn.h" #include <random> #include <vector> #include <cstdio> #include <cstdlib> /** * Implements a PolyaUrn with population 'total_options' and randomness parameter 'alpha'. * * Previously chosen picks have additional weight proportional to the number of times they were * previously chosen. Potentially there could be a very large number of these picks, so the * cumulative weights are stored in a binary tree for easy lookup. * * At each level 'ilevel' of the binary tree, the relevant node is indexed by index>>ilevel * (all but the bottom ilevel bits). Each node sums 2 nodes from the previous level, * or 2^ilevel nodes from the bottom layer. */ using namespace std; uniform_real_distribution<double> PolyaUrn::random(0.0, 1.0); long PolyaUrn::sample(mt19937_64& rng) { const double alpha = m_alpha; const long n = m_total_options; const long m = m_current_options; const long c = m_current_picks; double r = random(rng); if (alpha <= 0.0) return 0L; const double nalpha = n * alpha; // <- all 'n' options have weight 'alpha'. r *= (nalpha + c); // <- previously chosen options 'c' have additional unit weight. if (r < nalpha) { // First part of range represents completely-random alpha-weighted choice. long i = (long) (r / alpha); // Using that subrange, choose a member of the population. if (i >= m) return pick_new_index(); // Id has not been chosen before. else return pick_by_existing_index(i); // Id has been chosen before. } else { // Second part of range represents additional weight due to previous choices. r -= nalpha; // Using that subrange, long ic = (long) r; // 'ic' represents a particular previous choice. return pick_by_ic(ic); // Lookup which id it corresponds to. } } // Picking a new index is simple. The complicated part is correctly and efficiently initializing the // new nodes on the binary lookup tree. long PolyaUrn::pick_new_index() { const long index = m_current_options; auto& nodes = m_nodes; int nlevels = nodes.size(); ++m_current_options; ++m_current_picks; // Special case: initialize the first level with a single node with weight 1. if (nlevels == 0) { nodes.push_back(vector<long>{1L}); if (m_reserve) nodes[0].reserve(m_total_options); return index; } // Special case: initialize a new level because the index has reached a new power of 2. // The new node carries the sum from the previous level. if (index == 1<<(nlevels-1)) { long sum = nodes[nlevels-1][0]; nodes.push_back(vector<long>{sum}); if (m_reserve) nodes[nlevels].reserve((m_total_options>>nlevels)+1); ++nlevels; } // Starting at the bottom, add any new nodes that are needed on existing levels. size_t i = index; int ilevel = 0; do { nodes[ilevel].push_back(1L); i>>=1; ++ilevel; } while (i == nodes[ilevel].size()); // Then increment the weights on existing nodes. for(; ilevel<nlevels; ++ilevel) { ++nodes[ilevel][i]; i>>=1; } return index; } // Picking an existing index is trivial. The slightly complicated part is updating the nodes. long PolyaUrn::pick_by_existing_index(const long index) { auto& nodes = m_nodes; int nlevels = nodes.size(); ++m_current_picks; // This is not a new index so all the nodes already exist, need only be incremented. long i = index; for(int ilevel=0; ilevel<nlevels; ++ilevel) { ++nodes[ilevel][i]; i>>=1; } return index; } // Looking up a previous choice is more complex. The nodes must also be updated simultaneously. long PolyaUrn::pick_by_ic(long ic) { auto& nodes = m_nodes; int nlevels = nodes.size(); ++m_current_picks; // Look up the choice in the binary tree. Start at the top and work down. long i = 0L; for (int ilevel=nlevels-1; ilevel>=0; --ilevel) { i <<= 1; if (ic >= nodes[ilevel][i]) { ic -= nodes[ilevel][i]; i += 1; } ++nodes[ilevel][i]; } return i; } <file_sep>/core/Parser.h #pragma once #include <map> #include <set> #include <string> #include "Chromosome.h" class Parser { friend class FileCheckpointer; private : std::map<std::string, std::string> m_map; std::set<std::string> m_used; public: Parser() {}// for creating unassigned variables static bool parseBool ( const std::string& value, const std::string& key = ""); static double parseDouble ( const std::string& value, const std::string& key = ""); static long parseLong ( const std::string& value, const std::string& key = ""); static ChromosomeType parseChromosomeType ( const std::string& value, const std::string& key = ""); static double parseNonNegativeDouble( const std::string& value, const std::string& key = ""); static long parsePositiveLong( const std::string& value, const std::string& key = ""); Parser(std::map<std::string, std::string> map) : m_map(map) {} const std::string& getString(const std::string& key); bool getBool(const std::string& key); double getDouble(const std::string& key); long getLong(const std::string& key); ChromosomeType getChromosomeType(const std::string& key); double getNonNegativeDouble(const std::string& key); long getPositiveLong(const std::string& key); std::string getUnusedKeysAsString() const; std::string toString() const; bool operator==(const Parser& o) const { return m_map == o.m_map && m_used == o.m_used; } }; <file_sep>/core/Logger.h #pragma once #include <cstdio> class Logger { const bool m_verbose; protected: inline void log(const std::string& msg) { if (m_verbose) { printf("%s\n", msg.c_str()); fflush(stdout); } } public: Logger(bool vb) : m_verbose(vb) {} bool verbose() { return m_verbose; } virtual void logEvent(const std::string& msg) { log(msg); } virtual void logProgress(const std::string& msg) { log(msg); } }; <file_sep>/hpc/FileReader.h #pragma once #include <map> #include <string> #include "core/MutationRateHistory.h" #include "core/PopulationStructureHistory.h" class FileReader { public: static std::map<std::string,std::string> parseTOML(std::string input_filename); static PopulationStructureHistory readPopulationStructureHistory(std::string input_filename); static MutationRateHistory readMutationRateHistory(std::string input_filename); static void stopIfFindStopFile(); }; <file_sep>/core/AncestralChromosomes.h #pragma once #include <cstddef> #include "AncestralRecombinationGraph.h" #include "Chromosome.h" #include "HaploBlockVariants.h" #include "PersonNode.h" #include "PopulationStructureHistory.h" /** AncestralChromosomes: Generates and stores the ancestral genetic material of the whole population through all generations by storing, for each ancestral individual, a representation of their two chromosomes, but masked by the 'extancy patterns' that were calculated in the AncestralRecombinationGraph, in order to reduce the amount of information stored. Chromosomes are represented by a set of sequential pairs: block-locus and the allele at that locus. Masked / non-extant regions of chromosomes are represented by UNKNOWN_ALLELE. Contiguous regions with the same allele id are merged into one block-loci/allele-id pair. In practice, the large contiguous regions of UNKNOWN_ALLELE allow the representation to be greatly compressed in memory. */ class AncestralChromosomes { friend class FileCheckpointer; friend class FileMemorySaver; private: AncestralRecombinationGraph* m_graph; HaploBlockVariants* m_variants; // The nodes of the graph. std::vector<std::pair<std::vector<PersonNode>, std::vector<PersonNode>>> m_nodes; public: AncestralChromosomes() : m_graph(nullptr), m_variants(nullptr) {} // for creating unassigned variables bool unassigned() const { return m_nodes.empty(); } AncestralChromosomes( AncestralRecombinationGraph* graph, HaploBlockVariants* variants) : m_graph(graph), m_variants(variants), m_nodes(graph->getNumberOfGenerations()) {} AncestralChromosomes& initialiseFoundingGeneration(); AncestralChromosomes& forwardsDropAllGenerations( const double mu, std::mt19937_64& rng); AncestralChromosomes& forwardsDropOneGeneration(const long gen, const double mu, std::mt19937_64& rng); long getNumberOfGenerations() const { return m_nodes.size(); } const std::vector<PersonNode>& getMales(long gen) const { return m_nodes[gen].first; } const std::vector<PersonNode>& getFemales(long gen) const { return m_nodes[gen].second; } const std::pair<std::vector<PersonNode>, std::vector<PersonNode>>& getGeneration(long gen) const { return m_nodes[gen]; } std::pair<std::vector<PersonNode>, std::vector<PersonNode>>& getExtantGeneration() { return m_nodes[0]; } size_t getSizeInMemory(long gen) const; std::string toString(long gen) const; bool operator==(const AncestralChromosomes&) const; }; <file_sep>/core/BlocksRange.h #pragma once #include <cstddef> #include <functional> #include <random> #include <string> #include <utility> #include <vector> class BlocksRange { template<typename V> friend class Blocks; friend class FileCheckpointer; friend class FileMemorySaver; friend class HaploBlockBoundaries; private: std::vector<long> m_toggles; BlocksRange(std::vector<long>&& toggles) : m_toggles(toggles) {} BlocksRange combine (const BlocksRange &range_A, const BlocksRange &range_B, std::function<bool (bool, bool)> rule) const; public: /** Default constructor */ BlocksRange() {} /** Create BlocksRange where the whole range is empty/false. */ static BlocksRange createEmpty() { return BlocksRange(std::vector<long>{}); } /** Create BlocksRange where the whole range is full/true. */ static BlocksRange createFull() { return BlocksRange(std::vector<long>{0}); } /** Create a BlocksRange with a single flip at the specified location. */ static BlocksRange createOneToggle(long b) { return BlocksRange(std::vector<long>{b}); } /** Create a random BlocksRange which randomly starts as true or false, * and then has a number of flips distributed randomly at the given rate. */ static BlocksRange createRandomToggles(long blocks, double rate, std::mt19937_64& rng); /** Is the whole range empty/false? */ bool empty() const { return m_toggles.empty(); } /** Is the whole range full/true? */ bool full() const { return m_toggles.size() == 1 && m_toggles[0] == 0; } /** Number of blocks included in this range. * Must also pass max_range because BlocksRange does not end of range (for efficiency). */ long getSizeOfRange(long max_range) const; /** Return new BlocksRange, where every subrange that was true is now false, and vice versa. */ BlocksRange inverse() const; /** Return new BlocksRange that is union of 'this' and 'other'. */ BlocksRange unionWith(const BlocksRange& other) const; /** Return new BlocksRange that is union of 'this' and the inverse of 'other'. */ BlocksRange unionWithInverse(const BlocksRange& other) const; /** Return new BlocksRange that is intersection of 'this' and 'other'. */ BlocksRange intersectionWith(const BlocksRange& other) const; /** Return new BlocksRange that is intersection of 'this' and the inverse of 'other'. */ BlocksRange intersectionWithInverse(const BlocksRange& other) const; /** Return new BlocksRange that is symmetric-difference (XOR) between 'this' and 'other'. */ BlocksRange symmetricDifference(const BlocksRange& other) const; bool operator==(const BlocksRange&) const; std::string toString() const; size_t getSizeInMemory() const; }; <file_sep>/core/BlocksRange.cpp #include <algorithm> #include <functional> #include <iterator> #include <random> #include <string> #include <vector> #include "BlocksRange.h" using namespace std; long BlocksRange::getSizeOfRange(long max_blocks) const { long sum = 0L; int n = m_toggles.size(); for (int i=1; i<n; i+=2) { sum += m_toggles[i] - m_toggles[i-1]; } if (n % 2 == 1) { sum += max_blocks - m_toggles[n-1]; } return sum; } BlocksRange BlocksRange::createRandomToggles( long total_blocks, double toggle_rate, mt19937_64& rng) { // Generate how many random toggles there will be. int n_random = poisson_distribution<int>(toggle_rate)(rng); // Generate the toggles uniform_int_distribution<long> random(0, total_blocks-1); long toggles[n_random+1]; int it = 0; if (2 * random(rng) >= total_blocks) toggles[it++] = 0; // Start true or false. for (int i=0; i<n_random; i++) toggles[it++] = random(rng); // Add random toggles. // Sort toggles into order sort(toggles, toggles+it); // Remove duplicates: if there are n toggles the same value, then n <- n % 2 int prev = -1; int n = it; it = 0; for (int i=0; i<n; i++) { if (toggles[i] == prev) { --it; prev = -1; } else { prev = toggles[it++] = toggles[i]; } } // Copy the results into a new vector and return new BlocksRange. return BlocksRange(vector<long>(toggles,toggles+it)); } BlocksRange BlocksRange::inverse() const { int n = m_toggles.size(); vector<long> new_toggles; // If toggles start with 0, remove it. If not, add it. if (!m_toggles.empty() && m_toggles[0] == 0) { new_toggles.reserve(n-1); for (int i=1; i<n; i++) new_toggles.push_back(m_toggles[i]); return BlocksRange(move(new_toggles)); } else { new_toggles.reserve(n+1); new_toggles.push_back(0); for (int i=0; i<n; i++) new_toggles.push_back(m_toggles[i]); return BlocksRange(move(new_toggles)); } } void toggle(bool& value) { value = !value; } BlocksRange BlocksRange::combine ( const BlocksRange &range_A, const BlocksRange &range_B, function<bool (bool, bool)> rule) const { auto iterator_A = range_A.m_toggles.cbegin(); auto iterator_B = range_B.m_toggles.cbegin(); auto end_A = range_A.m_toggles.cend(); auto end_B = range_B.m_toggles.cend(); BlocksRange range_C; auto& toggle_positions_C = range_C.m_toggles; long block = 0; bool toggle_state_A = false; bool toggle_state_B = false; bool toggle_state_C = false; if (iterator_A != end_A && *iterator_A == block) { iterator_A++; toggle(toggle_state_A); } if (iterator_B != end_B && *iterator_B == block) { iterator_B++; toggle(toggle_state_B); } // Check if we need to add a toggle to C at block 0. if (toggle_state_C != rule(toggle_state_A, toggle_state_B)) { toggle_positions_C.push_back(block); toggle(toggle_state_C); } while (iterator_A != end_A && iterator_B != end_B) { // Advance A and/or B to next block where there is a toggle. long next_block_A = *iterator_A; long next_block_B = *iterator_B; if (next_block_A <= next_block_B) { block = *iterator_A++; toggle(toggle_state_A); } if (next_block_B <= next_block_A) { block = *iterator_B++; toggle(toggle_state_B); } // Check if we need to add a toggle to C. if (toggle_state_C != rule(toggle_state_A, toggle_state_B)) { toggle_positions_C.push_back(block); toggle(toggle_state_C); } } while (iterator_A != end_A) { // Advance A to next block where there is a toggle. block = *iterator_A++; toggle(toggle_state_A); // Check if we need to add a toggle to C. if (toggle_state_C != rule(toggle_state_A, toggle_state_B)) { toggle_positions_C.push_back(block); toggle(toggle_state_C); } } while (iterator_B != end_B) { // Advance B to next block where there is a toggle. block = *iterator_B++; toggle(toggle_state_B); // Check if we need to add a toggle to C. if (toggle_state_C != rule(toggle_state_A, toggle_state_B)) { toggle_positions_C.push_back(block); toggle(toggle_state_C); } } return range_C; } BlocksRange BlocksRange::unionWith(const BlocksRange& other) const { return combine(*this, other, [](bool a, bool b){ return a || b; }); } BlocksRange BlocksRange::unionWithInverse(const BlocksRange& other) const { return combine(*this, other, [](bool a, bool b){ return a || !b; }); } BlocksRange BlocksRange::intersectionWith(const BlocksRange& other) const { return combine(*this, other, [](bool a, bool b){ return a && b; }); } BlocksRange BlocksRange::intersectionWithInverse(const BlocksRange& other) const { return combine(*this, other, [](bool a, bool b){ return a && !b; }); } BlocksRange BlocksRange::symmetricDifference(const BlocksRange& other) const { return combine(*this, other, [](bool a, bool b){ return !a != !b; }); } bool BlocksRange::operator==(const BlocksRange& other) const { return equal(this->m_toggles.cbegin(), this->m_toggles.cend(), other.m_toggles.cbegin()); } string BlocksRange::toString() const { if (m_toggles.empty()) return "[empty]"; string s = ""; int last = m_toggles.size() - 1; for (int i=0; i<last; i+=2) { s += "[" + to_string(m_toggles[i]) + "," + to_string(m_toggles[i+1]) + ") "; } if (last%2==0) { s += "[" + to_string(m_toggles[last]) + ",end)"; } return s; } size_t BlocksRange::getSizeInMemory() const { return sizeof(vector<long>) + m_toggles.size() * sizeof(long); } <file_sep>/core/HaploBlockBoundaries.h #pragma once #include <initializer_list> #include <map> #include <random> #include <set> #include <vector> #include "BlocksRange.h" #include "Chromosome.h" /** HaploBlockBoundaries: Stores the boundaries where recombination events could happen, or are recorded to have happened, along the simulated chromosome. Used to generate new random recombination patterns and primordial haplotype block patterns (a haplotype block is a section of chromosome within which no recombination happens). Records which boundaries are actually used in order to define observable haplotype blocks (sections of chromosomes where no ancestral recombinations were observed to happen even if they logically could have). */ class HaploBlockBoundaries { friend class FileCheckpointer; private: std::vector<LocusId> m_block_boundaries; std::map<LocusId,long> m_block_boundary_used; public: HaploBlockBoundaries() {} // for creating unassigned variables HaploBlockBoundaries(long chromosome_length, long max_blocks, std::mt19937_64& rng); BlocksRange createRandomRecombinationPattern(double rate, std::mt19937_64& rng) const; long getChromosomeLength() const { return m_block_boundaries.back(); } void recordBlockBoundaries(const BlocksRange&); std::vector<LocusId> getRecordedBlockBoundaries() const; std::vector<LocusId> getRandomBlockBoundaries(long nblocks, std::mt19937_64& rng) const; std::string toString() const; bool operator==(const HaploBlockBoundaries&) const; }; <file_sep>/hpc/LoggerSmart.h #pragma once #include <ctime> #include "../core/Logger.h" class LoggerSmart : public Logger { private: const long minimum_interval; long previous_log_time; public: LoggerSmart(bool vb, long min_int) : Logger(vb), minimum_interval(min_int*CLOCKS_PER_SEC), previous_log_time(-min_int*CLOCKS_PER_SEC) {} virtual void logEvent(const std::string& msg) { log(msg); previous_log_time = -minimum_interval; } virtual void logProgress(const std::string& msg) { long current_time = clock(); if (current_time < previous_log_time + minimum_interval) return; previous_log_time = current_time; log(msg); } }; <file_sep>/hpc/FileSNPsWriter.cpp #include "FileSNPsWriter.h" #include <algorithm> #include <fstream> #include <iostream> using namespace std; void FileSNPsWriter::WriteSNPs( const string& output_filename, const HaploBlockVariants& variants, const pair<vector<PersonNode>, vector<PersonNode>>& whole_generation, mt19937_64& rng) { const long total_blocks = variants.getNumberBlocks(); const auto& boundary_loci = variants.getBlockBoundaries(); const long total_males = whole_generation.first.size(); const long total_females = whole_generation.second.size(); const long total_chromosomes = 2 * (total_males + total_females); ofstream ofs(output_filename, ofstream::out | ofstream::app); ofs << "NAMES"; for (int i=0; i<total_chromosomes; ++i) ofs << '\t' << i; ofs << endl; ofs << "REGION\tchr\t0\t" + to_string(boundary_loci.back()) << endl; // For every haplotype block. for (long ib=0; ib<total_blocks; ++ib) { LocusId block_locus = boundary_loci[ib]; LocusId last_locus = boundary_loci[ib+1]-1; const MutationGraph& graph = variants.getMutationGraph(block_locus); // Get the position/allele pairs const auto allele_ids = graph.getAlleleIds(); vector<pair<LocusId,AlleleId>> mutation_positions_alleles; for (AlleleId allele_id : allele_ids) { const auto nmuts = graph.getNumberOfMutations(allele_id); const auto& muts = graph.getMutations(allele_id); if ((size_t)nmuts == muts.size()) { for (int i=0; i<nmuts; ++i) { LocusId mut = muts[i].first; mutation_positions_alleles.emplace_back(mut,allele_id); } } else { for (int i=0; i<nmuts; ++i) { LocusId mut = uniform_int_distribution<long>(block_locus,last_locus)(rng); mutation_positions_alleles.emplace_back(mut, allele_id); } } } // Sort and space them, throw away any that don't fit. auto& vec = mutation_positions_alleles; sort(vec.begin(), vec.end()); const int nsites = vec.size(); const long block_length = last_locus - block_locus + 1; if ((size_t)block_length<vec.size()) vec.resize(block_length); for (int i=1; i<nsites; ++i) { if (vec[i-1].first>=vec[i].first) { vec[i].first=vec[i-1].first + 1; } while (vec[i].first>last_locus) { vec[i].first--; for (int j=i-1; j>=0; --j) { if (vec[j].first==vec[j+1].first) vec[j].first--; } } } // For every position in order on the block. for (auto& entry : mutation_positions_alleles) { const LocusId position = entry.first; const AlleleId source_allele_id = entry.second; string line(total_chromosomes, ' '); int ic=0; for (auto* persons : { &whole_generation.first, &whole_generation.second }) for (auto& person : *persons) for (auto* chromosome : { &person.chromosomeFromFather, &person.chromosomeFromMother }) { AlleleId allele = chromosome->getValue(block_locus); bool variant_present = graph.isDerivativeAllele(source_allele_id, allele); line[ic++] = variant_present ? 'A' : 'C'; } ofs << position << '\t' << line << endl; } } } <file_sep>/core/GraphDataBinned2D.h #pragma once #include <cmath> #include <string> #include <vector> class GraphDataBinned2D { public: std::vector<std::vector<double>> m_weight_bins; std::vector<std::vector<double>> m_value_bins; std::pair<double,double> m_range_x; std::pair<double,double> m_range_y; double m_delta_inv_x; double m_delta_inv_y; bool m_bin_includes_upper_bound; /** Create a data-structure for summarising data in bins for graphs. */ GraphDataBinned2D(std::pair<double,double> range_x, std::pair<double,double> range_y, std::size_t nbins, bool bin_includes_upper_bound = false) : m_weight_bins(nbins, std::vector<double>(nbins)), m_value_bins(nbins, std::vector<double>(nbins)), m_range_x(range_x), m_range_y(range_y), m_delta_inv_x(nbins/(range_x.second-range_x.first)), m_delta_inv_y(nbins/(range_y.second-range_y.first)), m_bin_includes_upper_bound(bin_includes_upper_bound) {} // For making copies, but with data zeroed, for use in omp parallel for loops. GraphDataBinned2D zeroedCopy() { return GraphDataBinned2D(m_range_x, m_range_y, m_value_bins.size(), m_bin_includes_upper_bound); } /** Sample the value at a particular position. */ inline void sampleValue(double x, double y, double value, double multiplier = 1.0) { const long n = (long)m_weight_bins.size(); double ifltx = m_delta_inv_x * (x - m_range_x.first); double iflty = m_delta_inv_y * (y - m_range_y.first); long ix = m_bin_includes_upper_bound ? ceil(ifltx) - 1 : ifltx; long iy = m_bin_includes_upper_bound ? ceil(iflty) - 1 : iflty; if (ix < 0 || ix >= n) return; if (iy < 0 || iy >= n) return; m_weight_bins.at(ix).at(iy) += multiplier; m_value_bins.at(ix).at(iy) += value * multiplier; } /** Sample weight at a particular position. */ inline void sampleWeight(double x, double y, double multiplier = 1.0) { sampleValue(x, y, 0.0, multiplier); } std::string toString(bool endbar=false) const; // For reduction in omp parallel for loops. GraphDataBinned2D& merge(GraphDataBinned2D& other); };
0d140563fedc0a466102eadd7c08e090b397d00e
[ "Markdown", "Makefile", "C", "C++", "Shell" ]
50
C++
DiscoveryInstitute/haplo
c2b49bc0920aaf68f4364646a30ef2614329b103
c7f8709216b07b297d311dd0f8f0c38a9776fc95
refs/heads/master
<file_sep>/* The four principles of "this"; * in your own words. explain the four principle for the "this" keyword below. * * 1. calling this in the global scope you the window/console object or 'the whole code' * 2. implicit binding, in a function called with a dot preceding 'this' refers to the object to the left of the dot * 3. whenever we use a constructor function, 'this' refers to the object that the function is returning * 4. using .call .apply or .bond can tell .this exactly what to bind to * * write out a code example of each explanation above */ // Principle 1 // code example for Window Binding function say(name){ //console.log(this); } say('ricardio'); // Principle 2 // code example for Implicit Binding const anObj = { ficAnimal : 'sneef', getAnimal : function (existence){ //console.log(this.ficAnimal + " " + existence); } } anObj.getAnimal('is fictional'); // Principle 3 // code example for New Binding function ships(kind){ this.phrase = 'look a '; this.end = ' ship'; this.kind = kind; this.exclaim = function(){ console.log(this.phrase + this.kind + this.end); } } const float = new ships('regular'); const fly = new ships('space'); float.exclaim(); fly.exclaim(); // Principle 4 // code example for Explicit Binding function dog(name){ this.word = "good doggy, " this.name = name; this.good = function(){ console.log(this.word + this.name); } } const dog1 = new dog('whistle'); const dog2 = new dog('randy'); dog1.good(); dog1.good.call(dog2);
29a50d5e6d4149632e78841795942841f22f891d
[ "JavaScript" ]
1
JavaScript
BlakeAnd/JavaScript-III
cf7c3fb723c5860ab07ed33c52e103230eee00e9
68b07046dd46e47337922cfcefff113399b8bdf0
refs/heads/master
<file_sep>$(document).ready(function(){ $(".r1").buttonset(); $('#keyword').tagEditor({initialTags:[],delimiter:',',maxLength:10,placeholder:'文章关键字...'}); }); //保存文章 function saveadd(){ //改变提交按钮为disabled状态,防止重复提交 $('#savebtn').attr("disabled",true).find("i").removeClass("icon-save").addClass("icon-spinner icon-spin").next().text("发布中"); //将整个表单POST给接口 $.post('/?action/11_1',$('#form1').serialize(),function(d){ if (!d.error) { swal({ title: "恭喜您", text: d.success, type: "success", showCancelButton: true, confirmButtonClass: "btn-success", confirmButtonText: "继续发布", cancelButtonText: "不加了,回首页", closeOnConfirm: false, closeOnCancel: false }, function(isConfirm) { if (isConfirm) { location.href='/?view/add'; } else { location.href='/?index'; } }); } else { swal({title:"出错了",text:""+d.error+"",type:"error",confirmButtonClass:"btn-danger"}); }; //恢复提交按钮 $('#savebtn').removeAttr("disabled").find("i").removeClass("icon-spinner icon-spin").addClass("icon-save").next().text("发布"); },'json'); }; //保存文章 function saveedit(){ //改变提交按钮为disabled状态,防止重复提交 $('#savebtn').attr("disabled",true).find("i").removeClass("icon-save").addClass("icon-spinner icon-spin").next().text("修改中"); //将整个表单POST给接口 $.post('/?action/11_1',$('#form1').serialize(),function(d){ if (!d.error) { swal({ title: "恭喜您", text: d.success, type: "success", showCancelButton: false, confirmButtonClass: "btn-success", closeOnConfirm: false }, function() { location.href='/?index'; }); } else { swal({title:"出错了",text:""+d.error+"",type:"error",confirmButtonClass:"btn-danger"}); }; //恢复提交按钮 $('#savebtn').removeAttr("disabled").find("i").removeClass("icon-spinner icon-spin").addClass("icon-save").next().text("修改"); },'json'); }; function showhide(n){ $('#showhide_div'+n).show(); $('#showhide_btn'+n).attr("onClick","") }; //动态添加图片表单项 function addimg() { var j = $('.pic_list').length var num; if (j>0){num=j}else{num=0}; var _temp = "<div class=\"control-group pic_list\" id=\"pic_list"+num+"\">" _temp += "<div class=\"controls\">" _temp += "<div class=\"input-prepend input-append\" style=\"margin-bottom:2px;\">" _temp += "<span class=\"add-on\">图片地址</span>" _temp += "<input class=\"input-xlarge picadd"+num+"\" name=\"picadd\" type=\"text\">" _temp += "<scr"+"ipt type=\"text/plain\" id=\"upload_ue"+num+"\" style=\"display:none;\"><\/scr"+"ipt>" _temp += "<Button class=\"btn btn-success\" type=\"Button\" onClick=\"upImage("+num+");\"><i class=\"icon-upload\"></i> 上传</Button></div>" _temp += "<div class=\"input-prepend input-append\" style=\"margin-bottom:2px;\">" _temp += "<span class=\"add-on\">图片标题</span>" _temp += "<input class=\"input-xlarge\" name=\"pictitle\" type=\"text\">" _temp += "<span class=\"add-on\" style=\"background-color:#fff;\"><label>" _temp += "<input type=\"radio\" name=\"coverImg\" value=\""+num+"\" style=\"margin:0px;padding:0px;display:inline-block;margin-bottom:0;vertical-align:middle;\">" _temp += " 设为封面</label></span></div>" _temp += "<div class=\"input-prepend input-append\" style=\"margin-bottom:2px;\">" _temp += "<span class=\"add-on\">图片链接</span>" _temp += "<input class=\"input-xlarge\" name=\"picurl\" type=\"text\" value=\"http://\">" _temp += "<Button class=\"btn btn-danger\" type=\"Button\" onClick=\"delImage("+num+");\"><i class=\"icon-trash\"></i> 删除图片</Button></div></div></div>" $("#pic_list").append(_temp); $('#picnum').val(num); UE.getEditor('upload_ue'+num).ready(function(){ UE.getEditor('upload_ue'+num).setDisabled(); UE.getEditor('upload_ue'+num).hide(); UE.getEditor('upload_ue'+num).addListener('afterUpfile',function(t,arg){ //$(".picadd"+num).attr("value",arg[0].url); $(".picadd"+num).val(arg[0].url); }); }); _temp = ""; }; //弹出图片上传的对话框 function upImage(i) { //var myImage = _editor.getDialog("attachment"); UE.getEditor('upload_ue'+i).getDialog("attachment").open(); }; function delImage(i){ var j = $('.pic_list').length; var picnum = $('#picnum').val(); $('#picnum').val(picnum-1); if (j==0){ $("#add_btn0").show(); }; $("#pic_list"+i).remove(); }; UE.getEditor('upload_ue999').ready(function(){ UE.getEditor('upload_ue999').setDisabled(); UE.getEditor('upload_ue999').hide(); UE.getEditor('upload_ue999').addListener('afterUpfile',function(t,arg){ //$(".picadd"+num).attr("value",arg[0].url); $(".fileURL").val(arg[0].url); }); }); //弹出图片上传的对话框 function upImage1() { //var myImage = _editor.getDialog("attachment"); UE.getEditor('upload_ue999').getDialog("attachment").open(); }; //动态添加下载地址表单项 function adddown() { var j = $('.down_list').length var num = j + 1; var _temp = "<div class=\"control-group down_list\" id=\"down_list"+num+"\">" _temp += "<div class=\"controls\"><select id=\"down_type\" name=\"down_type\" class=\"span2\"><option value=\"0\" selected>迅雷下载</option><option value=\"1\">旋风下载</option><option value=\"2\">电驴下载</option><option value=\"3\">磁力下载</option><option value=\"4\">本地下载</option><option value=\"5\">官方下载</option><option value=\"6\">云盘下载</option></select>" _temp += "<div class=\"input-append\">" _temp += "<input class=\"input-xlarge fileadd"+num+"\" name=\"text_downURL\" type=\"text\">" _temp += "<scr"+"ipt type=\"text/plain\" id=\"upfile_ue"+num+"\" style=\"display:none;\"><\/script>" _temp += "<Button class=\"btn btn-success\" type=\"Button\" onClick=\"upfile("+num+");\"><i class=\"icon-upload\"></i> 上传</Button>" _temp += "<Button class=\"btn btn-danger\" type=\"Button\" onClick=\"delfile("+num+");\"><i class=\"icon-trash\"></i> 删除</Button>" _temp += "</div></div></div>"; $("#down_list").append(_temp); $('#filenum').val(num); UE.getEditor('upfile_ue'+num).ready(function(){ UE.getEditor('upfile_ue'+num).setDisabled(); UE.getEditor('upfile_ue'+num).hide(); UE.getEditor('upfile_ue'+num).addListener('afterUpfile',function(t,arg){ //$(".picadd"+num).attr("value",arg[0].url); $(".fileadd"+num).val(arg[0].url); }); }); _temp = ""; }; //弹出图片上传的对话框 function upfile(i) { //var myImage = _editor.getDialog("attachment"); UE.getEditor('upfile_ue'+i).getDialog("attachment").open(); }; function delfile(i){ var j = $('.down_list').length; var filenum = $('#filenum').val(); $('#filenum').val(filenum-1); if (j==0){ $("#addfile_btn0").show(); }; $("#down_list"+i).remove(); }; function add_val(inputstr,str,type) { var tempstr = $('#'+inputstr).val(); if (type=="0") { if (tempstr==""){ $('#'+inputstr).val(str); }else{ $('#'+inputstr).val(tempstr+","+str); } }; if (type=="1") { $('#'+inputstr).val(str); }; };<file_sep># asp website based on asp vbscript and javascript <file_sep>$(document).ready(function(){ //悬停提示 $('body').tooltip({ selector: "[data-toggle=tooltip]" }); $('#slider').nivoSlider(); $('.apply img').jqthumb({ width: 221, height: 150, after: function(imgObj){ imgObj.css('opacity', 0).animate({opacity: 1},1000); } }); $('pre').addClass('prettyprint linenums') //格式化内容 uParse('#view_body', { rootPath: 'inc/public/ueditor-1.4.3/' }); $("#keystr").keyup(function() { if (event.keyCode == 13) { location.href = '/?a=s&k=' + $('#keystr').val(); } }); }); var jam = { post: function(url, params, fn) { if (!fn && typeof params == "function") { fn = params; params = {}; } $.post(url, params, function(data) { fn(data); }, 'json'); } } //翻页 function gopage(type,id,page){ if (type == "index") { location.href='/?board/0/'+page+'.html'; }else{ location.href='/?board/'+id+'/'+page+'.html'; } }; //用户登录 function login(){ if($("#autologin").prop("checked")){autologin='0'}else{autologin='1'} $.post('/?action/0_1', { password: <PASSWORD>').val(), autologin: autologin }, function(d) { if (!d.error) { swal({ title: "恭喜您", text: d.success, type: "success", showCancelButton: false, confirmButtonClass: "btn-success", closeOnConfirm: false }, function() { parent.location.href='/?index'; }); } else { swal({title:"出错了",text:""+d.error+"",type:"error",confirmButtonClass:"btn-danger"}); }; }, 'json'); } //用户登录 function logout(){ location.href='/?action/1_1'; } //搜索 function search() { location.href = '/?a=s&k=' + $('#keystr').val(); } function postfrom_(action, id) { $.get("/?action/"+action+"_"+id+".html",function(d) { if (!d.error) { swal({ title: "恭喜您", text: d.success, type: "success", showCancelButton: false, confirmButtonClass: "btn-success", closeOnConfirm: false }, function() { location.reload(); }); } else { swal({ title: "出错了", text: "" + d.error + "", type: "error", confirmButtonClass: "btn-danger" }); return; }; }, 'json'); } //文章分享 window._bd_share_config = { "common": { "bdSnsKey": {}, "bdText": "", "bdMini": "2", "bdMiniList": false, "bdPic": "", "bdStyle": "1", "bdSize": "24" }, "share": {} }; with(document) 0[(getElementsByTagName('head')[0] || body).appendChild(createElement('script')).src = 'http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion=' + ~ (-new Date() / 36e5)];<file_sep>// FileConverter.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <tchar.h> #include <stdio.h> #include <windows.h> int _tmain(int argc, _TCHAR* argv[]) { char fname_src[MAX_PATH]; char fname_dest[MAX_PATH]; char line[1024]; printf("input the src file:\n"); gets(fname_src); printf("input the dest file:\n"); gets(fname_dest); FILE* stream1 = fopen(fname_src, "r"); FILE* stream2 = fopen(fname_dest, "w"); int lineSize, lineNo = 0; BOOL bBegin = FALSE; while(fgets(line, _ARRAYSIZE(line), stream1) != NULL) { //滤掉结尾的\n lineSize = strlen(line); if(lineSize > 0 && line[lineSize - 1] == '\n') { line[lineSize - 1] = 0; lineSize--; } //可以开始转化了吗 if(strcmp(line, "[A]") == 0) { bBegin = TRUE; strcat(line, "\n"); fputs(line, stream2); continue; } if(!bBegin || line[0] == ';' || line[0] == '[' || lineSize == 0) { strcat(line, "\n"); fputs(line, stream2); continue; } //分解单词 char* pToken = strtok(line, " "); while(pToken != NULL) { fputs(pToken, stream2); fputs("\n", stream2); pToken = strtok(NULL, " "); } ++lineNo; if((lineNo & 0x3F) == 0x3F) { fflush(stream2); } } fclose(stream1); fclose(stream2); printf("It's Done!\n"); return 0; } <file_sep>var easp = "EasyAsp";<file_sep>; ------------------------------------------------------- ; 配置所有语言和配置文件 ; ; ; Default: 程序启动后默认选中的语言(它必须是Enabled) ; ; Enabled [+Index]: ; ; 是否启用该语言,关闭不常用语言以减小内存需求 ; ; ------------------------------------------------------- [Languages] Count=4 Default=1 Enabled1=1 Item1=C/C++ File1=Dicts\cpp.txt Enabled2=1 Item2=C# File2=Dicts\csharp.txt Enabled3=1 Item3=SQL File3=Dicts\sql.txt Enabled4=1 Item4=JavaScript File4=Dicts\js.txt ; ------------------------------------------------------- ; 通用配置,例如边框样式 ; ------------------------------------------------------- [Common] BorderStyle=border:1px solid #ccc; BaseStyle=font-family:Courier New;font-size:12px; ; ------------------------------------------------------- ; 特殊字符,需要转换的 ; ------------------------------------------------------- [SpecialChars] Count=3 Item1=< &lt; Item2=> &gt; Item3=& &amp; ; -------------------------------------------------------- ; 以下是颜色配置 ; Html: 该颜色在HTML代码中的属性字符串 ; Real: 16 进制表示的 RGB,用于显示在 RichEdit 中的颜色 ; ; 关键字分组: ; ; 关键字一共支持4组,在语言配置文件中,每个单词开头可以用 ; 0,1,2,3 字符表示这个关键字是第几组,如果没有数字,则默认 ; 被归类为第0组; ; ; -------------------------------------------------------- [Comment] Html=#008000 Real=RGB(0,0x80,0) [String] Html=#91268F Real=RGB(0x91,0x26,0x8F) [Number] Html=red Real=RGB(0xFF,0,0) [LineNumber] Html=#008080 Real=RGB(0,0x80,0x80) [Keyword0] Html=blue Real=RGB(0,0,0xFF) [Keyword1] Html=#2B91AF Real=RGB(43,145,175) [Keyword2] Html=blue Real=RGB(0,0,0xFF) [Keyword3] Html=blue Real=RGB(0,0,0xFF)
6b1c5c79c042987a662a8779b32343c141086a48
[ "JavaScript", "C++", "Markdown", "INI" ]
6
JavaScript
HugoChen1024/asp
28dae7803e16a868755024a7bfb1414e98b2a746
cbd102ec657a7160aaeb71a63df4d88ec02ce405
refs/heads/master
<file_sep># python's equivalent of # javascript object spread. python >= 3.5 def hello(a: int, b: str, c: float): print('a:', a) print('b:', b) print('c:', c) obj = {'a': 10, 'b': 'jack', 'c': 1.32} # this will no work. # TypeError: hello() missing 2 required positional arguments: 'b' and 'c' # print(hello(obj)) # use single `*` to spread `obj` and # map to hello args based on the order print('- printing `hello()` using single asterisk (*obj):') print(hello(*obj)) print() # use double `**` to spread `obj` and # map to hello args accordingin to `obj` keys print('- printing `hello()` using double asterisk (**obj):') print(hello(**obj)) print() # this will not work because key `a` is missing (deleted) del obj['a'] print(hello(**obj)) <file_sep>package main import ( "fmt" "log" "os" "strconv" "strings" "time" "github.com/wzulfikar/lab/go/imagescraper" ) // scraper file:///Users/strawhat/Desktop/Faculties.webarchive ".card__thumbnail img" // output: {image title|alt}_{filename}.jpg func main() { if len(os.Args) < 3 { fmt.Println("Usage: scraper [url] [selector] [dir]") return } url := os.Args[1] selector := os.Args[2] dir := os.Args[3] const scraperConcurrency = 5 countImages := 0 defer func() func() { start := time.Now() return func() { fmt.Printf("[DONE] Images scraped: %d\n", countImages) fmt.Println("Time elapsed:", time.Since(start)) } }()() if newUrl, from, to, pageOk := getUrlPage(url); pageOk { concurrency := 5 sem := make(chan bool, concurrency) for i := from; i <= to; i++ { sem <- true go func(i int) { defer func() { <-sem }() targetUrl := newUrl + strconv.Itoa(i) fmt.Printf("[START] %s\n", targetUrl) images := imagescraper.Scrape(targetUrl, selector, dir, scraperConcurrency) countImages += len(images) fmt.Println("[DONE]", targetUrl) }(i) } for i := 0; i < cap(sem); i++ { sem <- true } return } fmt.Println("Scraping images from", url) images := imagescraper.Scrape(url, selector, dir, scraperConcurrency) countImages = len(images) } func getUrlPage(url string) (string, int, int, bool) { param := strBetween(url, "[", "]") if param == "" || !strings.Contains(param, "-") { return "", 0, 0, false } page := strings.Split(param, "-") if len(page) != 2 { return "", 0, 0, false } page1, err := strconv.Atoi(page[0]) if err != nil { return "", 0, 0, false } page2, err := strconv.Atoi(page[1]) if err != nil { return "", 0, 0, false } if page1 >= page2 { log.Fatal("ERROR: URL contains invalid page. `page1` must be smaller than `page2`.") } url = strings.Replace(url, "["+param+"]", "", -1) return url, page1, page2, true } func strBetween(str string, a string, b string) string { // Get substring between two strings. posFirst := strings.Index(str, a) if posFirst == -1 { return "" } posLast := strings.Index(str, b) if posLast == -1 { return "" } posFirstAdjusted := posFirst + len(a) if posFirstAdjusted >= posLast { return "" } return str[posFirstAdjusted:posLast] } <file_sep>Exercises, practices, gist, etc. are stored here. If you want to discuss anything related to whatever you find inside this repo, visit [this link](https://github.com/wzulfikar/lab/issues) and click the "New issue" button.<file_sep>package main import ( "fmt" "sync" "time" ) type task struct { name string durationInSec int64 } // function that simulates running task (using sleep) func worker(name string, timeInSecs int64, wg *sync.WaitGroup) { defer wg.Done() fmt.Println("[STARTED]", name, ": Should take", timeInSecs, "seconds") // sleep for a while to simulate time consumed by event time.Sleep(time.Duration(timeInSecs) * time.Second) fmt.Println("[FINISHED]", name) } // Function to display total execution time // Usage: // defer timer()() func timer() func() { start := time.Now() return func() { fmt.Println("\nTotal execution time:", time.Since(start)) } } func main() { // use `defer` to display total // execution time when `main` finished defer timer()() var wg sync.WaitGroup var tasks = []task{ {"Task 1 - Longer Jump", 6}, {"Task 2 - Short Jump", 2}, {"Task 3 - Long Jump", 4}, } for _, task := range tasks { wg.Add(1) // try remove the `go` to run our tasks without // concurrency and see the diff in total execution time. go worker(task.name, task.durationInSec, &wg) } fmt.Println("→", len(tasks), "tasks are executed as go routines..") // go routine can't exist if the main thread has exited. // use `wg.Wait()` so the main thread won't exit before // items in WaitGroup finished. wg.Wait() } <file_sep>package main import ( "net/http" "net/url" "github.com/cssivision/reverseproxy" ) func main() { path, err := url.Parse("https://github.com") if err != nil { panic(err) return } handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { proxy := reverseproxy.NewReverseProxy(path) proxy.ServeHTTP(w, r) }) http.ListenAndServe(":8080", handler) } <file_sep>--- title: "SSH for Everyday Use" date: 2018-03-07T17:19:17+08:00 tags: [""] draft: true --- `TODO: write content` private key starts ``` -----BEGIN RSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: AES-128-CBC,BC89BA4DC3C8888DC41FDE0A302F5197 <KEY> ... redacted ... <KEY> <KEY> -----END RSA PRIVATE KEY----- ``` public key starts with (open ssh) "ssh-rsa" + key + comment - portion of public key is a "comment". you can remove it, or use it to identify info related to the public key. ``` ssh-rsa AAAAB3NzaC1yc2EAAAA...(redacted)...Fi9wrf+M7Q== [email protected] ``` change ssh private password (rarely). can also use to add password to existing private key: `ssh-keygen -p -f ~/.ssh/id_rsa` regenerating public key from private key: `ssh-keygen -t dsa -y > ~/.ssh/id_dsa.pub` common error: - `chmod 400 mykey.pem` (permission) (or chmod 600?) - reset host (remove from known_host): `ssh-keygen -R {hostname}`, ie. `ssh-keygen -R server.mydomain.com` https://blogs.oracle.com/pranav/how-to-send-message-to-users-logged-on-to-a-unix-terminal <p class="text-center">***</p> *Outline:* 1. difference public vs private key - how to easily tell if it's private or public 2. securing private key with password 3. adding public key to authorized_keys 4. revoking private key 5. <file_sep>package templates const Resolver = `package resolvers import ( "context" "errors" "strconv" graphql "github.com/neelance/graphql-go" {{ if .HasScalar }} "{{.Repo}}/modules/graphql/scalar" {{ end }} "{{.Repo}}/models" ) type {{.ResolverName}} struct { rr *{{.RootResolver}} o *models.{{.TypeName}} } func (rr *{{.RootResolver}}) {{.TypeName}}(ctx context.Context, args struct{ ID graphql.ID }) (*{{.ResolverName}}, error) { id, err := strconv.Atoi(string(args.ID)) if err != nil { return nil, errors.New("Failed to get ID of {{.TypeName}}") } o, err := models.Find{{.TypeName}}(rr.Db, uint(id)) if err != nil { return nil, errors.New("{{.TypeName}} not found") } return &{{.ResolverName}}{rr: rr, o: o}, nil } ` <file_sep>// Thu, 27 Apr 2017 at 17:49:43 MYT #include <iostream> #include <vector> #include <queue> using namespace std; #define INF (1<<30) #define pii pair<int, int> #include <cstdlib> void pause () { // pause the loop to observe changes in graph cout << "Press enter to continue ..."; cin.get(); } void clear_screen() { #ifdef WINDOWS std::system("cls"); #else // Assume POSIX std::system ("clear"); #endif } vector< vector<char> > graph; // char graph[size][size] // U R D L int dr [] = {-1, 0, 1, 0}; // vector<int> dr = {-1, 0, 1, 0}; int dc [] = { 0, 1, 0, -1}; // vector<int> dc = { 0, 1, 0, -1}; vector< vector <int> > dist; void generateGraph(int row, int col, char symbol) { graph.resize(row); dist.resize(row); for (int i=0; i < row; i++) { graph[i].assign(col, symbol); dist[i].assign(col, INF); } } template<class T> void displayGraph(vector< vector<T> >grid_2d) { for (int i=0; i < grid_2d.size(); i++) { for (int j=0; j < grid_2d[0].size(); j++) { if (grid_2d[i][j] == INF) { cout << "# "; } else { cout << grid_2d[i][j] << " "; } } cout << endl; } cout << endl; } bool isInside(int nr, int nc) { if (nr >= 0 && nr < graph.size() && nc >= 0 && nc < graph[0].size()) { return true; } return false; } /** * Recursive function * * @param sr [description] * @param sc [description] */ void bfs(int sr, int sc) { dist[sr][sc] = 0; queue< pii > q; q.push(make_pair(sr, sc)); while(!q.empty()){ pii cur = q.front(); q.pop(); for (int i=0; i< sizeof(dr); i++) { int nr = cur.first + dr[i]; int nc = cur.second + dc[i]; if (isInside(nr, nc)) { int new_distance = dist[cur.first][cur.second] + 1; if (new_distance < dist[nr][nc]) { dist[nr][nc] = new_distance; q.push(make_pair(nr, nc)); pause(); clear_screen(); displayGraph<int>(dist); } } } } // if (graph[sr][sc] != '#') return; // base case // graph[sr][sc] = depth; // for (int i = 0; i < sizeof(dr); i++) { // int nr = sr + dr[i]; // int nc = sc + dc[i]; // if (isInside(nr, nc)) { // dfs(nr, nc, depth + 1); // } // } } int main (){ generateGraph(5, 5, '#'); displayGraph<char>(graph); displayGraph<int>(dist); bfs(2, 2); displayGraph<int>(dist); return 0; }<file_sep>package main import ( "fmt" "log" ) func main() { defer func() { if err := recover(); err != nil { log.Printf("Something went wrong: %v\n", err) } }() // trigger panic with division by zero for i := 3; i >= 0; i-- { fmt.Printf("%d divided by %d is %d\n", 3, i, 3/i) } } <file_sep>Go WASM (Web Assembly) demo codes. Deployed to https://gowasm.surge.sh <file_sep>package main import "fmt" func main() { test := "hello*" fmt.Println(test[0 : len(test)-1]) } <file_sep>--- title: "Logstash and ETL" date: 2019-03-07T01:14:10+08:00 draft: true post_id: 26 aliases: [ "/posts/26", ] --- This is a post on how I try to relate ETL process when working with Logstash. In data-warehouse terminology, ETL (extract, transform, load) is a process where we extract data from its source, do any necessary transformation to that data, and load it to data repository. Logstash, on the other hand, is an open-source tool that can do such process. <!--more--> ### Scenario Let's assume that we are maintaining a messaging service that on top of storing messages in database, it also writes timestamp of message, message id, and message body to a log file. We want to have ability to query message body but we are not allowed to access the database. We have access to the log file, but the message body that's written there is hex-encoded. Here's a sample of the log file: ``` 2019-03-07T01:54:01+0800 1239823 54686520717569636b2062726f776e20f09fa68a206a756d7073206f766572203133206c617a7920f09f90b62e 2019-03-07T01:55:01+0800 4339822 6e6f7720796f7520736565206d6521 2019-03-07T01:57:11+0800 4339825 6920776173206865782d656e636f646564207573696e67206f6e6c696e6520746f6f6c2061742068747470733a2f2f637279707469692e636f6d2f70697065732f6865782d6465636f646572 2019-03-07T02:04:01+0800 4332825 49207573656420746f207468696e6b20492077617320696e64656369736976652e20427574206e6f772049276d206e6f7420746f6f20737572652e 2019-03-07T02:05:10+0800 4314225 4c6966652069732073686f72742e20536d696c65207768696c6520796f75207374696c6c206861766520746565746821 2019-03-07T02:08:00+0800 4314320 416c776179732072656d656d626572207468617420796f7527726520756e697175652e202a4a757374206c696b652065766572796f6e6520656c73652a2e ``` **Note** Above log file is space-separated value where the first column is message timestamp, followed by message id, and then the hex-encoded message body. To see the plaintext version of the first message body, we need to convert the message body from hex to ascii. Here's one way to do it (in ruby): ![decode hex to ascii using ruby](/images/irb-decode-hex.png) > Using ruby `pack('H*')` to decode hex, we know that `5468652071..` decodes to `The quick brown..`. ### The Plan We know that we won't be able to query the messages without transforming the message body from hex to plain text. So, we come up with a plan: 1. Send the log file from its original location (ie. a vps where the service is running) to a *transformation layer* 2. Tell the *transformation layer* to convert each hex-encoded message body to plain text 3. Push the transformed log to our data repository 4. Query the messages from data repository ### Solution This is the part where we relate ETL with Logstash, as we implement a solution for above plan. To begin with, we'll create a Logstash configuration that represents our solution: {{< highlight plaintext "linenos=table" >}} input { file { path => "/var/log/messaging-service/messages.log" } } filter { grok { match => "%{TIMESTAMP_ISO8601:timestamp} %{WORD:message_id} %{WORD:body_hex}" } mutate { add_field => ["decode_error"] } ruby { # attempt hex-decode if payload doesn't contain # whitespace and its length is even number. code => " body_hex = event.get('[body_hex]') maybeHex = ... begin if maybeHex event.set('[body_plain]', [body_hex].pack('H*')) end rescue Exception => e event.set('[decode_error]', e.to_s()) end " } } output { file { path => "/opt/messaging-service/messages-plain.log" } } {{< / highlight >}} plan: - parse each line in logfile to *extract* timestamp, message id, and body to its respective fields. related: `input` - *transform* the hex-encoded body to plaintext and store it to new field (body_plain). related: `filter` - *load* the transformed log to output (file, elasticsearch, stdout, etc.). related: `output` create filter. test in https://grokdebug.herokuapp.com ``` %{TIMESTAMP_ISO8601:timestamp} %{WORD:message_id} %{WORD:body_hex} ``` ### What's next? <file_sep>--- title: "GraphQL + SQLBoiler Generator" date: 2018-03-05T00:21:19+08:00 tags: ["go", "sqlboiler", "graphql"] draft: false --- This note as a continuation of my journey with Go template. Based on the knowledge of what template package can do, we'll generate a resolvers code from a given sqlboiler model struct to to satisfy graphql implementation of neelance/graphql-go. <!--more--> ## Synopsis I'm working on a project that uses MySQL as database, and wanted to have GraphQL implemented. To handle the database, we'll use SQLBoiler from [volatiletech/sqlboiler](https://github.com/volatiletech/sqlboiler) (they've very good documentation!). As for the GraphQL, we'll use [neelance/graphql-go](http://github.com/neelance/graphql-go). Now, the flow to implement the GraphQL is: 1. GraphQL endpoint starts with a root resolver, ie. `RootResolver`. A sample code would look like this: ```go // import graphql "http://github.com/neelance/graphql-go" resolver := &RootResolver{} var schema *graphql.Schema = graphql.MustParseSchema(resolvers.Schema, resolver) ``` 2. Every endpoint must have resolver. Assuming we want to create a graphql endpoint for `user`, then we'll have a `User()` method attached to `RootResolver`, that will return a `userResolver` 3. Every endpoint resolver (ie. `userResolver`), will resolve every available fields. If a `user` has 3 fields `name`, `email` and `username`, `userResolver` must have 3 accompanying methods: `Name()`, `Email()`, and `Username()` 4. Once `userResolver` is completed, update the graphql schema. We can represent the relationship of methods mentioned above like so: ``` ▾ RootResolver .User() *userResolver ▾ *userResolver .Name() string .Email() string .Username() string ``` ## Generator Approach Looking at the relationships, it will be a repetitive work to hand-code all the resolvers for each model. Thus, we'll come with a generator approach, that will take a struct, generate those resolvers code based on the struct, and store the generated codes to files inside the directory we choose. ## The Code ```go // import "github.com/wzulfikar/lab/go/graphqlboiler" type User struct { Name string Email string Username string } resolversDir := "/path-to-project/resolvers/" graphqlboiler.Boil(graphqlboiler.Tpl{ RootResolver: "RootResolver", Schema: User{}, Repo: "gitlab.com/wzulfikar/iiumpayment", }, resolversDir) ``` When above code is executed, the `graphqlboiler.Boil` will use Go's reflection ability from [pkg/reflect](https://golang.org/pkg/reflect/) to get the struct type, field names and field types. In this case, it will know that the struct's type name is `User`, and it has 3 fields; `Name`, `Email` and `Username`, which its types are all `string`. Using this information and common convention, the generator determines that the resolver name is `userResolver`, and proceeds with generating resolvers code for the `User` struct. Upon completion, there will be four new files stored in resolvers directory: ``` ▾ path-to-project/ ▾ resolvers/ user.go user_mutations.go user_result.go user_schema.go ``` Above four files contains the necessary codes to run the graphql; 1. `user.go` - attach `userResolver` to `RootResolver`, and - attach methods for `userResolver` (`Name()`, `Email()` and `Username()`) 2. `user_mutations.go` - attach mutation endpoint `CreateUser()` to `RootResolver`. 3. `user_result.go` - Contains complimentary codes to add pagination for the query 4. `user_schema.go` - the GraphQL schema os `User`, with exported variables Using the generator, we've completed steps 1 to 3 of the flow presented in [#Synopsis](#synopsis). All the repetitive steps are done by generator. We can proceed directly to step 4: updating our graphql schema, which basically just putting the variables from `user_schema.go` to the schema that will be parsed into `graphql.MustParseSchema()`. Once the schema is updated, we can run the test and spin up our graphql server! ## Closing The templates used to generate above codes are available at [wzulfikar/lab/graphqlboiler/templates](https://github.com/wzulfikar/lab/tree/master/go/graphqlboiler/templates). While the generator itself is by any mean not a sophisticated code, it has helped me in building GraphQL endpoint from the same scenario (a Go project with SQLBoiler and neelance/graphql-go). If you'd like to explore other graphql-go generator, you may want to see this: https://github.com/vektah/gqlgen. Lastly, the full code for the generator is available here: https://github.com/wzulfikar/lab/tree/master/go/graphqlboiler ***Till next. See ya!***<file_sep>const fs = require('fs') const matter = require('gray-matter') const idxPath = __dirname + '/../static/algolia-index' const idx = require(idxPath + '/raw.json') console.log(`[INFO] loaded ${idx.length} indices`) let curated = [] idx.forEach((item, i) => { const { content } = item try { let parsed = matter(content) if (parsed.data.draft || parsed.data.disableIndexing) { return } let uri = item.uri.replace(/_index$/, '').toLowerCase() if (uri.endsWith('.id')) { uri = '/' + uri.split('_index.').reverse().join('') } // sanitize parsed content parsed.content = parsed.content .replace(/\n/g, ' ') .replace(/(style=\".+\")|(class=\"[a-zA-Z0-9-_ ]+\")/ig, '') .replace(/(\*|\\n|\/p|\s+!|span|div|iframe|(\s+\/\s+)|(\s+p\s+))/ig, '') .replace(/\.\s{2,}/g, '. ') .trim() let [summary, body] = ['', parsed.content] if (body.includes('--more--')) { [summary, body] = parsed.content.split('--more--').map(section => section.trim()) } let type = uri.includes('/posts') ? 'POST' : 'PAGE' const { date, title, tags } = parsed.data let index = { objectID: uri, // manually set objectID for algolia coverImage: parsed.data.coverImg, date, type, title, summary, body, tags, } curated.push(index) } catch (e) { /* no-op */ } }) // write new index fs.writeFileSync(idxPath + '/curated.json', JSON.stringify(curated, null, 4)); console.log(`[INFO] index curated. collected ${curated.length} out of ${idx.length}.`)<file_sep>// generate graphql resolvers and schema // based on struct // // sample code: // // graphqlboiler.Boil(graphqlboiler.Tpl{ // RootResolver: "RootResolver", // schema: Person{}, // }, "./graphqlboiler/") package graphqlboiler import ( "bytes" "fmt" "html/template" "log" "os" "reflect" "strings" "github.com/jinzhu/inflection" "github.com/wzulfikar/lab/go/graphqlboiler/templates" "gopkg.in/volatiletech/null.v6" ) // sample schema type SampleSchemaPerson struct { Name string Age int Hobby null.String Birthdate null.Time married bool `json:"-"` } type resolverField struct { name string fieldType string } type Tpl struct { RootResolver string Schema interface{} Repo string } func Boil(tpl Tpl, path string) { typeName := string(reflect.TypeOf(tpl.Schema).Name()) resolverName := strings.ToLower(typeName[0:1]) + typeName[1:] + "Resolver" fields := reflectFields(tpl.Schema) model := strings.ToUpper(typeName[0:1]) + typeName[1:] modelPlural := inflection.Plural(model) data := struct { HasScalar bool TypeName, TypeNameLowerCase, SchemaFields, ModelPlural, ResolverName, RootResolver, Repo string }{ false, typeName, strings.ToLower(typeName[0:1]) + typeName[1:], schemaFields(fields), modelPlural, resolverName, tpl.RootResolver, tpl.Repo, } fmt.Println("Generating graphqlboiler for struct `" + typeName + "`") tplResolverFields := tplResolverFields(resolverName, fields) fmt.Println("✔ Resolver fields template") data.HasScalar = strings.Contains(tplResolverFields, "scalar") tplResolver, err := parseTpl(templates.Resolver, data) if err != nil { log.Fatal(err) } fmt.Println("✔ Resolver template") tplMutations, err := parseTpl(templates.Mutations, data) if err != nil { log.Fatal(err) } fmt.Println("✔ Mutations template") tplQueryResult, err := parseTpl(templates.QueryResult, data) if err != nil { log.Fatal(err) } fmt.Println("✔ Query result template") tplSchema, err := parseTpl(templates.Schema, data) if err != nil { log.Fatal(err) } fmt.Println("✔ Schema template") mustWrite(path+strings.ToLower(typeName)+".go", tplResolver+tplResolverFields) mustWrite(path+strings.ToLower(typeName)+"_result.go", tplQueryResult) mustWrite(path+strings.ToLower(typeName)+"_schema.go", tplSchema) mustWrite(path+strings.ToLower(typeName)+"_mutations.go", tplMutations) fmt.Println("✔ Write templates to file") fmt.Println("[DONE!]") } func tplResolverFields(resolverName string, fields []resolverField) string { var resolvers string var fldType string for _, field := range fields { fldName := field.name returnObj := `r.o.` + fldName preReturnCode := "" switch field.fieldType { case "Uint", "uint", "Int", "int": fldType = "int32" returnObj = `int32(r.o.` + fldName + `)` case "null.Uint": fldType = "*int32" preReturnCode = `if !r.o.` + fldName + `.Valid { return nil, nil } v := int32(r.o.` + fldName + `.Uint) ` returnObj = `&v` case "null.Int": fldType = "*int32" preReturnCode = `if !r.o.` + fldName + `.Valid { return nil, nil } v := int32(r.o.` + fldName + `.Int) ` returnObj = `&v` case "decimal": fldType = "scalar.Decimal" case "time", "Time": fldType = "scalar.Time" returnObj = `scalar.Time{r.o.` + fldName + `}` case "null.Time": fldType = "*scalar.Time" preReturnCode = `if !r.o.` + fldName + `.Valid { return &scalar.Time{}, nil } ` returnObj = `&scalar.Time{r.o.` + fldName + `.Time}` case "null.String": fldType = "*string" returnObj = `r.o.` + fldName + `.Ptr()` default: fldType = field.fieldType } if strings.ToUpper(fldName) == "ID" { if fldType == "int" { returnObj = `graphql.ID(strconv.Itoa(r.o.` + fldName + `))` } else { returnObj = `graphql.ID(r.o.` + fldName + `)` } fldType = "graphql.ID" } else if strings.HasSuffix(fldName, "ID") { fldName = strings.Replace(fldName, "ID", "", 1) o := strings.ToUpper(fldName[:1]) + fldName[1:] resolver := strings.ToLower(fldName[:1]) + fldName[1:] + "Resolver" fldType = "*" + resolver preReturnCode = `if r.o.R == nil || r.o.R.` + o + ` == nil{ r.o.L.Load` + o + `(r.rr.Db, true, r.o) } ` returnObj = `&` + resolver + `{rr: r.rr, o: r.o.R.` + o + `}` } resolvers += ` func (r *` + resolverName + `) ` + fldName + `() (` + fldType + `, error) { ` + preReturnCode + `return ` + returnObj + `, nil } ` } return strings.TrimRight(resolvers, "\n") + "\n" } func reflectFields(schema interface{}) (fields []resolverField) { rv := reflect.ValueOf(schema) for i := 0; i < rv.NumField(); i++ { fld := rv.Field(i) typeFld := rv.Type().Field(i) // don't reflect fields with json tag "-" if typeFld.Tag.Get("json") == "-" { continue } fldType := fld.Type().Name() if fld.Kind() == reflect.Struct { if fld.FieldByName("Valid").IsValid() { fldType = "null." + fldType } } fields = append(fields, resolverField{typeFld.Name, fldType}) } return fields } func schemaFields(fields []resolverField) string { var schemaFields string for _, field := range fields { fldType := strings.ToUpper(field.fieldType[0:1]) + field.fieldType[1:] fldName := strings.ToLower(field.name[0:1]) + field.name[1:] if strings.HasPrefix(fldType, "Uint") { fldType = strings.Replace(fldType, "Uint", "Int", 1) } // determine if a field is required or not if strings.HasPrefix(fldType, "Null.") { fldType = strings.Replace(fldType, "Null.", "", 1) } else { fldType += "!" } // field `id` should return graphql `ID!` if strings.ToUpper(fldName) == "ID" { fldName = "id" fldType = "ID!" } else if strings.HasSuffix(fldName, "ID") { fldName = strings.Replace(fldName, "ID", "", 1) fldType = strings.ToUpper(fldName[:1]) + fldName[1:] } schemaFields += fmt.Sprintf("\t%s: %s\n", fldName, fldType) } return strings.TrimRight(strings.TrimLeft(schemaFields, "\t"), "\n") } func parseTpl(tplString string, data interface{}) (string, error) { t, err := template.New("").Parse(tplString) if err != nil { return "", err } var tpl bytes.Buffer if err := t.Execute(&tpl, data); err != nil { return "", err } return tpl.String(), nil } func mustWrite(filename, content string) { file, err := os.Create(filename) if err != nil { panic(fmt.Sprintf("Cannot create file: %v", err)) } defer file.Close() fmt.Fprintf(file, content) } <file_sep>// Watch for new file in WORKDIR and run alpr. // USAGE: // WORKDIR=/Volumes/data/playground/plates COUNTRY=eu go run watchbinding.go package main import ( "fmt" "log" "os" "time" "github.com/openalpr/openalpr/src/bindings/go/openalpr" alprgo "github.com/wzulfikar/lab/go/alpr" ) func main() { defer func() { if err := recover(); err != nil { fmt.Errorf("panic: %v", err) time.Sleep(2 * time.Second) loop() } }() loop() } func loop() { // directory for alpr runtime data. ie, // /usr/local/share/openalpr/runtime_data workdir := os.Getenv("WORKDIR") runtimeDir := os.Getenv("RUNTIME_DIR") country := os.Getenv("COUNTRY") config := os.Getenv("CONFIG") h := alprgo.NewBindingHandler(country, config, runtimeDir) if !h.Alpr.IsLoaded() { fmt.Println("OpenAlpr failed to load!") return } defer h.Alpr.Unload() h.Alpr.SetTopN(20) fmt.Println("OpenAlpr started. Version:", openalpr.GetVersion()) fmt.Println("Scanning directory started") go alprgo.ScanDir(workdir, h) log.Fatal(alprgo.Watch(workdir, h)) } <file_sep>from udacidrone import Drone from udacidrone.connection import MavlinkConnection conn = MavlinkConnection('tcp:127.0.0.1:5760', threaded=True) drone = Drone(conn) drone.start() print("drone started") drone.take_control() drone.arm() drone.set_home_position(drone.global_position[0], drone.global_position[1], drone.global_position[2]) drone.takeoff(3) <file_sep>--- title: "Steal Like an Artist" date: 2018-07-15T16:18:42+08:00 tags: ["reflection"] draft: false post_id: 23 coverImg: /images/steal-like-an-artist-kindle-store.jpg coverAlt: Steal Like and Artist - Kindle Store aliases: [ "/posts/23", ] --- I was visiting a library in my block this morning, and stumbled upon a book authored by <NAME> in 2012, titled "Steal Like an Artist" (you can find it online in Amazon, Book Depository, etc.). Upon skimming few of its pages, I already felt like I want to finish the book soon. <!--more--> It's a good book, with a lot of takeaways that I can relate. Started reading it at 8.50am, finished the reading at 9.45am, and reading it again at 15.00. This post contains the things I read from the book, that I want myself to relate/reflect back, anytime in the future. All credits goes back to the author –– thanks for writing the book! <p class="text-center">***</p> 1. "*Wondering. Wandering.*" 2. *"There's nothing new under the sun."* As the French writer Andre Gide put it, "Everything that needs to be said has already been said. But, since no one was listening, everything must be said again" 3. "Here's a trick they teach you in art school. Draw two parallel lines on a piece of paper. *How many lines are there?* There's the first line, but then there's a line of negative space that runs between them. *See it? 1 + 1 = 3*" 4. A good example is genetics. You have a mother and you have a father. You posses features from both of them, *but the sum of you is bigger than their parts*. You're a remix of your mom, and dad, and all of your ancestors. 5. "We were kids without fathers. So we found our fathers on wax and on the streets and in history. We got to pick and choose the ancestors who would inspire the world we were going to make for ourselves" – <NAME> 6. The artist is a collector, not a hoarder. *Hoarders collect indiscriminately, artist collect selectively;* they only collect things that they really love. 7. The great thing about dead or remote masters is that they can't refuse you as an apprentice. You can learn whatever you want from them. 8. "Seeing yourself as part of a creative lineage will help you feel less alone as you start making your own stuff. I hang pictures of my favorite artists in my studio" 9. "School is one thing. Education is another. The two don't always overlap. *Whether you're in school or not, it's always your job to get yourself an education*" 10. You have to be curious about the world in which you live. *Look things up. Chase down every reference.* 11. "Don't ask question before you Google it. *You'll either find the answer, or you'll come up with a better question*." 12. "Whether I went to school or not, I would always study." – RZA 13. Don't worry about doing research. Just search. 14. "It's better to take what does not belong to you than to let it lie around neglected." – <NAME> *(I don't really agree with this, but a point is taken)* 15. "Guess what: None of us do. Ask anybody doing truly creative work, and they'll tell you the truth: *they don't know where the good stuff comes from*. They just show up to do their thing. Every day." 16. "Nobody is born with a style or a voice. *We learn by copying*." 17. "We're talking about practice here, not plagiarism –– plagiarism is trying to pass someone else's work as your own. Copying is about reverse-engineering." 18. "A wonderful flaw about human beings is that we're incapable of making perfect copies. *Our failure to copy our heroes is where we discover where our own thing lives.*" 19. As <NAME> said, "Those who do not want to imitate, produce nothing." 20. "If you have one person you're influenced by, everyone will say you're the next whoever. *But if you rip off a hundred people, everyone will say you're so original!*" 21. "What to copy is a little bit trickier. Don't just steal the style, *steal the thinking behind the style.*" 22. "If you just mimic the surface of somebody's work without understanding where they're coming from, *your work will never be anything more than a knockoff.*" 23. "I have stolen all of these moves from all these great players. *I just try to do them proud*, the guys who came before, *because I learned so much from them*." – <NAME> 24. In O'Brien's words, "It's our failure to become our perceived ideal that ultimately defines us and makes us unique." Thank goodness. 25. "In the end, merely imitating your heroes is not flattering them. Transforming their work into something of your own is how you flatter them. *Adding something to the world that only you can add.*" 26. "When we love a piece of work, we're desperate for more. We crave sequels. *Why not channel that desire into something productive?*" 27. The manifesto is this: Draw the art you want to see, start the business you want to run, play the music you want to hear, write the books you want to read, build the products you want to use –– do the work you want to see done. 28. "Work that only comes from the head isn't any good. You need to find a way to bring your body into your work. *Our nerves aren't a one-way street –– our bodies can tell our brains as much as our brain tells our bodies.* You know that phrase, *"going through the motions"*? The motion kickstarts our brain into thinking." 29. "The computer is really good for editing your ideas, and it's really good for getting your ideas ready for publishing out into the world, *but it's not really good for generating ideas.* There are too many opportunities to hit the delete key. *The computer brings out the uptight perfectionist in us –– we start editing ideas before we have them.*" 30. "Because once the computer is involved, *"things are on an inevitable path to being finished."* Whereas in my sketchbook, the possibilities are endless." – <NAME> (cartoonist) 31. "Once you start getting your ideas, then you can move over to your digital station and use the computer to help you execute and publish them." 32. "The work you do while you procrastinate is probably the work you should be doing for the rest of your life" – <NAME> 33. "I think it's good to have a lot of projects going at once so you can bounce between them" 34. "Practice productive procrastination" 35. "I love ironing my shirts –– *it's so boring, I almost always get good ideas.*" 36. Take time to mess around. Get lost. Wander. You never know where it's going to lead you. As the artist <NAME> says, "Avoiding work is the way to focus my mind." 37. You can't connect the dots looking forward, you can only connect them looking backwards – <NAME> 38. "Don't worry about unity from piece to piece. What unifies all of your work is the fact that you made it." 39. Tomlinson suggests that if you love different things, you just keep spending time with them. "*Let them talk to each other. Something will begin to happen.*" 40. "The classroom is wonderful, if artificial, place: Your professor *gets paid* to pay attention to your ideas, and your classmates *are paying* to pay attention to your ideas. Never again in your life will you have such a captive audience." Soon after, you'll learn that most of the world doesn't necessarily care about what you think. As the writer <NAME> says, "It's not that people are mean or cruel, they're just busy." 41. *In the beginning, obscurity is good.* When you're unknown, there's nothing to distract you from getting better. *No public image to manage*. You'll never get that freedom back again once people start paying you attention, and especially not once they start paying you money. *Enjoy obscurity while it lasts.* 42. The more open you're about sharing your passions, the closer people will feel to your work. When you open up your process and invite people, you learn. 43. "You don't put yourself online only because you've something to say –– you can put yourself online *to find something to say.*" 44. "If you're worried about giving your secrets away, *you can share your dots without connecting them.* It's your finger that has to hit the publish button." 45. "All you need is a little space, and a little time; a little self-imposed solitude, and temporary captivity" 46. *Leave home*; "Distance and difference are the secret tonic of creativity. When we get home, home is still the same. *But something in our mind has been changed,* and that changes everything." – <NAME> 47. Your brain gets too comfortable in your everyday surroundings. You need to make it uncomfortable. Travel makes the world look new, and when the world looks new, our brains work harder. 48. It helps to live around interesting people, and not necessarily people who do what you do. 49. "Be nice. The world is a small town." 50. "The only mofos in my circle are people that I can learn from" – Questlove 51. "You'll need: curiosity, kindness, stamina, and a willingness to look stupid." 52. "If you ever find that you're the most talented person in the room, you need to find another room." 53. *"Quit picking fights and go make something."*, "Complain about the way other people make software *by making software*" – <NAME> 54. "The best way to get approval is to not need it" 55. *Validation is for parking.* "Modern art = I could do that + *yeah, but you didn't*." – <NAME> 56. "So, get comfortable with being misunderstood, disparaged, or ignored. The trick is to be too busy doing your work to care." 57. "Instead of keeping a rejection file, *keep a praise file.* Use it sparingly –– don't get lost in past glory –– but keep it around for when you need the lift." 58. "It's better to burn out than to fade away" – <NAME> 59. "Be boring. It's the only way to get things done." 60. "Be regular and orderly in your life, so that you may be violent and original in your work" – <NAME> 61. "The art of holding money is all about saying no to consumer culture. Saying no to takeout, $4 lattes, and that shiny new computer when the old one still works fine." 62. *Keep your day job*. A day job gives you money, a connection to the world, and a routine. Freedom from financial stress also means freedom in your art. As photographer <NAME> says, "If you don't take money, they can't tell you what to do." The worst thing a day job does is take time away from you. 63. "What you'll probably find is that corollary to Parkinson's Law is usually true: Work gets done in the time available" 64. "The trick is to find a day job that pays decently, doesn't make you want to vomit, and leaves you with enough energy to make things in your spare time. Good day jobs aren't necessarily easy to find, but they're out there." 65. A calendar helps you plan work, gives you concrete goals, and keep you on track. "Get a calendar. Fill the boxes. *Don't break the chain.*" 66. "In this ages of information abundance and overload, those who get ahead will be the folks who figure out what to leave out, so they can concentrate on what's really important to them. Nothing is more paralyzing than the idea of limitless possibilities. The idea that you can do anything is absolutely terrifying." 67. "It seems contradictory, but when it comes to creative work, *limitations means freedom.*" Make things with the time, space, and materials you have, right now. 68. "The right constraints can lead to your very best work." 69. "Telling yourself you have all the time in the world, all the money in the world, all the colors in the palette, anything you want –– *that just kills creativity*." – <NAME> 70. "There are definite dangers in thinking you can do everything. Whittle down the stream so you can think. *Do with less. Start now.*" 71. What makes us interesting isn't just what we've experienced, but also what we haven't experienced. *Embrace limitations. Keep moving.* 72. "In the end, creativity isn't just the things we choose to put in, it's the things we choose to leave out." –– choose wisely. and have fun. 73. "Make things for people you love. For people you want to meet." 74. "Your parents invent you, and you take it from there." 75. "Some advice can be a vice. Feel free to take what you can use and leave the rest." <p class="text-center">***</p> {{< load-photoswipe >}}<file_sep><?php class FileGenerator{ public $vars; public $template; public function __construct($template, array $vars = []) { if ( ! is_string($template) ) throw new Exception('Type of $template should be string instead of ' . gettype($template)); $this->template = $template; $this->setVars($vars); } public function setVars(array $vars){ $this->vars = $vars; } public function parse(){ return $this->replace_template_vars($this->template, $this->vars); } public function put($output){ file_put_contents($output, $this->parse()); } private function replace_template_vars($template, array $vars){ foreach ($vars as $var_name_to_replace => $new_var_name) { $template = str_replace('{{' . $var_name_to_replace . '}}', $new_var_name, $template); } return $template; } } $template = file_get_contents('ModelTemplate.php'); $vars = [ 'namespace' => 'App\Polymorphic\Likeable', 'modelName' => 'Like', 'polymorphicName' => 'Likeable' ]; $template = new FileGenerator($template,$vars); // check what the generated file will look like var_dump($template->parse()); // store the file $template->put($vars['modelName'] . '.php'); // sample of ModelTemplate.php (input) // <?php // // namespace {{namespace}}; // // use Illuminate\Database\Eloquent\Model; // // class {{modelName}} extends Model // { // /** // * Get all of the owning {{polymorphicName}} models. // */ // public function {{polymorphicName}}() // { // return $this->morphTo(); // } // } // // The output will be `Like.php` // // <?php // // namespace App\Polymorphic\Likeable; // // use Illuminate\Database\Eloquent\Model; // // class Like extends Model // { // /** // * Get all of the owning Likeable models. // */ // public function Likeable() // { // return $this->morphTo(); // } // } <file_sep>### Lesson 3: Backyard Flyer 1. flight computer: a higher level program that control where the vehicle should go, etc 2. autopilot: a lower level program, ie. to control thrusts, etc 3. a drone programmer job is likely to deal with writing codes for the flight computer 4. `ipython`: python interactive shell with added features; qt-based, web-based notebook, gui, etc. 5. the simulator will start using port `5760` when the option is selected (Backyard Flyer, Motion Planning, or Controls). the port will be active as long as a session is activated, regardless of the control mode (manual/guided) 6. when running the drone code from python, make sure the simulator mode is set to "GUIDED" (not "MANUAL") 7. running `python` inside conda env will automatically use the python binary from conda 8. you can run from any folder and the dependencies will still be available for given conda environment as long as the packages were installed in the same environment 9. **EDP**: event driven programming; a dominant paradigm used in graphical user interface. 10. an asterisk in jupyter notebook (`[*]`) indicates that the current cell is (still) executing code. this can be used to determine if a cell contains a long-blocking code, etc. 11. a good example for event driven programming: a chatbot program; because in chatbot, programmer can't really know what the user will ask the chatbot. hence, instead of creating a sequential program, an event-driven program paradigm should be used. 12. when doing event driven programming, think above "state variable" > understanding python asterisk (`*`): https://medium.com/understand-the-python/understanding-the-asterisk-of-python-8b9daaa4a558 --- - relationship between numpy, scipy, pandas & scikit-learn: https://www.quora.com/What-is-the-relationship-among-NumPy-SciPy-Pandas-and-Scikit-learn-and-when-should-I-use-each-one-of-them <file_sep>package main import "fmt" func main() { c := circle{} s := square{} t := triangle{} // passing exactly 1 shape fmt.Println(getAreaOfAnyShape(c)) // passing more than 1 shape fmt.Println(getAreaOfAnyShape(c, s, t)) // passing no shape fmt.Println(getAreaOfAnyShape()) } // interface: set of methods type shape interface { area() string } type circle struct{} type square struct{} type triangle struct{} // using interface as function param // the `...` means we can pass zero to many shape func getAreaOfAnyShape(shapes ...shape) []string { // use slice for dynamic allocation areas := make([]string, len(shapes)) for key, s := range shapes { areas[key] = s.area() } return areas } // `circle`, `square` and `triangle` // (implicitly) implements `shape` interface // because it has all the methods defined in `shape` interface func (c circle) area() string { return "area of circle is: pi" } func (s square) area() string { return "area of square is: p x l" } func (t triangle) area() string { return "area of triangle is: p x l x t" } <file_sep>## Udacity: Intro to Self-driving Car > Sat, 14 Apr 2018 at 2:00:23 MYT Preview link: https://classroom.udacity.com/courses/nd113-preview ### Lesson 2: Finding Lane Lines - in python, make sure to copy arrays (ie. using `numpy.copy()`) instead of just using `=` (ie. `array_a = array_b`) because it's mutable - ROI: region of interest - region masking technique: - define thresholds - extract region of interest - mask color and region selection #### Canny Edge Detection - canny edge detection is an edge detection algorithm, developed by <NAME> in 1986 - the canny edge detection has been one of the default edge detectors in image processing - goal of canny edge detection: detect the boundary of an object in image - steps to do canny edge detection in a nutshell: 1. convert image to grayscale 2. compute the gradient: at this step, the brightness in each pixel will correspond to the strength of the gradient at that point 3. find the edges by tracing out the pixels that follow the strongest gradient - opencv has built-in function to perform canny edge detection: ``` edges = cv2.Canny(im_gray, low_threshold, high_threshold) ``` - the algorithm will first detect strong edge (strong gradient) pixels above the `high_threshold` - reject pixels below the `low_threshold`. - pixels with values between the `low_threshold` and `high_threshold` will be included as long as they are connected to strong edges - the output edges is a binary image with white pixels tracing out the detected edges and black everywhere else. See the [OpenCV Canny Docs](http://docs.opencv.org/2.4/doc/tutorials/imgproc/imgtrans/canny_detector/canny_detector.html) for more details. - as far as a ratio of `low_threshold` to `high_threshold`, John Canny himself recommended a low to high ratio of 1:2 or 1:3. - derivative in image operation: - small derivative == small change - big derivative == big change - we expect to find edges where the pixel values are changing *rapidly* - it's common to include additional Gaussian smoothing before running Canny, which is essentially a way of suppressing noise and spurious gradients by averaging (check out the OpenCV docs for GaussianBlur). `cv2.Canny()` actually applies Gaussian smoothing internally, but we include it here because you can get a different result by applying further smoothing (and it's not a changeable parameter within `cv2.Canny()`!). - using opencv, a steps to perform canny edge detection would be: 1. make gray version of our image 2. apply gassian blue 3. apply `cv2.Canny()` #### Hough Transform - a method to represent lines in parameter space, devised by <NAME> in 1962 - hough transform: conversion from image space (x vs y) to hough space (m vs b) - you can use Hough Transform to find lines from canny edges - a line in image space translates to a point (a dot) in hough space, and vice versa (a point in image space describes a line in Hough space) - in hough space, there can't be two parallel line; there must be intersection - "The intersection point at (m0, b0) represents the line y = m0x + b0 in image space and it must be the line that passes through both points!" - "The four major intersections between curves in Hough space correspond to the four sides of the square." - you can use `cv2.HoughLinesP()` to find lines at image using hough transform - python `imageio` library: a library that provides an easy interface to read and write a wide range of image data, including animated images, volumetric data, and scientific formats - python `moviepy` library: MoviePy is a Python module for video editing, which can be used for basic operations (like cuts, concatenations, title insertions), video compositing (a.k.a. non-linear editing), video processing, or to create advanced effects. It can read and write the most common video formats, including GIF. <file_sep>-- BEGINNING OF PROCEDURE AND FUNCTION DECLARATIONS /** * Function to get number of people managed by a manager */ CREATE OR REPLACE FUNCTION getMemberCount(emp_no IN INTEGER) RETURN NUMBER IS memberCount NUMBER(2); BEGIN SELECT COUNT(EMPNO) INTO memberCount FROM EMPLOYEE WHERE MGR = emp_no; RETURN(memberCount); END; / /** * Procedure to print management-related info (for member) */ CREATE OR REPLACE PROCEDURE displayMemberInfo(employee_name EMPLOYEE.ENAME%TYPE, member_count integer) AS BEGIN if member_count = 0 THEN DBMS_OUTPUT.PUT_LINE('- ' || employee_name || ' is not manager'); ELSIF member_count = 1 THEN DBMS_OUTPUT.PUT_LINE('- ' || employee_name || ' is managing 1 person'); ELSE DBMS_OUTPUT.PUT_LINE('- ' || employee_name || ' is managing ' || member_count || ' person'); END IF; END; / /** * Procedure to print management-related info (for manager) */ CREATE OR REPLACE PROCEDURE displayManagerInfo(employee_name EMPLOYEE.ENAME%TYPE, managerId EMPLOYEE.MGR%TYPE) AS BEGIN if managerId IS NULL THEN DBMS_OUTPUT.PUT_LINE('- ' || employee_name || ' is not being managed by anyone'); ELSE DBMS_OUTPUT.PUT_LINE('- ' || employee_name || ' is under supervision of employee #' || managerId); END IF; END; / /** * Function to get number of people managed by a manager */ CREATE OR REPLACE FUNCTION getMemberCount(emp_no IN INTEGER) RETURN NUMBER IS memberCount NUMBER(2); BEGIN SELECT COUNT(EMPNO) INTO memberCount FROM EMPLOYEE WHERE MGR = emp_no; RETURN(memberCount); END; / /** * Procedure to print management-related info (for member) */ CREATE OR REPLACE PROCEDURE displayMemberInfo(employee_name EMPLOYEE.ENAME%TYPE, member_count integer) AS BEGIN if member_count = 0 THEN DBMS_OUTPUT.PUT_LINE('- ' || employee_name || ' is not manager'); ELSIF member_count = 1 THEN DBMS_OUTPUT.PUT_LINE('- ' || employee_name || ' is managing 1 person'); ELSE DBMS_OUTPUT.PUT_LINE('- ' || employee_name || ' is managing ' || member_count || ' person'); END IF; END; / /** * Procedure to print management-related info (for manager) */ CREATE OR REPLACE PROCEDURE displayManagerInfo(employee_name EMPLOYEE.ENAME%TYPE, managerId EMPLOYEE.MGR%TYPE) AS BEGIN if managerId IS NULL THEN DBMS_OUTPUT.PUT_LINE('- ' || employee_name || ' is not being managed by anyone'); ELSE DBMS_OUTPUT.PUT_LINE('- ' || employee_name || ' is under supervision of employee #' || managerId); END IF; END; / -------- END OF PROCEDURE AND FUNCTION DECLARATIONS ------- -- BEGINNING OF ANONYMOUS BLOCK SET SERVEROUTPUT ON SET VERIFY OFF /** * Get detail of employee * by its employee number. * * Raise exception if input is not a valid number */ ACCEPT input PROMPT 'Enter employee number: ' DECLARE -- cursor declaration CURSOR employee_cursor IS SELECT E.EMPNO EMPNO, E.ENAME ENAME, E.JOB JOB, E.SAL SAL, B.BRANCH_NAME BRANCH_NAME, B.BRANCH_LOCATION BRANCH_LOCATION, E.HIREDATE, E.MGR MGR FROM EMPLOYEE E JOIN BRANCH B ON B.BRANCH_NUM = E.BRANCH_NUM WHERE EMPNO = '&input'; employee employee_cursor%ROWTYPE; -- declare user-defined exception EMPLOYEE_NOT_FOUND_EXCEPTION EXCEPTION; liner varchar2(30) := '----------------------------'; rpad_size integer := 13; months_worked integer; years_worked decimal; user_input varchar2(20) := '&input'; BEGIN OPEN employee_cursor; LOOP FETCH employee_cursor INTO employee; -- display descriptive message if no records found IF employee_cursor%NOTFOUND AND employee_cursor%ROWCOUNT = 0 THEN raise EMPLOYEE_NOT_FOUND_EXCEPTION; END IF; EXIT WHEN employee_cursor%NOTFOUND; -- use explicit cursor `employee_cursor` -- calculate months and years worked months_worked := ROUND(MONTHS_BETWEEN(CURRENT_DATE, employee.HIREDATE)); years_worked := ROUND(months_worked/12); -- craft employee info DBMS_OUTPUT.PUT_LINE(liner); DBMS_OUTPUT.PUT_LINE('Employee Info'); DBMS_OUTPUT.PUT_LINE(liner); DBMS_OUTPUT.PUT_LINE(RPAD('Emp No.', rpad_size) || ' : ' || employee.EMPNO); DBMS_OUTPUT.PUT_LINE(RPAD('Name', rpad_size) || ' : ' || employee.ENAME); DBMS_OUTPUT.PUT_LINE(RPAD('Job', rpad_size) || ' : ' || employee.JOB); DBMS_OUTPUT.PUT_LINE(RPAD('Salary', rpad_size) || ' : ' || employee.SAL); DBMS_OUTPUT.PUT_LINE(RPAD('Hiredate', rpad_size) || ' : ' || employee.HIREDATE); DBMS_OUTPUT.PUT_LINE(RPAD('Months Worked', rpad_size) || ' : ' || months_worked || ' (' || years_worked || 'yrs)'); DBMS_OUTPUT.PUT_LINE(RPAD('Branch', rpad_size) || ' : ' || employee.BRANCH_NAME); DBMS_OUTPUT.PUT_LINE(RPAD('Branch Loc.', rpad_size) || ' : ' || employee.BRANCH_LOCATION); -- craft header for management info DBMS_OUTPUT.PUT_LINE(''); DBMS_OUTPUT.PUT_LINE(liner); DBMS_OUTPUT.PUT_LINE('Management Info'); DBMS_OUTPUT.PUT_LINE(liner); -- call procedure to display info related to management displayMemberInfo(employee.ENAME, getMemberCount(employee.EMPNO)); displayManagerInfo(employee.ENAME, employee.MGR); END LOOP; CLOSE employee_cursor; -- start exception handler EXCEPTION -- handle oracle exception WHEN INVALID_NUMBER THEN DBMS_OUTPUT.PUT_LINE('Oops! Something went wrong..'); DBMS_OUTPUT.PUT_LINE('- "' || user_input || '" is not valid employee number'); DBMS_OUTPUT.PUT_LINE('- ' || 'Employee number must be integer'); -- handle user-defined exception WHEN EMPLOYEE_NOT_FOUND_EXCEPTION THEN DBMS_OUTPUT.PUT_LINE('Not found: employee with employee number ' || user_input || ' does not exist.'); END; / -- END OF ANONYMOUS BLOCK <file_sep>## Udacity: Intro to Self-driving Car > Sat, 14 Apr 2018 at 2:00:23 MYT Preview link: https://classroom.udacity.com/courses/nd113-preview **Instructure:** 1. <NAME> 2. <NAME> ### Lesson 1 - current approach for self-driving car: - robotic approach (collect data from array of sensors) - deep-learning approach (to mimic human behaviour) - both approach (robotic and deep-learning approach) will be discussed during this nano-degree program --- #### project overview (what we gonna do during the program) **Term 1: Computer Vision and Deep Learning** - project 1: finding lane lines - project 2: behavioral cloning (copy/clone human behaviour) - project 3: advanced lane finding and vehicle detection **Term 2: Sensor Fusion, Localization, and Control** - project 4: sensor fusion (integrating different type of sensors) - project 5: localization (making sense of vehicle's whereabout) - project 6: controller (steering wheel, etc) → *"it might sound trivial, but it's really easy to screw it up"* **Term 3: Path Planning & Controlling a Real Self-driving Car** - project 7: path planning (finding valid sequence of steps) - project 8: putting code in a real self-driving car --- - career support: contact udacity team career support - DARPA grand challenge for self-driving car (The Great Robot Race) 2015: https://youtu.be/saVZ_X9GfIM - business insider estimates that 10,000,000 (10 mil) self-driving cars will be on the road globally by 2020 → http://www.businessinsider.com/report-10-million-self-driving-cars-will-be-on-the-road-by-2020-2015-5-6 <file_sep>package templates const Mutations = `package resolvers import ( "context" graphql "github.com/neelance/graphql-go" "{{.Repo}}/models" ) func (rr *{{.RootResolver}}) Create{{.TypeName}}(ctx context.Context, args struct{ ID graphql.ID }) (*{{.ResolverName}}, error) { panic("TODO: handle Create{{.TypeName}} mutation") var o *models.{{.TypeName}} // Sample code: // o, err := NewBusiness(*args.Request) // if err != nil { // return nil, app.Error(err) // } return &{{.ResolverName}}{rr: rr, o: o}, nil } ` <file_sep>#include<iostream> using namespace std; int main(){ int in; cin >> in; cout << (in%4==0 || in%7==0 || in%47==0 || in%74==0 || in%477==0 ? "YES":"NO"); }<file_sep>#include <iostream> using namespace std; template<class T> class Node{ public: T value; Node<T>* left; Node<T>* right; Node(T value){ this->value = value; this->left = NULL; this->right = NULL; } }; template<class F> class BST{ // Binary Search Tree (BST) private: Node<F>* root; public: BST(){ root = NULL; } void insert(F value){ if(root==NULL){ root = new Node<F>(value); }else{ Node<F>* temp = root; while(temp!=NULL){ if(value > temp->value){ // go right, new value is greater than current tree node:w if(temp->right == NULL){ temp->right = new Node<F>(value); break; } temp = temp->right; }else{ // go left, new value is less than current tree node if(temp->left == NULL){ temp->left = new Node<F>(value); break; } temp = temp->left; } } } } bool find(F value){ Node<F>* temp = root; while(temp!=NULL){ if(value > temp->value){ temp = temp->right; }else if(value < temp->value){ temp = temp->left; }else{ return true; } } return false; } Node<F>* getMinNode(Node<F>* node){ while(node->left!=NULL){ node = node->left; } return node; } void deleteHelper(F value, Node<F>* current, Node<F>* parent = NULL){ if(value < current->value){ // 'value' is smaller, going left to search further deleteHelper(value, current->left, current); }else if(value > current->value){ // 'value' is bigger, going right to search further deleteHelper(value, current->right, current); }else if(value == current->value){ // Found match for the 'value' if(current->left!=NULL && current->right!=NULL){ // Has two child node Node<F>* minNode = getMinNode(current->right); current->value = minNode->value; deleteHelper(minNode->value, current->right, current); }else if(current->left!=NULL){ // Has only one child node, left child if(parent!=NULL){ if(parent->left == current) parent->left = current->left; // LL else parent->right = current->left; // RL }else{ root = current->left; } delete current; }else if(current->right!=NULL){ // Has only one child node, right child if(parent!=NULL){ if(parent->left == current) parent->left = current->right; // LR else parent->right = current->right; // RR }else{ root = current->right; } delete current; }else{ // Has no child node if(parent!=NULL){ if(parent->left == current) parent->left = NULL; else parent->right = NULL; }else{ root = NULL; } delete current; } } } void deleteNode(F value){ if(root!=NULL){ deleteHelper(value, root); } } void prefix(Node<F>* current){ if(current!=NULL){ cout<<current->value<<" "; prefix(current->left); prefix(current->right); } } void infix(Node<F>* current){ if(current!=NULL){ infix(current->left); cout<<current->value<<" "; infix(current->right); } } void postfix(Node<F>* current){ if(current!=NULL){ postfix(current->left); postfix(current->right); cout<<current->value<<" "; } } void display(int order=0){ if(order==0){ prefix(root); }else if(order==1){ infix(root); }else if(order==2){ postfix(root); } cout<<endl; } }; int main(){ BST<int> tree; int nums[] = {100,50,200,150,250,300}; for(int i=0;i<6;i++){ tree.insert(nums[i]); } tree.display(1); // Correct Output: 300 250 200 150 100 50 tree.deleteNode(200); tree.display(); // Correct Output: 100 150 250 300 50 cout<<tree.find(200); // Correct Output: 0 cout<<endl; cout<<tree.find(300); // Correct Output: 1 return 0; } <file_sep>--- title: "Practically, what is an API?" date: 2018-03-06T16:31:04+08:00 tags: ["tech", "programming"] draft: true --- `TODO: write content` <p class="text-center">***</p> *Outline:* 1. acronym for Application Programming Interface 2. public vs private api 3. difference between api and sdk 4. sample api: rest, graphql 5. commonly used in IT (tech, programming) 6. ref: https://medium.freecodecamp.org/what-is-an-api-in-english-please-b880a3214a82<file_sep>package main import ( "bytes" "fmt" "log" "text/template" "github.com/wzulfikar/lab/go/graphqlboiler/templates" ) func main() { data := struct { TypeName, ResolverName, RootResolver string }{"Person", "personResolver", "RootResolver"} tpl, err := parseTpl(templates.Resolver, data) if err != nil { log.Fatal(err) } fmt.Println(tpl) } func parseTpl(tplString string, data interface{}) (string, error) { t, err := template.New("").Parse(tplString) if err != nil { return "", err } var tpl bytes.Buffer if err := t.Execute(&tpl, data); err != nil { return "", err } return tpl.String(), nil } <file_sep>if you're doing whitebox testing (code in same package with test file) and found the undefined error even tho the vars/functions are in same package, you may have run the test for single file (ie. `cd my_code && go test my_code_test.go`). try run the test as a _whole_ (ie. `cd my_code && go test .`). if you don't want to run the whole file, specify the test with `-run` option. it will only run tests that match the regular expression passed to `-run` option. ie. `go test . -run 2` will check test files inside the directory but only run `hello_test.Test2` because `Test2` is the only test that has `2` in the directory. > Running the whole test in same directory won't hurt too because go cache the test result. if the code doesn't change, it will use the cached result.<file_sep>import threading import time class myThread (threading.Thread): def __init__(self, threadID, delay): threading.Thread.__init__(self) self.threadID = threadID print("thread #{} created".format(self.threadID)) self.delay = delay def run(self): print("Starting", self.threadID) print_time('time from thread {}'.format(self.threadID), self.delay) print("Exiting thread", self.threadID) def print_time(threadName, delay): print("sleeping for", delay, "seconds") time.sleep(delay) print("%s: %s" % (threadName, time.ctime(time.time()))) # Create new threads t1 = myThread(1, 1) t2 = myThread(2, 2) # t3 = myThread(2, 2) # Start new Threads t1.start() t2.start() t1.join() t2.join() print("Exiting Main Thread") <file_sep>-- script to create NORTHWOODS database -- revised 8/17/2002 JM -- modified 3/17/2004 LM DROP TABLE enrollment CASCADE CONSTRAINTS; DROP TABLE course_section CASCADE CONSTRAINTS; DROP TABLE term CASCADE CONSTRAINTS; DROP TABLE course CASCADE CONSTRAINTS; DROP TABLE student CASCADE CONSTRAINTS; DROP TABLE staff CASCADE CONSTRAINTS; DROP TABLE location CASCADE CONSTRAINTS; CREATE TABLE LOCATION (loc_id NUMBER(6), bldg_code VARCHAR2(10), room VARCHAR2(6), capacity NUMBER(5), CONSTRAINT location_loc_id_pk PRIMARY KEY (loc_id)); CREATE TABLE staff (s_id NUMBER(6), s_last VARCHAR2(30), s_first VARCHAR2(30), s_mi CHAR(1), loc_id NUMBER(5), s_phone VARCHAR2(10), s_rank VARCHAR2(9), s_super NUMBER(6), s_pin NUMBER(4), s_image BLOB, CONSTRAINT stafs_s_id_pk PRIMARY KEY(s_id), CONSTRAINT stafs_loc_id_fk FOREIGN KEY (loc_id) REFERENCES location(loc_id)); CREATE TABLE student (student_id VARCHAR2(6), s_last VARCHAR2(30), s_first VARCHAR2(30), s_mi CHAR(1), s_address VARCHAR2(25), s_city VARCHAR2(20), s_state CHAR(2), s_zip VARCHAR2(10), s_phone VARCHAR2(10), s_class CHAR(2), s_dob DATE, s_pin NUMBER(4), s_id NUMBER(6), time_enrolled INTERVAL YEAR TO MONTH, CONSTRAINT student_s_id_pk PRIMARY KEY (student_id), CONSTRAINT student_s_id_fk FOREIGN KEY (s_id) REFERENCES staff(s_id)); CREATE TABLE TERM (term_id NUMBER(6), term_desc VARCHAR2(20), status VARCHAR2(20), start_date DATE, CONSTRAINT term_term_id_pk PRIMARY KEY (term_id), CONSTRAINT term_status_cc CHECK ((status = 'OPEN') OR (status = 'CLOSED'))); CREATE TABLE COURSE (course_no VARCHAR2(7), course_name VARCHAR2(25), credits NUMBER(2), CONSTRAINT course_course_id_pk PRIMARY KEY(course_no)); CREATE TABLE COURSE_SECTION (c_sec_id NUMBER(6), course_no VARCHAR2(7) CONSTRAINT course_section_courseid_nn NOT NULL, term_id NUMBER(6) CONSTRAINT course_section_termid_nn NOT NULL, sec_num NUMBER(2) CONSTRAINT course_section_secnum_nn NOT NULL, s_id NUMBER(6), c_sec_day VARCHAR2(10), c_sec_time DATE, c_sec_duration INTERVAL DAY TO SECOND, loc_id NUMBER(6), max_enrl NUMBER(4) CONSTRAINT course_section_maxenrl_nn NOT NULL, CONSTRAINT course_section_csec_id_pk PRIMARY KEY (c_sec_id), CONSTRAINT course_section_cid_fk FOREIGN KEY (course_no) REFERENCES course(course_no), CONSTRAINT course_section_loc_id_fk FOREIGN KEY (loc_id) REFERENCES location(loc_id), CONSTRAINT course_section_termid_fk FOREIGN KEY (term_id) REFERENCES term(term_id), CONSTRAINT course_section_fid_fk FOREIGN KEY (s_id) REFERENCES staff(s_id)); CREATE TABLE ENROLLMENT (student_id VARCHAR2(6), c_sec_id NUMBER(6), grade CHAR(1), CONSTRAINT enrollment_pk PRIMARY KEY (student_id, c_sec_id), CONSTRAINT enrollment_sid_fk FOREIGN KEY (student_id) REFERENCES student(student_id), CONSTRAINT enrollment_csecid_fk FOREIGN KEY (c_sec_id) REFERENCES course_section (c_sec_id)); ---- inserting into LOCATION table INSERT INTO location VALUES (1, 'CR', '101', 150); INSERT INTO location VALUES (2, 'CR', '202', 40); INSERT INTO location VALUES (3, 'CR', '103', 35); INSERT INTO location VALUES (4, 'CR', '105', 35); INSERT INTO location VALUES (5, 'BUS', '105', 42); INSERT INTO location VALUES (6, 'BUS', '404', 35); INSERT INTO location VALUES (7, 'BUS', '421', 35); INSERT INTO location VALUES (8, 'BUS', '211', 55); INSERT INTO location VALUES (9, 'BUS', '424', 1); INSERT INTO location VALUES (10, 'BUS', '402', 1); INSERT INTO location VALUES (11, 'BUS', '433', 1); INSERT INTO location VALUES (12, 'LIB', '217', 2); INSERT INTO location VALUES (13, 'LIB', '222', 1); --- inserting records into staff INSERT INTO staff VALUES (1, 'Marx', 'Teresa', 'J', 9, '4075921695', 'Associate', 4, 6338, EMPTY_BLOB()); INSERT INTO staff VALUES (2, 'Zhulin', 'Mark', 'M', 10, '4073875682', 'Full', NULL, 1121, EMPTY_BLOB()); INSERT INTO staff VALUES (3, 'Langley', 'Colin', 'A', 12, '4075928719', 'Assistant', 4, 9871, EMPTY_BLOB()); INSERT INTO staff VALUES (4, 'Brown', 'Jonnel', 'D', 11, '4078101155', 'Full', NULL, 8297, EMPTY_BLOB()); INSERT INTO staff VALUES (5, 'Sealy', 'James', 'L', 13, '4079817153', 'Associate', 2, 6089, EMPTY_BLOB()); --- inserting records into STUDENT INSERT INTO student VALUES ('JO100', 'Jones', 'Tammy', 'R', '1817 Eagleridge Circle', 'Tallahassee', 'FL', '32811', '7155559876', 'SR', TO_DATE('07/14/1985', 'MM/DD/YYYY'), 8891, 1, TO_YMINTERVAL('3-2')); INSERT INTO student VALUES ('PE100', 'Perez', 'Jorge', 'C', '951 Rainbow Dr', 'Clermont', 'FL', '34711', '7155552345', 'SR', TO_DATE('08/19/1985', 'MM/DD/YYYY'), 1230, 1, TO_YMINTERVAL('4-2')); INSERT INTO student VALUES ('MA100', 'Marsh', 'John', 'A', '1275 West Main St', 'Carrabelle', 'FL', '32320', '7155553907', 'JR', TO_DATE('10/10/1982', 'MM/DD/YYYY'), 1613, 1, TO_YMINTERVAL('3-0')); INSERT INTO student VALUES ('SM100', 'Smith', 'Mike', NULL, '428 Markson Ave', 'Eastpoint', 'FL', '32328', '7155556902', 'SO', TO_DATE('09/24/1986', 'MM/DD/YYYY'), 1841, 2, TO_YMINTERVAL('2-2')); INSERT INTO student VALUES ('JO101', 'Johnson', 'Lisa', 'M', '764 Johnson Place', 'Leesburg', 'FL', '34751', '7155558899', 'SO', TO_DATE('11/20/1986', 'MM/DD/YYYY'), 4420, 4, TO_YMINTERVAL('1-11')); INSERT INTO student VALUES ('NG100', 'Nguyen', 'Ni', 'M', '688 4th Street', 'Orlando', 'FL', '31458', '7155554944', 'FR', TO_DATE('12/4/1986', 'MM/DD/YYYY'), 9188, 3, TO_YMINTERVAL('0-4')); --- inserting records into TERM INSERT INTO term (term_id, term_desc, status) VALUES (1, 'Fall 2005', 'CLOSED'); INSERT INTO term (term_id, term_desc, status) VALUES (2, 'Spring 2006', 'CLOSED'); INSERT INTO term (term_id, term_desc, status) VALUES (3, 'Summer 2006', 'CLOSED'); INSERT INTO term (term_id, term_desc, status) VALUES (4, 'Fall 2006', 'CLOSED'); INSERT INTO term (term_id, term_desc, status) VALUES (5, 'Spring 2007', 'CLOSED'); INSERT INTO term (term_id, term_desc, status) VALUES (6, 'Summer 2007', 'OPEN'); --- inserting records into COURSE INSERT INTO course VALUES ('MIS 101', 'Intro. to Info. Systems', 3); INSERT INTO course VALUES ('MIS 301', 'Systems Analysis', 3); INSERT INTO course VALUES ('MIS 441', 'Database Management', 3); INSERT INTO course VALUES ('CS 155', 'Programming in C++', 3); INSERT INTO course VALUES ('MIS 451', 'Web-Based Systems', 3); --- inserting records into COURSE_SECTION INSERT INTO course_section VALUES (1, 'MIS 101', 4, 1, 2, 'MWF', TO_DATE('10:00 AM', 'HH:MI AM'), TO_DSINTERVAL('0 00:00:50.00'), 1, 140); INSERT INTO course_section VALUES (2, 'MIS 101', 4, 2, 3, 'TR', TO_DATE('09:30 AM', 'HH:MI AM'), TO_DSINTERVAL('0 00:01:15.00'), 7, 35); INSERT INTO course_section VALUES (3, 'MIS 101', 4, 3, 3, 'MWF', TO_DATE('08:00 AM', 'HH:MI AM'), TO_DSINTERVAL('0 00:00:50.00'), 2, 35); INSERT INTO course_section VALUES (4, 'MIS 301', 4, 1, 4, 'TR', TO_DATE('11:00 AM', 'HH:MI AM'), TO_DSINTERVAL('0 00:01:15.00'), 6, 35); INSERT INTO course_section VALUES (5, 'MIS 301', 5, 2, 4, 'TR', TO_DATE('02:00 PM', 'HH:MI PM'), TO_DSINTERVAL('0 00:01:15.00'), 6, 35); INSERT INTO course_section VALUES (6, 'MIS 441', 5, 1, 1, 'MWF', TO_DATE('09:00 AM', 'HH:MI AM'), TO_DSINTERVAL('0 00:00:50.00'), 5, 30); INSERT INTO course_section VALUES (7, 'MIS 441', 5, 2, 1, 'MWF', TO_DATE('10:00 AM', 'HH:MI AM'), TO_DSINTERVAL('0 00:00:50.00'), 5, 30); INSERT INTO course_section VALUES (8, 'CS 155', 5, 1, 5, 'TR', TO_DATE('08:00 AM', 'HH:MI AM'), TO_DSINTERVAL('0 00:01:15.00'), 3, 35); INSERT INTO course_section VALUES (9, 'MIS 451', 5, 1, 2, 'MWF', TO_DATE('02:00 PM', 'HH:MI PM'), TO_DSINTERVAL('0 00:00:50.00'), 5, 35); INSERT INTO course_section VALUES (10, 'MIS 451', 5, 2, 2, 'MWF', TO_DATE('03:00 PM', 'HH:MI PM'), TO_DSINTERVAL('0 00:00:50.00'), 5, 35); INSERT INTO course_section VALUES (11, 'MIS 101', 6, 1, 1, 'MTWRF', TO_DATE('08:00 AM', 'HH:MI AM'), TO_DSINTERVAL('0 00:01:30.00'), 1, 50); INSERT INTO course_section VALUES (12, 'MIS 301', 6, 1, 2, 'MTWRF', TO_DATE('08:00 AM', 'HH:MI AM'), TO_DSINTERVAL('0 00:01:30.00'), 6, 35); INSERT INTO course_section VALUES (13, 'MIS 441', 6, 1, 3, 'MTWRF', TO_DATE('09:00 AM', 'HH:MI AM'), TO_DSINTERVAL('0 00:01:30.00'), 5, 35); --- inserting records into ENROLLMENT INSERT INTO enrollment VALUES ('JO100', 1, 'A'); INSERT INTO enrollment VALUES ('JO100', 4, 'A'); INSERT INTO enrollment VALUES ('JO100', 6, 'B'); INSERT INTO enrollment VALUES ('JO100', 9, 'B'); INSERT INTO enrollment VALUES ('PE100', 1, 'C'); INSERT INTO enrollment VALUES ('PE100', 5, 'B'); INSERT INTO enrollment VALUES ('PE100', 6, 'A'); INSERT INTO enrollment VALUES ('PE100', 9, 'B'); INSERT INTO enrollment VALUES ('MA100', 1, 'C'); INSERT INTO enrollment VALUES ('MA100', 12, NULL); INSERT INTO enrollment VALUES ('MA100', 13, NULL); INSERT INTO enrollment VALUES ('SM100', 11, NULL); INSERT INTO enrollment VALUES ('SM100', 12, NULL); INSERT INTO enrollment VALUES ('JO101', 1, 'B'); INSERT INTO enrollment VALUES ('JO101', 5, 'C'); INSERT INTO enrollment VALUES ('JO101', 9, 'C'); INSERT INTO enrollment VALUES ('JO101', 11, NULL); INSERT INTO enrollment VALUES ('JO101', 13, NULL); INSERT INTO enrollment VALUES ('NG100', 11, NULL); INSERT INTO enrollment VALUES ('NG100', 12, NULL); ALTER TABLE staff DROP COLUMN s_image; COMMIT; <file_sep>--- title: "Keep It Sane" date: 2019-06-16T03:34:27+08:00 tags: ["workflow", "xp"] draft: false # post_id: POST_ID hideToc: true # aliases: [ # "/posts/POST_ID", # ] --- This is a list of issues that I've dealt with at least once. The list would serve as a shortcut to save me time from trying to google the solution again and again. It's like index of things that had bitten me in the past. <!--more--> The list will be updated from time to time as new issue occurs. ## macOS <details open> <summary class="collapsible">collapse</summary> 1. [Source Tree](https://www.sourcetreeapp.com) keep asking for password ([image](/images/macos-sourcetree-keep-asking-for-password.png)) - **tldr**: `git config --global credential.helper osxkeychain` - ref: [stackoverflow](https://stackoverflow.com/questions/38489022/sourcetree-keeps-asking-for-github-password) - Keychain asking password two times - *(Not solved yet)* - NAS disk prompt keeps popping up - *(Not solved yet)* - Activate "Do Not Disturb" mode (disable all notifications) - `alt+click` on notification icon in menu bar. See: [macOS_DnD.mp4](/videos/macOS_DnD.mp4). - macOS won't boot; grey folder with question mark appears during boot - Unfortunately, your SSD might have failed you. Try replacing it. - Blog post: WIP </details> ## Ubuntu <details open> <summary class="collapsible">collapse</summary> 1. Stuck in boot screen (Ubuntu's purple screen) - Login to [recovery mode](/images/ubuntu-recovery-mode.jpg), run `fsck`, reboot. - Recover data from unbootable ubuntu - Boot to [Finnix rescue cd](https://www.finnix.org/Download), activate ssh server, recover data using sftp. See: [Vultr blog post](https://www.vultr.com/docs/using-finnix-rescue-cd-to-rescue-repair-or-backup-your-linux-system) (or see [snapshot](/images/vultr-finnix-rescue-cd.png)). </details> ## Android <details open> <summary class="collapsible">collapse</summary> 1. [Termux](https://termux.com) can't access device storage - Open termux and run `termux-setup-storage` - Termux history is not active - *(Not solved yet)* - Share termux shell as web app - Download [gotty](https://github.com/yudai/gotty), run `./gotty -w sh`, and visit `http://<device-ip>:8080` from browser. - Share android screen to local computer (eg. for demo/presentation) - Install [ScreenStream](https://play.google.com/store/apps/details?id=info.dvkr.screenstream) to stream device screen (mirror) over http. No root required. See: [github repo](https://github.com/dkrivoruchko/ScreenStream). </details> ## Dev <details open> <summary class="collapsible">collapse</summary> 1. Debug GraphQL requests in browser - Use [GraphQL Network](https://chrome.google.com/webstore/detail/graphql-network/igbmhmnkobkjalekgiehijefpkdemocm?hl=en-GB) extension - GraphQL error "GROUP BY clause is incompatible with sql_mode=only_full_group_by" - Remove 'ONLY_FULL_GROUP_BY' from mysql's `sql_mode`. Example: ``` SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY,','')); ``` - See: [stackoverflow](https://stackoverflow.com/questions/23921117/disable-only-full-group-by) - Setting git commit author per repo basis - run this command in root directory of git repo (based on [dereenigne.org](https://dereenigne.org/git/set-git-email-address-on-a-per-repository-basis/)): ``` echo "[user] name = <<NAME>> email = <author oemail>" >> .git/config ``` - Need to quickly switch proxy server for command line environment - use [`proxify.sh`](https://github.com/wzulfikar/lab/blob/master/bash/proxify.sh) - Preview JSON response in Opera: - Install [json-lite](https://addons.opera.com/en/extensions/details/json-lite/) extension - Save time typing `localhost` by aliasing `l` to `localhost` - `echo '127.0.0.1 l' >> /etc/hosts`. `curl l:3000` is now equivalent to `curl localhost:3000` - Create alias for IP address of hostpot-providing device (Android) - `echo '192.168.43.1 android.local' >> /etc/hosts`. See: [stackoverflow](https://stackoverflow.com/questions/17302220/android-get-ip-address-of-a-hotspot-providing-device) - Generate fake data to fill web form - [Form Filler](https://chrome.google.com/webstore/detail/form-filler/bnjjngeaknajbdcgpfkgnonkmififhfo/related?hl=en) </details> ## Workflow <details open> <summary class="collapsible">collapse</summary> 1. Debugging NodeJS, Go, Bash, etc. with vscode - *(Blog post in progress)* - need to grab screen shot and use it as quick reference - use grabit - need to upload file and share it randomly - use transfer.sh - [SublimeText 3](https://www.sublimetext.com/3): show current file in sidebar - `ctrl+0` (ctrl+zero). See: [stackoverflow](https://stackoverflow.com/a/15179191/5381120) - Display full path of file in sublime - See: [stackoverflow](https://stackoverflow.com/a/25948759/5381120) - change command+click handler in iterm (macOS) - *(Not solved yet)* - Convenient scripts: - [collate](https://github.com/wzulfikar/lab/blob/master/bash/collate): combine images to one pdf file - [makegif](https://github.com/wzulfikar/lab/blob/master/bash/makegif), [makemp4](https://github.com/wzulfikar/lab/blob/master/bash/makemp4): convert videos into (optimized) gif/mp4 </details> <!-- ## Others <details open> <summary class="collapsible">collapse</summary> - Can't keep making mistake on opening my washer - add glow-in-the dark sticker. </details> --> {{< load-photoswipe >}}<file_sep> drop table dependents; drop table employees; drop table departments; drop table locations; drop table countries; drop table jobs; drop table regions; CREATE TABLE regions ( region_id NUMBER PRIMARY KEY, region_name VARCHAR2 (25) DEFAULT NULL ); CREATE TABLE jobs ( job_id NUMBER PRIMARY KEY, job_title VARCHAR2 (35) NOT NULL, min_salary NUMBER (8, 2) DEFAULT NULL, max_salary NUMBER (8, 2) DEFAULT NULL ); CREATE TABLE countries ( country_id CHAR (2) PRIMARY KEY, country_name VARCHAR2 (40) DEFAULT NULL, region_id NUMBER NOT NULL, FOREIGN KEY (region_id) REFERENCES regions (region_id) ON DELETE CASCADE ); CREATE TABLE locations ( location_id NUMBER PRIMARY KEY, street_address VARCHAR2 (40) DEFAULT NULL, postal_code VARCHAR2 (12) DEFAULT NULL, city VARCHAR2 (30) NOT NULL, state_province VARCHAR2 (25) DEFAULT NULL, country_id CHAR (2) NOT NULL, FOREIGN KEY (country_id) REFERENCES countries (country_id) ON DELETE CASCADE ); CREATE TABLE departments ( department_id NUMBER PRIMARY KEY, department_name VARCHAR2 (30) NOT NULL, location_id NUMBER DEFAULT NULL, FOREIGN KEY (location_id) REFERENCES locations (location_id) ON DELETE CASCADE ); CREATE TABLE employees ( employee_id NUMBER PRIMARY KEY, first_name VARCHAR2 (20) DEFAULT NULL, last_name VARCHAR2 (25) NOT NULL, email VARCHAR2 (100) NOT NULL, phone_number VARCHAR2 (20) DEFAULT NULL, hire_date DATE NOT NULL, job_id NUMBER NOT NULL, salary NUMBER (8, 2) NOT NULL, manager_id NUMBER DEFAULT NULL, department_id NUMBER DEFAULT NULL, FOREIGN KEY (job_id) REFERENCES jobs (job_id) ON DELETE CASCADE, FOREIGN KEY (department_id) REFERENCES departments (department_id) ON DELETE CASCADE, FOREIGN KEY (manager_id) REFERENCES employees (employee_id) ); CREATE TABLE dependents ( dependent_id NUMBER PRIMARY KEY, first_name VARCHAR2 (50) NOT NULL, last_name VARCHAR2 (50) NOT NULL, relationship VARCHAR2 (25) NOT NULL, employee_id NUMBER NOT NULL, FOREIGN KEY (employee_id) REFERENCES employees (employee_id) ON DELETE CASCADE ); -- Insert data into the regions table. INSERT INTO regions (region_id, region_name) VALUES (1, 'Europe'); INSERT INTO regions (region_id, region_name) VALUES (2, 'Americas'); INSERT INTO regions (region_id, region_name) VALUES (3, 'Asia'); INSERT INTO regions (region_id, region_name) VALUES (4, 'Middle East and Africa'); -- Insert data into the jobs table. INSERT INTO jobs ( job_id, job_title, min_salary, max_salary) VALUES ( 1, 'Public Accountant', '4200.00', '9000.00' ); INSERT INTO jobs ( job_id, job_title, min_salary, max_salary) VALUES ( 2, 'Accounting Manager', '8200.00', '16000.00' ); INSERT INTO jobs ( job_id, job_title, min_salary, max_salary) VALUES ( 3, 'Administration Assistant', '3000.00', '6000.00' ); INSERT INTO jobs ( job_id, job_title, min_salary, max_salary) VALUES ( 4, 'President', '20000.00', '40000.00' ); INSERT INTO jobs ( job_id, job_title, min_salary, max_salary) VALUES ( 5, 'Administration Vice President', '15000.00', '30000.00' ); INSERT INTO jobs ( job_id, job_title, min_salary, max_salary) VALUES ( 6, 'Accountant', '4200.00', '9000.00' ); INSERT INTO jobs ( job_id, job_title, min_salary, max_salary) VALUES ( 7, 'Finance Manager', '8200.00', '16000.00' ); INSERT INTO jobs ( job_id, job_title, min_salary, max_salary) VALUES ( 8, 'Human Resources Representative', '4000.00', '9000.00' ); INSERT INTO jobs ( job_id, job_title, min_salary, max_salary) VALUES ( 9, 'Programmer', '4000.00', '10000.00' ); INSERT INTO jobs ( job_id, job_title, min_salary, max_salary) VALUES ( 10, 'Marketing Manager', '9000.00', '15000.00' ); INSERT INTO jobs ( job_id, job_title, min_salary, max_salary) VALUES ( 11, 'Marketing Representative', '4000.00', '9000.00' ); INSERT INTO jobs ( job_id, job_title, min_salary, max_salary) VALUES ( 12, 'Public Relations Representative', '4500.00', '10500.00' ); INSERT INTO jobs ( job_id, job_title, min_salary, max_salary) VALUES ( 13, 'Purchasing Clerk', '2500.00', '5500.00' ); INSERT INTO jobs ( job_id, job_title, min_salary, max_salary) VALUES ( 14, 'Purchasing Manager', '8000.00', '15000.00' ); INSERT INTO jobs ( job_id, job_title, min_salary, max_salary) VALUES ( 15, 'Sales Manager', '10000.00', '20000.00' ); INSERT INTO jobs ( job_id, job_title, min_salary, max_salary) VALUES ( 16, 'Sales Representative', '6000.00', '12000.00' ); INSERT INTO jobs ( job_id, job_title, min_salary, max_salary) VALUES ( 17, 'Shipping Clerk', '2500.00', '5500.00' ); INSERT INTO jobs ( job_id, job_title, min_salary, max_salary) VALUES ( 18, 'Stock Clerk', '2000.00', '5000.00' ); INSERT INTO jobs ( job_id, job_title, min_salary, max_salary) VALUES ( 19, 'Stock Manager', '5500.00', '8500.00' ); -- Insert data into the countries table. INSERT INTO countries (country_id, country_name, region_id) VALUES ('AR', 'Argentina', 2); INSERT INTO countries (country_id, country_name, region_id) VALUES('AU', 'Australia', 3); INSERT INTO countries (country_id, country_name, region_id) VALUES ('BE', 'Belgium', 1); INSERT INTO countries (country_id, country_name, region_id) VALUES ('BR', 'Brazil', 2); INSERT INTO countries (country_id, country_name, region_id) VALUES ('CA', 'Canada', 2); INSERT INTO countries (country_id, country_name, region_id) VALUES ('CH', 'Switzerland', 1); INSERT INTO countries (country_id, country_name, region_id) VALUES ('CN', 'China', 3); INSERT INTO countries (country_id, country_name, region_id) VALUES ('DE', 'Germany', 1); INSERT INTO countries (country_id, country_name, region_id) VALUES ('DK', 'Denmark', 1); INSERT INTO countries (country_id, country_name, region_id) VALUES ('EG', 'Egypt', 4); INSERT INTO countries (country_id, country_name, region_id) VALUES ('FR', 'France', 1); INSERT INTO countries (country_id, country_name, region_id) VALUES ('HK', 'HongKong', 3); INSERT INTO countries (country_id, country_name, region_id) VALUES ('IL', 'Israel', 4); INSERT INTO countries (country_id, country_name, region_id) VALUES ('IN', 'India', 3); INSERT INTO countries (country_id, country_name, region_id) VALUES ('IT', 'Italy', 1); INSERT INTO countries (country_id, country_name, region_id) VALUES ('JP', 'Japan', 3); INSERT INTO countries (country_id, country_name, region_id) VALUES ('KW', 'Kuwait', 4); INSERT INTO countries (country_id, country_name, region_id) VALUES ('MX', 'Mexico', 2); INSERT INTO countries (country_id, country_name, region_id) VALUES ('NG', 'Nigeria', 4); INSERT INTO countries (country_id, country_name, region_id) VALUES ('NL', 'Netherlands', 1); INSERT INTO countries (country_id, country_name, region_id) VALUES ('SG', 'Singapore', 3); INSERT INTO countries (country_id, country_name, region_id) VALUES ('UK', 'United Kingdom', 1); INSERT INTO countries (country_id, country_name, region_id) VALUES ( 'US', 'United States of America', 2 ); INSERT INTO countries (country_id, country_name, region_id) VALUES ('ZM', 'Zambia', 4); INSERT INTO countries (country_id, country_name, region_id) VALUES ('ZW', 'Zimbabwe', 4); -- Insert data into the locations table. INSERT INTO locations ( location_id, street_address, postal_code, city, state_province, country_id) VALUES ( 1400, '2014 Jabberwocky Rd', '26192', 'Southlake', 'Texas', 'US' ); INSERT INTO locations ( location_id, street_address, postal_code, city, state_province, country_id) VALUES (1500, '2011 Interiors Blvd', '99236', 'South San Francisco', 'California', 'US' ); INSERT INTO locations ( location_id, street_address, postal_code, city, state_province, country_id) VALUES ( 1700, '2004 Charade Rd', '98199', 'Seattle', 'Washington', 'US' ); INSERT INTO locations ( location_id, street_address, postal_code, city, state_province, country_id) VALUES ( 1800, '147 Spadina Ave', 'M5V 2L7', 'Toronto', 'Ontario', 'CA'); INSERT INTO locations ( location_id, street_address, postal_code, city, state_province, country_id) VALUES ( 2400, '8204 Arthur St', NULL, 'London', NULL, 'UK' ); INSERT INTO locations ( location_id, street_address, postal_code, city, state_province, country_id) VALUES ( 2500, 'Magdalen Centre, The Oxford Science Park', 'OX9 9ZB', 'Oxford', 'Oxford', 'UK' ); INSERT INTO locations ( location_id, street_address, postal_code, city, state_province, country_id) VALUES ( 2700, 'Schwanthalerstr. 7031', '80925', 'Munich', 'Bavaria', 'DE' ); -- Insert departments table. INSERT INTO departments ( department_id, department_name, location_id) VALUES (1, 'Administration', 1700); INSERT INTO departments ( department_id, department_name, location_id) VALUES (2, 'Marketing', 1800); INSERT INTO departments ( department_id, department_name, location_id) VALUES (3, 'Purchasing', 1700); INSERT INTO departments ( department_id, department_name, location_id) VALUES (4, 'Human Resources', 2400); INSERT INTO departments ( department_id, department_name, location_id) VALUES (5, 'Shipping', 1500); INSERT INTO departments ( department_id, department_name, location_id) VALUES (6, 'IT', 1400); INSERT INTO departments ( department_id, department_name, location_id) VALUES (7, 'Public Relations', 2700); INSERT INTO departments ( department_id, department_name, location_id) VALUES (8, 'Sales', 2500); INSERT INTO departments ( department_id, department_name, location_id) VALUES (9, 'Executive', 1700); INSERT INTO departments ( department_id, department_name, location_id) VALUES (10, 'Finance', 1700); INSERT INTO departments ( department_id, department_name, location_id) VALUES (11, 'Accounting', 1700); -- Insert data into employees table INSERT INTO employees ( employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, manager_id, department_id) VALUES ( 100, 'Steven', 'King', '<EMAIL>', '515.123.4567', '17-JUN-87', 4, '24000.00', NULL, 9 ); INSERT INTO employees ( employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, manager_id, department_id) VALUES ( 101, 'Neena', 'Kochhar', '<EMAIL>', '515.123.4568', '21-SEP-89', 5, '17000.00', 100, 9 ); INSERT INTO employees ( employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, manager_id, department_id) VALUES ( 102, 'Lex', '<NAME>', '<EMAIL>', '515.123.4569', '13-JAN-93', 5, '17000.00', 100, 9 ); INSERT INTO employees ( employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, manager_id, department_id) VALUES ( 103, 'Alexander', 'Hunold', '<EMAIL>', '590.423.4567', '3-JAN-90', 9, '9000.00', 102, 6 ); INSERT INTO employees ( employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, manager_id, department_id) VALUES ( 104, 'Bruce', 'Ernst', '<EMAIL>', '590.423.4568', '21-MAY-91', 9, '6000.00', 103, 6 ); INSERT INTO employees ( employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, manager_id, department_id) VALUES ( 105, 'David', 'Austin', '<EMAIL>', '590.423.4569', '25-JUN-97', 9, '4800.00', 103, 6 ); INSERT INTO employees ( employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, manager_id, department_id) VALUES ( 106, 'Valli', 'Pataballa', '<EMAIL>', '590.423.4560', '05-FEB-98', 9, '4800.00', 103, 6 ); INSERT INTO employees ( employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, manager_id, department_id) VALUES ( 107, 'Diana', 'Lorentz', '<EMAIL>', '590.423.5567', '7-FEB-99', 9, '4200.00', 103, 6 ); INSERT INTO employees ( employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, manager_id, department_id) VALUES ( 108, 'Nancy', 'Greenberg', '<EMAIL>', '515.124.4569', '17-AUG-94', 7, '12000.00', 101, 10 ); INSERT INTO employees ( employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, manager_id, department_id) VALUES ( 109, 'Daniel', 'Faviet', '<EMAIL>', '515.124.4169', '16-AUG-94', 6, '9000.00', 108, 10 ); INSERT INTO employees ( employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, manager_id, department_id) VALUES ( 110, 'John', 'Chen', '<EMAIL>', '515.124.4269', '28-SEP-97', 6, '8200.00', 108, 10 ); INSERT INTO employees ( employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, manager_id, department_id) VALUES ( 111, 'Ismael', 'Sciarra', '<EMAIL>', '515.124.4369', '30-SEP-97', 6, '7700.00', 108, 10 ); INSERT INTO employees ( employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, manager_id, department_id) VALUES ( 112, '<NAME>', 'Urman', 'jose <EMAIL>', '515.124.4469', '7-MAR-98', 6, '7800.00', 108, 10 ); INSERT INTO employees ( employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, manager_id, department_id) VALUES ( 113, 'Luis', 'Popp', '<EMAIL>', '515.124.4567', '7-DEC-99', 6, '6900.00', 108, 10 ); INSERT INTO employees ( employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, manager_id, department_id) VALUES ( 114, 'Den', 'Raphaely', '<EMAIL>', '515.127.4561', '7-DEC-94', 14, '11000.00', 100, 3 ); INSERT INTO employees ( employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, manager_id, department_id) VALUES ( 115, 'Alexander', 'Khoo', '<EMAIL>', '515.127.4562', '18-MAY-95', 13, '3100.00', 114, 3 ); INSERT INTO employees ( employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, manager_id, department_id) VALUES ( 116, 'Shelli', 'Baida', '<EMAIL>', '515.127.4563', '24-DEC-97', 13, '2900.00', 114, 3 ); INSERT INTO employees ( employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, manager_id, department_id) VALUES ( 117, 'Sigal', 'Tobias', '<EMAIL>', '515.127.4564', '24-JUL-97', 13, '2800.00', 114, 3 ); INSERT INTO employees ( employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, manager_id, department_id) VALUES ( 118, 'Guy', 'Himuro', '<EMAIL>', '515.127.4565', '15-NOV-98', 13, '2600.00', 114, 3 ); INSERT INTO employees ( employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, manager_id, department_id) VALUES ( 119, 'Karen', 'Colmenares', '<EMAIL>', '515.127.4566', '10-AUG-99', 13, '2500.00', 114, 3 ); INSERT INTO employees ( employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, manager_id, department_id) VALUES ( 120, 'Matthew', 'Weiss', '<EMAIL>', '650.123.1234', '18-JUL-96', 19, '8000.00', 100, 5 ); INSERT INTO employees ( employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, manager_id, department_id) VALUES ( 121, 'Adam', 'Fripp', '<EMAIL>', '650.123.2234', '10-APR-97', 19, '8200.00', 100, 5 ); INSERT INTO employees ( employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, manager_id, department_id) VALUES ( 122, 'Payam', 'Kaufling', '<EMAIL>', '650.123.3234', '1-MAY-95', 19, '7900.00', 100, 5 ); INSERT INTO employees ( employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, manager_id, department_id) VALUES ( 123, 'Shanta', 'Vollman', '<EMAIL>', '650.123.4234', '10-OCT-97', 19, '6500.00', 100, 5 ); INSERT INTO employees ( employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, manager_id, department_id) VALUES ( 126, 'Irene', 'Mikkilineni', '<EMAIL>', '650.124.1224', '28-SEP-98', 18, '2700.00', 120, 5 ); INSERT INTO employees ( employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, manager_id, department_id) VALUES ( 145, 'John', 'Russell', '<EMAIL>', NULL, '01-OCT-96', 15, '14000.00', 100, 8 ); INSERT INTO employees ( employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, manager_id, department_id) VALUES ( 146, 'Karen', 'Partners', '<EMAIL>', NULL, '5-JAN-97', 15, '13500.00', 100, 8 ); INSERT INTO employees ( employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, manager_id, department_id) VALUES ( 176, 'Jonathon', 'Taylor', '<EMAIL>', NULL, '24-MAR-98', 16, '8600.00', 100, 8 ); INSERT INTO employees ( employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, manager_id, department_id) VALUES ( 177, 'Jack', 'Livingston', '<EMAIL>', NULL, '23-APR-98', 16, '8400.00', 100, 8 ); INSERT INTO employees ( employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, manager_id, department_id) VALUES ( 178, 'Kimberely', 'Grant', '<EMAIL>', NULL, '24-MAY-99', 16, '7000.00', 100, 8 ); -- Insert data into the dependents table INSERT INTO dependents ( dependent_id, first_name, last_name, relationship, employee_id) VALUES ( 4, 'Jennifer', 'King', 'Child', 100); INSERT INTO dependents ( dependent_id, first_name, last_name, relationship, employee_id) VALUES ( 5, 'Johnny', 'Kochhar', 'Child', 101 ); INSERT INTO dependents ( dependent_id, first_name, last_name, relationship, employee_id) VALUES ( 6, 'Bette', '<NAME>', 'Child', 102 ); INSERT INTO dependents ( dependent_id, first_name, last_name, relationship, employee_id) VALUES ( 7, 'Grace', 'Faviet', 'Child', 109 ); INSERT INTO dependents ( dependent_id, first_name, last_name, relationship, employee_id) VALUES ( 8, 'Matthew', 'Chen', 'Child', 110 ); INSERT INTO dependents ( dependent_id, first_name, last_name, relationship, employee_id) VALUES ( 9, 'Joe', 'Sciarra', 'Child', 111 ); INSERT INTO dependents ( dependent_id, first_name, last_name, relationship, employee_id) VALUES ( 10, 'Christian', 'Urman', 'Child', 112 ); INSERT INTO dependents ( dependent_id, first_name, last_name, relationship, employee_id) VALUES ( 11, 'Zero', 'Popp', 'Child', 113 ); INSERT INTO dependents ( dependent_id, first_name, last_name, relationship, employee_id) VALUES ( 12, 'Karl', 'Greenberg', 'Child', 108 ); INSERT INTO dependents ( dependent_id, first_name, last_name, relationship, employee_id) VALUES ( 14, 'Vivien', 'Hunold', 'Child', 103 ); INSERT INTO dependents ( dependent_id, first_name, last_name, relationship, employee_id) VALUES ( 15, 'Cuba', 'Ernst', 'Child', 104 ); INSERT INTO dependents ( dependent_id, first_name, last_name, relationship, employee_id) VALUES ( 16, 'Fred', 'Austin', 'Child', 105 ); INSERT INTO dependents ( dependent_id, first_name, last_name, relationship, employee_id) VALUES ( 17, 'Helen', 'Pataballa', 'Child', 106 ); INSERT INTO dependents ( dependent_id, first_name, last_name, relationship, employee_id) VALUES ( 18, 'Dan', 'Lorentz', 'Child', 107 ); INSERT INTO dependents ( dependent_id, first_name, last_name, relationship, employee_id) VALUES ( 22, 'Elvis', 'Khoo', 'Child', 115 ); INSERT INTO dependents ( dependent_id, first_name, last_name, relationship, employee_id) VALUES ( 23, 'Sandra', 'Baida', 'Child', 116 ); INSERT INTO dependents ( dependent_id, first_name, last_name, relationship, employee_id) VALUES ( 24, 'Cameron', 'Tobias', 'Child', 117 ); INSERT INTO dependents ( dependent_id, first_name, last_name, relationship, employee_id) VALUES ( 25, 'Kevin', 'Himuro', 'Child', 118 ); INSERT INTO dependents ( dependent_id, first_name, last_name, relationship, employee_id) VALUES ( 26, 'Rip', 'Colmenares', 'Child', 119 ); INSERT INTO dependents ( dependent_id, first_name, last_name, relationship, employee_id) VALUES ( 27, 'Julia', 'Raphaely', 'Child', 114 ); INSERT INTO dependents ( dependent_id, first_name, last_name, relationship, employee_id) VALUES ( 28, 'Woody', 'Russell', 'Child', 145 ); INSERT INTO dependents ( dependent_id, first_name, last_name, relationship, employee_id) VALUES ( 29, 'Alec', 'Partners', 'Child', 146 ); INSERT INTO dependents ( dependent_id, first_name, last_name, relationship, employee_id) VALUES ( 30, 'Sandra', 'Taylor', 'Child', 176 );<file_sep>#include<iostream> using namespace std; string func(string str) { return (str.find("0000000") != -1 || str.find("1111111") != -1) ? "YES" : "NO"; } void test() { cout << (func("001001") == "NO" ? "✔ " : "✘ "); cout << (func("1000000001") == "YES" ? "✔ " : "✘ "); } int main(){ test(); // string s; // cin >> s; // cout << func(s); }<file_sep># While normal functions are defined using the def keyword, # in Python, anonymous functions are defined using the `lambda` keyword. print('- lambda to add two numbers', (lambda x, y: x + y)(4, 2)) def multiplier(base: int) -> int: return lambda x: base * x m = multiplier(5) print("m of 5 =", m(5)) print("m of 2 =", m(2)) <file_sep>package main import ( "encoding/json" "fmt" ) type context struct { Ctx string `json:"ctx"` Data map[string]string `json:"data"` } func main() { ctx := &context{ "merchant.checkout", map[string]string{ "hello": "asa", }, } b, err := json.Marshal(ctx) if err != nil { fmt.Println(err) return } fmt.Println("json of ctx:", string(b)) ctxJson := []byte(`{"ctx":"merchant.checkout","data":{"hello":"from json"}}`) if err := json.Unmarshal(ctxJson, ctx); err != nil { fmt.Println(err) return } fmt.Println("data of ctx", ctx) } <file_sep>-- Class #4: Wed, 20 Sep 2017 at 14:23:36 MYT # exercise 1 SET LINESIZE 75 SET PAGESIZE 50 TTITLE 'LIST OF BOOKS || TYPE: PSY' -- `|` means new line COLUMN bcode HEADING 'BOOK|CODE' FORMAT A10 COLUMN title HEADING 'BOOK|TITLE' FORMAT A10 COLUMN type HEADING 'BOOK|TYPE' FORMAT A10 COLUMN price HEADING 'PRICE' FORMAT $999.99 SELECT book_code bcode , title, type, price FROM book WHERE type = 'PSY'; SET LINESIZE 80 TTITLE OFF CLEAR COLUMNS # exercise 2 SET LINESIZE 75 SET PAGESIZE 50 TTITLE 'LIST OF BOOKS' -- `|` means new line BREAK ON type SKIP 2 COLUMN bcode HEADING 'BOOK|CODE' FORMAT A10 COLUMN title HEADING 'BOOK|TITLE' FORMAT A10 COLUMN type HEADING 'BOOK|TYPE' FORMAT A10 COLUMN price HEADING 'PRICE' FORMAT $999.99 SELECT type, book_code bcode, title, price FROM book WHERE type IN ('POE', 'ART'); SET LINESIZE 80 TTITLE OFF CLEAR COLUMNS # exercise 3 SET LINESIZE 100 SET PAGESIZE 50 TTITLE 'LIST OF BOOKS' -- `|` means new line BREAK ON city SKIP 2 ON publisher_code SKIP 2 COLUMN city HEADING 'CITY' FORMAT A20 COLUMN publisher_code HEADING 'PUB' FORMAT A5 COLUMN title HEADING 'TITLE' FORMAT A40 select p.city city, p.publisher_code, b.title from book b join publisher p on b.publisher_code = p.publisher_code where p.city IN ('Boston', 'Boulder CO', 'Westport CT') order by p.city; SET LINESIZE 80 TTITLE OFF CLEAR COLUMNS -- Class #5: Mon, 25 Sep 2017 at 14:10:36 MYT -- see `sql-block1.sql` & `sql-block2.sql` -- Class #6: Wed, 27 Sep 2017 at 14:33:02 MYT -- see `cursor1.sql`<file_sep>package main import ( "fmt" "reflect" "strings" ) func main() { structReflect() } func structReflect() { person := struct { Name string `json:"name"` Age int married bool }{ "<NAME>", 34, false, } rv := reflect.ValueOf(person) for i := 0; i < rv.NumField(); i++ { fld := rv.Field(i) typeFld := rv.Type().Field(i) fmt.Printf("Field #%d : %s\n", i, typeFld.Name) fmt.Printf("Type : %s\n", fld.Type()) fmt.Printf("Tag : %s\n", typeFld.Tag) fmt.Printf("JSON Tag : %s\n", typeFld.Tag.Get("json")) fieldUnexported := typeFld.Name[0:1] == strings.ToLower(typeFld.Name[0:1]) if fieldUnexported { fmt.Printf("Value : not available (unexported)\n") } else { fmt.Printf("Value : %v\n", fld.Interface()) } fmt.Println() } } <file_sep>--- title: "PPI-IIUM Producation 2018: Finding Passion in University" date: 2018-03-27T20:00:34+08:00 publishAt: 2018-03-30T20:00:00+08:00 tags: ["xp", "reflection"] draft: false hideToc: true --- Earlier this week, I received an invitation from Persatuan Pelajar Indonesia (PPI) –– an Indonesian Students Society at my campus (IIUM, Malaysia), to become a speaker of a sharing session event titled "Producation". The event will be held at IIUM this coming Friday, March 30. <!--more--> The name "Producation" is an acronym for "Professional Education". In a nutshell, it's a sharing session to help improve participants' understanding of professionalism. There will be four speakers for the event, each with different topic to share. The topic I'll be sharing is titled "Finding Passion in University". That's it, finding your passion, while you're in university –– of course, it's not about whether you're passionate with the university itself. While waiting for the day of the event to come, I kind of thinking to prepare the things that I'd like to share by drafting it here and publishing it after the event. There'll be only 15 minutes slot for each session; wouldn't be nice if I missed a thing to share just because I didn't prepare. I'm not calling myself professional, but I've around 5 years experience working with professionals –– mostly in IT companies, and I'd like to share what I've learnt from them. If you're interested to the Google Slides used during the event (sharing session), you can find it at the end of this post. ### 1. Skolafund [![skolafund logo](/images/sf-logo-with-slogan-sm.png#featured)](https://skolafund.com) Skolafund (https://skolafund.com) is a crowdfunding education focused on higher education. Think of it as [kickstarter](https://www.kickstarter.com), [gofundme](https://www.gofundme.com), or [launchgood](https://www.launchgood.com), but for funding university tuition fee, research project, and other education-related. It started in 2015, four of us, and we were all still studying in our university –– two of us at National University of Singapore (NUS) and the other two (me and my friend) at International Islamic University Malaysia (IIUM). I've learnt a lot from my team. Importance of communication, commitment, etc. But what I'd like to share is what we've found and see as common students' problem: communication. Since we deal with the students on daily basis (ie. vetting campaigns, answering queries, etc.) , we'd be credible enough to share a thing or two on this matter. #### Common Problem: Communication We can agree that a good intention, can be misinterpreted just because it's not well-communicated (hence the term, _miscommunication_). At Skolafund, we've found so many students with appealing stories for their campaigns, with the purest of intentions, but not well-communicated. In this case, the writing communication. Put aside the logical flow of the writing and let's get to the more obvious part: grammar. A campaign story might be appealing, but having too many grammatical errors will make the readers think that the campaign was not seriously created. _And that can hurt Skolafund's professional pride._ We created the platform so people who want to donate can donate peacefully, without thinking whether the campaign is a scam or not. Thus, having low quality campaigns is not an option. _It will simply hurt us._ ### 2. Learning Process: The Loop We've related the term "professionalism" in point 1: Skolafund. The word "professionalism" itself gives us cue that it must be related to profession. Reflecting on those times I've worked at Skolafund, and other times working with other people, I realized that there are still more to learn, which has changed my perspective on how I see teaching and learning activity in classroom. Prior to this, I used to come to class, listen to the lecture, and _I'll get what I get, no complaints_. Nothing to lose, because I didn't have anything to look for at the first place. Things changed: the more I worked with those people, the more I know that there are still a lot of things to learn. During the works, I'll put in mind the things that I doubted or simply didn't know. Those things, those questions I've in mind, I'd bring it to class and ask it to the lecturer. Now, I've better motive to come to class. I know what I'm looking for, because I took time to find what is it that I'm looking for. I've something to lose if I didn't took the correct subject. I've created a loop that will keep me driven: *learn - work - learn*. And more importantly, I've found what I think as _the joy of learning_. That is, when you know what you want to look for, fight your way to find it, and you finally find it. _You know, those "aha" moments._ ### 3. Relate Yourself To me, university life is one of those places where you can easily relate things to yourself. With the variety of subjects we take, assignments we have, places we visit, activities we join, etc., it's almost unlikely that we can't find anything related to ourselves. In university, anyone can try to become a good or bad listener _through_ lectures. A student can explore what it takes to do a research by joining research group. People can assess if they've what it takes to be a team-player by doing group activities. Stimulate yourself with activities you've in university. If you're trying to find what's your passion, or what you relate to; <u>_don't just do it, bring your consciousness, and get enlightened_</u>. ### 4. Bonus I like to think of writing as an easy way to discover our passion. Choose one topic that you like to write. Start writing. Don't bother with the end result of your writing. If you find yourself indulged and pleased during the process of writing that particular topic, then probably that topic is what you're passionate about. Still related to writing, there's this website that provide examples and templates to help you start writing. Check the website and see for youself: [writewellapp.com](http://writewellapp.com). Lastly, while not everyone is a fan of writing in computer (typing), having ability to type fast can be extremely helpful in today's world, where most things are digitalized. For this, you can check [typing.com](https://www.typing.com), a fun website for you to practice on your fast-typing skill. ### Closing Not everyone in university study what he/she genuinely want to study. Some became doctors because they want to please their parents, some took certain course because that's the course offered by the scholarship, etc. Nothing's wrong with that. But when someone does it out of thought that there's no other option, that's the problem. We can't control what could happen to us at the moment, but we can control how we react. Take a time for yourself, read your current situation and use it for your benefit: find what you can relate to yourself. Once you've your findings, go for it. If you find yourself fighting for it, that is, you might have found your passion. <iframe src="https://docs.google.com/presentation/d/e/2PACX-1vT7biNAKKUWk1EpFNFZsE-8Xd41iuZqOkY0uYUSeLYawhbxPAefWDjRC9OQvjucVerHCvPYE2BShpzq/embed?start=false&loop=false&delayms=3000" frameborder="0" width="100%" height="350" allowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true"></iframe> <br/> ***Till next. See ya!*** <file_sep>package alprgo import ( "fmt" "log" "os" "path/filepath" "time" "github.com/openalpr/openalpr/src/bindings/go/openalpr" ) type BindingHandler struct { Country string Config string RuntimeDir string ProcessedImagesPath string Alpr *openalpr.Alpr } func NewBindingHandler(country, config, runtimeDir string) *BindingHandler { alpr := openalpr.NewAlpr(country, config, runtimeDir) processedImagesPath := "processed" return &BindingHandler{country, config, runtimeDir, processedImagesPath, alpr} } // TODO: // figure out cgo panic when `RecognizeByFilePath` is run in routine: // "terminating with uncaught exception of type std::out_of_range: vector" func (h *BindingHandler) Handle(imagePath string) { r, err := h.Alpr.RecognizeByFilePath(imagePath) if err != nil { fmt.Println("alprResultErr:", err) return } go h.handleResult(imagePath, &r) } func (h *BindingHandler) handleResult(imagePath string, alprResult *openalpr.AlprResults) { var plates []string minConfidence := float32(85.0) hit := "HIT" for _, result := range alprResult.Plates { for i, candidate := range result.TopNPlates { if candidate.OverallConfidence > minConfidence && i < 3 { plates = append(plates, candidate.Characters) } } } if len(plates) == 0 { fmt.Println("No license detected") hit = "MISS" } else { fmt.Println(plates) } // move processed image path := filepath.Dir(imagePath) imageFile := filepath.Base(imagePath) ts := time.Now().Format("2006-01-02-150405") processedImage := fmt.Sprintf("%s-%s__%s", ts, hit, imageFile) processedPath := fmt.Sprintf("%s/%s/%s", path, h.ProcessedImagesPath, processedImage) if err := os.Rename(imagePath, processedPath); err != nil { log.Println("moveProcessedImageErr:", err) } } <file_sep>// Watch for new file in WORKDIR and run alpr. // USAGE: // WORKDIR=/Volumes/data/playground/plates COUNTRY=eu go run watchexec.go package main import ( "fmt" "log" "os" alprgo "github.com/wzulfikar/lab/go/alpr" ) func main() { workdir := os.Getenv("WORKDIR") adjustStdout := true country := "eu" processedImagesPath := "processed" h := alprgo.NewExecHandler(adjustStdout, country, processedImagesPath) fmt.Println("Scanning directory started") go alprgo.ScanDir(workdir, h) log.Fatal(alprgo.Watch(workdir, h)) } <file_sep>package main import ( "fmt" "image/color" "log" "os" "github.com/wzulfikar/lab/go/gocvgo" "gocv.io/x/gocv" ) func main() { if len(os.Args) < 3 { fmt.Println("Usage:\n\trelay {classifierfile} {videourl}") return } // prepare classifier fd, err := gocvgo.NewFaceDetector(os.Args[1], color.RGBA{0, 0, 255, 0}) if err != nil { log.Fatal(err) } defer fd.Close() url := os.Args[2] log.Println("Opening video at", url) v, err := gocv.VideoCaptureFile(url) if err != nil { fmt.Printf("error opening video capture file: %v\n", url) return } defer v.Close() relay(v, url, fd) } func relay(video *gocv.VideoCapture, title string, fd *gocvgo.FaceDetector) { // open display window window := gocv.NewWindow("Video Relay: " + title) defer window.Close() // prepare image matrix img := gocv.NewMat() defer img.Close() log.Println("Started relaying video") for { if ok := video.Read(&img); !ok { fmt.Printf("cannot read file %d\n", title) return } if img.Empty() { continue } fd.Draw(&img, "Human") // show the image in the window, and wait 1 millisecond window.IMShow(img) if window.WaitKey(1) >= 0 { break } } } <file_sep>package main import ( "fmt" "github.com/asaskevich/EventBus" ) const EVENT_1 = "demo:event-1" const EVENT_2 = "demo:event-2" // Demonstrate the use of event bus in Go // using asaskevich/EventBus package func main() { bus := EventBus.New() registerListeners(bus) // Trigger "event 1", no args bus.Publish(EVENT_1) // Trigger "event 2", with args bus.Publish(EVENT_2, "Hello", "World") // Remove (unsubsribe) listener from event bus.Unsubscribe(EVENT_1, eventOneListener1) fmt.Println("\nListener has been unsubsribed") bus.Publish(EVENT_1) // spew.Dump(bus) } func registerListeners(bus EventBus.Bus) { bus.Subscribe(EVENT_1, eventOneListener1) bus.Subscribe(EVENT_1, eventOneListener2) bus.Subscribe(EVENT_2, eventTwoListener) } func eventOneListener1() { fmt.Println("Listener 1 executed") } func eventOneListener2() { fmt.Println("Listener 2 executed") } func eventTwoListener(args ...interface{}) { fmt.Printf("Listener 3 executed. Args: %v", args) } <file_sep>package main import ( "fmt" "strings" ) func do(s1, s2 string) int { s1 = strings.ToLower(s1) s2 = strings.ToLower(s2) if s1 < s2 { return -1 } else if s1 > s2 { return 1 } return 0 } // func Test(t *testing.T) { // a := assert.New(t) // // a.Equal( 0, do("aaaa", "aaaA")) // a.Equal(-1, do("abs", "Abz")) // a.Equal( 1, do("abcdefg", "AbCdEfF")) // } func main() { var s1, s2 string fmt.Scan(&s1, &s2) fmt.Println(do(s1, s2)) } <file_sep>package main import ( "bytes" "io/ioutil" "log" "path" "github.com/davecgh/go-spew/spew" "github.com/spf13/viper" ) func main() { v := viper.New() if err := addViperConfig(v, "/path/to/config.json"); err != nil { log.Fatal(err) } spew.Dump(v.Get("asdf")) } func addViperConfig(v *viper.Viper, conf string) error { ext := path.Ext(conf) v.SetConfigType(ext[1:]) data, err := ioutil.ReadFile(conf) if err != nil { return err } if err := v.ReadConfig(bytes.NewBuffer(data)); err != nil { return err } return nil } <file_sep>package main import ( "fmt" "log" "os" "os/signal" "syscall" "time" ) // function to display total execution time func timer() func() { start := time.Now() return func() { log.Println("Total execution time:", time.Since(start)) } } func main() { defer timer()() pause := make(chan bool) resume := make(chan bool) paused := false go func(pause chan bool, resume chan bool, paused *bool) { for { select { case <-pause: fmt.Println("Received pause signal. Press ^C to resume") case <-resume: fmt.Println("Resuming..") default: } if !*paused { fmt.Println("In loop.. Press ^C to pause or ^\\ to quit") time.Sleep(time.Second) } } }(pause, resume, &paused) signalCh := make(chan os.Signal) signal.Notify(signalCh, os.Interrupt, syscall.SIGTERM) go func(paused *bool) { for { select { case <-signalCh: if !*paused { *paused = true pause <- true } else { *paused = false resume <- true } } } }(&paused) exitSignal := make(chan os.Signal) signal.Notify(exitSignal, syscall.SIGQUIT) <-exitSignal fmt.Println("Program exited.") } <file_sep>package main import ( "fmt" ) func do(s string) string { if length := len(s); length > 10 { return fmt.Sprintf("%c%d%c", s[0], length-2, s[length-1]) } return s } // func Test(t *testing.T) { // a := assert.New(t) // a.Equal("word", do("word")) // a.Equal("l10n", do("localization")) // a.Equal("i18n", do("internationalization")) // a.Equal("p43s", do("pneumonoultramicroscopicsilicovolcanoconiosis")) // a.Equal("abcdefghij", do("abcdefghij")) // } func main() { var n int var s string fmt.Scan(&n) for n > 0 { fmt.Scan(&s) fmt.Println(do(s)) n-- } } <file_sep>package main import ( "io/ioutil" "log" "github.com/matcornic/hermes" "github.com/skratchdot/open-golang/open" ) const previewFile = "hermespreview.html" // Sample use case: // Auto preview using python `entr`. // `find . -name \*.go | entr sh -c "go run hermespreview.go"` func main() { log.Println("Generating email preview..") h := hermesInit() emailBody, _ := h.GenerateHTML(email(payload())) ioutil.WriteFile("preview.html", []byte(emailBody), 0644) open.Start(previewFile) log.Println("✔ Done") } // 1. Configure and initialize hermes func hermesInit() hermes.Hermes { return hermes.Hermes{ // Optional Theme Theme: new(hermes.Default), Product: hermes.Product{ // Appears in header & footer of e-mails Name: "Hermes", Link: "https://example-hermes.com/", // Optional product logo Logo: "http://www.duchess-france.org/wp-content/uploads/2016/01/gopher.png", }, } } // 2. Payload set up type MailPayload struct { user_name string } func payload() MailPayload { return MailPayload{ "<NAME>", } } // 3. Craft email content func email(payload MailPayload) hermes.Email { return hermes.Email{ Body: hermes.Body{ Name: payload.user_name, Intros: []string{ "Welcome to Hermes! We're very excited to have you on board.", }, Dictionary: []hermes.Entry{ {Key: "Firstname", Value: "Jon"}, {Key: "Lastname", Value: "Snow"}, {Key: "Birthday", Value: "01/01/283"}, }, Actions: []hermes.Action{ { Instructions: "To get started with Hermes, please click here:", Button: hermes.Button{ Text: "Confirm your account", Link: "https://hermes-example.com/confirm?token=<PASSWORD>", }, }, }, Outros: []string{ "Need help, or have questions? Just reply to this email, we'd love to help.", }, }, } } <file_sep>CREATE OR REPLACE PROCEDURE Emp_Proc (peno IN employee.empno%TYPE pename OUT employee.ename%TYPE pjob OUT employee.job%TYPE pbranch_name OUT employee.branch_name%TYPE pbranch_location OUT employee.branch_location%TYPE) AS SELECT ename, job, branch_name, branch_location INTO pename, pjob, pbranch_name, pbranch_location FROM employee NATURAL JOIN branch WHERE empno = peno; BEGIN -- Find employee details END Emp_Proc; ACCEPT eno PROMPT 'Enter the employee number: ' -- ANONYMOUS BLOCK DECLARE BEGIN v_name v_job v_bname v_blocation employee.ename%TYPE; employee.job%TYPE; branch.branch_name%TYPE; branch.branch_location%TYPE; END; Emp_Proc(&eno, v_name, v_job, v_bname, v_blocation); DBMS_OUTPUT.put_line('Name: ' || v_name); DBMS_OUTPUT.put_line('Job: ' || v_job); DBMS_OUTPUT.put_line('Branch Name: ' || v_bname); DBMS_OUTPUT.put_line('Branch Location: ' || v_blocation); END; /<file_sep>#include <iostream> #include <list> using namespace std; // template template<class T> class Node { public: T value; Node<T>* left; Node<T>* right; Node(T value) { this->value = value; this->left = NULL; this->right = NULL; } }; template<class F> class BST { private: Node<F> *root; void prefix (Node<F>* current) { if (current != NULL) { cout << current->value << ' '; prefix(current->left); prefix(current->right); } } void infix (Node<F>* current) { if (current != NULL) { infix(current->left); cout << current->value << ' '; infix(current->right); } } void reverseInfix (Node<F>* current) { if (current != NULL) { reverseInfix(current->right); cout << current->value << ' '; reverseInfix(current->left); } } void postfix (Node<F>* current) { if (current != NULL) { postfix(current->left); postfix(current->right); cout << current->value << ' '; } } public: BST(){ root = NULL; } void insert (F value) { if (root == NULL) { root = new Node<F>(value); } else { Node<F>* temp = root; while (temp != NULL) { if (value > temp->value) { if (temp->right == NULL) { temp->right = new Node<F>(value); break; } temp = temp->right; } else { if (temp->left == NULL) { temp->left = new Node<F>(value); break; } temp = temp->left; } } } } bool find (F value) { Node<F>* temp = root; while (temp != NULL) { if (value == temp->value) { return true; } temp = value > temp->value ? temp->right : temp->left; } return false; } void display (int order = 0) { switch (order) { case 0: cout << "Displaying tree in PREFIX mode:\n"; prefix(root); break; case 1: cout << "Displaying tree in INFIX mode:\n"; infix(root); break; case 2: cout << "Displaying tree in POSTFIX mode:\n"; postfix(root); break; case 3: cout << "Displaying tree in REVERSE-INVIX mode:\n"; reverseInfix(root); break; default: prefix(root); } } }; int main() { BST<int> tree; tree.insert(5); tree.insert(10); tree.insert(3); tree.insert(7); tree.insert(10); tree.insert(7); tree.display(3); string findNode = tree.find(11) ? "Found" : "Not found"; cout << "\nNode 11 is " << findNode; string findNode2 = tree.find(10) ? "Found" : "Not found"; cout << "\nNode 10 is " << findNode2; return 0; } <file_sep>--- title: "Http vs Https" date: 2018-03-06T17:34:04+08:00 tags: [""] draft: true --- `TODO: write content` <p class="text-center">***</p> *Outline:* 1. <file_sep>-- Mon, 25 Sep 2017 at 14:59:32 MYT SET SERVEROUTPUT ON SET VERIFY OFF ACCEPT bcode prompt 'Enter the book code: ' DECLARE v_title book.title%TYPE; v_price book.price%TYPE; v_price_discounted book.price%TYPE; BEGIN SELECT title, price, CASE WHEN TYPE = 'ART' THEN ROUND(price / (1-0.10), 2) WHEN TYPE = 'FIC' THEN ROUND(price * (1-0.15), 2) ELSE price END INTO v_title, v_price, v_price_discounted FROM book WHERE book_code = '&bcode'; DBMS_OUTPUT.PUT_LINE ('The title of the books is ' || v_title); DBMS_OUTPUT.PUT_LINE ('Original Price: RM ' || v_price); DBMS_OUTPUT.PUT_LINE ('The price after discount: RM ' || v_price_discounted); END; / SET SERVEROUTPUT OFF SET VERIFY ON <file_sep>--- title: "{{ replace .TranslationBaseName "-" " " | title }}" date: {{ .Date }} tags: [""] draft: true hideToc: true post_id: POST_ID aliases: [ "/posts/POST_ID", ] --- TODO: summary <!--more--> TODO: content <p class="text-center">***</p> *Outline:* 1. {{< load-photoswipe >}} <file_sep>--- title: "Understanding Cross Platform Environment" date: 2018-04-16T00:53:21+08:00 tags: [""] draft: true --- `TODO: write content` <p class="text-center">***</p> *Outline:* 1. <file_sep>--- title: "Mind Not Found" date: 2018-03-07T10:47:38+08:00 tags: [""] draft: true --- `TODO: write content` <p class="text-center">***</p> *Outline:* 1. woke up late 2. decided to not enter class 3. enter next class, lecturer ask why i enter the class 4. a bit confused, and realised of everythings 5. conclusion: mind wasn't there.<file_sep>#include<iostream> #include <bits/stdc++.h> using namespace std; int main(){ char str1[100], str2[100]; cin >> str1 >> str2; cout << stricmp(str1, str2); return 0; }<file_sep>package resolvers import ( "context" "github.com/volatiletech/sqlboiler/queries/qm" "/models" "/modules/graphql/app" ) type PersonResultResolver struct { totalCount int64 pageInfo *app.PageInfoResolver items []*personResolver } func (r *PersonResultResolver) PageInfo() *app.PageInfoResolver { return r.pageInfo } type PersonFilter struct { // Add Person filter here } type PersonesArgs struct { Page *app.PageArgs Filter *PersonFilter } func (rr *RootResolver) People(ctx context.Context, args *PersonesArgs) (*PersonResultResolver, error) { var mods []qm.QueryMod if args.Filter != nil { whereMods, err := app.WhereMods([]app.MaybeMod{ // Add mods for qm.Where here. See: app.MaybeMod }) if err != nil { return nil, err } mods = append(mods, whereMods...) } count, err := models.People(rr.Db, mods...).Count() if err != nil { return nil, nil } pageInfo, err := args.Page.PageInfo(count) if err != nil { return nil, err } mods = append(mods, pageInfo.QM()...) o, err := models.People(rr.Db, mods...).All() if err != nil { return nil, err } result := &PersonResultResolver{ totalCount: count, pageInfo: pageInfo.Resolver(), } for _, row := range o { result.items = append(result.items, &personResolver{rr: rr, o: row}) } return result, nil } func (r *PersonResultResolver) TotalCount() (int32, error) { return int32(r.totalCount), nil } func (r *PersonResultResolver) Items() ([]*personResolver, error) { return r.items, nil } <file_sep>SET SERVEROUTPUT ON SET VERIFY OFF ACCEPT pcode PROMPT 'Enter the publisher code: ' DECLARE CURSOR c1 IS SELECT BOOK_CODE, TITLE, PRICE FROM book WHERE PUBLISHER_CODE = '&pcode'; book_rec c1%ROWTYPE; BEGIN OPEN c1; LOOP FETCH c1 INTO book_rec; EXIT WHEN c1%NOTFOUND; -- use explicit cursor `c1` DBMS_OUTPUT.PUT_LINE (book_rec.book_code || ' ' || book_rec.title || ' ' || book_rec.price); END LOOP; CLOSE c1; END; /<file_sep>package main import ( "fmt" "os" "os/signal" cron "gopkg.in/robfig/cron.v2" ) func main() { for { c := cron.New() c.AddFunc("* * * * * *", func() { fmt.Println("Every second") }) c.AddFunc("@daily", func() { fmt.Println("Every day") }) go c.Start() sig := make(chan os.Signal) signal.Notify(sig, os.Interrupt, os.Kill) <-sig } // Inspect the cron job entries' next and previous run times. // spew.Dump(c.Entries()) } <file_sep>// run the program and generate the version string: // go run -ldflags "-X 'main.VersionString=1.0 (beta)'" gogenerate.go // // you can also use -ldflags in `go build`: // go run -ldflags "-X 'main.VersionString=1.0 (beta)'" gogenerate.go package main import ( "fmt" ) var VersionString = "(unset)" func main() { fmt.Println("Version:", VersionString) } <file_sep>select s.student_id, c.course_no from STUDENT s join enrollment e on s.student_id = e.student_id join course_section c on e.c_sec_id = c.c_sec_id where c.course_no = 'MIS 101' and c.course_no != 'MIS 451'; select databases from dual; -- Practice 2.1 -- insert classes conducted in BUS and CR to respective tables `Class_Bus` and `Class_CR` with ONE INSERT STATEMENT -- delete table DROP TABLE Class_Bus;DROP TABLE Class_CR; -- insert INSERT ALL<file_sep>#include <iostream> #include <vector> #include <string> #include <sstream> #include <iterator> using namespace std; string run(string str) { // parse str to args istringstream buf(str); istream_iterator<std::string> beg(buf), end; vector<std::string> tokens(beg, end); std::string::size_type sz; // h, w, l, v int args[4]; for (int i = 0; i < tokens.size(); ++i) { args[i] = std::stoi (tokens[i], &sz); } /** * KEYWORD: "<PASSWORD>" */ // calc volume long long int leon = args[0] * args[1] * args[2]; long long int pyramid = args[3]; // cout << "leon: " << leon << " pyramid: " << pyramid; if (leon * 1000 <= pyramid) { return "YES"; } return "NO"; } void test() { cout << (run("1 1 1 1") == "NO" ? "✔ " : "✘ "); cout << (run("1 1 1 1000") == "YES" ? "✔ " : "✘ "); cout << (run("1 1 1 10000") == "YES" ? "✔ " : "✘ "); cout << (run("10 10 10 1000") == "NO" ? "✔ " : "✘ "); cout << (run("100 100 1000 1000") == "NO" ? "✔ " : "✘ "); } int main(){ // test(); return 0; string a; cin >> a; cout << run(a); return 0; }<file_sep>## Udacity: Intro to Self-driving Car > Sat, 14 Apr 2018 at 2:00:23 MYT Preview link: https://classroom.udacity.com/courses/ud013-preview/lessons/631bcee2-d6bf-49a9-a2a9-168214e8d278/concepts/e19213bb-bf3e-4d16-aa8d-fe80d5e008f1 ### Lesson 3 #### Deep Learning - neural network: machine learning algorithm that you can train using input like camera, sensor, etc. and generate output - the idea of neural network is that it learns from observing the world, we don't have to teach it anythin specific - deep learning: a term that describes big multi-layer neural network. it's also a term for using deep neural network to solve a problem. - deep learning is relatively new, until the last few years where computer simply works fast enough to train deep neural network effectively. and with that, automotive manufacture can apply deep learning technique to drive a car in real time #### Tracking Pipeline 1. in tracking pipeline, we'll run a search for a car in each frame of video using sliding window technique - in the case of overlapping detection when doing sliding window technique, the center of overlapping window will be taken as the object - in sliding window technique, we identify false positive detection by checking if it only appears in one frame (and not the next frame) - adding **high covenance detection** will give us ability to detect how a center of overlap (a center of object) is moving from time to time and eventually estimate when it will appear in each subsequent frame (aka. predict where the object will be) <file_sep>DROP TABLE AUTHOR CASCADE CONSTRAINTS; DROP TABLE BOOK CASCADE CONSTRAINTS; DROP TABLE BRANCH CASCADE CONSTRAINTS; DROP TABLE INVENTORY CASCADE CONSTRAINTS; DROP TABLE WROTE CASCADE CONSTRAINTS; DROP TABLE PUBLISHER CASCADE CONSTRAINTS; DROP TABLE EMPLOYEE CASCADE CONSTRAINTS; CREATE TABLE AUTHOR (AUTHOR_NUM DECIMAL(2,0) PRIMARY KEY, AUTHOR_LAST CHAR(12), AUTHOR_FIRST CHAR(10) ); CREATE TABLE BOOK (BOOK_CODE CHAR(4) PRIMARY KEY, TITLE CHAR(40), PUBLISHER_CODE CHAR(3), TYPE CHAR(3), PRICE DECIMAL(4,2), PAPERBACK CHAR(1) ); CREATE TABLE BRANCH (BRANCH_NUM DECIMAL(2,0) PRIMARY KEY, BRANCH_NAME CHAR(50), BRANCH_LOCATION CHAR(50), NUM_EMPLOYEES DECIMAL(2,0) ); CREATE TABLE INVENTORY (BOOK_CODE CHAR(4), BRANCH_NUM DECIMAL(2,0), ON_HAND DECIMAL(2,0), PRIMARY KEY (BOOK_CODE, BRANCH_NUM) ); CREATE TABLE PUBLISHER (PUBLISHER_CODE CHAR(3) PRIMARY KEY, PUBLISHER_NAME CHAR(25), CITY CHAR(20) ); CREATE TABLE WROTE (BOOK_CODE CHAR(4), AUTHOR_NUM DECIMAL(2,0), SEQUENCE DECIMAL(1,0), PRIMARY KEY (BOOK_CODE, AUTHOR_NUM) ); CREATE TABLE EMPLOYEE (EMPNO NUMBER(4) NOT NULL, ENAME VARCHAR2(10), JOB VARCHAR2(9), MGR NUMBER(4), HIREDATE DATE, SAL NUMBER(7, 2), COMM NUMBER(7, 2), BRANCH_NUM NUMBER(2)); INSERT INTO AUTHOR VALUES (1,'Morrison','Toni'); INSERT INTO AUTHOR VALUES (2,'Solotaroff','Paul'); INSERT INTO AUTHOR VALUES (3,'Vintage','Vernor'); INSERT INTO AUTHOR VALUES (4,'Francis','Dick'); INSERT INTO AUTHOR VALUES (5,'Straub','Peter'); INSERT INTO AUTHOR VALUES (6,'King','Stephen'); INSERT INTO AUTHOR VALUES (7,'Pratt','Philip'); INSERT INTO AUTHOR VALUES (8,'Chase','Truddi'); INSERT INTO AUTHOR VALUES (9,'Collins','Bradley'); INSERT INTO AUTHOR VALUES (10,'Heller','Joseph'); INSERT INTO AUTHOR VALUES (11,'Wills','Gary'); INSERT INTO AUTHOR VALUES (12,'Hofstadter','<NAME>.'); INSERT INTO AUTHOR VALUES (13,'Lee','Harper'); INSERT INTO AUTHOR VALUES (14,'Ambrose','<NAME>.'); INSERT INTO AUTHOR VALUES (15,'Rowling','J.K.'); INSERT INTO AUTHOR VALUES (16,'Salinger','J.D.'); INSERT INTO AUTHOR VALUES (17,'Heaney','Seamus'); INSERT INTO AUTHOR VALUES (18,'Camus','Albert'); INSERT INTO AUTHOR VALUES (19,'Collins, Jr.','Bradley'); INSERT INTO AUTHOR VALUES (20,'Steinbeck','John'); INSERT INTO AUTHOR VALUES (21,'Castelman','Riva'); INSERT INTO AUTHOR VALUES (22,'Owen','Barbara'); INSERT INTO AUTHOR VALUES (23,'O''Rourke','Randy'); INSERT INTO AUTHOR VALUES (24,'Kidder','Tracy'); INSERT INTO AUTHOR VALUES (25,'Schleining','Lon'); INSERT INTO BOOK VALUES ('0180','A Deepness in the Sky','TB','SFI',7.19,'Y'); INSERT INTO BOOK VALUES ('0189','Magic Terror','FA','HOR',7.99,'Y'); INSERT INTO BOOK VALUES ('0200','The Stranger','VB','FIC',8.00,'Y'); INSERT INTO BOOK VALUES ('0378','Venice','SS','ART',24.50,'N'); INSERT INTO BOOK VALUES ('079X','Second Wind','PU','MYS',24.95,'N'); INSERT INTO BOOK VALUES ('0808','The Edge','JP','MYS',6.99,'Y'); INSERT INTO BOOK VALUES ('1351','Dreamcatcher: A Novel','SC','HOR',19.60,'N'); INSERT INTO BOOK VALUES ('1382','Treasure Chests','TA','ART',24.46,'N'); INSERT INTO BOOK VALUES ('138X','Beloved','PL','FIC',12.95,'Y'); INSERT INTO BOOK VALUES ('2226','Harry Potter and the Prisoner of Azkaban','ST','SFI',13.96,'N'); INSERT INTO BOOK VALUES ('2281','Van <NAME> Gauguin','WP','ART',21.00,'N'); INSERT INTO BOOK VALUES ('2766','Of Mice and Men','PE','FIC',6.95,'Y'); INSERT INTO BOOK VALUES ('2908','Electric Light','FS','POE',14.00,'N'); INSERT INTO BOOK VALUES ('3350','Group: Six People in Search of a Life','BP','PSY',10.40,'Y'); INSERT INTO BOOK VALUES ('3743','Nine Stories','LB','FIC',5.99,'Y'); INSERT INTO BOOK VALUES ('3906','The Soul of a New Machine','BY','SCI',11.16,'Y'); INSERT INTO BOOK VALUES ('5163','Travels with Charley','PE','TRA',7.95,'Y'); INSERT INTO BOOK VALUES ('5790','Catch-22','SC','FIC',12.00,'Y'); INSERT INTO BOOK VALUES ('6128','Jazz','PL','FIC',12.95,'Y'); INSERT INTO BOOK VALUES ('6328','Band of Brothers','TO','HIS',9.60,'Y'); INSERT INTO BOOK VALUES ('669X','A Guide to SQL','CT','CMP',37.95,'Y'); INSERT INTO BOOK VALUES ('6908','Franny and Zooey','LB','FIC',5.99,'Y'); INSERT INTO BOOK VALUES ('7405','East of Eden','PE','FIC',12.95,'Y'); INSERT INTO BOOK VALUES ('7443','Harry Potter and the Goblet of Fire','ST','SFI',18.16,'N'); INSERT INTO BOOK VALUES ('7559','The Fall','VB','FIC',8.00,'Y'); INSERT INTO BOOK VALUES ('8092','<NAME>','BA','PHI',14.00,'Y'); INSERT INTO BOOK VALUES ('8720','When Rabbit Howls','JP','PSY',6.29,'Y'); INSERT INTO BOOK VALUES ('9611','Black House','RH','HOR',18.81,'N'); INSERT INTO BOOK VALUES ('9627','Song of Solomon','PL','FIC',14.00,'Y'); INSERT INTO BOOK VALUES ('9701','The Grapes of Wrath','PE','FIC',13.00,'Y'); INSERT INTO BOOK VALUES ('9882','Slay Ride','JP','MYS',6.99,'Y'); INSERT INTO BOOK VALUES ('9883','The Catcher in the Rye','LB','FIC',5.99,'Y'); INSERT INTO BOOK VALUES ('9931','To Kill a Mockingbird','HC','FIC',18.00,'N'); INSERT INTO BRANCH VALUES (1,'<NAME>','16 Riverview',10); INSERT INTO BRANCH VALUES (2,'Henry On The Hill','1289 Bedford',6); INSERT INTO BRANCH VALUES (3,'<NAME>','Brentwood Mall',15); INSERT INTO BRANCH VALUES (4,'H<NAME>shore','Eastshore Mall',9); INSERT INTO INVENTORY VALUES ('0180',1,2); INSERT INTO INVENTORY VALUES ('0189',2,2); INSERT INTO INVENTORY VALUES ('0200',1,1); INSERT INTO INVENTORY VALUES ('0200',2,3); INSERT INTO INVENTORY VALUES ('0378',3,2); INSERT INTO INVENTORY VALUES ('079X',2,1); INSERT INTO INVENTORY VALUES ('079X',3,2); INSERT INTO INVENTORY VALUES ('079X',4,3); INSERT INTO INVENTORY VALUES ('0808',2,1); INSERT INTO INVENTORY VALUES ('1351',2,4); INSERT INTO INVENTORY VALUES ('1351',3,2); INSERT INTO INVENTORY VALUES ('1382',2,1); INSERT INTO INVENTORY VALUES ('138X',2,3); INSERT INTO INVENTORY VALUES ('2226',1,3); INSERT INTO INVENTORY VALUES ('2226',3,2); INSERT INTO INVENTORY VALUES ('2226',4,1); INSERT INTO INVENTORY VALUES ('2281',4,3); INSERT INTO INVENTORY VALUES ('2766',3,2); INSERT INTO INVENTORY VALUES ('2908',1,3); INSERT INTO INVENTORY VALUES ('2908',4,1); INSERT INTO INVENTORY VALUES ('3350',1,2); INSERT INTO INVENTORY VALUES ('3743',2,1); INSERT INTO INVENTORY VALUES ('3906',2,1); INSERT INTO INVENTORY VALUES ('3906',3,2); INSERT INTO INVENTORY VALUES ('5163',1,1); INSERT INTO INVENTORY VALUES ('5790',4,2); INSERT INTO INVENTORY VALUES ('6128',2,4); INSERT INTO INVENTORY VALUES ('6128',3,3); INSERT INTO INVENTORY VALUES ('6328',2,2); INSERT INTO INVENTORY VALUES ('669X',1,1); INSERT INTO INVENTORY VALUES ('6908',2,2); INSERT INTO INVENTORY VALUES ('7405',3,2); INSERT INTO INVENTORY VALUES ('7443',4,1); INSERT INTO INVENTORY VALUES ('7559',2,2); INSERT INTO INVENTORY VALUES ('8092',3,1); INSERT INTO INVENTORY VALUES ('8720',1,3); INSERT INTO INVENTORY VALUES ('9611',1,2); INSERT INTO INVENTORY VALUES ('9627',3,5); INSERT INTO INVENTORY VALUES ('9627',4,2); INSERT INTO INVENTORY VALUES ('9701',1,2); INSERT INTO INVENTORY VALUES ('9701',2,1); INSERT INTO INVENTORY VALUES ('9701',3,3); INSERT INTO INVENTORY VALUES ('9701',4,2); INSERT INTO INVENTORY VALUES ('9882',3,3); INSERT INTO INVENTORY VALUES ('9883',2,3); INSERT INTO INVENTORY VALUES ('9883',4,2); INSERT INTO INVENTORY VALUES ('9931',1,2); INSERT INTO PUBLISHER VALUES ('AH','Arkham House','Sauk City WI'); INSERT INTO PUBLISHER VALUES ('AP','Arcade Publishing','New York'); INSERT INTO PUBLISHER VALUES ('BA','Basic Books','Boulder CO'); INSERT INTO PUBLISHER VALUES ('BP','Berkley Publishing','Boston'); INSERT INTO PUBLISHER VALUES ('BY','Back Bay Books','New York'); INSERT INTO PUBLISHER VALUES ('CT','Course Technology','Boston'); INSERT INTO PUBLISHER VALUES ('FA','Fawcett Books','New York'); INSERT INTO PUBLISHER VALUES ('FS','<NAME>','New York'); INSERT INTO PUBLISHER VALUES ('HC','HarperCollins Publishers','New York'); INSERT INTO PUBLISHER VALUES ('JP','Jove Publications','New York'); INSERT INTO PUBLISHER VALUES ('JT','<NAME>','Los Angeles'); INSERT INTO PUBLISHER VALUES ('LB','Lb Books','New York'); INSERT INTO PUBLISHER VALUES ('MP','McPherson and Co.','Kingston'); INSERT INTO PUBLISHER VALUES ('PE','Penguin USA','New York'); INSERT INTO PUBLISHER VALUES ('PL','Plume','New York'); INSERT INTO PUBLISHER VALUES ('PU','Putnam Publishing Group','New York'); INSERT INTO PUBLISHER VALUES ('RH','Random House','New York'); INSERT INTO PUBLISHER VALUES ('SB','Schoken Books','New York'); INSERT INTO PUBLISHER VALUES ('SC','Scribner','New York'); INSERT INTO PUBLISHER VALUES ('SS','<NAME>','New York'); INSERT INTO PUBLISHER VALUES ('ST','Scholastic Trade','New York'); INSERT INTO PUBLISHER VALUES ('TA','Taunton Press','Newtown CT'); INSERT INTO PUBLISHER VALUES ('TB','Tor Books','New York'); INSERT INTO PUBLISHER VALUES ('TH','<NAME>','New York'); INSERT INTO PUBLISHER VALUES ('TO','Touchstone Books','Westport CT'); INSERT INTO PUBLISHER VALUES ('VB','Vintage Books','New York'); INSERT INTO PUBLISHER VALUES ('WN','<NAME>','New York'); INSERT INTO PUBLISHER VALUES ('WP','Westview Press','Boulder CO'); INSERT INTO WROTE VALUES ('0180',3,1); INSERT INTO WROTE VALUES ('0189',5,1); INSERT INTO WROTE VALUES ('0200',18,1); INSERT INTO WROTE VALUES ('0378',11,1); INSERT INTO WROTE VALUES ('079X',4,1); INSERT INTO WROTE VALUES ('0808',4,1); INSERT INTO WROTE VALUES ('1351',6,1); INSERT INTO WROTE VALUES ('1382',23,2); INSERT INTO WROTE VALUES ('1382',25,1); INSERT INTO WROTE VALUES ('138X',1,1); INSERT INTO WROTE VALUES ('2226',15,1); INSERT INTO WROTE VALUES ('2281',9,2); INSERT INTO WROTE VALUES ('2281',19,1); INSERT INTO WROTE VALUES ('2766',20,1); INSERT INTO WROTE VALUES ('2908',17,1); INSERT INTO WROTE VALUES ('3350',2,1); INSERT INTO WROTE VALUES ('3743',16,1); INSERT INTO WROTE VALUES ('3906',24,1); INSERT INTO WROTE VALUES ('5163',20,1); INSERT INTO WROTE VALUES ('5790',10,1); INSERT INTO WROTE VALUES ('6128',1,1); INSERT INTO WROTE VALUES ('6328',14,1); INSERT INTO WROTE VALUES ('669X',7,1); INSERT INTO WROTE VALUES ('6908',16,1); INSERT INTO WROTE VALUES ('7405',20,1); INSERT INTO WROTE VALUES ('7443',15,1); INSERT INTO WROTE VALUES ('7559',18,1); INSERT INTO WROTE VALUES ('8092',12,1); INSERT INTO WROTE VALUES ('8720',8,1); INSERT INTO WROTE VALUES ('9611',5,2); INSERT INTO WROTE VALUES ('9611',6,1); INSERT INTO WROTE VALUES ('9627',1,1); INSERT INTO WROTE VALUES ('9701',20,1); INSERT INTO WROTE VALUES ('9882',4,1); INSERT INTO WROTE VALUES ('9883',16,1); INSERT INTO WROTE VALUES ('9931',13,1); INSERT INTO EMPLOYEE VALUES (7369, 'SMITH', 'CLERK', 7902, TO_DATE('17-DEC-1990', 'DD-MON-YYYY'), 800, NULL, 2); INSERT INTO EMPLOYEE VALUES (7499, 'ALLEN', 'SALESMAN', 7698, TO_DATE('20-FEB-1991', 'DD-MON-YYYY'), 1600, 300, 3); INSERT INTO EMPLOYEE VALUES (7521, 'WARD', 'SALESMAN', 7698, TO_DATE('22-FEB-1991', 'DD-MON-YYYY'), 1250, 500, 3); INSERT INTO EMPLOYEE VALUES (7566, 'JONES', 'MANAGER', 7839, TO_DATE('2-APR-1991', 'DD-MON-YYYY'), 2975, NULL, 2); INSERT INTO EMPLOYEE VALUES (7654, 'MARTIN', 'SALESMAN', 7698, TO_DATE('28-SEP-1991', 'DD-MON-YYYY'), 1250, 1400, 3); INSERT INTO EMPLOYEE VALUES (7698, 'BLAKE', 'MANAGER', 7839, TO_DATE('1-MAY-1991', 'DD-MON-YYYY'), 2850, NULL, 3); INSERT INTO EMPLOYEE VALUES (7782, 'CLARK', 'MANAGER', 7839, TO_DATE('9-JUN-1991', 'DD-MON-YYYY'), 2450, NULL, 1); INSERT INTO EMPLOYEE VALUES (7788, 'SCOTT', 'ANALYST', 7566, TO_DATE('09-DEC-1992', 'DD-MON-YYYY'), 3000, NULL, 20); INSERT INTO EMPLOYEE VALUES (7839, 'KING', 'PRESIDENT', NULL, TO_DATE('17-NOV-1991', 'DD-MON-YYYY'), 5000, NULL, 1); INSERT INTO EMPLOYEE VALUES (7844, 'TURNER', 'SALESMAN', 7698, TO_DATE('8-SEP-1991', 'DD-MON-YYYY'), 1500, 0, 3); INSERT INTO EMPLOYEE VALUES (7876, 'ADAMS', 'CLERK', 7788, TO_DATE('12-JAN-1993', 'DD-MON-YYYY'), 1100, NULL, 2); INSERT INTO EMPLOYEE VALUES (7900, 'JAMES', 'CLERK', 7698, TO_DATE('3-DEC-1991', 'DD-MON-YYYY'), 950, NULL, 3); INSERT INTO EMPLOYEE VALUES (7902, 'FORD', 'ANALYST', 7566, TO_DATE('3-DEC-1991', 'DD-MON-YYYY'), 3000, NULL, 2); INSERT INTO EMPLOYEE VALUES (7934, 'MILLER', 'CLERK', 7782, TO_DATE('23-JAN-1992', 'DD-MON-YYYY'), 1300, NULL, 1); COMMIT;<file_sep>package main import ( "fmt" "path" ) func main() { file := "/user/test/test.json" fmt.Println("dir:", path.Dir(file)) fmt.Println("base:", path.Base(file)) fmt.Println("ext:", path.Ext(file)) fmt.Println("clean:", path.Clean(file)) _, split := path.Split(file) fmt.Println("split:", split) } <file_sep>package main import ( "fmt" "strings" ) func do(s string) string { var result string s = strings.ToLower(s) for i := 0; i < len(s); i++ { if s[i] == 'y' || s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u' { continue } result += fmt.Sprintf(".%c", s[i]) } return result } // func Test(t *testing.T) { // a := assert.New(t) // a.Equal(".t.r", do("tour")) // a.Equal(".c.d.f.r.c.s", do("Codeforces")) // a.Equal(".w.p.w.l", do("wpwl")) // a.Equal(".k.t.j.q.h.p.q.s.v.h.w", do("ktajqhpqsvhw")) // } func main() { var s string fmt.Scan(&s) fmt.Println(do(s)) } <file_sep>--- title: "A Case of Git Branching Model" date: 2018-04-12T18:08:45+08:00 tags: [""] draft: true --- `TODO: write content` ``` ▾ master ▾ hotfix ‣ hotfix 1 ⚑ pull request to master - code review - merge hotfix to master - merge master to develop ‣ hotfix 2 ..[redacted].. ‣ hotfix n ..[redacted].. ▾ develop ⚑ pull request to master - test develop branch in staging - merge develop to master - tag the merge with new release version ‣ feature 1 ⚑ pull request to develop - sync with develop using git rebase - code review for the feature - test the feature - merge feature to develop ‣ feature 2 ..[redacted].. ‣ feature n ..[redacted].. ``` <p class="text-center">***</p> *Outline:* 1. https://datasift.github.io/gitflow/IntroducingGitFlow.html 2. don't rebase shared branch (master, develop). rebase feature branch only (if the feature it's being worked by individu, not shared) 3. graphical difference between merge & rebase 4. pushing *rebased* feature branch to server <file_sep>// walk dir recursively and run command package main import ( "fmt" "log" "os" "os/exec" "path/filepath" "strconv" "strings" "time" ) // adjust your code here func handle(path string) { cmd := "python3" args := []string{ "/Volumes/data/playground/face-postgre/face-add.py", path, } execCmd(cmd, args) filename := filepath.Base(path) mv(path, "/data/processed-images/"+filename) } func main() { if len(os.Args) < 3 { fmt.Println("USAGE : walker [dir] [concurrency]") fmt.Println("SAMPLE: walker ~/data/images 10") return } dir := os.Args[1] concurrency, err := strconv.Atoi(os.Args[2]) if err != nil { log.Fatal(err) } log.Println("[INIT] Walking directory", dir, "with", concurrency, "concurrency") sem := make(chan bool, concurrency) fileCount := 0 defer func() func() { start := time.Now() return func() { log.Println("[DONE] Files walked:", fileCount) fmt.Println("Time elapsed:", time.Since(start)) } }()() _ = filepath.Walk(dir, func(path string, f os.FileInfo, err error) error { if err != nil { fmt.Println("filepath error:", err) } else { fileCount++ log.Printf("Processing file #%d: %s\n", fileCount, f.Name()) if f.IsDir() || f.Name() == ".DS_Store" { log.Println("[SKIP]", path) } else if concurrency == 0 { handle(path) } else if concurrency > 0 { sem <- true go func(path string) { defer func() { <-sem }() handle(path) }(path) } } return err }) if concurrency > 0 { for i := 0; i < cap(sem); i++ { sem <- true } } } func execCmd(cmd string, args []string) { cmdString := cmd + " " + strings.Join(args, " ") log.Println("[START]", cmdString) b, err := exec.Command(cmd, args...).Output() if err != nil { log.Println("exec output error:", err) } fmt.Printf("%s\n", b) } func mv(from, to string) { if err := os.Rename(from, to); err != nil { log.Println("mv failed:", err) return } fmt.Println("[MOVE]", from, "to", to) } func rm(path string) { if err := os.Remove(path); err != nil { log.Println("rm failed:", err) return } fmt.Println("[REMOVE]", path) } <file_sep>--- title: "MITM à la Bettercap" date: 2018-03-26T01:53:42+08:00 tags: ["networking"] draft: true --- `TODO: write content` set net.sniff.verbose false net.sniff on # http proxy set http.proxy.script caplets/proxy-script-test.js set http.proxy.sslstrip true set http.proxy.port 80 http.proxy on # https proxy set https.proxy.script caplets/proxy-script-test.js set https.proxy.sslstrip true set https.proxy.port 443 https.proxy on # redirect connections to our machine arp.spoof on <p class="text-center">***</p> *Outline:* 1. <file_sep>package main import ( "fmt" "log" nemclient "github.com/wzulfikar/go-nem-client" prettyjson "github.com/hokaccha/go-prettyjson" ) func main() { c, _ := nemclient.NewClient("http://23.228.67.85:7890") tx, err := c.GetAllTransactions("TC6Z5CY3TX4V3UCTWFZLCSEH6WOSIZ4PU2RURAHN", "", "") // tx, err := c.GetUnconfirmedTransactions("TDJDSDTS2UD2TLEZEO5DEG6BABJ64M6FTZTHQI6E") if err != nil { log.Fatal(err) } s, _ := prettyjson.Marshal(tx) fmt.Println(string(s)) } <file_sep><?php namespace App\Http\Middleware; use Auth; use Closure; class AppLogsAuth extends Authenticate { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $envs = [ 'production' ]; if(in_array(app()->environment(), $envs)) { $user = config('app-logs.user'); $password = config('app-logs.password'); if($request->getUser() != $user && $request->getPassword() != $password) { $headers = ['WWW-Authenticate' => 'Basic']; return response('Unauthorized', 401, $headers); } } return $next($request); } } <file_sep>#!/usr/bin/env python import sys import wave import time import numpy as np from websocket import create_connection from wav_visdom import WavVisdom class wav_ws: """wrapper for python websocket""" def __init__(self, url: str, dummy: False): self.dummy = dummy if self.dummy: print('wav_ws initiated with dummy mode ON') return self.ws = create_connection(url) def send_binary(self, in_data) -> None: if self.dummy: return self.ws.send_binary(in_data) def close(self) -> None: if self.dummy: print('[DUMMY] wav_ws.close') return self.ws.close() def ws_stream_wav(url: str, # websocket connection wav_file: str, result: dict, dummy: bool, plot: False)-> (int, float): print("using websocket to stream wav file:") print("- file:", wav_file) print("- endpoint:", url) if result is not None: if 'frames_sent' not in result or 'duration_sent' not in result: print('invalid result object: \ either frames_sent or duration_sent is not found') exit(1) plotter = WavVisdom() if plot else None ws = wav_ws(url, dummy) wf = wave.open(wav_file, 'r') nframes = wf.getnframes() # frame rate, also referred as sampling rate (or sample rate), # is the number of samples of audio carried per second. framerate = wf.getframerate() sampwidth = wf.getsampwidth() channels = wf.getnchannels() # duration in seconds duration = nframes / float(framerate) # frame per ms fpms = int(nframes / (duration * 1000)) print() print("wav file info:") print("- nframes:", nframes) print("- channels:", channels) print("- duration:", duration, "seconds") print("- frame rate:", framerate) print("- sample width:", sampwidth) print("- frame per ms:", fpms) target_rate = 16000 if target_rate != framerate: print('[ERROR] frame rate (sample rate) does not match target rate: {} != {}'.format( framerate, target_rate)) return # https://stackoverflow.com/questions/47865690/how-to-get-number-of-framesor-samples-per-sec-or-ms-in-a-audio-wav-or-mp3 first_frame = wf.readframes(1) sampleRate = np.fromstring(first_frame, np.int16) print("- sample rate:", sampleRate) print() frames_sent = 0 # send ms worth of frames in each packet ms_per_frame = 20 rate = fpms * ms_per_frame print("→ sending {} frames ({}ms) per iteration:".format(rate, ms_per_frame)) # adjust this if you get stuttering voice # during playback (ie. via pyaudio) stream_wait_ms_adjust = 0.01 stream_wait_ms = (ms_per_frame / 1000) - stream_wait_ms_adjust print('- stream wait (ms):', stream_wait_ms) while(frames_sent < nframes): if frames_sent + rate > nframes: rate = nframes - frames_sent waveData = wf.readframes(rate) frames_sent += rate # send the audio binary and sleep after # ms_per_frame to mimic streaming process ws.send_binary(waveData) time.sleep(stream_wait_ms) if plotter is not None: plotter.draw(waveData, framerate, frames_sent, nframes) progress = int(frames_sent / nframes * 100) print(' frame {} of {} ({}%)'.format( frames_sent, nframes, progress), end="\r") if result is not None: result['frames_sent'] = frames_sent result['duration_sent'] = frames_sent / fpms / 1000 # time.sleep(5) ws.close() if __name__ == '__main__': if len(sys.argv) < 2: print("Waver - stream audio to websocket endpoint") print("USAGE : waver.py <endpoint> <wav-file>") print(" : waver.py ws://localhost:8000/socket recording1.wav") exit() result = {'frames_sent': 0, 'duration_sent': 0.} try: ws_stream_wav( sys.argv[1], sys.argv[2], plot=False, dummy=False, result=result) except KeyboardInterrupt: print("\n\nreceived keyboard interrupt") except Exception as e: print("[ERROR]", e) finally: print("\n[DONE] length of audio sent: {:.1f} seconds".format( result['duration_sent'])) print() print("main exited") <file_sep>// Send email using AWS SES using gomail // with aws smtp creds (without aws sdk) package main import ( "fmt" "os" "gopkg.in/gomail.v2" //go get gopkg.in/gomail.v2 ) // adjust config below based on your aws account. // how to get the config: // 1. visit https://console.aws.amazon.com/ses/home // 2. navigate to "SMTP Settings" // 3. take note of the server name and port // 4. click "Create My SMTP Credentials" to create smtp user & password var awsconf = struct { smtpuser, smtppass, host string port int }{ smtpuser: os.Getenv("AWS_SES_SMTP_USER"), smtppass: os.Getenv("AWS_SES_SMTP_PASS"), // adjust the host according to your configuration host: "email-smtp.us-east-1.amazonaws.com", port: 465, } const ( // The name of the configuration set to use for this message. // If you comment out or remo3ve this variable, you will also need to // comment out or remove the header below. // ConfigSet = "ses-inbound-s3" // The subject line for the email. Subject = "Amazon SES Test (Gomail)" // The HTML body for the email. HtmlBody = "<html><head><title>SES Sample Email</title></head><body>" + "<h1>Amazon SES Test Email (Gomail)</h1>" + "<p>This email was sent with " + "<a href='https://aws.amazon.com/ses/'>Amazon SES</a> using " + "the <a href='https://github.com/go-gomail/gomail/'>Gomail " + "package</a> for <a href='https://golang.org/'>Go</a>.</p>" + "</body></html>" //The email body for recipients with non-HTML email clients. TextBody = "This email was sent with Amazon SES using the Gomail package." // The tags to apply to this message. Separate multiple key-value pairs // with commas. // If you comment out or remove this variable, you will also need to // comment out or remove the header on line 80. // Tags = "genre=test,genre2=test2" // The character encoding for the email. CharSet = "UTF-8" ) func main() { // sender address must be verified with Amazon SES. sender := os.Getenv("AWS_SES_SENDER_EMAIL") senderName := "AWS SES Test" // If your account is still in the sandbox, // recipient address must be verified. // read more about aws ses sandobx: // https://docs.aws.amazon.com/ses/latest/DeveloperGuide/request-production-access.html recipient := os.Getenv("TO") // Create a new message. m := gomail.NewMessage() fmt.Println("- sending AWS SES email..") fmt.Println(" from:", m.FormatAddress(sender, senderName)) fmt.Println(" to:", recipient) // Set the main email part to use HTML. m.SetBody("text/html", HtmlBody) // Set the alternative part to plain text. m.AddAlternative("text/plain", TextBody) // Construct the message headers, including a Configuration Set and a Tag. m.SetHeaders(map[string][]string{ "From": {m.FormatAddress(sender, senderName)}, "To": {recipient}, "Subject": {Subject}, // Comment or remove the next line if you are not using a configuration set // "X-SES-CONFIGURATION-SET": {ConfigSet}, // Comment or remove the next line if you are not using custom tags // "X-SES-MESSAGE-TAGS": {Tags}, }) // Send the email. d := gomail.NewPlainDialer( awsconf.host, awsconf.port, awsconf.smtpuser, awsconf.smtppass) // Display an error message if something goes wrong; otherwise, // display a message confirming that the message was sent. if err := d.DialAndSend(m); err != nil { fmt.Println(err) } else { fmt.Println("Email sent!") } } <file_sep>#include<iostream> #include<string> #include<sstream> using namespace std; string run(int x) { // (1) y = 2 * x + 1 // (2) z - 2 * y = x // (3) w = x + y - z int y = 2 * x + 1; int z = x + (2 * y); int w = x + y - z; stringstream ss; ss << y << " " << z << " " << w; return ss.str(); } void test() { cout << (run(0) == "1 2 -1" ? "✔ " : "✘ "); cout << (run(-999) == "-1997 -4993 1997" ? "✔ " : "✘ "); cout << (run(999) == "1999 4997 -1999" ? "✔ " : "✘ "); } int main(){ test(); return 0; int a; cin >> a; cout << run(a); return 0; }<file_sep>--- title: "Python Handy Conversions" date: 2018-03-09T02:35:48+08:00 tags: ["programming", "python"] draft: true --- `TODO: write content` - string to hex (import binascii or codecs): binascii.hexlify == binascii.b2a_hex == codecs.decode("...", "hex") == 'hello world'.decode('hex') - hex to string (import binascii or codecs): binascii.unhexlify == binascii.a2b_hex == codecs.encode("...", "hex") == 'hex_string'.decode('hex') - base64 encoding: 'hello world'.encode('base64') - base64 decoding: 'hello world'.decode('base64') - ascii to binary: bin(int('hello'.encode('hex'),16)) - binary to ascii - binary to int: `int('0b110100001100101011011000110110001101111', 2)` - int to binary: `bin(123123435234)` - int to hex: `hex(23423434)` - int to oct: `oct(23423434)` note: the `'bla bla'.encode|decode` pattern is removed in python 3 if on unix, can use built-in `base64` like so: `echo "hello world" | base64` for encoding, and `echo "aGVsbG8gd29ybGQK" | base64 -D` for decoding 6236343a20615735305a584a755a58526659323975646d567963326c76626c3930623239736331397962324e72 - python playground online: https://repl.it <p class="text-center">***</p> *Outline:* (all in python 2) 1. decode hex: codecs.decode("707974686f6e2d666f72756d2e696f", "hex") 2. ascii to hex: binascii.a2b_hex (ascii to binary) 3. how to identify base64 string? 4. how to identify hex string? codecs.decode(0x11, "binary") codecs.decode("110110", "bit") crypto challenge: https://github.com/VulnHub/ctf-writeups/blob/master/2016/angstrom-ctf/what-the-hex.md --- 6557393149475a766457356b4947526c4948646c61513d - 'flag{YoU_h4v3_f0und_de_w31}'[::-1] ← reverse string ctf: NjY1NDQ1N2E2NDMxMzk2YzVhNDYzOTZiNjI2ZTU1Nzc1YTZjMzg3YTY0NmE1MjZmNTgzMTU2NzY1\nNzU4NzQ2ZTU5NTc3ODZkMGE https://github.com/VulnHub/ctf-writeups/blob/master/2016/angstrom-ctf/supersecure.md --- hex to binary: `bin(int('hello'.encode('hex'), 16))` binary to hex: `hex(0b110100001100101011011000110110001101111)[2:].decode('hex')` octal to int (or int from octal): `int('211212323', 8)` int to octal: `oct(121241)` octal to string: `hex(int('06414533066157', 8))[2:].decode('hex')` int from hex: `int(0xfffabcdde)` ← think of "casting" to int (hex to int) int from bin: `int(0b111010101100101010)` hex from octal: `hex(023234)` ← think of "casting" to hex (octal to hex) bin from int: `bin(234234234234234)` ← think of "casting" to binary (int to bin)<file_sep>https://www.dataquest.io/blog/jupyter-notebook-tips-tricks-shortcuts/ - esc to enter command mode (see command mode keys in command palette) - blue: command mode activated - use `!` to execute shell command 81 77 77 81 78 76 82 79 77 <file_sep># include "DList.h" int randomInt (int MAX = 100) { return (rand() % MAX) + 1; } void makeListOfTenNumbers (DList<int> list) { cout << "Making list of 10 numbers..\n"; int N = 10; for (int i = 0; i < N; i++) { int number = randomInt(); list.push_back(number); } } void deleteList (DList<int> list) { cout << "Deleting list..\n"; int deletedItem; while (!list.isEmpty()) { list.delete_front(); cout << "Deleted " << deletedItem << " from list\n"; } } int recursive (int N) { return N <= 2 ? N : recursive(N - 3) + recursive(N - 2) + recursive(N - 1); } int main () { cout << "Starting Labtest 2..\n\n"; DList<int> list; makeListOfTenNumbers(list); list.display(); cout << "Printing in reverse order..\n"; list.display(true); deleteList(list); list.display(); return 0; } <file_sep>function rightAlignedStars (n, reversed) { var stars = ''; for(var i = 0; i <= n; i++) { var padding = n - i; for (var pad = 0; pad <= padding; pad++) { stars += ' '; } for (var newStar = 0; newStar < i; newStar++) { stars += "*"; } stars += "\n"; } if (reversed) { stars = stars.split("\n").reverse().join("\n"); } return stars; }<file_sep>## Elements of AI ### Chapter 2: AI Problem Solving - the first stage of the problem solving process: defining the choices and their consequences <file_sep><?php $repos = [ // to pull, // visit http://your-domain.com/puller.php?repo=my-app 'my-app' => '/opt/production/my-app', ]; // make sure that your web server // user (eg. nginx, www-data, apache, etc) has necessary // permission to execute the command inside the directory. // uncomment below code to check who's your web server user // die(`echo $(whoami)`); $repo = isset($repos[$_GET['repo']]) ? $repos[$_GET['repo']] : null; if(!$repo) http_response_code(404) && die("Not found: '{$_GET['repo']}' 🤔"); // reset everything & pull the latest from repo's origin $gitCmd = 'git reset --hard && git pull origin -f'; $command = 'cd ' . $repo . ' && ' . $gitCmd; $exec = shell_exec($command); $msg = $exec ?: "Failed to execute command: `$gitCmd`"; echo $_GET['repo'] . ' → ' . $msg; die(); <file_sep>#include <iostream> # include "Queue.h" # include "Stack.h" using namespace std; // Thu, 16 Mar 2017 at 18:52:45 MYT int main () { cout << "Starting Labtest 3..\n\n"; Stack<int> stack; stack.push(1); stack.push(2); stack.push(3); while (!stack.isEmpty()) { cout << "Popped " << stack.pop() << " from stack\n"; } cout << "\n"; Queue<int> queue; queue.push(1); queue.push(2); queue.push(3); while (!queue.isEmpty()) { cout << "Popped " << queue.pop() << " from queue\n"; } return 0; }<file_sep>#include<iostream> #include <bits/stdc++.h> using namespace std; int main(){ char s; while(cin >> s) { if(!strchr("AEIOUYaeiouy",s)) cout << '.' << (char) tolower(s); } }<file_sep>package main import ( "github.com/go-vgo/robotgo" ) func main() { robotgo.ScrollMouse(10, "up") robotgo.MouseClick("left", true) robotgo.MoveMouseSmooth(100, 200, 1.0, 100.0) } <file_sep>package main import ( "fmt" "log" "net/http" "net/http/httputil" "net/url" "os" "time" ) type Prox struct { target *url.URL proxy *httputil.ReverseProxy } func NewProxy(target string) *Prox { url, _ := url.Parse(target) return &Prox{target: url, proxy: httputil.NewSingleHostReverseProxy(url)} } var listenAddr = "127.0.0.1:9001" type transport struct{} func (t *transport) RoundTrip(request *http.Request) (*http.Response, error) { start := time.Now() response, err := http.DefaultTransport.RoundTrip(request) if err != nil { // failed to reach upstream return nil, err } elapsed := time.Since(start) key := request.Method + " " + request.URL.Path log.Println(elapsed, key) return response, nil } func main() { if len(os.Args) < 2 { fmt.Println("usage: proxier <origin url>") fmt.Println("example: proxier http://localhost:8888") return } origin, _ := url.Parse(os.Args[1]) director := func(req *http.Request) { req.Header.Add("X-Forwarded-Host", req.Host) req.Header.Add("X-Origin-Host", origin.Host) req.URL.Scheme = "http" req.URL.Host = origin.Host } proxy := &httputil.ReverseProxy{ Director: director, Transport: &transport{}, } http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { proxy.ServeHTTP(w, r) }) log.Printf("proxier is listening at %s", listenAddr) log.Printf("all requests will be forwarded to %s", origin) log.Fatal(http.ListenAndServe(listenAddr, nil)) } <file_sep>--- title: "My Take on Go Template" date: 2018-03-04T20:23:44+08:00 draft: false tags: ["go"] hideToc: true --- In programming, string interpolation is common. Using ES6 (JavaScript), string interpolation can be done like this: <!--more--> ```js const name = "Yondu" let greeting = `Hi ${name}!` console.log(greeting) // yields "Hi Yondu!" ``` In Go, above code is similar to: ```go // #1 approach: using `+` name := "Yondu" greeting := "Hi " + name + "!" fmt.Println(greeting) // #2 approach: using `fmt.Sprintf` name := "Yondu" greeting := fmt.Sprintf("Hi %s!", name) fmt.Println(greeting) ``` You may have noticed that we didn't use `${...}` in Go. It's simply because that's not how we do it in Go. However, sometimes we want to interpolate more stuffs. Something like: ``` Hello world! I'm {{ name }}. I'm {{ age }} years old! Nice to meet you! ``` When we see above text, we may have thought of the word *"template"*, because it has a placeholder-like formatting (the use of `{{ }}`). Go provides a built-in package, [`text/template`](https://golang.org/pkg/text/template/) and [`html/template`](https://golang.org/pkg/html/template/), to deal with this template related operations. ## Enter: Go Template ![gopher](/images/gopher-head-sm.png#featured) Let's start with a sample code: ```go // import "text/template" // create template string tplString := ` Hello world! I'm {{ .Name }}. I'm {{ .Age }} years old! Nice to meet you :D ` // initialize the template tmpl, _ := template.New("template_name").Parse(tplString) // create the data to pass to template data := struct { Name, Age string }{ "Yondu", "110", } // execute the template var tpl bytes.Buffer _ = tmpl.Execute(&tpl, data) // Get string representation of our template and print it fmt.Println(tpl.String()) ``` [Run in Go Playground](https://play.golang.org/p/DlSE2I-f0er) You may notice that in above code, we used `{{ }}` in `tplString`. In Go template, the `{{ }}` is used to execute Actions. An action can mean a data evaluation or control structures. In our code, it's a data evaluation: printing variable. You should also notice the use of dot (`.`), which is how we access a variable in Go template. In real life, you may want to separate template to its own files. For example, this is how your folder may look like: ``` ▾ <mypackage>/ ▾ templates/ nav.tpl footer.tpl sidebar.tpl ``` And the content of those `*.tpl` files is something like: ```go // nav.tpl package templates Nav := ` This is my navigation template. {{ .Link.Home }} {{ .Link.About }} {{ .Link.Login }} ` ``` Using this approach – separating template files, it will be easier to edit the template and to use it. In our `nav.tpl` example above, the template string is stored in an exported variable `Nav`. An exported variable is a variable that can be accessed from other of the package. *Exporting* variable is easy: make its first letter uppercase (same goes to functions). In this case, we can access `Nav` from other package using `templates.Nav` like so: ```go // main.go import "mypackage/templates" tmpl, _ := template.New("nav").Parse(templates.Nav) ``` <p class="text-center red">✽ ✽ ✽ </p> So far, we've only used a template string from variable. Can we just pass a file and treat it as a template? Yup! You can use `.ParseFiles`: ```go data := ... tmpl, _ := template.New("my-template").ParseFiles("my-template-file.txt") var tpl bytes.Buffer _ = tmpl.Execute(&tpl, data) fmt.Println(tpl.String()) ``` However, you may want to note that when passing a file as argument like in above `ParseFiles()` code, you should consider passing exact path. While passing relative path still works, it will be changed according to where the binary is run. So, be careful! ## Closing It's interesting that Go provides a built-in package to handle template. Now, you can go wild and explore more about Go template (maybe, start with the difference between `text/template` and `html/template`). Have a good journey, stay safe, and don't get lost! ***Till next. See ya!***<file_sep>package main import ( "fmt" "time" ) func main() { now := time.Now() t2 := now.Add(time.Second * 100000) fmt.Println(t2) fmt.Println("now", now) then := now.Add(-3 * time.Hour) fmt.Println("then", then) fmt.Println("then mysql", then.Format("2006-01-02 15:04:05")) // show time diff in hours diff := now.Sub(t2) fmt.Println(diff.Hours()) daysAgo, _ := time.Parse(time.RFC822, "07 Feb 18 10:00 UTC") fmt.Println("sub in hours:", int(now.Sub(daysAgo).Hours()/24)) if int(now.Sub(daysAgo).Hours()/24) == 2 { fmt.Printf("%v was two days ago", daysAgo) } } <file_sep>#include<iostream> #include<string> #include<sstream> #include<vector> using namespace std; vector<string> split( string str, char sep = ' ' ) { vector<string> splitted; istringstream stm(str); string token; while(std::getline(stm, token, sep)) splitted.push_back(token); return splitted; } string run(string dict, string rand) { // check args // cout << "dict: " << dict << " | rand: " << rand << endl; vector<string> in_dict = split(dict); vector<string> in_rand = split(rand); stringstream aladeen; for (int i = 0; i < in_rand.size(); ++i) { for (int j = 0; j < in_dict.size(); ++j) { if (in_dict[j] == in_rand[i]) { in_rand[i] = "Aladeen"; } } } for (int i = 0; i < in_rand.size(); ++i) { if (i == in_rand.size() - 1) { aladeen << in_rand[i]; } else { aladeen << in_rand[i] << "\n"; } } // cout << aladeen.str(); return aladeen.str(); } void test() { cout << (run("Positive Negetive", "Positive Wadiya Negetive") == "Aladeen\nWadiya\nAladeen" ? "✔ " : "✘ "); cout << (run("Easy Hard Impossible", "Aladeen Impossible Easy Hard") == "Aladeen\nAladeen\nAladeen\nAladeen" ? "✔ " : "✘ "); } int main(){ // test(); return 0; int dict_n; bool first_dict = true; cin >> dict_n; string dict; while (dict_n > 0) { string in; cin >> in; if (first_dict || dict_n == 0) { dict += in; } else { dict += " " + in; } first_dict = false; --dict_n; } int rand_n; bool first_rand = true; cin >> rand_n; string rand; while (rand_n > 0) { string in; cin >> in; if (first_rand || rand_n == 0) { rand += in; } else { rand += " " + in; } first_rand = false; --rand_n; } cout << run(dict, rand); return 0; }<file_sep>--- title: "One Week With Kindle App" date: 2018-03-06T17:42:35+08:00 tags: ["hobby", "tech"] draft: true --- `TODO: write content` <p class="text-center">***</p> *Outline:* 1. <file_sep>// file: yo_test.go // run test: go test . package hello import ( "fmt" "testing" ) func Test1(t *testing.T) { fmt.Println("test 1") SayHi() // ← undefined } func Test2(t *testing.T) { fmt.Println("test 2") SayHi() // ← undefined } <file_sep>package main import ( "os" "github.com/wzulfikar/lab/go/graphqlboiler" ) // sample struct type Person struct { Name string Age int married bool `json:"-"` } // Generate graphql boilerplate from given schemas func main() { schemas := []interface{}{ Person{}, } for _, schema := range schemas { graphqlboiler.Boil(graphqlboiler.Tpl{ RootResolver: "RootResolver", Schema: schema, }, os.Getenv("RESOLVERS_DIR")) } } <file_sep>package main import ( "fmt" "time" ) func main() { t1 := task1() ch1 := make(chan T1) go func() { time.Sleep(time.Second * 2) // once task2 is done, inform ch1 ch1 <- task2(t1) }() ch2 := make(chan T2) go func() { time.Sleep(time.Second * 3) // once task3 is done, inform ch2 ch2 <- task3(t1) }() var t1Received T1 var t2Received T2 const loopIntervalSeconds = time.Second for { select { // send `ch1` to `t1Received` case t1Received = <-ch1: fmt.Println(t1Received, "channel received") // send `ch2` to `t2Received` case t2Received = <-ch2: fmt.Println(t2Received, "channel received") default: fmt.Println("Waiting for channel..") } if (t1Received != T1{} && t2Received != T2{}) { break } time.Sleep(loopIntervalSeconds) } // task4 will be executed as soon as // `t1Received` & `t2Received` arrive task4(t1Received, t2Received) } type T1 struct { name string } type T2 struct { name string } func task1() T1 { fmt.Println("Task 1 done") return T1{"Task1"} } func task2(t1 T1) T1 { fmt.Println("Task 2 done") return t1 } func task3(t1 T1) T2 { fmt.Println("Task 3 done") return T2{"Task2"} } func task4(t1 T1, t2 T2) { fmt.Println("Task 4 done") } <file_sep>#ifndef DLIST_H #define DLIST_H #include <iostream> using namespace std; template<class T> class Item { public: T value; Item<T>* next; Item<T>* prev; }; template<class T> class DList { private: Item<T>* head; Item<T>* tail; public: DList () { head = new Item<T>(); tail = new Item<T>(); head->next = tail; head->prev = NULL; tail->next = NULL; tail->prev = head; } void push_back(T value){ Item<T>* item = new Item<T>(); item->value = value; item->next = tail; item->prev = tail->prev; tail->prev->next = item; tail->prev = item; } T pop_back () { if (isEmpty()) { cout << "List is empty. Nothing to pop"; return false; } else { Item<T>* temp = tail->prev; tail->prev = temp->prev; temp->prev->next = tail; T value = temp->value; delete temp; return value; } } T back () { if (!isEmpty()) { return tail->prev->value; } } void push_front (T value) { Item<T>* item = new Item<T>(); item->value = value; item->next = head->next; item->prev = head; head->next->prev = item; head->next = item; } T pop_front () { if(isEmpty()) { cout << "List is empty. Nothing to pop"; } else { Item<T>* temp = head->next; head->next = temp->next; temp->next->prev = head; T value = temp->value; delete temp; return value; } } void delete_front () { if(isEmpty()) { cout << "List is empty. Nothing to delete"; } else { Item<T>* temp = head->next; head->next = temp->next; temp->next->prev = head; T value = temp->value; delete temp; } } T front () { if (!isEmpty()) { return head->next->value; } } bool isEmpty () { return head->next == tail; } void display (bool reverse = false) { Item<T>* temp = new Item<T>(); if (reverse) { temp = tail; while (temp->prev != head) { cout << temp->prev->value << " → "; temp = temp->prev; } } else { temp = head; while (temp->next != tail) { cout << temp->next->value << " → "; temp = temp->next; } } cout << "END" << endl; } }; #endif<file_sep>#include "Dlist.h" template<class T> class Queue : public DList<T> { public: Queue () { } void push(T value){ this->push_back(value); } T pop(){ return this->pop_front(); } }; <file_sep>--- title: "Go Concurrency With Limit" date: 2018-04-13T06:58:35+08:00 tags: [""] draft: true --- `TODO: write content` <p class="text-center">***</p> *Outline:* 1. http://jmoiron.net/blog/limiting-concurrency-in-go/<file_sep># serve.sh runs hugo dev server for local development # make env vars accessible by hugo export $(cat .env) echo "[INFO] service hugo for dev" HUGO_LOCAL_DEV=true \ BUILD_ID=$(git describe --always) \ hugo server -F -D --config ./config.dev.toml <file_sep>package main import ( "fmt" "strings" ) func do(s string) string { uppercased := strings.ToUpper(s) lowercased := strings.ToLower(s) if s == uppercased { return lowercased } if s[0] == lowercased[0] && s[1:] == uppercased[1:] { return fmt.Sprintf("%c%s", uppercased[0], lowercased[1:]) } return s } // func Test(t *testing.T) { // a := assert.New(t) // a.Equal("Caps", do("cAPS")) // a.Equal("Lock", do("Lock")) // a.Equal("cAPSlOCK", do("cAPSlOCK")) // a.Equal("oops", do("OOPS")) // } func main() { var s string fmt.Scan(&s) fmt.Println(do(s)) } <file_sep>package alprgo import ( "fmt" "log" "github.com/pkg/errors" fsnotify "gopkg.in/fsnotify.v1" ) type AlprHandlerInterface interface { Handle(imagePath string) } func Watch(path string, handler AlprHandlerInterface) error { if path == "" { return errors.New("path can't be empty") } fmt.Println("alprwatcher started. Watching " + path) watcher, err := fsnotify.NewWatcher() if err != nil { return errors.Wrap(err, "NewWatcher") } defer watcher.Close() done := make(chan bool) go func() { for { select { case event := <-watcher.Events: // log.Println("event:", event.Name, event.Op) if event.Op == event.Op&fsnotify.Create && event.Name != ".DS_Store" { log.Println("new file:", event.Name) handler.Handle(event.Name) } case err := <-watcher.Errors: log.Fatal("watcher.Errors", err) } } }() err = watcher.Add(path) if err != nil { return errors.Wrap(err, "watcher.Add") } <-done return nil } <file_sep>--- title: "Recent Updates" hidden: true hideToc: true hideSharer: true hideHeadline: true hidePrevNextPost: true disableIndexing: true # disableDisqus: true --- <div style="text-align: center;"> <span>Last 3 commits:</span> <div> <iframe src="https://wzulfikar.github.io/vue-github-commits/embed.html?repo=wzulfikar/lab" scrolling="no" height="400" width="400" style="border: none;overflow-y: hidden;"></iframe> </div> </div><file_sep>package resolvers import ( "context" graphql "github.com/neelance/graphql-go" "/models" ) func (rr *RootResolver) CreatePerson(ctx context.Context, args struct{ID graphql.ID}) (*personResolver, error) { panic("TODO: handle CreatePerson mutation") var o *models.Person // Sample code: // o, err := NewBusiness(*args.Request) // if err != nil { // return nil, app.Error(err) // } return &personResolver{rr: rr, o: o}, nil } <file_sep>## Udacity: AI for Robotics > Mon, 16 Apr 2018 at 17:53:18 MYT **Link to course**: https://classroom.udacity.com/courses/cs373 **Instructors:** 1. <NAME>, University of Toronto, Professor, Institute for Aerospace Studies 2. <NAME>, Professor of Aeronautics, MIT ### Lesson 1: Localization Overview 1. 2004: first self-driving car test (in desert) by stanford <file_sep>--- title: "Hello Hugo!" date: 2018-03-03T02:33:20+08:00 tags: ["experiment", "go"] draft: false hideToc: true coverImg: /images/hugo-logo.png#featured coverAlt: gohugo --- <p class="text-center">Another experiment on how/where I write things I like to write <i>(Duh)</i>.</p> <p class="text-center red">***</p> So, I've been through the path of Wordpress, Tumblr, Ghost, and recently, Gitbook. Each has its own merits and drawbacks. However, I see something interesting from Hugo, that I didn't see in my previous adventures with other writing tools. <!--more--> Before we go to Hugo, I'd like to clarify the context by telling more about what I've found in my previous writing tools, and what I'm looking for. ## Wordpress Wordpress (https://wordpress.org) has been around since [2003](https://en.wikipedia.org/wiki/WordPress) and can be seen as one of the most famous blogging tools, or CMS (Content Management System). And by being most famous, it means that people can find help and support easily. It has a good [built-in visual editor](/images/wordpress-editor.jpg) and so many [themes](https://wordpress.org/themes/) to choose from. Many things can be integrated using ready-made plugins (ie. google analytics, image gallery, e-commerce, etc.). *Good things.* To get started with Wordpress is not so much difficult. Most hosting providers have built-in Wordpress package. Technical wise, an online Wordpress instance will need a hosting, database (MySQL), and domain. Since Wordpress stores its contents (posts, settings, etc) in database, doing a full backup means having a copy of files in the hosting and data stored in database. I haven't really had a bad experience when using Wordpress. However, the visual editor seems too slow for me to work with, and an internet connection is required to access the editor. Well, I can just write somewhere and paste to Wordpress editor when I've internet connection, but I prefer not to. With that downside, I started to look for something else. ## Tumblr In [Tumblr](https://www.tumblr.com), things seem to be less complicated than Wordpress. You don't need to have your own hosting or to install your own database. The editor is good, getting started is just about creating new account. Your posts are hosted in Tumblr at no cost. Actually, I kind of felt comfortable using Tumblr. Not so long after, I realize that I've to be connected (internet) to write. Besides that, using Tumblr means that I don't actually have full-control of my blog to customize. For those who like to customize their blog, they may not like it. Long story short, I started another search for writing tools.. ## Ghost Ghost is a blogging platform released on [2013](https://en.wikipedia.org/wiki/Ghost_(blogging_platform)). What I like the most about Ghost is its [clean, and user-friendly interface](https://user-images.githubusercontent.com/120485/28764244-344050c0-75d5-11e7-9314-45bc4177164e.png). Aside from that, it's actually an open source project (see: https://github.com/TryGhost/Ghost). To get started, you can install Ghost on your own server ([self-host](https://docs.ghost.org/v1/docs/getting-started-guide)), or subscribe to their managed service: [Ghost(Pro)](https://ghost.org). In my case, I used self-host version of Ghost. Installation is not difficult, things went well as expected. You may want to note that Ghost is coded in Node.js (a programming language) that's not as common as PHP (used to build Wordpress) when it comes to shared hosting. Hence, installing Ghost may not be available in most shared web hosting providers. Overall, I don't really have a complain for Ghost. However, I actually still looking for something that I can put my writing offline, and post it later when I've internet connection. Also, I'd prefer to not put my contents in database, so it still can be seen anywhere. ## Gitbook [Gitbook](https://www.gitbook.com) is kind of interesting. It's a platform to write book and publish content online. It has an offline editor where you can start writing and post later. In Gitbook, your contents are stored as files, in your computer. There's no need for database. To get started with Gitbook, you can create an account there (https://gitbook.com) and download [Gitbook Editor](https://www.gitbook.com/editor). Open your Gitbook Editor, sign in with your account, and you can start writing. Try to explore Gitbook features from online resources and you'll find some interesting stuffs, like the ability to download your contents as PDF or ePub. There's something off with Gitbook tho. It's meant for publishing book. While what I'm looking for is something to publish blog-like contents, which have time-related contents. With that reasoning, I feel like there must be a more suitable tool for this. ## Hello Hugo! Hugo (http://gohugo.io) takes different approach compared to other tools we've discussed. It's a static site generator, something like [Jekyll](https://jekyllrb.com). Static site generator basically means that Hugo will takes your contents and build a static site from it. Since it's static, you can host your site at no cost in platforms like [GitHub](https://github.com), [Gitlab](https://gitlab.com), [Netlify](https://www.netlify.com), [surge.sh](https://surge.sh), etc. Since we mentioned Jekyll, how does Hugo differ from Jekyll? Jekyll is built using Ruby (a programming language), which means that you'll need Ruby in your machine to use Jekyll. Yep, it's something *techy*. Hugo is built using Go (another programming language) that can produce a binary for multiple platform. People who developed Hugo have published it as a binary (a self executable program) that anyone can download. Hence, to use Hugo, one doesn't need to have Go programming language installed in their machine. They just need to have the Hugo binary. See more: [Hugo Quick Start](http://gohugo.io/getting-started/quick-start/). > Hugo released its [v0.16](https://github.com/gohugoio/hugo/releases?after=v0.17) – the first Hugo release that wasn't tagged as `pre-release`, on June 2016. With Hugo, all my contents are stored as files (markdown files, to be specific). There's no need for database. I can write my contents offline and publish it later. I can see my files anywhere, and I can use any editor I like (VIM, VSCode, SublimeText, etc). If you wonder what markdown is, it's a form of formatting similar to how you [format message in Whatsapp](https://faq.whatsapp.com/en/android/26000002/). Try writing markdown yourself here: http://markdownlivepreview.com. While I personally convinced to use Hugo (this blog itself is built using Hugo), it might not be for everyone since it involves some *techy* steps in its flow of writing contents. Nevertheless, I hope that knowing Hugo can somehow benefits you. Yup, you've reached the end of this post! And to end this, there's also a good writing platform that you may want to check out: [Medium](https://medium.com). ***Till next. See ya!*** ![Gopher mascot](/images/gopher-head.png#featured "Gopher mascot") <p class="text-center">**The Go gopher: an iconic mascot of Go project.*</p> {{< load-photoswipe >}} <file_sep>--- title: "Presenting Presentation. With 'Present'." date: 2019-03-01T18:01:47+08:00 tags: [""] draft: true --- ![gopher](/images/gopher-head-sm.png#featured) <!--more--> go get golang.org/x/tools/cmd/present <file_sep>package resolvers import ( "context" "errors" "strconv" graphql "github.com/neelance/graphql-go" "/models" ) type personResolver struct { rr *RootResolver o *models.Person } func (rr *RootResolver) Person(ctx context.Context, args struct{ID graphql.ID}) (*personResolver, error) { id, err := strconv.Atoi(string(args.ID)) if err != nil { return nil, errors.New("Failed to get ID of Person") } o, err := models.FindPerson(rr.Db, uint(id)) if err != nil { return nil, errors.New("Person not found") } return &personResolver{rr: rr, o: o}, nil } func (r *personResolver) Name() (string, error) { return r.o.Name, nil } func (r *personResolver) Age() (int32, error) { return int32(r.o.Age), nil } <file_sep>--- title: WhatsApp dan “Social Engineering” date: 2018-03-06T16:30:37+08:00 tags: ["experiment", "social"] draft: true --- `TODO: write content` <p class="text-center">***</p> *Outline: (follow english version)* <file_sep>--- title: "Journey to ~~The West~~ Find VPS" date: 2018-04-01T01:16:15+08:00 tags: ["review", "devops"] draft: true --- objectives: - focus on on-demand vps - ease of deployment - pricing conclusion: - time-wise, most providers can deploy vps within 1 min process - digital ocean is the easiest to use (frequent deployment, toying, etc) - digitalocean.com digital ocean referral (earn $10 credit): https://m.do.co/c/2daa556e6f4e - easy-on-eyes UI - need credit card - google: http://cloud.google.com : free f1-micro (500mb ram, 1vcpu, non-ssd 20gb) - UI too cluttered - need credit card - overkill - aws: - like google, too many options - overkill - vultr.com - nice ui - need credit card(?) - linode.com - old ui (they're building new one, they said) - need credit card(?) <p class="text-center">***</p> *Outline:* 1. <file_sep>package main import ( "os" "github.com/davecgh/go-spew/spew" "github.com/spf13/viper" ) // Sample usage: // VIPER_PATH=.env VIPER_FILE=yml VIPER_NAME=config go viperdemo.go func main() { v := viper.New() v.AddConfigPath(os.Getenv("VIPER_PATH")) v.SetConfigFile(os.Getenv("VIPER_FILE")) v.SetConfigName(os.Getenv("VIPER_NAME")) v.ReadInConfig() spew.Dump(v.GetBool("disabled_modules.trello")) } <file_sep>import random as rd from matplotlib import pyplot as plt def simulate_dice_rolls(N): roll_counts = [0, 0, 0, 0, 0, 0] for i in range(N): roll = rd.choice([1, 2, 3, 4, 5, 6]) index = roll - 1 roll_counts[index] = roll_counts[index] + 1 return roll_counts def show_roll_data(roll_counts): number_of_sides_on_die = len(roll_counts) for i in range(number_of_sides_on_die): number_of_rolls = roll_counts[i] number_on_die = i + 1 print(number_on_die, "came up", number_of_rolls, "times") def visualize_one_die(roll_data): roll_outcomes = [1, 2, 3, 4, 5, 6] fig, ax = plt.subplots() ax.bar(roll_outcomes, roll_data) ax.set_xlabel("Value on Die") ax.set_ylabel("# rolls") ax.set_title("Simulated Counts of Rolls") plt.show() roll_data = simulate_dice_rolls(1000) show_roll_data(roll_data) visualize_one_die(roll_data) <file_sep>package getty import ( "fmt" "io" "log" "net/http" "os" "path/filepath" "github.com/pkg/errors" ) func urlOk(url string) bool { resp, err := http.Head(url) if err != nil { log.Println("urlOkErr:", err) return false } resp.Body.Close() return resp.StatusCode == http.StatusOK } // infer name of file from url if filename is empty string ("") func Get(url, filename, dir string) error { if !urlOk(url) { return fmt.Errorf("[NOT FOUND] %s", url) } resp, err := http.Get(url) if err != nil { return errors.Wrap(err, "GET") } defer resp.Body.Close() // Check server response if resp.StatusCode != http.StatusOK { return fmt.Errorf("bad status: %s", resp.Status) } if filename == "" { filename = filepath.Base(url) } out, err := os.Create(filepath.Join(dir, filename)) if err != nil { return err } defer out.Close() // Writer the body to file _, err = io.Copy(out, resp.Body) if err != nil { return err } return nil } <file_sep>package main import ( "fmt" "log" "time" "github.com/gorhill/cronexpr" cron "gopkg.in/robfig/cron.v2" ) func main() { // gorhill() robfig() } func robfig() { // doc: gopkg.in/robfig/cron.v2/doc.go // robfig/cron's cron spec (cron expression) // cronExpr := "0 0 8 * * *" // everyday at 8am // cronExpr := "* */5 * * * *" // every multiple of 5 minutes (e.g. 5, 10, 15, 20, 25, etc.) // cronExpr := "* */30 * * * *" // every multiple of 30 seconds // cronExpr := "0 * * * * *" // every beginning of minutes // cronExpr := "* 0 * * * *" // every hour // cronExpr := "* 0 0 * * *" // daily at midnight // cronExpr := "* 0 0 * * SUN" // sunday at midnight cronExpr := "* 0 0 1 * *" // every first day of month at midnight // cronExpr := "0 0 0 */15 * *" // 15th of current month (?) // cronExpr := "0 0 */3 * * *" // everyday in 3hrs windows // cronExpr := "0 0 8 * * 1" // 8am every monday c := cron.New() c.AddFunc(cronExpr, func() { log.Println("Cron job executed") }) c.Start() now := time.Now() fmt.Printf("Cron entry for `%s`:\n", cronExpr) entry := c.Entries()[0] fmt.Printf("- Prev time : %s\n", entry.Prev) fmt.Printf("- Current time : %s\n", now.Format("2006-01-02 15:04:05")) fmt.Printf("- Next time : %s\n", entry.Next) fmt.Printf("- Current to next : %s", diffTime(entry.Next, now)) fmt.Println() // done := make(chan bool) // <-done } func gorhill() { // cron docs: https://godoc.org/github.com/robfig/cron cronExpr := "0 8 * * * *" nextTimes := cronexpr.MustParse(cronExpr).NextN(time.Now(), 5) fmt.Printf("Next 5 times of cron expression `%s`:\n", cronExpr) for i, next := range nextTimes { fmt.Printf("%d. %s\n", i+1, next) } } func diffTime(t1, t2 time.Time) string { diff := t1.Sub(t2) if diff.Hours() < 24 { return diff.String() } days := int(diff.Hours() / 24) hrs := int(diff.Hours()) % (24 * days) mins := int(diff.Minutes()) - (days * 24 * 60) - (hrs * 60) return fmt.Sprintf("%dd %dh %dm", days, hrs, mins) } <file_sep>package main import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) func do(s string) string { // your code here return s } // put the test case here. // comment this func before // submitting to codeforces func Test(t *testing.T) { a := assert.New(t) a.Equal("house", do("HoUse")) a.Equal("VIP", do("ViP")) a.Equal("matrix", do("maTRIx")) } // http://codeforces.com/problemset/problem/59/A func main() { var in string fmt.Scan(&in) } <file_sep>package main import ( "encoding/json" "fmt" "log" "time" "github.com/davecgh/go-spew/spew" "github.com/fatih/color" prettyjson "github.com/hokaccha/go-prettyjson" ) // struct UnixTime will be used // as custom field in Person struct type UnixTime struct { time.Time } // Custom marshal function for UnixTime. // It converts Go time to JSON number. func (t UnixTime) MarshalJSON() ([]byte, error) { return json.Marshal(t.Time.Unix()) } // Custom unmarshal function for UnixTime. // It converts JSON number to Go time. func (t *UnixTime) UnmarshalJSON(data []byte) error { var i int64 if err := json.Unmarshal(data, &i); err != nil { return err } t.Time = time.Unix(i, 0) return nil } type Person struct { Name string `json:"name"` Age int32 `json:"age"` Gender string `json:"gender"` // Birthday demonstrates the use of custom // type `UnixTime` for specific field (Birthday). // // Birthday field will be converted using custom // UnmarshalJSON from JSON number to Go's time Birthday UnixTime `json:"birthday"` // EmptyField demonstrates the behavior of a field // that's defined in struct but is not in the JSON EmptyField string `json:"empty"` // A field which value is nil will not be *omitted* // from the encoding if it has has omitempty option. OmittedField string `json:"omitted,omitempty"` } func main() { // create function to print colored title title := color.New(color.FgGreen).Add(color.Underline).PrintlnFunc() note := color.New(color.FgBlue).PrintlnFunc() // create byte representation of JSON string p := []byte(`{ "name":"<NAME>", "age":23, "gender":"Male", "birthday":761849888, "omitted":"" }`) title("\n→ JSON byte to struct (unmarshal):") var person Person err := json.Unmarshal(p, &person) if err != nil { log.Fatal(err) } spew.Dump(person) title("\n→ Convert Person struct to JSON (marshal):") var jsonPerson []byte jsonPerson, err = json.Marshal(person) if err != nil { log.Fatal(err) } spew.Dump(jsonPerson) title("\n→ Convert Person struct to JSON (marshal) and cast to string:") spew.Dump(string(jsonPerson)) title("\n→ Pretty-print JSON struct (using hokaccha/go-prettyjson):") s, _ := prettyjson.Marshal(person) fmt.Println(string(s)) note("👆 Note that Person field 'OmittedField' is not included in JSON (because omitempty option is set)") } <file_sep>--- title: "OSX, Time Machine, and SSHFS" date: 2018-03-20T21:52:39+08:00 tags: [""] draft: true --- ![time machine logo](/images/time-machine-mac-icon-sm.png#featured) <p class="text-center"><i>*Time Machine Logo</i></p> `TODO: write content` > The secret to creativity is knowing how to hide your sources. > -- <cite>adsf asdf [^1]</cite> [^1]:http://www.quotedb.com/quotes/2112 <p class="text-center">***</p> *Outline:* 1. no issue using external drive (partitioned) 2. keep resetting backup with NAS → changed 8mb bands to 128mb https://apple.stackexchange.com/questions/93215/how-can-i-avoid-repeated-time-machine-must-create-a-new-backup-errors-when-bac 3. no limit for backup with NAS and never finish first backup → create image, mount using sshfs, set mounted disk as tm destination 4. easiest path could be using apple time capsule 5. seagate central 2TB https://www.cnet.com/products/seagate-central-series/review/ 6. tplink AC1750 https://www.tp-link.com/us/products/details/cat-5508_RE450.html limit size on nas: https://www.youtube.com/watch?v=Nq7mSizqUSI limit using command but doesn't work: https://www.defaults-write.com/time-machine-setup-a-size-limit-for-backup-volumes/ sshfs https://www.digitalocean.com/community/tutorials/how-to-use-sshfs-to-mount-remote-file-systems-over-ssh https://linode.com/docs/networking/ssh/using-sshfs-on-linux/ https://askubuntu.com/questions/777116/sshfs-giving-remote-host-has-disconnected https://superuser.com/questions/709820/sshfs-is-failing-with-remote-host-has-disconnected "(sudo) sshfs (-o allow_other) -o sshfs_debug user@computer:/mountpoint /localmountpoint" <file_sep>SET SERVEROUTPUT ON SET VERIFY OFF -- a trigger that calculates and updates the respective aircraft hours flown<file_sep>package alprgo import ( "fmt" "io/ioutil" "path/filepath" ) func ScanDir(dir string, h AlprHandlerInterface) error { files, err := ioutil.ReadDir(dir) if err != nil { return err } for _, f := range files { if !f.IsDir() && f.Name() != ".DS_Store" { fmt.Printf("Found: %s\n", f.Name()) h.Handle(filepath.Join(dir, f.Name())) } } return nil } <file_sep>This `gopher` directory is symlink-ed to `/Users/strawhat/go/src/local-dev` so you can develop go packages locally and import using `local-dev/{package-name}`. Once pushed to public repo (github, gopkg, etc), refactor the `local-dev` to the respective repo. ie. from `local-dev/go-nem-clerk` to `github.com/wzulfiar/go-nem-clerk`.<file_sep>package main import "fmt" func main() { defer fmt.Println("deferred code") if true { fmt.Println("if block") return } fmt.Println("end") } <file_sep>#include <stdio.h> int main() { char matric[8]; int q1, q2, q3, q4; float sum, avg; float totalAvg = 0; int count = 0; while (1) { printf("Enter student %d matric number :", count + 1); scanf("%s", matric); // break loop if (matric[0] == '0') { break; } printf("Enter quiz 1:"); scanf("%d", &q1); printf("Enter quiz 2:"); scanf("%d", &q2); printf("Enter quiz 3:"); scanf("%d", &q3); printf("Enter quiz 4:"); scanf("%d", &q4); // calculate sum sum = q1 + q2 + q3 + q4; printf("Sum is %.0f\n", sum); // calculate avg avg = sum / 4; totalAvg += avg; count++; } totalAvg /= count; printf("Number of students: %d\n", count); printf("Average marks for this class is : %.2f\n", totalAvg); // system("pause"); return 0; }<file_sep>package main import ( "fmt" "strings" "testing" "github.com/stretchr/testify/assert" ) /** * If the inner volume of a pyramid is * at least 1000 times bigger than the volume of his body, * then he considers that pyramid big enough for him to play * all day long and be happy. * * you need to figure out if a pyramid * will make Leon happy or not given the height, * width and length of Leon and the inner volume of a pyramid. * * Input * The first line of input will consists of four integers * h (1 ≤ h ≤ 100), w (1 ≤ w ≤ 100), l (1 ≤ l ≤ 1000) and v (1 ≤ v ≤ 1010). * * Output * Print "YES" if the given pyramid makes Leon happy else * "NO" without the qoutes. */ func do(s1 string) string { s1. if s1 < s2 { return -1 } else if s1 > s2 { return 1 } return 0 } func Test(t *testing.T) { a := assert.New(t) a.Equal("NO", do("1 1 1 1")) a.Equal("NO", do("100 100 1000 1000")) } func main() { var s1, s2 string fmt.Scan(&s1, &s2) fmt.Println(do(s1, s2)) } <file_sep>> Thu, 3 May 2018 at 0:35:25 MYT ### Lesson 8: Technical Interview Techniques 1. 7 steps process during technical interview to make it successful: 1. clarifying the question 2. generating inputs & outputs 3. generating test cases 4. brainstorming 5. runtime analysis 6. coding 7. debugging - ***clarify the question***: to make sure that you're solving the right problem > **IMPORTANT NOTE** > you need to prove to the interviewer that you won't dive head first into the problem and potentially write code that doesn't solve the initial issue - hands-on practice: find island in 2d matrix (only vertical & horizontal, without diagonal). hint: breadth-first problem - *provoke* the interviewer with possible test-cases (as well as edge cases) to get more hints on how the bigger picture of the problem - it's always a good idea to think about handling none type in your code - try to take interviewer's cues to guide you to the solution - being able to take in interviewer's feedback demonstrates teamwork skill - do runtime analysis to estimate the efficiency of your code <file_sep>--- title: "Gotcha!" date: 2019-06-25T20:26:16+08:00 tags: ["programming"] draft: false hideToc: true #post_id: POST_ID #aliases: [ # "/posts/POST_ID", #] --- Collection of programming gotchas I have personally encountered. And made me confused. <!--more--> # Shell <details open> <summary class="collapsible">collapse</summary> 1. `echo` vs `echo -n`. Use the latter if you want to check for hash. {{< highlight bash "linenos=table" >}} echo "hello world" | shasum -a 256 # trailing newline is included in hash echo -n "hello world" | shasum -a 256 # use -n to exclude trailing newline{{< / highlight >}} {{< show-repl-it url="https://repl.it/@wzulfikar/shell-gotcha-echo?lite=true" >}} </details> # JS <details open> <summary class="collapsible">collapse</summary> 1. Watch out for [control characters'](https://en.wiktionary.org/wiki/Appendix:Control_characters) padding when encoding to hex. {{< highlight php "linenos=table" >}} const controlChar = '\n' const hex = Buffer.from(controlChar).toString('hex') hex == controlChar.charCodeAt(0).toString(16) // false hex == controlChar.charCodeAt(0).toString(16).padStart(2, '0') // true{{< / highlight >}} {{< show-repl-it url="https://repl.it/@wzulfikar/js-gotcha-char-code?lite=true" >}} </details> <file_sep>## Elements of AI ### Chapter 1 - applications of AI: 1. self-driving cars 2. content recommendation - related implications: filter bubbles, echo-chambers, troll factories, fake news, and new forms of propaganda. 3. image and video processing - The popularity of AI in the media is in part due to the fact that people have started using the term when they refer to things that used to be called by other names. - Why is the public perception of AI is so nebulous? - reason 1: no officially agreed definition - reason 2: the legacy of science fiction - key term in AI: - **autonomy**: ability to perform tasks in complex environment without constant guidance by a user - **adaptivity**: ability to improve performance by learning from experience - **suitcase word**: terms that carry a whole bunch of different meanings that come along even if we intend only one of them. coined by ["<NAME>"](https://en.wikipedia.org/wiki/Marvin_Minsky) - "it would sometimes be more appropriate to talk about the "AIness" (as in happiness or awesomeness) rather than arguing whether something is AI or not." - *if you'd like to talk like a pro, avoid saying "an AI", and instead say "an AI method".* ### Related fields - **Machine learning** can be said to be a subfield of AI, which itself is a subfield of computer science. Machine learning enables AI solutions that are adaptive. - key term for machine learning: Systems that improve their performance in a given task with more and more experience or data. - **Deep learning** is a subfield of machine learning. the "depth" in "deep learning" refers to the complexity of a mathematical model employed. - **Data science** is a recent *umbrella term* (term that covers several subdisciplines) that includes machine learning and statistics, certain aspects of computer science including algorithms, data storage, and web application development - **Robotics** means building and programming robots so that they can operate in complex, real-world scenarios. In a way, robotics is the ultimate challenge of AI since it requires a combination of virtually all areas of AI, ie. computer vision & speech recognition (for sensing the environment), natural language processing, cognitive modelling & affective computing (for interacting and working with humans). - Many of the robotics-related AI problems are best approached by machine learning, which makes machine learning a central branch of AI for robotics. - "On the other hand, an only-software based solutions such as customer service chatbot, even if they are sometimes called `software robots´ aren´t counted as (real) robotics." - A convenient way to visualize a taxonomy is an [Euler diagram](https://en.wikipedia.org/wiki/Euler_diagram). A taxonomy does not need to be strictly hierarchical (ie, a discipline can be a subfield of more than one more general topic). ### Philosophy of AI - in "Turing Test", an entity is intelligent if it cannot be distinguished from another intelligent entity by observing its behavior. - some of criticism on turing test: - "does being human-like mean you are intelligent?" - **Narrow vs General AI**: Narrow AI refers to AI that handles one task. General AI, or Artificial General Intelligence (AGI) refers to a machine that can handle any intellectual task. - the ideal of AGI has been all but abandoned by the AI researchers because of lack of progress towards it in more than 50 years despite all the effort. In contrast, narrow AI makes progress in leaps and bounds. - **Strong vs Weak AI**: Strong AI would amount to a “mind” that is genuinely intelligent and self-conscious (aka. being intelligent). Weak AI is what we actually have, namely systems that exhibit intelligent behaviors despite being “mere“ computers (aka. acting intelligently). <file_sep>package main import ( "fmt" "os" "github.com/plivo/plivo-go" ) func main() { if len(os.Args) < 3 { fmt.Println("USAGE : plivo <plivo key>") fmt.Println("SAMPLE: plivo NDEwYWQ2Mjg3...SDFkjsdf23") return } key := os.Args[1] client, err := plivo.NewClient(key, &plivo.ClientOptions{}) if err != nil { panic(err) } // client.Messages.Create(plivo.MessageCreateParams{ // Src: "60142616200", // Dst: "601111220034", // Text: "Hello, world!", // }) client.Calls.Create(plivo.CallCreateParams{ From: "60123123123", To: "60123123123", AnswerURL: "http://example.com", }) fmt.Println("Done ✔") } <file_sep>int vuln (char *userinput){ char buffer[256]; // force an overflow memcpy(buffer, input, 1024); return 1; }<file_sep>--- title: "Recreating Slides from Video Presentation" date: 2019-01-13T03:17:34+08:00 tags: [""] draft: true --- `TODO: write content` This is some image [^1]. This is another image [^2]. - [ ] asdfa - [x] asdfasd from this: {{< gallery >}} {{< figure src="/images/aws-reinvent-2017_sony-playstation/full/1a.png" >}} {{< figure src="/images/aws-reinvent-2017_sony-playstation/full/1b.png" >}} {{< figure src="/images/aws-reinvent-2017_sony-playstation/full/2.png" >}} {{< /gallery >}} to this: {{< gallery >}} {{< figure src="/images/aws-reinvent-2017_sony-playstation/cropped/1a.png" >}} {{< figure src="/images/aws-reinvent-2017_sony-playstation/cropped/1b.png" >}} {{< figure src="/images/aws-reinvent-2017_sony-playstation/cropped/2.png" >}} {{< /gallery >}} combine the cropped images into one pdf: <embed src="/docs/redis-couchbase-migration_sony-playstation.pdf" width="100%" height="375" type='application/pdf'> <p class="text-center">***</p> *Outline:* 1. [^1]: /images/aws-reinvent-2017_sony-playstation/cropped/1a.png [^2]: /my-page-on-monkeys/ {{< load-photoswipe >}}<file_sep>package slackwebhook // TODO: // - redirect // - google recaptcha func templateFormSubmitted(redirect string) string { return ` <html> Form submitted! <br/> <a href="` + redirect + `">← Back to site</a> </html> ` } func templateFormError(err, site string) string { backToSite := "" if site != "" { backToSite = `<br/><a href="` + site + `">← Back to site</a>` } return ` <html> <h4>Oops! Something went wrong :(</h4> <br/> ` + err + ` ` + backToSite + ` </html> ` } <file_sep>package main import ( "bufio" "fmt" "log" "os" "time" "github.com/wzulfikar/lab/go/getty" ) func main() { if len(os.Args) < 3 { fmt.Println("Usage: getty [wordlist] [dir]") return } wordlist := os.Args[1] dir := os.Args[2] downloadCount := 0 // change to mutex and pass to getasync defer func() func() { start := time.Now() return func() { log.Printf("[DONE] Files downloaded: %d. Time elapsed: %s", downloadCount, time.Since(start)) } }()() file, err := os.Open(wordlist) if err != nil { log.Fatal(err) } defer file.Close() const concurrency = 5 sem := make(chan bool, concurrency) baseurl := os.Getenv("BASEURL") scanner := bufio.NewScanner(file) for scanner.Scan() { url := baseurl + scanner.Text() + ".jpeg" log.Println("[START]", url) sem <- true go func(url string) { defer func() { <-sem }() if err := getty.Get(url, "", dir); err != nil { log.Println(err) } else { downloadCount++ log.Println("[DONE]", url) } }(url) } if err := scanner.Err(); err != nil { log.Fatal(err) } for i := 0; i < cap(sem); i++ { sem <- true } } <file_sep>#include<iostream> using namespace std; main() { int a,a1=0,a2=0,a3=0,a4=0; cin>>a; while(a1==a2||a1==a3||a1==a4||a2==a3||a2==a4||a3==a4) { a=a+1; a1=a%10; a2=a/10%10; a3=a/100%10; a4=a/1000%10; } cout<<a; }<file_sep>--- title: "Hugo Throwback" date: 2018-03-11T02:33:20+08:00 tags: ["experiment", "go"] draft: true --- 1. using hugo-theme-cactus-plus - enable tags by: 1. adding `tag` in `taxonomies` in config file, ie. ``` [taxonomies] tag = "tags" ``` 2. add `tags` in page's frontmatter. ie. `tags = ["go"]` 3. visit posts by tags from `/tags/go` 2. frontmatter - use `=` with `+++` divider (toml), or `:` when `---` is used (yaml) 3. still build when there's error (no error display) 4. need to read docs thoroughly to understand the features. the docs is awesome tho! 5. to add translation: - add `language` and its weight in config, ie. ``` [languages.en] weight = 1 [languages.id] weight = 2 ``` - create post with language suffix, ie. `about/_index.id.md`<file_sep>> Thu, 3 May 2018 at 0:35:25 MYT ### Lesson 3: Searching and Sorting 1. **binary search**: search given item by recursively halving the collection (ordered collection) and check if the median is greater than the item 2. binary search efficiency: `O(log2(n) + 1)`, which basically is same as `O(log2(n))`. hence, the binary search efficiency is `O(log2(n))`. 3. in computer science, log base 2 is more common instead of log base 2 (because we deal with binary a lot) 4. tips to calculate efficiency: - create result table - identify the pattern - convert the pattern into big o notation 5. during interview, your commitment to solve a problem could mean a lot to your interviewer <file_sep>SET SERVEROUTPUT ON CREATE OR REPLACE TRIGGER hrs_flown BEFORE INSERT OR UPDATE OR DELETE ON charter FOR EACH ROW BEGIN IF DELETING THEN UPDATE aircraft SET ac_hours_flown = ac_hours_flown - :old.char_hours_flown WHERE ac_number = :old.ac_number; DBMS_OUTPUT.PUT_LINE('Charter trip deleted and aircraft hours flown updated.'); ELSE UPDATE aircraft SET ac_hours_flown = ac_hours_flown + :new.char_hours_flown WHERE ac_number = :new.ac_number; DBMS_OUTPUT.PUT_LINE('Charter trip added/updated and aircraft hours flown updated.'); END IF; END; / <file_sep>package main import ( "bytes" "fmt" "io/ioutil" "log" "strconv" "github.com/willf/pad" ) func main() { file := "generator.txt" fmt.Println("Generating strings into", file) var b bytes.Buffer generate(&b) write(&b, file) fmt.Printf("Done ✔") } func write(b *bytes.Buffer, file string) { err := ioutil.WriteFile(file, b.Bytes(), 0644) if err != nil { log.Fatal(err) } } func generate(b *bytes.Buffer) { generateID(b, 10, 18, 3, 9999) } func generateID(b *bytes.Buffer, fromYear, toYear, semesterCount, studentCount int) { if semesterCount > 3 { fmt.Println("`semesterCount` can't exceed max number of 3") return } if studentCount > 9999 { fmt.Println("`studentCount` can't exceed max number of 9999") return } for year := fromYear; year <= toYear; year++ { for semester := 1; semester <= semesterCount; semester++ { for count := 0; count <= studentCount; count++ { b.WriteString(fmt.Sprintf("%d%d%s\n", year, semester, pad.Left(strconv.Itoa(count), 4, "0"))) } } } } <file_sep>#include <iostream> using namespace std; template<class K, class V> class Node{ public: K key; V value; int height; Node<K,V>* left; Node<K,V>* right; Node(K key, V value){ this->key = key; this->value = value; this->height = 1; this->left = NULL; this->right = NULL; } }; template<class K, class V> class AVLTree{ private: Node<K,V>* root; public: AVLTree(){ root = NULL; } int get_height(Node<K,V>* cur){ int lh = (cur->left==NULL ? 0:cur->left->height); int rh = (cur->right==NULL ? 0:cur->right->height); return max(lh,rh)+1; } int get_balance_factor(Node<K,V>* node){ int b = (node->left==NULL ? 0:node->left->height) - (node->right==NULL ? 0:node->right->height); return b; } Node<K,V>* ll_rotation(Node<K,V>* z){ Node<K,V>* y = z->left; z->left = y->right; y->right = z; z->height-=2; return y; } Node<K,V>* rr_rotation(Node<K,V>* z){ Node<K,V>* y = z->right; z->right = y->left; y->left = z; z->height-=2; return y; } Node<K,V>* lr_rotation(Node<K,V>* z){ Node<K,V>* y = z->left; z->left = ll_rotation(y); return rr_rotation(z); } Node<K,V>* rl_rotation(Node<K,V>* z){ Node<K,V>* y = z->right; z->right = rr_rotation(y); return ll_rotation(z); } void insert_helper(K key, V value, Node<K,V>*& current, bool& isAdded){ if(current==NULL){ current = new Node<K,V>(key, value); isAdded = true; return; } if(key < current->key){ insert_helper(key, value, current->left, isAdded); }else if(key > current->key){ insert_helper(key, value, current->right, isAdded); }else{ // the 'key' already exists in the tree return; } if(isAdded){ current->height = get_height(current); int b = get_balance_factor(current); if(b < -1){ if(get_balance_factor(current->right) > 0){ current = rl_rotation(current); }else{ current = rr_rotation(current); } }else if(b > 1){ if(get_balance_factor(current->left) > 0){ current = ll_rotation(current); }else{ current = lr_rotation(current); } } } } void insert(K key, V value){ bool isAdded = false; insert_helper(key, value, root, isAdded); } void preOrder(Node<K,V>* current, int level=0){ if(current!=NULL){ cout<<"("<<current->key<<","<<current->value<<") "; preOrder(current->left,level+1); preOrder(current->right,level+1); } } void display(int order=0){ if(order==0){ preOrder(root); } cout<<endl; } }; int main(){ AVLTree<int, char> tree; for(int i=0;i<10;i++){ char ch = 'A'+i; tree.insert(i+1,ch); tree.display(); } return 0; }<file_sep>package main import ( "fmt" "os" "time" "github.com/Sirupsen/logrus" ) func LogToFile(filename string) error { file, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0755) if err == nil { logrus.SetOutput(file) } return err } func main() { if err := LogToFile("/tmp/logrustest.log"); err != nil { logrus.Fatal("Failed to log to file") } for i := 0; i < 3; i++ { logrus.Warn(fmt.Sprintf("%d. This is a test log..", i+1)) time.Sleep(1 * time.Second) } logrus.Info("Logrus test done.") fmt.Println("Logrus test done.") } <file_sep># initiate dist directory if not exist if [ ! -d dist ]; then git clone https://github.com/wzulfikar/wzulfikar.com.git dist else git pull origin master fi # make env vars accessible by hugo export $(cat .env) # generate static files BUILD_ID=$(git describe --always) hugo --minify if [ "$1" != "--build-only" ]; then # push static files to remote repo ( cd dist git add . git commit -m 'build' git push -u origin master ) fi <file_sep># adapted from # https://github.com/aymericdamien/TensorFlow-Examples/ from __future__ import absolute_import, division, print_function import numpy as np import tensorflow as tf import tensorflow.contrib.eager as tfe # eager execution, a define-by-run interface for tensorflow # to execute operations immediately (wihout tf session). print("- enabling Eager execution..") tfe.enable_eager_execution() print(" done ✔") print() print("- defining constant tensors:") a = tf.constant(2) b = tf.constant(3) print(" a = {}, b = {}".format(a, b)) print() print("- running operations without tf.Session:") print(" [ADD] a + b =", a + b) print(" [MUL] a * b =", a * b) print() print("- creating Tensors and NumpyArray variables (for mixing operations):") a = tf.constant([[6., 1.], [1., 0.]], dtype=tf.float32) b = np.array([[4., 0.], [5., 1.]], dtype=np.float32) print(" Tensor `a`: [{} {}]".format(a[0], a[1])) print(" NumpyArray `b`: [{} {}]".format(b[0], b[1])) print() add = a + b print("- addition of Tensor & NumpyArray (a + b):") print(" [{} {}]".format(add[0], add[1])) print() mul = tf.matmul(a, b) print("- multiplication (dot product) of Tensor `a` & NumpyArray `b`:") print(" a * b = [{} {}]".format(mul[0], mul[1])) print(""" calculation steps: [a] * [b] [ab] +------+ +------+ | 6, 1 | | 4, 0 | → 6*4 + (1*5), 6*0 + (1*1) → 29, 1 | 1, 0 | | 5, 1 | → 1*4 + (0*5), 0*0 + (0*1) → 4, 0 +------+ +------+ """) <file_sep>import time from enum import Enum import numpy as np from udacidrone import Drone from udacidrone.connection import MavlinkConnection from udacidrone.messaging import MsgID # create enum by creating a class # that extends python's `Enum` class Phases(Enum): MANUAL = 0 ARMING = 1 TAKEOFF = 2 LANDING = 3 DISARMING = 4 WAYPOINTS = 5 class BackyardFlyer(Drone): def __init__(self, connection, waypoints=[]): super().__init__(connection) self.target_position = np.array([0.0, 0.0, 0.0]) self.in_mission = True # initial state self.flight_phase = Phases.MANUAL self.waypoints = waypoints self.waypoints_reached = [] # Register all your callbacks here. # `register_callback()` is inherited from `udacidrone.Drone`. # The callbacks will be triggered whenever # `udacidrone.messaging` changes. self.register_callback(MsgID.LOCAL_POSITION, self.local_position_callback) self.register_callback(MsgID.LOCAL_VELOCITY, self.velocity_callback) self.register_callback(MsgID.STATE, self.state_callback) def waypoints_transition(self, cb): print("waypoints transition") time.sleep(3) self.flight_phase == Phases.WAYPOINTS altitude = self.target_position[2] heading = 0.0 for point in self.waypoints: if len(point) < 3: point.append(altitude) if len(point) < 4: point.append(heading) self.cmd_position(*point) self.waypoints_reached.append(point) print("- flying to point {} of {}: {}".format( len(self.waypoints_reached), len(self.waypoints), point)) time.sleep(5) # run callback print("{} waypoints reached. executing callback..".format( len(self.waypoints_reached))) cb() def local_position_callback(self): if self.flight_phase == Phases.TAKEOFF: if len(self.waypoints_reached) < len(self.waypoints): self.waypoints_transition(self.landing_transition) return # coordinate conversion altitude = -1.0 * self.local_position[2] # check if altitude is within 95% of target if altitude > 0.95 * self.target_position[2]: self.landing_transition() def _home_distance(self): return (abs(self.global_position[0] - self.global_home[0]), abs(self.global_position[1] - self.global_home[1])) def _around_home(self): east, north = self._home_distance() return east < 0.01 and north < 0.01 def _safe_to_land(self): return abs(self.local_position[2]) < 0.01 def velocity_callback(self): print("velocity_callback. phase:", self.flight_phase) print("- altitude:", self.local_position[2]) print("- safe to land:", self._safe_to_land()) print("- home distance:", self._home_distance()) print("- around home:", self._around_home()) if self.flight_phase == Phases.LANDING: if not self._around_home(): print("going home..") print("- home distance:", self._home_distance()) print('- global pos', self.global_position[0:2]) print('- global home', self.global_home[0:2]) self.cmd_position(0., 0., 3., 0.) time.sleep(3) if not self._safe_to_land(): print("landing..") time.sleep(3) self.cmd_position(0., 0., 0., 0.) time.sleep(3) self.disarming_transition() def state_callback(self): if not self.in_mission: return if self.flight_phase == Phases.MANUAL: self.arming_transition() elif self.flight_phase == Phases.ARMING: if self.armed: self.takeoff_transition() elif self.flight_phase == Phases.DISARMING: if not self.armed: self.manual_transition() def arming_transition(self): print("arming transition") self.take_control() self.arm() # set the current location to be the home position print("setting home position..") self.set_home_position(self.global_position[0], self.global_position[1], self.global_position[2]) self.flight_phase = Phases.ARMING def takeoff_transition(self): print("takeoff transition") target_altitude = 3.0 self.target_position[2] = target_altitude self.takeoff(target_altitude) self.flight_phase = Phases.TAKEOFF def landing_transition(self): print("landing transition") self.land() self.flight_phase = Phases.LANDING def disarming_transition(self): print("disarm transition") self.disarm() self.flight_phase = Phases.DISARMING def manual_transition(self): print("manual transition") self.release_control() self.stop() self.in_mission = False self.flight_phase = Phases.MANUAL def start(self): self.start_log("Logs", "NavLog.txt") print("starting connection") super().start() self.stop_log() if __name__ == "__main__": conn = MavlinkConnection('tcp:127.0.0.1:5760', threaded=False, PX4=False) square_waypoints = [ [2.0, 0.0], # fly forward by 5 points [2.0, -2.0], # fly to left by 5 points [0.0, -2.0], # fly backward by 5 points [0.0, 0.0]] # back to home position drone = BackyardFlyer(conn, square_waypoints) time.sleep(2) drone.start() <file_sep>// print stars :v function stars (n, reversed) { var stars = ''; for(var i = 0; i <= n; i++) { for (var newStar = 0; newStar < i; newStar++) { stars += "*"; } stars += "\n"; } if (reversed) { stars = stars.split("\n").reverse().join("\n"); } return stars; } const N = 2; console.log("Number of stars:", N); console.log(star(N)); console.log('Reversed version:') console.log(star(N, true));<file_sep>package main import ( "fmt" "os" ) func main() { // a behavior test of using relative file path // test 1: `cd path-to/lab/go && go run gofile.go` → file exists // test 2: `cd path-to/lab && go run go/gofile.go` → file doesn't exists if _, err := os.Stat("./gofile.go"); err == nil { fmt.Println("file exist") } else { fmt.Println("file doesn't exist") } } <file_sep>#include <iostream> #include <list> using namespace std; class Product { public: string name; Product(string name) { this->name = name; } }; typedef list<Product*> ProductList; ProductList::iterator it; void displayProducts (ProductList products) { int counter = 1; printf("\nDisplaying product(s)..\n"); for(it = products.begin(); it != products.end(); it++) printf(" %d. %s\n", counter++, (*it)->name.c_str()); printf("\n%lu product(s) succesfully displayed ✔\n", products.size()); } void appendProduct (Product* p, ProductList *products) { products->push_back(p); printf("Product added: %s\n", p->name.c_str()); } void deleteProduct (string productName, ProductList *products) { bool isDeleted = false; for(it = products->begin(); it != products->end(); it++) { if ((*it)->name == productName) { isDeleted = true; products->remove(*it); printf("\n✔ Product '%s' has been succesfully deleted.\n", productName.c_str() ); break; } } if (!isDeleted) { printf("\n❗️ Failed to delete product:\n Product '%s' doesn't exist.\n", productName.c_str() ); } } void insertProductAtIndex (Product *product, int insertAtIndex, ProductList *products) { const unsigned long MAX_INDEX = products->size() - 1; if (insertAtIndex > MAX_INDEX) { printf("\n❗️ Failed to insert product '%s' at index %d:\n Index shouldn't exceed %lu\n", product->name.c_str(), insertAtIndex, MAX_INDEX ); return; } int counter = 0; for(it = products->begin(); it != products->end(); it++) { if (counter == insertAtIndex) { products->insert(it, product); break; } counter++; } } // TASKS: // - create list ✔ // - append new product ✔ // - insert product to specific location ✔ // - delete product ✔ // - display ✔ int main() { ProductList products; appendProduct(new Product("yoloo"), &products); appendProduct(new Product("second product"), &products); appendProduct(new Product("third product"), &products); appendProduct(new Product("forth product"), &products); // deleteProduct("yoloo", &products); insertProductAtIndex(new Product("fifth product at idx 2"), 2, &products); displayProducts(products); return 0; } <file_sep>## Refactoring UI > Sat, 14 Apr 2018 at 1:07:14 MYT **Subject:** bad-about.com 1. https://fontsinuse.com 2. usecontrast.com <file_sep>> Thu, 3 May 2018 at 0:35:25 MYT ### Lesson 6: Graphs 1. graphs: data structure designed to show relationship between objects. graph also called as "network" 2. graph doesn't really have a root node (like trees do) since it can possibly contain a cycle connection 3. sample of cycle in graph: `A, B, C, D, E, F, A` 4. nodes can be thought as part of graph that store data and edges are the connection between nodes. however, edges can also store data too. 5. edges usually contain data about the strength of the connection 6. similar to trees, graph also has "node" or "vertex". in fact, a tree is just a specific type of graph 7. **directed graph**: graph in which the edges has an additional property to indicates its direction (ie. one-way direction) 8. in a sentence, you may think of a noun as node in graph, and a verb as edges. for example: "from san fransisco, travel to tokyo": - san fransisco (noun): node1 - travel (verb): edge - tokyo (node): node2 9. **undirected-graph**: graph without the sense of direction in its edges. ie, graph of people relationship 10. **DAG**: Directed Acyclic Graph; a directed graph with no cycles 11. **Connectivity** == **Graph Theory** 12. **connectivity**: the minimum number of elements that need to be removed for the graph to become disconnected 13. **disconnected graphs**: there is some vertex or group of vertices that have no connection with the rest of the graph. 14. **weakly connected graph**: A directed graph is weakly connected when only replacing all of the directed edges with undirected edges can cause it to be connected. Imagine that your graph has several vertices with one outbound edge, meaning an edge that points from it to some other vertex in the graph. There's no way to reach all of those vertices from any other vertex in the graph, but if those edges were changed to be undirected all vertices would be easily accessible. 15. **connected graph**: there's some path between one vertex and every other vertex 16. **strongly connected**: strongly connected directed graphs must have a path from every node and every other node. So, there must be a path from A to B AND B to A. 17. **edge list**: list of edges (2d list), ie. ```py [[0,1], [1,2] [1,3], [2,3]] ``` 19. **adjacency list**: a way to represent adjacent graph. the 2d array will contains list of edges in which the index is adjacent to the id of the vertex ```py [[1], [0,2,3] [1,3], [1,2]] # - edge at index `0` is `[1]`, # which means that the vertex with id `0` is connected to vertex with id `1`. # - at index `1`, we have `[0,2,3]`, # which means that the vertext with id `1` is connected to vertex 0, 2, and 3 # - same interpretation is applied to edges at index 2 (`[1,3]`) and 3 (`[1,2]`) ``` 20. **adjacency matrix**: another way to represent graph using list (2d array). node IDs are mapped to array indices. sample of adjacency matrix: ```py 0 1 2 3 0 [[0,1,0,0] 1 [1,0,1,1] 2 [0,1,0,1] 3 [0,1,1,0]] ``` > matrix is also known as rectangular array (see, it looks like rectangular!) <file_sep>package templates const QueryResult = `package resolvers import ( "context" "github.com/volatiletech/sqlboiler/queries/qm" "{{.Repo}}/models" "{{.Repo}}/modules/graphql/app" ) type {{.TypeName}}ResultResolver struct { totalCount int64 pageInfo *app.PageInfoResolver items []*{{.ResolverName}} } func (r *{{.TypeName}}ResultResolver) PageInfo() *app.PageInfoResolver { return r.pageInfo } type {{.TypeName}}Filter struct { // Add {{.TypeName}} filter here } type {{.TypeName}}esArgs struct { Page *app.PageArgs Filter *{{.TypeName}}Filter } func (rr *{{.RootResolver}}) {{.ModelPlural}}(ctx context.Context, args *{{.TypeName}}esArgs) (*{{.TypeName}}ResultResolver, error) { var mods []qm.QueryMod if args.Filter != nil { whereMods, err := app.WhereMods([]app.MaybeMod{ // Add mods for qm.Where here. See: app.MaybeMod }) if err != nil { return nil, err } mods = append(mods, whereMods...) } count, err := models.{{.ModelPlural}}(rr.Db, mods...).Count() if err != nil { return nil, nil } pageInfo, err := args.Page.PageInfo(count) if err != nil { return nil, err } mods = append(mods, pageInfo.QM()...) o, err := models.{{.ModelPlural}}(rr.Db, mods...).All() if err != nil { return nil, err } result := &{{.TypeName}}ResultResolver{ totalCount: count, pageInfo: pageInfo.Resolver(), } for _, row := range o { result.items = append(result.items, &{{.ResolverName}}{rr: rr, o: row}) } return result, nil } func (r *{{.TypeName}}ResultResolver) TotalCount() (int32, error) { return int32(r.totalCount), nil } func (r *{{.TypeName}}ResultResolver) Items() ([]*{{.ResolverName}}, error) { return r.items, nil } ` <file_sep>// Use the //export comment (eg. line 9) // to annotate functions you wish // to make accessible to // other languages. package main import "C" //export Hello func Hello() *C.char { return C.CString("Hello world from Go!") } // an empty main function must be declared func main() {} <file_sep>--- title: "Ban Network Users Using Bettercap" date: 2018-03-25T23:40:17+08:00 tags: ["networking"] draft: true --- ![bettercap logo](/images/bettercap/bettercap-logo-sm.png#featured) `TODO: write content` <p class="text-center">***</p> *Outline:* 1. run bettercap 2. activate net.probe module to start probing for hosts in network: `net.probe on` 3. show hosts in network: `net.show` 4. start banning all hosts (except you): `arp.ban on` - run curl from seagate: timeout - run curl from current machine: pass 5. ban specific host:`set arp.spoof.targets 192.168.0.102; arp.ban on` 6. arp.spoof docs https://github.com/bettercap/bettercap/wiki/arp.spoof 7. think of arp.ban as netcut (http://www.arcai.com/what-is-netcut/)<file_sep>import threading import time class WithThread(threading.Thread): """pass a function and its payload to run in thread""" def __init__(self, fn, *payload): threading.Thread.__init__(self) self.locals = locals() def run(self): self.locals['fn'](*self.locals['payload']) def command1(delay, name): print('command1:', name, 'sleeping for', delay) time.sleep(delay) print('[DONE]', name) def command2(name): print('command2:', 'hello', name) print('[DONE]', name) if __name__ == "__main__": threads = {} for x in range(1, 5): threads[x] = WithThread(command1, 2, 'thread #{}'.format(x)) threads[x].start() for x in range(6, 10): threads[x] = WithThread(command2, 'thread #{}'.format(x)) threads[x].start() # tell python to wait till all threads to finish. # comment below code and `print("done")` will be # executed before the threads finished. for i, t in threads.items(): t.join() print("main exited") <file_sep>### Lesson 2: Probability Preview 1. Localization: determining where a self-driving car is in the world - the mathematical framework to get information is called statistic. bayes is the core of statistics. - statistic vs probability: - statistic: give data to find causes - probability: give causes to find data - statistics & probability: a language to find relationship between data and causes - P notation of fair coin: `P(heads)` → read: probability of the coin of coming up heads - probability starts from 0 to 1 (float number) - example of probability of fair coin: - `P(heads)`: 0.5 (50% chance to come up heads) - `P(tails)`: 0.5 (50% chance to come up tails) - `P(A)`: `A` means complimentary outcomes of a probability - `P(A) = 1 - P(¬A)` (`¬A` means opposite event) - composite event: `P.P...P` (independence) - A self-driving car makes hundreds of calculations about probabilistic events every second, but the events are not as clean as a coin flip, ie: - *What is the probability that this sensor measurement is accurate to within 5 centimeters?* - *What is the probability that some other vehicle will turn left at this intersection? Go straight? Turn right?* - *The radar and lidar measurements seem to disagree! What's the probability that the range finder somehow became detached from the roof?* - "In fact, humans drive (reasonably) safely with imperfect knowledge all the time!" - read `P(cloudy) = 0.0`: no chance (0% chance) of cloudy, definitely will not be cloudy. `P(cloudy) = 1.0` means definitely will be cloudy (100% chance) - `P(cloudy | measurement)`: reads "best estimate for the probability that it is cloudy, given the `measurement`" > Self driving cars take new sensor measurements as often as possible to ensure the data they use to make probabilistic predictions is as "fresh" (and therefore as useful) as possible. - **conditional probability**: taking advantage from what we know to make better estimate of what we don't, ie: - `P(cloudy | measurement)`: use current weather as `measurement` to estimate the chance of being cloudy in next 5 minutes - **Dependant Event**: *Two events are dependent if the outcome or occurrence of the first affects the outcome or occurrence of the second so that the probability is changed*, ie. "The outcome of choosing the first card has affected the outcome of choosing the second card" - sample case of dependant event in medical space: ``` P(POSITIVE | CANCER) = 0.9 P(NEGATIVE | CANCER) = 0.1 ``` → the outcome of the blood test (positive/negative) depends whether the patient has cancer or not. *if the patient has cancer, the probability of the blood test to become positive is 0.9, and negative is 0.1* - another sample notation: `P(POSITIVE | ¬CANCER) = 0.8` reads *"probability of the test to come up positive when the patient HAS NO cancer is 80%"* - you can build truth table based on probability values - given `P(CANCER) = 0.1` and `P(POSITIVE | CANCER) = 0.9`, what's value of `P(CANCER | POSITIVE)` ? - ans (0.09): ``` ‣ P(CANCER | POSITIVE) = P(CANCER) * P(POSITIVE) ‣ P(CANCER | POSITIVE) = 0.1 * 0.9 ‣ P(CANCER | POSITIVE) = 0.09 ✔ ``` - the notation of above question is this: ``` CANCER TEST P( ) Y P ? (ans: 0.09) Y N N P N N ``` - propeller drivers air in a particular direction. it can be a ***tractor*** which pulls air downward thru the propeller, or ***pusher***, which push the air upward. quadrocopter, the propellers act as tractor to drive the drone upward - the more the number of tests, the closer the result to the probability. think of how close 10 coin toasts make to create 50% chance of getting heads compared to 1000 coin toasts. the 1000 toasts will make the 50% chance more probable (consistent) --- - i took probability course in my uni. but i learnt deeper about probability in this self-driving course. <file_sep>## Udacity Flying Car Nanodegree > Sat, 14 Apr 2018 at 2:00:23 MYT Preview link: https://classroom.udacity.com/courses/ud787-preview Instructors: 1. <NAME>, University of Toronto, Professor, Institute for Aerospace Studies 2. <NAME>, Professor of Aeronautics, MIT ### Lesson 2: Intro to Autonomous Flight 1. wright brothers: kitty hawk, north carolina - the wright brothers did differently from previous aircraft designers in which the wright brothers designed the aircraft with adjustable wing shape (to imitate the flight of birds) - first autopilot: 1912, by Sperry Corporation (Elmer Sperry). "autopilot": a system used to control the trajectory of an aircraft without *constant* 'hands-on' control by a human operator being required - **quadrotors**: or quad, or drone with 4 rotors - more drone (and autonomous drone) becomes possible because; - cheaper microcontroller (ie. to perform in-flight data crunching tasks) - the availability of high-density battery that makes the quadrotor possible without traditional fuel (gas, oil, etc) - development of GPS (global positioning system). a small drone can now be outfitted with a gps system and give constant updates on its position - *summary*: powerful lightweight computer + battery + gps - why use quadrotor to learn autonomous flight? - its symmetric simplicity makes understanding dynamics and control easier - it's the most accessible and affordable commercial vechicles, which makes it a great test platform to run code on real hardware - quadrator can perform VTOL (virtual take-off and landing) which is crucial to be able to operate in urban environment - summary: simplicity of design, accesibility & vtol > **why a single rotor helicopter need to have single rotor in its tail?** *so the body doesn't spin together (out of control) with the rotor.* read more: angular momentum #### Quadrotor Components 1. 4 rotors. each of 2 rotors that sits in one another spins in the same direction and hence, the two pairs of propellers on a quadrotor spin in opposite directions (the net torque from the two pairs of propellers cancel out so the vehicle is stable in flight) 2. motors (to move the rotors) 3. **inertial measurement unit (IMU)**: an electronic device that measures and reports a body's specific force, angular rate, and sometimes the magnetic field surrounding the body, using a combination of accelerometers and gyroscopes, sometimes also magnetometers. 4. battery 5. gps 6. camera 7. frame: a base where everything else is connected. should be strong but light > Suppose your power supply has an operating range between 3-7 volts and to generate the appropriate amount of thrust for your quad (given it's weight, propeller size etc.) you need to achieve 15,000 RPMs when you're comfortably in the middle of the power supply's operating range. What's a good KV value for your motors? > > **ans**: 3000 KV (the middle of our power supply range is 5. Kv = RPM/volt → 15000 / 5 → 3000) #### More on Quadrotor Components 1. brushed vs brushless motor: http://www.quantumdev.com/brushless-motors-vs-brush-motors-whats-the-difference/ 2. currently, battery technology is not as good as carbon-based fuels in delivering energy. and the way the electric motors convert energy to flight power is not as efficient as combustion engine. but, electric motor is the easiest to work with. 3. quadrotor use brushless motor so to spin faster and more efficient 4. **ESC (Electronic Speed Controller)**: tells motors how fast they should spin 5. `Kv = RPMs / volts`. Kv describes the RPMs that a motor will achieve (under zero load) when a given voltage is applied. ie, a motor that can do 4000 RPMs when 2 volts are applied gets a Kv rating of 2000 (4000 / 2 = 2000) 6. quadrotor has 2 clockwise rotors and 2 counter-clockwise rotors to allow zero-net torque 7. propeller has `radius` property. the bigger the radius, the slower the propeller will spin. 8. propeller also has `pitch` property (the *twist* of the propeller). formally, `pitch` is a linear distance where the propeller will move forward as a result of one rotation. 9. larger pitch props will move more air per revolution, and low pitch props (much flatter) to move lesser air per revolution 10. larger pitch is generally more efficient as it moves more air per revolution but it has lower thrust which make it less suitable for hovering in air. on the other hand, lower pitch has higher thrust which makes it suitable for hovering under heavy load (but they'd use up the battery more faster). 11. there are quadrotor that has *variable-pitch propeller* that can do low-pitch for hover and high-pitch for fast-forward motion. however, variable-pitch propeller is a lot more complicated. hence, you'd probably see fixed-pitch propellers more in drone. 12. battery used in quadrotor need to be able to discharge very quickly, which can be dangerous, compared to those batteries used in laptop or cellphone (although they use same battery technology, Lithium Polymer aka LiPo) 13. when picking battery, make sure that it has enough power to last comfortably during the mission, as well as bringing the payload 14. most of quadrotor power (from battery) goes to (consumed by) the motors 15. the quadrotor will hover when all the propellers spin fast enough to just bounce the gravity 16. the way you induce motion to quadrotor without it spinning uncontrollably is to increase the thrust on *adjacent* motors that spin on opposite direction 17. **euler angle**: three angles introduced by <NAME> to describe the orientation of a rigid body with respect to a fixed coordinate system. 18. with all the tasks to control the thrusts in a quadrotor, manually controlling all four motors to fly the quad would be essentially impossible 19. autopilot adjust and control all the thrusts. however, it needs to know the control attitude of the vehicle. to do so, it uses information from the sensors: IMU (inertial measurement unit) 20. most IMU contains 3 gyroscopes and 3 accelerometers 21. accelerometer can tell us which way is down by referencing to gravity 22. **MEMS**: Micro Electro Mechanical System. it's a modern gyroscope to allow us to have an equivalent of 3 accelerometers and 3 gyroscopes into a tiny chip, ie. in smartphone 23. quadrotor can detect gps anomaly by combining datas from different sensors it has; barometer, IMU, camera, etc. 24. in quadrotor, a flight computer is equivalent to human brain (the one that controls the flight) 25. drone's **attitude control (autopilot) loop** (always running in the background): ``` IMU → Autopilot ↑ ↓ Vehicle ← Motors ``` 26. drone's **position control loop**: ``` GPS → Flight Computer ↑ ↓ attitude control loop ← Target Thrust Vector ``` 27. the autopilot loop might be executed in 50 cycles per second (50hz) while the position loop might be executed in few times per seconds. the two loops doesn't necessarily need to be synchronized. --- - building robot in human-centered environment is a challenge. it needs to be aware of its surroundings - <NAME>: founder of Udacity, CEO of kitty hawk - Flying Card Nanodegree (FCND) Simulator: https://github.com/udacity/FCND-Simulator-Releases - conundrum: a confusing and difficult problem or question <file_sep>from concurrent.futures import ThreadPoolExecutor import time class Task: def __init__(self, name: str): self.name = name self.counter = 0 def run(self): time.sleep(1) self.counter += 1 print('[TASK {}] counter: {}'.format(self.name, self.counter)) task1 = Task('1') task2 = Task('2') task3 = Task('3') pool1 = ThreadPoolExecutor(max_workers=1) pool2 = ThreadPoolExecutor(max_workers=1) pool3 = ThreadPoolExecutor(max_workers=1) for i in range(5): pool1.submit(task1.run) pool1.submit(task2.run) pool1.submit(task3.run) print('[DONE] program reached end of line') <file_sep>package main import ( "fmt" ) func main() { ford := Car{} ford.name = "Ford" ford.color = "black" ford.start() ford.move(40) ford.stop() fmt.Println("Is engine started?", ford.isStarted) ferrari := Car{} ferrari.name = "Ferrari" ferrari.color = "red" ferrari.start() stopAnyVehicle(&ford) stopAnyVehicle(&ferrari) // because `Vehicle` has start and stop method // which has pointer, // this won't work (see the err msg): // mustang := Car{} // stopAnyVehicle(mustang) // unless you do: // mustang := &Car{} // stopAnyVehicle(mustang) // or: // mustang := Car{} // stopAnyVehicle(&mustang) } type Vehicle interface { start() move(speed int) stop() } type Car struct { isStarted bool name string color string } // what's the diff between `func (c Car)` & `func (c *Car)`? // `func (c Car)` will pass Car by value // while `func (c *Car)` will pass it by reference. // try change receiver of start method below from // `c *Car` to `c Car`. // see: https://golang.org/doc/faq#methods_on_values_or_pointers func (c *Car) start() { c.isStarted = true fmt.Println("engine is started") } func (c Car) move(speed int) { if !c.isStarted { panic("Engine not started") } fmt.Println("the", c.name, "car which color is ", c.color, "is moving at", speed, "km/h") } func (c *Car) stop() { c.isStarted = false fmt.Println(c.name, "is stopped") } func stopAnyVehicle(v Vehicle) { v.stop() } <file_sep>package main import ( "log" "strings" "github.com/wzulfikar/lab/go/yell" ) func main() { out, err := yell.Yell("git", "describe", "--always") if err != nil { if strings.Contains("not a git repository", out.String()) { log.Fatal("directory is not a git repo") return } log.Fatal(err) } // spew.Dump(out) log.Printf(out.String()) } <file_sep>import ctypes lib = ctypes.cdll.LoadLibrary("./hello.so") # in Python, Go's `*C.char` maps to `ctypes.c_char_p` lib.Hello.restype = ctypes.c_char_p print "%s" % lib.Hello() <file_sep>// Thu, 20 Apr 2017 at 17:42:03 MYT #include <iostream> #include <vector> using namespace std; vector< vector<char> > graph; // char grapch[size][size] // U R D L int dr [] = {-1, 0, 1, 0}; // vector<int> dr = {-1, 0, 1, 0}; int dc [] = { 0, 1, 0, -1}; // vector<int> dc = { 0, 1, 0, -1}; bool isInside(int r, int c) { if (r >= 0 && r < graph.size() && c >= 0 && c < graph[0].size()) { return true; } return false; } /** * Recursive function * * @param sr [description] * @param sc [description] */ void dfs(int sr, int sc, char depth='A') { if (graph[sr][sc] != '#') return; // base case graph[sr][sc] = depth; for (int i = 0; i < sizeof(dr); i++) { int nr = sr + dr[i]; int nc = sc + dc[i]; if (isInside(nr, nc)) { dfs(nr, nc, depth + 1); } } } void generateGraph(int row, int col, char symbol) { graph.resize(row); for (int i=0; i < row; i++) { graph[i].assign(col, symbol); } } void displayGraph() { for (int i=0; i < graph.size(); i++) { for (int j=0; j < graph[i].size(); j++) { cout << graph[i][j] << " "; } cout << endl; } cout << endl; } int main (){ generateGraph(5, 5, '#'); displayGraph(); dfs(4, 0); displayGraph(); }<file_sep>// upload index file to algolia require('dotenv').config() const algoliasearch = require('algoliasearch') const appId = process.env.ALGOLIA_APP_ID const adminKey = process.env.ALGOLIA_ADMIN_KEY const indexName = process.env.ALGOLIA_INDEX_NAME const client = algoliasearch(appId, adminKey); const index = client.initIndex(indexName); const data = require(__dirname + '/../static/algolia-index/curated.json') index.addObjects(data, (err, content) => { if (err) { console.log('[ERROR] failed to upload index to algolia:', err.message) return } const dashboardUrl = `https://www.algolia.com/apps/${appId}/explorer/browse/${indexName}` console.log('[INFO] index uploaded. see at dashboard:', dashboardUrl); });<file_sep>import tensorflow as tf a = tf.constant([ [1., 2.], [3., 1.]]) b = tf.constant([ [True, False], [False, False], [True, True]]) c = tf.constant([ [1, 3, 11, 41]]) d = tf.constant([ [1., 2., 4., 2.], [1., 2., 1., 5.]]) e = tf.constant(3) print("- showing shapes of valid Tensors:") print(" shape of `a`:", a.dtype, a.shape) print(" shape of `b`:", b.dtype, b.shape) print(" shape of `c`:", c.dtype, c.shape) print(" shape of `d`:", d.dtype, d.shape) print(" shape of `e`:", d.dtype, e.shape) print() print("- showing shapes of invalid Tensors:") try: f = tf.constant([ [1., ], [1.0, 2.], [1.0, 2.]]) except ValueError as e: print(" - shape of `f` is invalid:\n ", e) try: g = tf.constant([ [1., None]]) except TypeError as e: print(" - shape of `g` is invalid:\n ", e) try: h = tf.constant([ [1.], [1.0, 2.]]) except ValueError as e: print(" - shape of `h` is invalid:\n ", e) <file_sep>// Hi there, // you've come this far to see // the "bio roulette". Thanks! const quote = (...args) => { const [byline, word] = [args.shift(), args.join("<br/>")] return `<i>${word}</i></br>– ${byline}` } const words = [ "What should I put for bio?", "Is this my bio now?", "AWS – <i>'Anything' Web Service</i>", "BIO – <i>Back in Office</i>", "IMO – <i>I Made One</i>", "WWW – <i>World Will Wait</i>", "WWW – <i>World Wide Wallet</i>", quote("<NAME>", "Don't count the days. Make the days count."), quote("The Jogging Baboon", "It gets easier. Every day it gets a little easier.", "But you got to do it every day."), quote("Batman", "I'm Batman"), ]; // get random number as index (including `min`, excluding `max`) const [min, max] = [0, words.length] const randomIdx = Math.floor(Math.random() * max) + min // update header bio document.getElementById('header--bio').innerHTML = words[randomIdx]<file_sep>package main import ( "fmt" "strings" ) func do(s string) string { a := strings.Count(s, "A") d := strings.Count(s, "D") if a > d { return "Anton" } if a < d { return "Danik" } return "Friendship" } // put the test case here. // comment this func before // submitting to codeforces // func Test(t *testing.T) { // a := assert.New(t) // a.Equal("Anton", do("ADAAAA")) // a.Equal("Danik", do("DDDAADA")) // a.Equal("Friendship", do("DADADA")) // } // http://codeforces.com/problemset/problem/734/A func main() { var s string var n int fmt.Scan(&n, &s) fmt.Println(do(s)) } <file_sep>package main import ( "fmt" "os" "strings" "github.com/davecgh/go-spew/spew" "io/ioutil" "github.com/spf13/viper" ) var parsedFiles []string // Sample snippet: // `CONFIG_DIR=/path-to-config-dir CONFIG_SUFFIX=sample go run viperparse.go` // // `CONFIG_SUFFIX` is optional. Above snippet will parse // configurations from all files which endings contain string "sample". func main() { v := viper.New() appConfigDir := os.Getenv("CONFIG_DIR") v.AddConfigPath(appConfigDir) err := v.ReadInConfig() // Handle errors reading the config file if err != nil { panic(fmt.Errorf("Fatal error config file: %s \n", err)) } files, err := ioutil.ReadDir(appConfigDir) if err != nil { panic(err) } parseFiles(v, files, os.Getenv("CONFIG_SUFFIX")) v.AutomaticEnv() v.SetEnvKeyReplacer(strings.NewReplacer(".", "_")) fmt.Println("→ Parsed files:\n", parsedFiles) fmt.Println("\n→ Parsed value:") v.SetDefault("config-key-here", "Please adjust your config key (line 45)") spew.Dump(v.Get("config-key-here")) } func parseFiles(v *viper.Viper, files []os.FileInfo, fileSuffix string) { var suffix string if fileSuffix != "" { suffix = fmt.Sprintf("\"%s\"", fileSuffix) } else { suffix = "no" } fmt.Printf("Parsing %d files.. (using suffix: %s)\n", len(files), suffix) for _, file := range files { nameSplit := strings.Split(file.Name(), ".") name := strings.Join(nameSplit[:len(nameSplit)-1], ".") if fileSuffix != "" { if len(nameSplit) < 2 { continue } if nameSplit[len(nameSplit)-2] == fileSuffix { readConfigName(name, v) } } else if len(nameSplit) == 2 { readConfigName(name, v) } } } func readConfigName(filename string, v *viper.Viper) { parsedFiles = append(parsedFiles, filename) v.SetConfigName(filename) err := v.MergeInConfig() if err != nil { panic(fmt.Errorf("Fatal error config file: %s \n", err)) } } <file_sep>--- title: "I Forgot My Keepass Master Password" date: 2019-04-01T18:36:08+08:00 draft: true tags: [security, hashcat, password manager] post_id: 28 aliases: [ "/posts/28", ] --- Today was just like another day, until I realized that I can't open my keepass password manager. Apparently, I forgot my master password. <!--more--> Keepass is an open source password manager (see: https://keepass.info) that offers similar features of other password managers like keychain (macOS), lastpass.com (online), etc. If you have never seen Keepass before, check this video. {{< youtube grf_LyudTE0 >}} </br> Here's what happens in the video: 1. Open "Keepass" app (I'm running Ubuntu 18.04) 2. Create new keepass db at `~/Desktop/Database.kdbx` and save it 3. Insert master password for the new keepass db 4. Insert name for the db (I named it `MyDatabase`) 5. Add new login entry "**Some Login**" (in real life, this can be website login, etc.) 6. Lastly, save the changes I made to my keepass The steps in the video should give you some context on how Keepass works. You store your password in Keepass, and Keepass will store it securely in keepass db (in our case, it's `~/Desktop/Database.kdbx`). It's considered secure because the db file is encrypted with the master password: the content of keepass db won't be accessible (won't be decrypted) until the corect master password is supplied. Losing/forgetting master password means losing all your stored logins. I don't want to go through "forget password" routine of every website or services that I used. So, instead of giving up, I kept trying to insert whatever password I remember. _No luck._ ![keepass wrong master password](/images/keepass-wrong-password.gif) asdfaf ![sample password list](/images/keepass-password-list-hashcat.png) ![hashcate keepass hashmode 13400](/images/hashcat-hashmode-keepass-13400.png) ![extract hash from keepass db](/images/extract-hash-from-keepass-db.png) ![extract hash from keepass db](/images/hashcat-error-need-force.png) ![extract hash from keepass db](/images/hashcat-completed.png) ![extract hash from keepass db](/images/hashcat-subsequent-run.png) ![extract hash from keepass db](/images/hashcat-password-from-potfile.png) ![extract hash from keepass db](/images/hashcat-potfile-content.png) <file_sep>package slackwebhook import ( "errors" "fmt" "log" "net/http" "strings" "github.com/ashwanthkumar/slack-go-webhook" "github.com/haisum/recaptcha" "github.com/spf13/viper" ) type webhook struct { webhook string server string channels map[string]bool origins map[string]bool re *recaptcha.R } func NewHandler(server, configDir string) func(w http.ResponseWriter, r *http.Request) { v := viper.New() v.AddConfigPath(configDir) if err := v.ReadInConfig(); err != nil { log.Fatal(err) } wh := &webhook{ v.GetString("webhook"), server, make(map[string]bool), make(map[string]bool), nil, } if s := v.GetString("recaptchasecret"); s != "" { wh.re = &recaptcha.R{ Secret: s, } } for _, o := range v.GetStringSlice("origins") { wh.origins[o] = true } for _, c := range v.GetStringSlice("channels") { wh.channels[c] = true } if v.GetString("webhook") == "" || len(wh.origins) == 0 || len(wh.channels) == 0 { log.Fatal("Invalid configuration") } return wh.handlePayload } func (wh *webhook) Send(payload slack.Payload) error { if payload.Channel == "" { return fmt.Errorf("Channel cannot be empty") } if !wh.channels[payload.Channel] { return fmt.Errorf("Invalid channel: %s", payload.Channel) } err := slack.Send(wh.webhook, "", payload) if len(err) > 0 { return err[0] } return nil } // test: // curl -d "channel=#test&text=hello+world&author=yolo" -X POST http://localhost:9090 func (wh *webhook) handlePayload(w http.ResponseWriter, r *http.Request) { var err error var site, redirect string var skipThankyou, wantJson bool defer func() { if wantJson { if err != nil { http.Error(w, `{"ok":false,"msg":"`+err.Error()+`"}`, http.StatusBadRequest) return } fmt.Fprintf(w, `{"ok":true,"msg":"Payload sent"}`) } else { if err != nil { w.Write([]byte(templateFormError(err.Error(), site))) return } if redirect == "" { redirect = site } if skipThankyou { http.Redirect(w, r, redirect, http.StatusSeeOther) return } w.Write([]byte(templateFormSubmitted(redirect))) } }() // cors origin := strings.SplitAfter(r.Header.Get("Origin"), "://") referer := strings.SplitAfter(r.Header.Get("Referer"), "://") if len(origin) < 2 { if len(referer) > 1 && referer[1] != wh.server { err = errors.New("Bad referer") return } err = errors.New("Invalid origin") return } else if !wh.origins[origin[1]] { err = errors.New("Bad origin") return } // prepare slack payload attachment := &slack.Attachment{} payload := slack.Payload{ Username: "WebFormBot", IconEmoji: ":robot_face:", } r.ParseForm() // honeypot if strings.Join(r.Form["_gotcha"], "") != "" { return } site = strings.Join(r.Form["_site"], "") wantJson = strings.Join(r.Form["_json"], "") == "true" if err = wh.checkParams(r); err != nil { return } for k, v := range r.Form { switch strings.ToLower(k) { // app specific (underscore prefix) case "_site", "g-recaptcha-response", "_gotcha": continue case "_redirect": redirect = strings.Join(v, "") case "_skipthankyou": if strings.Join(v, "") == "true" { skipThankyou = true } // slack message case "text": payload.Text = strings.Join(v, "") case "channel": payload.Channel = strings.Join(v, "") // slack attachment case "pretext": pretext := strings.Join(v, "") attachment.PreText = &pretext case "attachmentcolor": color := strings.Join(v, "") attachment.Color = &color // slack fields default: attachment = attachment.AddField(slack.Field{Title: k, Value: strings.Join(v, "")}) } } payload.Attachments = []slack.Attachment{*attachment} err = wh.Send(payload) if err != nil && strings.Contains(err.Error(), "no such host") { err = errors.New("Error connecting to slack") } } func (wh *webhook) checkParams(r *http.Request) error { // check `_site` if strings.Join(r.Form["_site"], "") == "" { return errors.New("`_site` parameter is required") } // verify google recaptcha if wh.re != nil && !wh.re.Verify(*r) { return errors.New("Invalid captcha") } return nil } <file_sep>serve: go run server.go build: GOARCH=wasm GOOS=js go build -o lib.wasm main.go # download wasm_exec.js script that will # work with go1.11.2 wasm binary wasm_exec.js: wget https://raw.githubusercontent.com/golang/go/release-branch.go1.11/misc/wasm/wasm_exec.js deploy: cp lib.wasm index.html wasm_exec.js dist/ surge dist <file_sep>const { appId, searchKey, indexName } = HUGO_ENV.algolia const subIndexTrigger = '/' const subIndex = instantsearch({ appId, apiKey: searchKey, indexName: 'personal', searchParameters: { hitsPerPage: 5, }, }); const mainIndex = instantsearch({ appId, apiKey: searchKey, indexName, searchParameters: { hitsPerPage: 5, }, searchFunction: function(helper) { var searchResults = $('#hits'); if (helper.state.query === '') { searchResults.hide() return } let subIndexQuery = '' if (helper.state.query.startsWith(subIndexTrigger)) { subIndexQuery = helper.state.query.replace(subIndexTrigger, '') } if (subIndexQuery.length) { subIndex.helper.setQuery(subIndexQuery).search(); subIndex.helper.search() } else { // perform the regular search & display the search results helper.search(); } searchResults.show(); } }); mainIndex.addWidget( instantsearch.widgets.searchBox({ loadingIndicator: 'loading..', container: '#search-box', placeholder: ' \uf002 Search site', autofocus: false, }) ); const months = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', ] mainIndex.addWidget( instantsearch.widgets.hits({ container: '#hits', templates: { empty: 'No results found', item: hit => { let date = hit.date && new Date(hit.date) if (date) { date = `${months[date.getMonth()].toUpperCase()} ${date.getDate()}, ${date.getFullYear()}` } let tags = hit.tags ? '· ' + hit.tags.map(tag => `<span class="tag">${tag}</span>`).join(', ') : ''; return ` <div class="hit-title"> <a href="${hit.objectID}"> ${hit.coverImage ? `<img src="${hit.coverImage}"/>` : ''} <h4> ${hit._highlightResult.title.value} <span class="subtitle">${date || hit._highlightResult.type.value} ${tags}</span> </h4> <span class="summary"> ${hit.summary ? hit._highlightResult.summary.value : hit._highlightResult.body.value.split(' ').splice(0, 35).join(' ')} </span> </a> </div> <hr/>` } } }) ); subIndex.addWidget( instantsearch.widgets.hits({ container: '#hits', templates: { empty: 'No results found', item: hit => { let date = hit.timestamp && new Date(hit.timestamp) if (date) { date = `${months[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()}` } return ` <div class="hit-title"> <a href="${hit.url}"> <h4> <img src="${hit.thumbsUrl}" style="width: 40px; margin: 0px 0.5em 0.2em 0.2em; display: inline-block;"/> <div style="display: inline-block;"> <span>${hit._highlightResult.title.value}</span> <span class="subtitle">${hit._highlightResult.description.value}</span> <span class="subtitle" style="font-weight: 400;">${date}</span> </div> </h4> <span class="summary"> ${hit.text.endsWith('.jpg') ? `<img src="${hit.text}"/>` : hit._highlightResult.text.value.split(' ').splice(0, 35).join(' ')} </span> </a> </div> <hr/>` } } }) ); mainIndex.start(); subIndex.start(); $searchBoxInput = $('input.ais-search-box--input') $wrapper = $('#instantsearch-wrapper') $hitsWrapper = $('div#hits') $resetWrapper = $('span.ais-search-box--reset-wrapper') $('a#trigger-search').click(() => { $wrapper.toggle() }) $resetWrapper.click(e => { $searchBoxInput.val('') $searchBoxInput.focus() }) $searchBoxInput.focus(e => { e.target.style.width = '140px' e.target.style.paddingRight = '2.2em' }) $searchBoxInput.blur(e => { if (!e.target.value.trim().length) { e.target.style.width = '' e.target.style.paddingRight = '' e.target.value = '' $resetWrapper.hide() } }) // use https://keycode.info to get keycode number window.addEventListener("keyup", function (e) { // press '/' to start searching if (e.keyCode == '191' && !$searchBoxInput.is(':focus')) { $searchBoxInput.focus() return } // press 'esc' to exit search box if (e.keyCode == '27') { $searchBoxInput.val('') $searchBoxInput.trigger('blur') $hitsWrapper.hide() return } }, false); <file_sep>package alprgo import ( "bytes" "encoding/json" "fmt" "log" "os" "os/exec" "path/filepath" "time" "github.com/pkg/errors" ) type ExecHandler struct { AdjustStdout bool Country string ProcessedImagesPath string } func NewExecHandler(adjustStdout bool, country, processedImagesPath string) *ExecHandler { return &ExecHandler{adjustStdout, country, processedImagesPath} } func (h *ExecHandler) Handle(imagePath string) { go h.handle(imagePath) } func (h *ExecHandler) handle(imagePath string) { alprResult := &alprResult{} if err := alprResult.exec(imagePath, h.AdjustStdout, "-c", h.Country); err != nil { fmt.Println(err) return } var plates []string minConfidence := 85.0 hit := "HIT" for _, result := range alprResult.Results { for i, candidate := range result.Candidates { if candidate.Confidence > minConfidence && i < 3 { plates = append(plates, candidate.Plate) } } } if len(plates) == 0 { fmt.Println("No license detected") hit = "MISS" } else { fmt.Println(plates) } // move processed image path := filepath.Dir(imagePath) imageFile := filepath.Base(imagePath) ts := time.Now().Format("2006-01-02-150405") processedImage := fmt.Sprintf("%s-%s__%s", ts, hit, imageFile) processedPath := fmt.Sprintf("%s/%s/%s", path, h.ProcessedImagesPath, processedImage) if err := os.Rename(imagePath, processedPath); err != nil { log.Println("moveProcessedImageErr:", err) } } func (r *alprResult) exec(imagePath string, adjustStdout bool, args ...string) error { cmd := "alpr" args = append(args, "-j", imagePath) log.Println("Processing image:", cmd, args) b, err := exec.Command(cmd, args...).Output() if err != nil { return errors.Wrap(err, "exec output") } if adjustStdout { b = bytes.TrimLeft(b, "[ INFO:0] Initialize OpenCL runtime...") } return json.Unmarshal(b, r) } // generated from https://mholt.github.io/json-to-go/ type alprResult struct { Version int `json:"version"` DataType string `json:"data_type"` EpochTime int64 `json:"epoch_time"` ImgWidth int `json:"img_width"` ImgHeight int `json:"img_height"` ProcessingTimeMs float64 `json:"processing_time_ms"` RegionsOfInterest []struct { X int `json:"x"` Y int `json:"y"` Width int `json:"width"` Height int `json:"height"` } `json:"regions_of_interest"` Results []struct { Plate string `json:"plate"` Confidence float64 `json:"confidence"` MatchesTemplate int `json:"matches_template"` PlateIndex int `json:"plate_index"` Region string `json:"region"` RegionConfidence int `json:"region_confidence"` ProcessingTimeMs float64 `json:"processing_time_ms"` RequestedTopn int `json:"requested_topn"` Coordinates []struct { X int `json:"x"` Y int `json:"y"` } `json:"coordinates"` Candidates []struct { Plate string `json:"plate"` Confidence float64 `json:"confidence"` MatchesTemplate int `json:"matches_template"` } `json:"candidates"` } `json:"results"` } <file_sep>package templates const Schema = `package resolvers var {{.TypeName}}Type = "{{.TypeName}}" var {{.TypeName}}Schema = ` + "`" + ` type {{.TypeName}} { {{.SchemaFields}} } // TODO: add fields for filter // input {{.TypeName}}Filter { // } ` + "` + {{.TypeName}}Result" + ` var {{.TypeName}}Result = ` + "`" + ` type {{.TypeName}}Result implements QueryResult { totalCount: Int! pageInfo: PageInfo! items: [{{.TypeName}}]! } ` + "`" + ` var {{.TypeName}}Query = ` + "`" + ` {{.TypeNameLowerCase}}(id: ID!): {{.TypeName}}! ` + "`" + ` var {{.TypeName}}Mutations = ` + "`" + ` create{{.TypeName}}(id: ID!): {{.TypeName}}! ` + "`" <file_sep>// scrape image from given url with selector package imagescraper import ( "fmt" "log" "net/http" "net/url" "os" "path/filepath" "strings" "github.com/PuerkitoBio/goquery" "github.com/pkg/errors" "github.com/wzulfikar/lab/go/getty" ) func Scrape(targetUrl, selector, dir string, concurrency int) []string { res, err := http.Get(targetUrl) if err != nil { log.Fatal(err) } defer res.Body.Close() if res.StatusCode != 200 { log.Fatalf("status code error: %d %s", res.StatusCode, res.Status) } urlParsed, err := url.Parse(targetUrl) if err != nil { log.Fatal(errors.Wrap(err, "url.Parse")) } baseUrl := fmt.Sprintf("%s://%s", urlParsed.Scheme, urlParsed.Host) // Load the HTML document doc, err := goquery.NewDocumentFromReader(res.Body) if err != nil { log.Fatal(err) } // pass non-empty SKIP_FILE to skip scraping image files var skipFile = os.Getenv("SKIP_FILE") var images []string sem := make(chan bool, concurrency) // Find the review items doc.Find(selector).Each(func(i int, s *goquery.Selection) { // For each item found, get the band and title src, ok := s.Attr("src") if !ok { fmt.Printf("node[%d] does not have `src` attribute\n", i) return } if strings.HasPrefix(src, "/") { src = baseUrl + src } file := filepath.Base(src) if skipFile != "" && file == skipFile { fmt.Println("File skipped:", src) return } filename := file if text, ok := s.Attr("title"); ok { filename = text + "_" + filename } else if text, ok := s.Attr("alt"); ok { filename = text + "_" + filename } filename = strings.Replace(filename, " ", "_", -1) sem <- true go func(src, filename, dir string) { defer func() { <-sem }() if err := getty.Get(src, filename, dir); err != nil { log.Printf("Failed to download image from %s: %v\n", src, err) return } images = append(images, src) log.Println("Image downloaded:", filename) }(src, filename, dir) }) for i := 0; i < cap(sem); i++ { sem <- true } return images } <file_sep>--- title: "Using Bettercap (v2.0) Proxy" date: 2018-03-24T02:10:11+08:00 tags: ["intro", "networking"] draft: false hideToc: true coverImg: /images/bettercap/bettercap-logo-sm.png#featured coverAlt: Bettercap logo --- ## What is Bettercap? If you are into networking tools for ARP spoof, sniffing, and other MITM-like utilities, you've probably heard about ettercap[^1]. Bettercap, which *sounds* similar to ettercap, is a networking tool like ettercap. Some people like to relate the name "Bettercap" as _better ettercap_. <!--more--> Quoting from its github repository at https://github.com/bettercap/bettercap, it's _"The state of the art network attack and monitoring framework"_. ## Why Bettercap? This is where I find it interesting. The first time I knew about Bettercap was when it still built using ruby (v1.0). In Feb 2018, Bettercap author, <NAME> ([@evilsocket](https://twitter.com/evilsocket)), reimplemented Bettercap (v2.0) using Go[^2]. With this reimplementation, Bettercap is now a cross-platform single binary program. Unlike its previous version where you've to install ruby to run it, in Bettercap v2.0, you just need to download the binary and you're all set! 😎 ## Using Bettercap: HTTP Proxy Now that we know how easy is it to install Bettercap, let's go ahead and try one of its feature: **HTTP proxy**. Bettercap has built-in feature to create HTTP proxy and use javascript file to interact with the connection. To demonstrate this functionality, we'll: 1. Run Bettercap on local machine 2. Set proxy and js file to change server response 3. Test if the proxy is working using curl *The first step*, running Bettercap in local machine (I'm using macOS in this case), is pretty straightforward. Download the binary for your OS[^3], and run it from your command line: `path/to/bettercap`. An interactive Bettercap session will appear, something like this: ![bettercap init](/images/bettercap/bettercap-init.jpg) <p class="figure-text">Figure 1: initializing bettercap (command line)</p> *Going to step 2*, we'll need to set a proxy and create a js file to interact with proxied connection. Before activating the proxy, let's create a `proxy-script.js` file in our desktop: ```js // file: ~/desktop/proxy-script.js // called when script is loaded function onLoad() { console.log( "PROXY SCRIPT LOADED" ); } // called after a request is proxied and there's a response function onResponse(req, res) { res.ContentType = "rogue-content"; res.Body = "me was here"; } ``` <p class="figure-text">Figure 2: js code inside desktop/proxy-script.js</p> Now that the proxy-script is in place, we can bring up the HTTP proxy by running this command (in bettercap session): ![bettercap proxy on](/images/bettercap/bettercap-proxy-on.jpg) <p class="figure-text">Figure 3: activating bettercap http.proxy module</p> In above image, you should've noticed that the interpreter displayed `PROXY SCRIPT LOADED` after loading the proxy script. Yep, that specific string `PROXY SCRIPT LOADED` is the one we set inside our `console.log` of `onLoad()` function in `proxy-script.js` (see: figure 2). The `set http.proxy.script` tells Bettercap where to look for our js file. `set http.proxy.address` sets which address we'd like to bind the Bettercap proxy. Lastly, when all the variables for http.proxy are set, we activate the module using `http.proxy on`. <p class="text-center">***</p> *We're reaching our last step, step 3!* We've successfully activated `http.proxy` module. If you've issue activating it, try run the bettercap command as administrator (or via `sudo`). In this step, we'll test if our proxy is actually working by sending a request using curl command. If you're on windows and you don't have `curl` installed, you can download it from here: https://curl.haxx.se/download.html. Based on our code in `proxy-script.js` file, the respond we should get when sending request using proxy is `me was here` (see `onResponse` function, figure 2). To test that, we'll first send a direct request to google to see what's the original respond, and then we'll send another request to google using proxy. The GIF in Figure 4 below shows how it works: ![bettercap proxy gif](/images/bettercap/bettercap-proxy-google.gif) <p class="figure-text">Figure 4: Bettercap proxy in action</p> *Voila!* The proxy is working, and sending request to google.com (and to any other domain) via our proxy will get the respond modified to `me was here`. Notice that when we send the proxied request, our bettercap session displays new *event stream* `http.proxy.spoofed-response`. To sum up above operation, here's the logical flow: ``` → user sends request with bettercap proxy → bettercap proxy handle the request and modify it → user gets modified respond ``` ## Closing That's it, a short demonstration on how we utilize Bettercap HTTP proxy module to interact with proxied connection and modify the response. In real world scenario, above operation can be used by any attacker to *smuggle* malicious script in HTTP response –– and the user will still think that nothing has changed, instead of changing the whole response to `me was here`. Knowing how easy to do this should give us more awareness when using random proxy in internet. Just like what we've demonstrated here, yeah, the proxy providers can easily do funky stuffs as we browse the internet. *Unless you really trust, don't use them to browse your confidential informations.* I'd like to write one or two more posts to demonstrate other Bettercap features. But in the meantime, take your time exploring [Bettercap wiki](https://github.com/bettercap/bettercap/wiki) and see for yourself what it's capable of. ***Till next. See ya!*** [^1]:https://en.wikipedia.org/wiki/Ettercap_(software) [^2]:https://www.evilsocket.net/2018/02/27/All-hail-bettercap-2-0-one-tool-to-rule-them-all/ [^3]:https://github.com/bettercap/bettercap/releases <file_sep>package main import "bitbucket.org/skolafund/skolafund/modules/trello" func main() { // trello.Run() trello.Sample() } <file_sep>--- title: "About" hidden: true disableDisqus: true --- Just a random dude writing on the internet. Interested about tech and communication. <p class="text-center">***</p> I initially started with PHP (2013). Joined as junior software developer and started developing web system using Yii framework. Not long after, I moved on to other projects and have been using Laravel for around 3 years since then Mid 2015, I took another experience as front-end dev. Started with vue js, and moved to react after 1 year of using vue. Have been using react since then. Early 2017, there was a need to migrate PHP-backed system to Go, to increase efficiency and modularity (go's single binary) and that was the first project where I applied my Go knowledge. Recently, I've been doing personal project for a competition using python to predict the emotion of a stream of wav audio. To sum up, I like to tinker with technologies, and getting into the loop of learn, apply, repeat. ### Want some referrals? - vultr: https://www.vultr.com/?ref=7203686 - digital ocean (get $10 in credit): https://m.do.co/c/2daa556e6f4e <file_sep>package main import ( "fmt" "strings" ) func main() { s := "<EMAIL>" fmt.Println(maskString(s, "*")) s = "<EMAIL>" fmt.Println(maskString(s, "*")) s = "One" fmt.Println(maskString(s, "*")) s = "<NAME>" fmt.Println(maskString(s, "*")) s = "Yuni" fmt.Println(maskString(s, "*")) s = "<EMAIL>" fmt.Println(maskString(s, "*")) s = "<NAME>" fmt.Println(maskString(s, "*")) s = "<NAME>" fmt.Println(maskString(s, "*")) s = "<NAME>" fmt.Println(maskString(s, "*")) s = "One two three four" fmt.Println(maskString(s, "*")) } func maskString(s, mask string) string { s = strings.TrimSpace(s) l := len(s) maskFrom := l / 3 maskEnd := l / 4 // limit maskFrom & maskEnd if maskFrom > 4 { maskFrom = 4 } if maskEnd > 3 { maskEnd = 3 } masked := s[0:maskFrom] prev := "" for i := maskFrom; i < l; i++ { c := s[i : i+1] if c == "@" || c == "." || c == " " || i >= l-maskEnd { masked += c } else if prev == " " { masked += c maskEnd-- } else { masked += mask } prev = c } return masked } <file_sep>> Fri, 27 Apr 2018 at 5:48:07 MYT ### Lesson 2: List-Based Collection 1. collection: group of things - list-based collection: collection with few additional rules/constraints, ie. order - linked list store reference for next element - adding element into linked list is easy because it's just a matter of changing the reference, hence the constant time (unlike adding element in array where it requires to shift all subsequent elements) - doubly linked list is just linked list, with added reference to its previous element (instead of just next element) - stacks: put element on top of each other → **LIFO** (last in first out) - stacks can be very useful when we only care about the most recent element - specific term used in stacks: - `push`: adding element into stack - `pop`: take element from stack - queue: kind-of opposite of stack - structure of queue: **FIFO** (first in first out) - common terms used in queue: - `enqueue`: adding element to tail - `dequeue`: remove head element - `peek`: looking at head element without actually removing it - **deque**: double-ended queue; a queue that can be queued/dequeued from both direction - **priority queue**: queue with added constraint (priority point). element with highest priority will be taken first when doing dequeue operation (doesn't follow FIFO structure). if element has same priority, the oldest element will be taken. <file_sep>dev: ./script/dev.sh snapshot: hugo && git add -A && git commit -m "hugo snapshot" && git push @echo "done." build: ./script/publish.sh --build-only publish: ./script/publish.sh sync-index: @echo "updating algolia index.." @yarn index:sync<file_sep>package main import ( "fmt" ) func main() { words := []string{"foo", "bar", "baz"} done := make(chan bool) defer close(done) for _, word := range words { go func(word string) { // time.Sleep(1 * time.Second) fmt.Println(word) done <- true }(word) } // Do concurrent things here // This blocks and waits for signal from channel for i := 0; i < len(words); i++ { <-done } } <file_sep>package main import "github.com/davecgh/go-spew/spew" type ParamsAllTransactions struct { Address string `url:"address"` Hash string `url:"hash,omitempty"` Id string `url:"hash,omitempty"` } var TransactionsPath = struct { All string Incoming string Unconfirmed string }{ "/account/transfers/all", "/account/transfers/incoming", "/account/unconfirmedTransactions", } var Paths = struct { Transactions []apiPath }{ Transactions: []apiPath{ {"incom", "asdfa"}, }, } func main() { spew.Dump(Paths.Transactions) } <file_sep>## Udacity: Intro to Self-driving Car > Sat, 14 Apr 2018 at 2:00:23 MYT Preview link: https://classroom.udacity.com/courses/ud013-preview/lessons/ab5998f5-8d95-4604-a4a3-5246768986d8/concepts/f645ea5b-caeb-467f-ac45-3f7f835c38fc ### Lesson 4 - Sensor fusion focuses on combining data coming in from a vehicle's lidar and radar sensors in order to detect objects in the world around it. ##### LIDAR (Light Imaging Detection and Ranging) - Used to detect objects on the surface as well as their size and exact disposition - LIDAR uses laser light pulses to scan the environment as opposed to radio or sound waves - LIDAR was invented by U.S military and NASA more than 45 years ago for measuring distance in space. first commercial usage occur on 1995 for topographical needs - LIDAR algorithm in a nutshell: 1. Emit laser signals 2. Laser signals reach an obstacle 3. Signal reflects from the obstacle 4. Signal returns to the receiver 5. A laser pulse is registered - compared to sound waves, using LIDAR, the light is 1.000.000 times faster than the sound - A LIDAR can build an exact 3D monochromatic image of an object - Some disadvantages of using LIDAR: - Limited usage in nighttime/cloudy weather. - Operating altitude is only 500-2000m. - Quite an expensive technology. ##### RADAR (Radio Detection and Ranging) - used to detect objects at a distance, define their speed and disposition - invented in 1940, right before World War II; however, development actually started in 1886 when one German physicist realized that radio waves could reflect from solid objects. - compared with LIDAR, RADAR uses radio waves instead of of light (the use of different signals to detect objects; light vs radio wave) - RADAR can easily operate in cloudy weather conditions, and at night. It also has a longer operating distance. > Articles on lidar vs radar: > - http://www.archer-soft.com/en/blog/lidar-vs-radar-comparison-which-system-better-automotive - http://robotsforroboticists.com/lidar-vs-radar/ #### Kalman Filters - a simpler sensor fusion technique (ie. combining data from LIDAR and RADAR) - **extended kalman filter**: capable of handling more complex motion and measurement models #### PID Control - CTE: crosstrack error - reference trajectory: represents a suggested path by which the controlled variable should converge on the set-point in a specified manner - when driving a car, the program will steer in proportion to CTE. which means that the larger the error the more the vehicle will be turned toward reference trajectory - larger CTE basically means that the vehicle is moving further away from reference trajectory #### Model Predictive Control - sliding window technique: <file_sep>## Udacity Browswer Rendering Optimization > Wed, 2 May 2018 at 21:54:37 MYT Course link: https://classroom.udacity.com/courses/ud860/lessons/4138328558/concepts/41570785750923 **Instructors:** 1. <NAME>, Developer Advocate at Google 2. <NAME>, Course Developer at Udacity ### Lesson 1: The Critical Rendering Path <file_sep>package graphqlboiler import ( "fmt" "testing" ) func TestReflectFields(t *testing.T) { fields := reflectFields(SampleSchemaPerson{}) fmt.Println(fields) } <file_sep>--- title: "Javascript Rot N" date: 2018-03-09T18:34:23+08:00 tags: [""] draft: true --- `TODO: write content` `rotDecode("yololo", 13)` `rotEncode("yololo", 13)` http://www.rot-n.com [Run in JSBin](https://jsbin.com/nezojor/edit?js,output) <p class="text-center">***</p> *Outline:* 1. <file_sep><?php /** * Overload app's dotenv based on domain. * The file that contains domain-based environment * is stored in the same directory of this file and has * same file name as the domain itself. * * If this file is stored in `/domain_environments/` and you * want to load domain env for `me.com`, store environment * vars of `me.com` in `/domain_environments/me.com` file. */ function getDomainEnvFromArgv($removeFromArgv = false) { $domainEnvPrefix = '-domain_env='; $args = $_SERVER['argv']; foreach ($args as $key => $arg) { if (stripos($arg, $domainEnvPrefix) !== false) { list(, $domain_env) = explode($domainEnvPrefix, $arg); if ($removeFromArgv) { unset($_SERVER['argv'][$key]); } return $domain_env; } } return null; } $domain_env = !empty($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : getDomainEnvFromArgv(); // overload .env file if `domain_env` is succesfully retrieved if ($domain_env && file_exists(__DIR__ . '/' . $domain_env)) { $dotenv = new Dotenv\Dotenv(__DIR__, $domain_env); $dotenv->overload(); } <file_sep>SET SERVEROUTPUT ON SET VERIFY OFF ACCEPT bcode prompt 'Enter the book code: ' DECLARE v_title book.title%TYPE; BEGIN SELECT title INTO v_title FROM book WHERE book_code = '&bcode'; DBMS_OUTPUT.PUT_LINE ('The title of the books is ' || v_title); END; / SET SERVEROUTPUT OFF SET VERIFY ONmove <file_sep>--- title: "WhatsApp and Social Engineering" date: 2018-03-06T16:30:37+08:00 tags: ["experiment", "social"] draft: true --- `TODO: write content` <p class="text-center">***</p> *Outline:* 1. what's social engineering - human is by nature willing to help 2. borrow random smartphone to track location - applicable to other app that provides live location feature (ie. telegram) 2. borrow random smartphone to *sniff* chat via web<file_sep>#include <iostream> #include <vector> #include <string> #include <sstream> #include <iterator> #include <cstring> #include <vector> #include <cstring> #include <algorithm> using namespace std; vector<string> split( string str, char sep = ' ' ) { vector<string> splitted; istringstream stm(str); string token; while(std::getline(stm, token, sep)) splitted.push_back(token); return splitted; } string run(string john, string jane) { vector<string> john_things = split(john); vector<string> jane_things = split(jane); int max = john_things.size(); if (jane_things.size() > max) { max = jane_things.size(); } int matches = 0; for (int i = 0; i < john_things.size(); ++i) { for (int j = 0; j < jane_things.size(); ++j) { if (john_things[i] == jane_things[j]) { matches++; } } } // cout << "matches: " << matches << " ds " << max/2; if (matches > max/2) { return "Forever Dead"; } return "Alive"; } void test() { cout << (run("gaming puzzle sleeping", "chocolate sleeping") == "Alive" ? "✔ " : "✘ "); cout << (run("food programming anime travelling", "food shopping anime travelling") == "Forever Dead" ? "✔ " : "✘ "); cout << (run("pizza burger pasta spaghetti biriyani", "vegetables") == "Alive" ? "✔ " : "✘ "); } int main(){ // test(); return 0; int n,j; string john, jane; cin >> n; cin >> john; cin >> j; cin >> jane; cout << run(john, jane); return 0; }<file_sep>#include <iostream> using namespace std; template<class K, class V> class Node { public: K key; V value; int height; Node<K, V>* left; Node<K, V>* right; Node (K key, V value) { this->key = key; this->value = value; this->height = 1; this->left = NULL; this->right = NULL; } }; template<class K, class V> class AVLTree { private: Node<K, V>* root; public: AVLTree () { root = NULL; } int getBalanceFactor (Node<K, V>* node) { int b = getHeight(node->left) - getHeight(node->right); return b; } Node<K, V>* ll_rotation (Node<K,V>* z) { } Node<K, V>* rr_rotation (Node<K,V>* z) { } Node<K, V>* lr_rotation (Node<K,V>* z) { } Node<K, V>* rl_rotation (Node<K,V>* z) { } void insertHelper (K key, V value, Node<K,V>*& current, bool& isAdded) { if (current == NULL) { current = new Node<K,V>(key, value); isAdded = true; return; } if (key < current->key) { insertHelper(key, value, current->left, isAdded); } else if (key > current->key) { insertHelper(key, value, current->right, isAdded); } else { // the 'key' is already exists return; } } void insert (K key, V value) { bool isAdded = false; insertHelper(key, value, root, isAdded); } void preOrder (Node<K, V>* cur) { if (cur != NULL) { cout << " (" << cur->key << ", " << cur->value << ") "; preOrder(cur->left); preOrder(cur->right); } } void display (int order = 0) { if (order == 0) { preOrder(root); } cout << endl; } }; int main() { return 0; } <file_sep>package main import ( "log" "net/http" "os" "github.com/wzulfikar/lab/go/slackwebhook" ) const listenAddr = "localhost:9090" func main() { handler := slackwebhook.NewHandler(listenAddr, os.Getenv("CONFIG_DIR")) http.HandleFunc("/", handler) log.Println("Listening at port 9090 ") log.Fatal(http.ListenAndServe(listenAddr, nil)) } <file_sep>--- title: "About" hidden: true disableDisqus: true --- Rakyat biasa. Tertarik dengan teknologi dan komunikasi.<file_sep>from multiprocessing import Pool import time def square(x): print("square: sleeping for 2 second") time.sleep(2) # calculate the square of the value of x return x * x def add(x, y): print("add: sleeping for 2 second") time.sleep(2) # sum the value of x and y return x + y if __name__ == '__main__': # Define the dataset dataset = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] # Output the dataset print('Dataset: ' + str(dataset)) # Run function of single arg with a pool of 5 agents # having a chunksize of 3 until finished agents = 5 chunksize = 3 with Pool(processes=agents) as pool: square_result = pool.map(square, dataset, chunksize) # run same pool config for function with multiple args with Pool(processes=agents) as pool: add_result = pool.starmap(add, [ (1, 2), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (3, 1)]) # Output the result print('Square result: ' + str(square_result)) print('Sum result: ' + str(add_result)) <file_sep>## Hugo Site: wzulfikar.com - `make publish`: build static files and send to github page - `make publish sync-index`: publish and sync algolia index **Note on Algolia app key** - don't expose admin key (`ALGOLIA_ADMIN_KEY`) to frontend. use `ALGOLIA_SEARCH_KEY` instead. - docs: https://www.algolia.com/doc/guides/security/api-keys/<file_sep>#include "Dlist.h" template<class T> class Stack : public DList<T> { public: Stack(){ } void push(T value){ this->push_back(value); } T pop(){ return this->pop_back(); } }; <file_sep>package main import ( "fmt" "log" "math/rand" "time" "github.com/fatih/color" "github.com/rs/xid" "github.com/satori/go.uuid" "github.com/teris-io/shortid" ) func main() { terisshortid() rs_xid() satoriuuid() randSeqGenerator() } func terisshortid() { defer timer("github.com/teris-io/shortid")() fmt.Println("\n=== Generator used: github.com/teris-io/shortid ===\n") // initialize generator sid, err := shortid.New(1, shortid.DefaultABC, 2342) if err != nil { log.Fatal(err) } // // generate the short id var id string for i := 0; i < 5; i++ { id, err = sid.Generate() if err != nil { log.Fatal(err) } fmt.Printf("shortid %d: %s\n", i+1, id) } } func satoriuuid() { defer timer("github.com/satori/go.uuid")() fmt.Println("\n=== Generator used: github.com/satori/go.uuid ===\n") for i := 0; i < 5; i++ { fmt.Printf("uuid %d: %s\n", i+1, uuid.NewV4()) } // Parsing UUID from string input u2, err := uuid.FromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8") if err != nil { fmt.Println("Something went wrong: %s", err) } fmt.Println("\nTest parsing uuid from string") fmt.Println("Successfully parsed:", u2) } func rs_xid() { defer timer("github.com/rs/xid")() fmt.Println("\n=== Generator used: github.com/rs/xid ===\n") for i := 0; i < 5; i++ { fmt.Printf("xid %d: %s\n", i+1, xid.New()) } } func randSeqGenerator() { defer timer("randSeq")() fmt.Println("\n=== Generator used: randSeq ===\n") // seed before generating randSeq rand.Seed(time.Now().UnixNano()) for i := 0; i < 5; i++ { fmt.Printf("xid %d: %s\n", i+1, randSeq(11)) } } var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890") func randSeq(n int) string { b := make([]rune, n) for i := range b { b[i] = letters[rand.Intn(len(letters))] } return string(b) } func timer(taskName string) func() { start := time.Now() return func() { color.Cyan("\n=== " + taskName + " done in " + time.Since(start).String() + " ===\n") } } <file_sep>package main import ( "fmt" "time" cron "gopkg.in/robfig/cron.v2" ) func main() { j := &CronJob{PrintText: "Hello world"} // execute cron job manually (ie. testing purpose). // A `Job` is an interface with single function `Run()` // j.Run() // or add job to robfig/cron and execute: // 1: add cron job c := cron.New() c.AddJob("* * * * * *", j) c.Start() // 2: simulate a running system with channel // for robfig/cron to operate. // use `ctrl+c` to stop. done := make(chan bool) <-done } type CronJob struct { PrintText string } func (j *CronJob) Run() { now := time.Now().Format("2006-01-02 15:04:05") fmt.Printf("=== CRON JOB STARTED: %s ===\n", now) fmt.Println(j.PrintText) fmt.Println("=== CRON JOB DONE ===") } <file_sep>--- title: "Pragmatic Shell: First Few Lines" date: 2019-03-16T18:42:14+08:00 tags: [""] draft: true post_id: 27 aliases: [ "/posts/27", ] --- One of few lines I like to begin my shell script with is the lines that will display "usage" info: a one-liner of what the script is, how to use the script, and some examples. "sometimes, the hardest part is to start" <!-- more --> # Motive style="font-weight: 300; border-bottom: 2px solid #8a8a8a;" Here is some sample code taken from my `len` script (available at [github](https://github.com/wzulfikar/lab/tree/master/bash/len)): after encoding the {{< highlight sh "linenos=table" >}} #!/usr/bin/env sh if [ -z "$1" ]; then echo "len –– get length of passed argument (ie. string)" echo "usage: len <string>" exit fi {{< / highlight >}} *Outline:* 1. <file_sep>import visdom import numpy as np from concurrent.futures import ThreadPoolExecutor class WavVisdom: def __init__(self): # default opens up to http://localhost:8097 # make sure visdom server is running: # `python -m visdom.server` self.v = visdom.Visdom() self.canvas = 'wav_visdom' self.thread_pool = ThreadPoolExecutor(max_workers=1) print('checking visdom.server..') print('make sure you have it running (ie. `python -m visdom.server`)') assert self.v.check_connection() print('visdom is up') if not self.v.win_exists(self.canvas): self.v.bar(np.zeros(shape=(80, 1)), win=self.canvas) self.counter = 0 def draw(self, waveData, framerate, frames_sent, nframes): self.thread_pool.submit( self._draw, waveData, framerate, frames_sent, nframes) def _draw(self, waveData, framerate, frames_sent, nframes): # resample to 2 signal = np.fromstring(waveData, 'Int16')[::2] # resize each item signal = [x / 200 for x in signal] self.v.bar(signal, win=self.canvas) # clear plot in last frame if frames_sent == nframes: self.v.bar(np.zeros(shape=(80, 1)), win=self.canvas) return <file_sep>// inspired from https://tutorialedge.net/golang/go-webassembly-tutorial/ package main import ( "syscall/js" ) func sayHello(i []js.Value) { targetEl := i[0].String() js.Global().Get("document").Call("getElementById", targetEl).Set("value", "Hello wasm from Go!") } func registerCallbacks() { // bind `sayHello` in web env to above `sayHello` function js.Global().Set("sayHello", js.NewCallback(sayHello)) } func main() { c := make(chan struct{}, 0) println("go wasm is initialized") js.Global().Get("document").Call("wasmReady") registerCallbacks() <-c } <file_sep># docs: https://www.tensorflow.org/api_docs/python/tf/placeholder import tensorflow as tf print("- creating placeholder for 2 columns data with any number of rows") placeholder = tf.placeholder(tf.float32, shape=[None, 2]) print("- creating computation `c` with placeholder") c = placeholder print("- creating tensorflow session") s = tf.Session() print("- running computation `c` with values for placeholder") print(" result #1:", s.run(c, feed_dict={placeholder: [[1, 3]]})) print(" result #2:", s.run(c, feed_dict={placeholder: [[5, 1], [2, 4]]})) # this will fail because placeholder data is invalid. # expected 2 columns but got 1 column only. # change the args to 2 columns (ie. `[[3, 2]]`) # and it will work. try: print(s.run(c, feed_dict={placeholder: [[], []]})) except ValueError as e: print(" result #3 (invalid):", e) try: print(s.run(c, feed_dict={placeholder: [[2, 4, 1]]})) except ValueError as e: print(" result #4 (invalid):", e) <file_sep><?php namespace App\Traits; use Whoops\Handler\JsonResponseHandler; use Whoops\Handler\PrettyPageHandler; use Whoops\Util\Misc; trait RenderExceptionWithWhoops { private function renderExceptionWithWhoops(\Exception $e, $editor = null) { $isAjax = Misc::isAjaxRequest(); $handler = $isAjax ? new JsonResponseHandler : new PrettyPageHandler; if (!$isAjax && $editor) { // https://github.com/filp/whoops/blob/master/docs/Open%20Files%20In%20An%20Editor.md $handler->setEditor($editor); } $whoops = new \Whoops\Run; $whoops->pushHandler($handler); return new \Illuminate\Http\Response( $whoops->handleException($e), $e->getStatusCode(), $e->getHeaders() ); } } <file_sep>## Introduction to Computer Vision (Udacity) > George University > https://classroom.udacity.com/courses/ud810 ### Lesson 1: Introduction 1. CV: computer vision - CP: computational photography - illusion of power: "I called Megan and she comes." > but megan has the real power, which is video editing - Prof. <NAME> (funny :v) - goal of CV: write computer program that can *interpret* images - how to make computer processes video and recognize actions? - IEEE Journal: **The Faces of Engagement: Automatic Recognition of Student Engagementfrom Facial Expressions** → https://ieeexplore.ieee.org/document/6786307/ - cgi: industrial light and magic (ILM): ilm.com - what's the deal with computer vision: - object recognition - OCR - face recognition - special effects and 3D modelling - smart cars - sports - vision based interaction (xbox kinect depth image, etc) - security (surveilance, etc) - medical imaging (image-guided surgery, etc) - ***vision IS NOT image processing*** - your brain tell you what you see, hence it can creates *illusion* - the triangle in computer vision: - computational models (math) - algorithm - real images - [octave](https://www.gnu.org/software/octave/): open-source equivalent for matlab - install octave macos: `brew install octave` - read more: https://wiki.octave.org/Octave_for_macOS ### Lesson 2: Images as Functions - an image can be thought of: - a function of `I(x, y)`: give the intensity or value at position (x, y) - a 2D array of numbers ranging from some minimum to some maximum (0 to 255) - above function `I(x, y)` represents single channel image (monochrome, black and white, etc). a color image will have a stacked function (vector-valued) like this: ``` f(x, y) = | r(x, u) | # r for red | g(x, u) | # g for green | b(x, u) | # b for blue ``` - an image is mapping of `f(x,y)` to intensity, which looks like this: ``` x = (10, 210) y = (15, 165) intensity = (0, 10) image = f(x, y) + intensity ``` - rgb (red, green, blue) = 3 channels/planes - "A 3-channel color image is a **mapping** from a 2-dimensional space of locations to a 3-dimensional space of color intensity values." - 3 channels color image can be thought as this function: ``` f: R * R → R * R * R [x] [y] [intensity] ``` - `sample`: the 2D space on a regular grid - `quantize`: each sample (round to nearest integer) - TIL: `pixel` stands for picture element - based on above knowledges on image (image as function, its mapping to intensity, etc), we can say that **a digital image is a representation of a matrix of integer values** - in digital images, the height of a picture is equivalent to its rows, its width is equivalent to columns, and its area (h*w) is equivalent to pixels - in a colored digital image, each pixel contains multiple different colors (or channel/plane), ie. red, green, blue in each pixel means a 3-channel digital image - **MATLAB INDEXING STARTS AT 1!!** and so does `octave` - draw line on image using octave; ``` # load image im = imread('images/bali.jpg') # display the image imshow(im) # draw the line line([1 512],[256 256], 'color', 'r') ``` - quantizing image: - to quantize an image, convert each number in the matrix and round down (floor function) - use `size()` to get size of an image: ``` # using octave > size(img) ans = 768 1024 3 ``` - 8 "byte" = indicates the bit depth - addition of image is element by element operation. hence, the size of images must match. - `uint8` = 0 to 255 - be mindful of data type of the image you're using when doing arithmetic operation --- review: - overall fun learning process, fun instructor and fun way of communicatin the materials - bit-sized, succinct materials - prbbly my first enjoyable and learnable online lecture video on a considerably more serious topic <file_sep>#include<iostream> #include<string> #include<sstream> using namespace std; string func(string str) { const int LEN = str.size(); if (LEN <= 10) { return str; } stringstream ss; ss << str[0] << LEN-2 << str[LEN-1]; return ss.str(); } void test() { cout << (func("4") == "" ? "✔ " : "✘ "); cout << (func("word") == "word" ? "✔ " : "✘ "); cout << (func("localization") == "l10n" ? "✔ " : "✘ "); cout << (func("internationalization") == "i18n" ? "✔ " : "✘ "); } int main(){ // test(); int n; string word; cin >> n; for(int i = 0;i < n;i++) { cin >> word; cout << func(word) << endl; } }<file_sep>--- title: "Using Vscode Debugger" date: 2019-06-23T03:23:01+08:00 tags: [""] draft: true post_id: POST_ID aliases: [ "/posts/POST_ID", ] --- TODO: summary <!--more--> TODO: content <p class="text-center">***</p> *Outline:* - Bash - WIP - Python - WIP - Node - settings > node > auto attach - run in terminal: `node --inspect-brk <js script>` - Debugging Go with vscode - ref: https://scotch.io/tutorials/debugging-go-code-with-visual-studio-code<file_sep>#include<iostream> #include<string> using namespace std; string func(string str) { const string NEEDLE = "WUB"; const string REPLACEMENT = " "; int pos = str.find(NEEDLE); while (pos != -1) { str.replace(pos, 3, REPLACEMENT); pos = str.find(NEEDLE); } return str; } void test() { cout << (func("WUBWUBABCWUB") == "ABC" ? "✔ " : "✘"); cout << (func("WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB") == "WE ARE THE CHAMPIONS MY FRIEND" ? "✔ " : "✘"); } int main(){ // test(); string a; cin>>a; cout << func(a); }<file_sep># this directory demonstrates the interop of go codes # in other languages by utilizing c shared object (the `.so` binary). # flow: # - write the go codes (hello.go) # - compile to shared object (hello.so) # - import the .so file in other languages to call the go code build: go build -o hello.so -buildmode=c-shared hello.go run-c: gcc -o hello.bin hello-caller.c ./hello.so ./hello.bin run-node: node hello-caller.js run-python: python hello-caller.py run-ruby: ruby hello-caller.rb <file_sep>SET SERVEROUTPUT ON SET VERIFY OFF /** * Function to calculate age. No return value. */ CREATE OR REPLACE FUNCTION calc_age(birthdate IN STUDENT.S_DOB%TYPE) RETURN NUMBER IS age DECIMAL(4,1); BEGIN age := ROUND(MONTHS_BETWEEN(SYSDATE, birthdate)/12, 1); RETURN(age); END; / /** * Procedure with IN and OUT args */ CREATE OR REPLACE PROCEDURE count_courses_completed(s_id IN STUDENT.STUDENT_ID%TYPE, courses_completed OUT integer) AS BEGIN SELECT count(grade) INTO courses_completed FROM enrollment where student_id = s_id; END; / /** * Procedure to display enrolled courses of given student id. */ CREATE OR REPLACE PROCEDURE display_enrolled_courses(input ENROLLMENT.STUDENT_ID%TYPE) AS -- cursor declaration CURSOR student_cursor IS select en.grade GRADE, cs.course_no COURSE_NO, cs.c_sec_id SECTION from enrollment en join course_section cs on en.c_sec_id = cs.c_sec_id where en.student_id = upper(input); student student_cursor%ROWTYPE; grade varchar2(10); STUDENT_NOT_FOUND_EXCEPTION EXCEPTION; BEGIN DBMS_OUTPUT.PUT_LINE(RPAD('COURSE', 10) || RPAD('SECTION', 10) || RPAD('GRADE', 10)); DBMS_OUTPUT.PUT_LINE('----------------------------------------------'); OPEN student_cursor; LOOP FETCH student_cursor INTO student; -- display descriptive message if no records found IF student_cursor%NOTFOUND AND student_cursor%ROWCOUNT = 0 THEN raise STUDENT_NOT_FOUND_EXCEPTION; END IF; EXIT WHEN student_cursor%NOTFOUND; -- use explicit cursor `employee_cursor` grade := student.GRADE; IF (grade IS NULL) THEN grade := 'INCOMPLETE'; END IF; DBMS_OUTPUT.PUT_LINE(RPAD(student.COURSE_NO, 10) || RPAD(student.SECTION, 10) || RPAD(grade, 10)); END LOOP; CLOSE student_cursor; -- start exception handler EXCEPTION -- handle user-defined exception WHEN STUDENT_NOT_FOUND_EXCEPTION THEN DBMS_OUTPUT.PUT_LINE('Not found: student id "' || input || '" has not enrolled to any courses'); END display_enrolled_courses; / -- ANONYMOUS BLOCK STARTS HERE -- ACCEPT input PROMPT 'Enter student id: ' DECLARE -- cursor declaration CURSOR student_cursor IS select s.STUDENT_ID STUDENT_ID, s.S_FIRST S_FIRST, s.S_LAST S_LAST, s.S_PHONE S_PHONE, s.S_DOB S_DOB, s.S_ADDRESS S_ADDRESS from student s where s.STUDENT_ID = upper('&input'); -- support uppercase and lowercase input student student_cursor%ROWTYPE; -- declare user-defined exception STUDENT_NOT_FOUND_EXCEPTION EXCEPTION; liner varchar2(30) := '----------------------------'; name varchar2(50) := '----------------------------'; rpad_size integer := 17; user_input varchar2(20) := '&input'; courses_completed integer(3); BEGIN OPEN student_cursor; LOOP FETCH student_cursor INTO student; -- display descriptive message if no records found IF student_cursor%NOTFOUND AND student_cursor%ROWCOUNT = 0 THEN raise STUDENT_NOT_FOUND_EXCEPTION; END IF; EXIT WHEN student_cursor%NOTFOUND; -- use explicit cursor `employee_cursor` -- call procedure count_courses_completed(student.STUDENT_ID, courses_completed); -- craft employee info DBMS_OUTPUT.PUT_LINE(liner); DBMS_OUTPUT.PUT_LINE('Student Info'); DBMS_OUTPUT.PUT_LINE(liner); DBMS_OUTPUT.PUT_LINE(RPAD('Student Id.', rpad_size) || ' : ' || student.STUDENT_ID); DBMS_OUTPUT.PUT_LINE(RPAD('Name', rpad_size) || ' : ' || student.S_FIRST || ' ' || student.S_LAST); DBMS_OUTPUT.PUT_LINE(RPAD('Address', rpad_size) || ' : ' || student.S_ADDRESS); DBMS_OUTPUT.PUT_LINE(RPAD('Phone', rpad_size) || ' : ' || student.S_PHONE); DBMS_OUTPUT.PUT_LINE(RPAD('Birthdate', rpad_size) || ' : ' || student.S_DOB); DBMS_OUTPUT.PUT_LINE(RPAD('Age', rpad_size) || ' : ' || calc_age(student.S_DOB) || ' year-old'); DBMS_OUTPUT.PUT_LINE(RPAD('Courses Completed', rpad_size) || ' : ' || courses_completed); END LOOP; CLOSE student_cursor; DBMS_OUTPUT.NEW_LINE; DBMS_OUTPUT.NEW_LINE; DBMS_OUTPUT.PUT_LINE('####### ENROLLMENT DETAIL #######'); DBMS_OUTPUT.NEW_LINE; DBMS_OUTPUT.NEW_LINE; display_enrolled_courses(student.STUDENT_ID); -- start exception handler EXCEPTION -- handle user-defined exception WHEN STUDENT_NOT_FOUND_EXCEPTION THEN DBMS_OUTPUT.PUT_LINE('Not found: student with student number "' || user_input || '" does not exist.'); END; / -- END OF ANONYMOUS BLOCK <file_sep>> Fri, 27 Apr 2018 at 5:48:07 MYT ### Lesson 1: Introduction and Efficiency 1. common dimension to think in efficiency: time and space, ie. how long it takes for the program to finish and how much storage it needs 2. efficiency of code is described with big O notation: `O(n)` (in linear time) 3. example of big o notations: - `O(log(n))` - `O(1)` (aka `(On + 1)`) - `O(n+1)` - etc. 4. the `n` in `O(n)` represents the length of an input to your function 5. when we talk about efficiency, we often talk about the worst case scenario. for example, if we were talking about the best case scenario in alphabet, then we'll take `1` as best scenario (1 is minimum letter in alphabet) and `26` as the worst case scenario (26 is total number of alphabet) 6. average case means the average of best and worst case. in point number 5, the average case would be the number between 1 to 26, which is 13. hence, 13 is the average case. 7. best case, worst case and average case may not always approximate nicely. thus, you should specify (ie. to your interviewer) which case you're talking about 8. in interview, space efficiency is usually asked less than time efficiency 9. example of notation for space efficiency: `O(3n)` (ie. a function to copy input string 3 times) 12. big o cheatsheet: http://bigocheatsheet.com 11. sample code to practice on calculating efficiency using big o notation: ```py """input manatees: a list of "manatees", where one manatee is represented by a dictionary a single manatee has properties like "name", "age", et cetera n = the number of elements in "manatees" m = the number of properties per "manatee" (i.e. the number of keys in a manatee dictionary)""" # O(n) aka. linear def example1(manatees): for manatee in manatees: print manatee['name'] # O(1) aka. constant def example2(manatees): print manatees[0]['name'] print manatees[0]['age'] # O(nm): each property multiple by each manatee def example3(manatees): for manatee in manatees: for manatee_property in manatee: print manatee_property, ": ", manatee[manatee_property] # O(n^2) aka. n squared (iterating over `manatess` list twice) def example4(manatees): oldest_manatee = "No manatees here!" for manatee1 in manatees: for manatee2 in manatees: if manatee1['age'] < manatee2['age']: oldest_manatee = manatee2['name'] else: oldest_manatee = manatee1['name'] print oldest_manatee ``` <file_sep>--- title: "Fabulosly Kill (fkill) Process by Port Number" date: 2018-03-26T12:49:55+08:00 tags: ["devops"] draft: true hideToc: true --- ![fkill logo](/images/bettercap/fkill-logo.jpg#featured) `TODO: write content` https://www.npmjs.com/package/fkill-cli <blockquote class="twitter-tweet" data-lang="en"><p lang="en" dir="ltr">You can now search and kill processes by port number with the latest `fkill-cli` version, thanks to <a href="https://twitter.com/kevvayo?ref_src=twsrc%5Etfw">@kevvayo</a>. <a href="https://t.co/yzVkFWoh2c">https://t.co/yzVkFWoh2c</a> <a href="https://t.co/fzc8I4ZNEF">pic.twitter.com/fzc8I4ZNEF</a></p>&mdash; <NAME> (@sindresorhus) <a href="https://twitter.com/sindresorhus/status/974343649600323584?ref_src=twsrc%5Etfw">March 15, 2018</a></blockquote> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script> <p class="text-center">***</p> *Outline:* 1. interactive search: search by name or port 2. fkill: fabulously kill 3. unix way: - find process by port: `lsof -i:8080` - kill the process: `kill $(lsof -t -i:8080)` (use -t to only get the process id) <file_sep>from typing import NamedTuple # python >= 3.6.0 import time class Person(NamedTuple): name: str age: int gender: str married: bool = False # default value (python >= 3.6.1) # initialize person `eve` with all args eve = Person(name='Eve', age=31, gender='female', married=True) print(type(eve)) print(eve) print() # initialize person `bob` omitting default arg `married` bob = Person(name='Bob', age=21, gender='male') print(type(bob)) print(bob) print() # this will not work: # TypeError: __new__() missing 1 required positional argument: 'gender' try: dan = Person(name='Dan', age=22) except TypeError as e: print('failed to initialize person `dan`:\n', e) <file_sep>#include <iostream> using namespace std; int main(){ int n, m; cout << "Insert value for 'n': "; cin >> n; cout << "Insert value for 'm': "; cin >> m; // declare 2d array of n x n int arr[n][n]; cout << "Size of array is " << n << " x " << n << "\n"; // initiate arrays to 0 for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { arr[i][j] = 0; } } for (int i = 0; i < m; i++) { int u,v; cout << "Insert value for 'u': "; cin >> u; cout << "Insert value for 'v': "; cin >> v; // change the cell cout << "Changing value of cell " << u << ":" << v << "\n"; // dunno why but it doesn't crash when // i input u or v with value greater or equal than n. // it supposed to crash right? -_ arr[u][v] = 1; } cout << "Displaying arrays..\n"; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << arr[i][j] << " "; } cout << endl; } return 0; }<file_sep>package main import ( "bufio" "encoding/json" "fmt" "net/http" "net/url" "os" ) // Using Google prediction API to detect the language of // given words (or sentences) and translate it to english. func main() { s := bufio.NewScanner(os.Stdin) fmt.Print("> ") // create a loop of s.Scan to act as interpreter for s.Scan() { res, err := post(s.Text()) if err != nil { fmt.Println("failed:", err) continue } // predictedLang := res.OutputMulti[0].Label // label, ok := labels[res.OutputLabel] // if !ok { // label = res.OutputLabel // } fmt.Println(res.OutputMulti) fmt.Print("> ") } } func detectLang(t string) string { return "" } func translate(t string, fromLang string, toLang string) string { return "" } // response struct to handle // response from Google Prediction API type response struct { Kind string ID string OutputLabel string OutputMulti []struct { Label string Score string } OutputValue float64 } func post(q string) (*response, error) { v := url.Values{ "model": []string{"Language Detection"}, "Phrase": []string{q}, } const endpoint = "http://try-prediction.appspot.com/predict" res, err := http.PostForm(endpoint, v) if err != nil { return nil, err } defer res.Body.Close() // decode response body to result struct var result response err = json.NewDecoder(res.Body).Decode(&result) if err != nil { return nil, err } return &result, nil } <file_sep>SET SERVEROUTPUT ON -- CREATE TABLE test (test1 CHAR(2)); CREATE OR REPLACE TRIGGER test_var BEFORE INSERT OR UPDATE OR DELETE ON test -- test is table name FOR EACH ROW BEGIN DBMS_OUTPUT.PUT_LINE(':new.test: ' || :new.test1); DBMS_OUTPUT.PUT_LINE(':old.test: ' || :old.test1); END; / <file_sep>package resolvers var PersonType = "Person" var PersonSchema = ` type Person { name: String! age: Int! } // TODO: add fields for filter // input PersonFilter { // } ` + PersonResult var PersonResult = ` type PersonResult implements QueryResult { totalCount: Int! pageInfo: PageInfo! items: [Person]! } ` var PersonQuery = ` person(id: ID!): Person! ` var PersonMutations = ` createPerson(id: ID!): Person! `<file_sep>--- title: "A Night with Kubernetes" date: 2018-03-21T23:13:40+08:00 tags: ["devops", "cloud"] draft: false coverImg: /images/kubernetes_logo-sm.png#featured coverAlt: Kubernetes logo --- <p class="figure-text">Kubernetes Logo.</p> ### What is Kubernetes? Dealing with lot of applications that are containerized (ie. via docker) and installed across regions can cause headache; from restarting containers, deploying to multiple nodes, scaling, etc. Kubernetes is a tool to help us deal with such situation by putting those containers in a _cluster_. <!--more--> ### Kubernetes Cluster, Nodes, Deployments, and Pods Knowing these four terms will help us understand how Kubernetes work. **Cluster** is basically a pool of machines, which at least one of it acts as a cluster master, and the other machines act as worker machines (slaves). As you may've guessed, master machine will manage the operation of its slaves. **Node** is a term used to address a worker machine in a cluster. **Deployments** refer to the applications we want to deploy or have deployed. **Pod**, the smallest unit in Kubernetes, is a group of one or more containers that makes up an application or service. You can think of pod as your logical host, or virtual machine. The overall logical view of a Kubernetes cluster would look like this: ``` ▾ Kubernetes Cluster ▾ Master #1 ▾ Deployment "app1" ▾ Node #1 ▾ Pod "app1-2035384211" nginx redis Pod ... ▾ Deployment "app2" ▾ Node #1 Pod "app2-2035384224" [redacted] Pod ... ▾ Deployment "app3" ▾ Node #1 Pod "app3-2035384277" [redacted] ... ▾ Node #2 Pod "app3-2035384122" [redacted] ▾ Deployment "app-xyz" ... ▾ Master #N ... ``` <p class="figure-text">Figure 1: Logical view of typical Kubernetes cluster</p> As shown in above structure, it's a a Kubernetes cluster with single master. However, we still can add more master (master N). Our master #1 currently contains 3 deployments; `app1`, `app2`, and `app3`. In practice, you'd see those three apps as web server, cache, or your custom application. The `app1` has been deployed to one node, `Node #1`. Each deployment will have a unique suffix in its pod name, just like `app1-2035384211`. Digging deeper into pod `app1-2035384211`, we know that it runs two containers; nginx and redis. For every pod we have in our Kubernetes cluster, we can execute command (bash, etc) in it using `kubectl`. Below command will run bash in nginx container of pod `app1-2035384211`: `kubectl exec -it app1-2035384211 --container nginx -- /bin/bash` Going to deployment `app2`, it shows that pod `app2-2035384224` has been deployed to `Node #1`, which means that at this point, our `Node #1` contains 2 deployments; `app1` and `app2`. Deployment `app3` is a bit different than the previous two deployments because it has been deployed to two nodes (`Node #1` and `Node #2`). In other words, our `app3` has been scaled into two instances, which spread into two nodes. Together with `app3`, our `Node #1` now contains 3 deployments; `app1`, `app2`, and `app3`. Our `Node #2` however, only contains single pod so far, which is `app3-2035384122`. ### Creating Kubernetes Cluster To simulate the structure in figure 1, we'll create a Kubernetes Cluster of three machines. One machine for cluster master, and other two as nodes. Let's name these machines as `vm1`, `vm2`, and `vm3` for this demonstration. Next, creating the cluster is quite straightforward: **1. Install kubernetes dependencies** ``` # taken from # https://zihao.me/post/creating-a-kubernetes-cluster-from-scratch-with-kubeadm/ # 1. prepare new repos apt-get -y install apt-transport-https ca-certificates software-properties-common curl # 2. add docker repo curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add - add-apt-repository \ "deb [arch=amd64] https://download.docker.com/linux/ubuntu \ $(lsb_release -cs) \ stable" # 3. add kubernetes repo curl -fsSL https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key add - add-apt-repository \ "deb https://apt.kubernetes.io/ \ kubernetes-$(lsb_release -cs) \ main" # install dependencies apt-get update && apt-get install -y docker-ce kubelet kubeadm kubernetes-cni ``` If everything went well, the `docker`, `kubectl`, and `kubeadm` commands should be available in your machines. **2. Initialize `vm1` as master** - ssh to `vm1` - run `kubeadm init` The `kubeadm init` command will output something like this: ``` kubeadm join --token token.abc.def {server_ip}:6443 --discovery-token-ca-cert-hash sha256:blabla ``` **3. Make the other machines join the cluster** - ssh to `vm2` - run the `kubeadm join` command from step 2 - install container network interface (CNI[^2]) ``` # using weave CNI for now, but you can try other choices kubectl apply -f https://git.io/weave-kube-1.6 ``` - repeat for `vm3` <p class="text-center">***</p> *The two important parts to create Kubernetes cluster from above steps is that we did `kubeadm init` in `vm1` to make it as cluster master, and then `kubeadm join ...` from other machines to join the cluster.* Now that we've a cluster master and joined the other two machines to our cluster master, we can verify if it's reflected in our list nodes by executing this command in cluster master: `kubectl get nodes` ![kubernetes nodes](/images/kubernetes-nodes.jpg) <p class="figure-text">Figure 2: Displaying Kubernetes nodes</p> > If you forgot to install CNI in step 3, your node status will likely yield `Pending` instead of `Ready` In figure 2, you must have noticed that before we run `kubectl get nodes`, we set an environment variable `KUBECONFIG`. This variable refers to the config file used by `kubectl`, which defaults to `~/.kube/config`. However, we changed it since the we want the `kubectl` to interact with our cluster master, whose config is stored `/etc/kubernetes/admin.conf` (generated when we run `kubeadm init` command). Another approach if we don't want to change the `KUBECONFIG` is to pass a config file to kubectl's `--kubeconfig` arg, as follow: `kubectl get nodes --kubeconfig=/etc/kubernetes/admin.conf` ### Creating Deployment You can create Kubernetes deployment using file or directly passing container's image url. For this demonstration, we'll create a deployment named `app1` which simply is a hello-world-nginx app pulled from public docker hub at `kitematic/hello-world-nginx`. To do so, we just need to execute this command: `kubectl run app1 --image=kitematic/hello-world-nginx --port=80` Above command will create one deployment named `app1` and one pod which name prefix is `app1`. The `--port=80` argument indicates that we want to expose port 80 of the image. To verify if the deployment and pod exist, run this command: ``` kubectl get deployments kubectl get pods ``` ![kubernetes deployments](/images/kubernetes-deployments.jpg) <p class="figure-text">Figure 3: Listing Kubernetes deployments and pods</p> As shown in above image, we've successfully deployed our `app1` and the pods is running in one of our node. To get more detailed info of our `app1-ff7b44c5d-q8rxd` pod (the node where the pod has been deployed, state, IP, restart count, etc.), run this command: `kubectl describe pods app1-ff7b44c5d-q8rxd` ### Exposing Deployments Creating deployments will only create pods and assign it to internal IP of the cluster, which doesn't make the app accessible from outside vm; we can't access app1 from `{ip-of-vm}:{port-of-app1}`. To make the app publicly accessible, we'll need to expose our deployment. For this demonstration, we'll use the `NodePort` type which will bind our deployment port to vm's port: `kubectl expose deployment app1 --type=NodePort --port 80` Once `app1` is exposed, we can verify by checking the list of ports have been bound to our vm (the Kubernetes Services[^3]), using `kubectl get service`: ![kubernetes services](/images/kubernetes-expose-service.jpg) <p class="figure-text">Figure 4: List of Kubernetes Services</p> We can see that port 80 of our `app1` is bound to port `30485` (of our vm1), which means that the `app1` is now publicly accessible from `{ip-of-vm1}:30485`. If the IP of your `vm1` is `172.16.31.10`, then you can access `app1` from `172.16.31.10:30485`. ### Closing That's it! We've explored quite a lot of Kubernetes; the structure, nodes, deployments, and all the way down to make the app accessible from internet. Of course, accessing your app from `172.16.31.10:30485` instead of `172.16.31.10` is not intuitive, which is why, in practice, we'd put another layer to handle it (ie. proxy, load balancer, or ingress[^4]). The next thing that you may want to explore is [Kubernetes Dashboard](https://github.com/kubernetes/dashboard), which enables us to control all Kubernetes things visually; deploying nodes, executing command in pods, deleting deployments, adjusting number of replicas, etc. Lastly, while this post is not meant to be an in-depth notes of Kubernetes, hopefully it gives you a better idea of what Kubernetes is and what is it capable of. Also, they've a very complete documentation, which is awesome! See it here: https://kubernetes.io/docs/home/ _"It turns out to be a long night of exploring Kubernetes"_ 😆 ***Till next. See ya!*** [^1]:https://zihao.me/post/creating-a-kubernetes-cluster-from-scratch-with-kubeadm/ [^2]:https://github.com/containernetworking/cni [^3]:https://kubernetes.io/docs/concepts/services-networking/service/ [^4]:https://kubernetes.io/docs/concepts/services-networking/ingress/ {{< load-photoswipe >}} <file_sep>// this file serve index.html, lib.wasm, and wasm_exec.js files. // in practice, you don't need this server.go file since you // can host the 3 files statically. package main import ( "flag" "log" "net/http" ) var ( listen = flag.String("listen", ":8181", "listen address") dir = flag.String("dir", ".", "directory to serve") ) func main() { flag.Parse() log.Printf("listening on %q...", *listen) log.Fatal(http.ListenAndServe(*listen, http.FileServer(http.Dir(*dir)))) } <file_sep>package main import ( "fmt" "os/exec" "strings" ) func main() { alpr := "docker" exec_cmd(alpr) } // https://stackoverflow.com/questions/20437336/how-to-execute-system-command-in-golang-with-unknown-arguments func exec_cmd(cmd string) { parts := strings.Fields(cmd) head := parts[0] parts = parts[1:] out, err := exec.Command(head, parts...).Output() if err != nil { fmt.Printf("%s", err) } fmt.Printf("%s", out) // wg.Done() // Need to signal to waitgroup that this goroutine is done } <file_sep>#include<iostream> using namespace std; int main(){ char s[4]; int n,x=0; cin>>n; for(;n--;){ cin>>s; if(int(s[1])==43) x++; else x--; } cout<<x; }<file_sep>// naive wrapper of os/exec package yell import ( "bytes" "errors" "fmt" "os/exec" ) func Yell(name string, arg ...string) (bytes.Buffer, error) { var out bytes.Buffer var stderr bytes.Buffer cmd := exec.Command(name, arg...) cmd.Stdout = &out cmd.Stderr = &stderr err := cmd.Run() if err != nil { return bytes.Buffer{}, errors.New(fmt.Sprintf("%s: %s", err.Error(), stderr.String())) } return out, nil } <file_sep>require 'ffi' module Hello extend FFI::Library ffi_lib './hello.so' # function Hello receives no argument (`[]`) # and returns string (`:string`) attach_function :Hello, [], :string end print Hello.Hello() <file_sep>// face detector usage: // // // color for the rect when faces detected // fd, err := NewFaceDetector(cascadeClassifierXmlFile, color.RGBA{0, 0, 255, 0}) // if err != nil { // log.Fatal(err) // } // defer fd.Close() // // fd.Draw(img) // window.IMShow(img) package gocvgo import ( "fmt" "image" "image/color" "log" "gocv.io/x/gocv" ) type FaceDetector struct { XmlFile string RectColor color.RGBA classifier gocv.CascadeClassifier } func NewFaceDetector(xmlFile string, RectColor color.RGBA) (*FaceDetector, error) { // load classifier to recognize faces classifier := gocv.NewCascadeClassifier() if !classifier.Load(xmlFile) { return nil, fmt.Errorf("Error reading cascade file: %v\n", xmlFile) } return &FaceDetector{xmlFile, RectColor, classifier}, nil } // When face presents, draw rectangular with given // color `RectColor` along with the label. func (fd *FaceDetector) Draw(img *gocv.Mat, label string) { // detect faces rects := fd.classifier.DetectMultiScale(*img) if len(rects) > 0 { log.Printf("%s found: %d\n", label, len(rects)) } // draw a rectangle around each face on the original image, // along with text label for _, r := range rects { gocv.Rectangle(img, r, fd.RectColor, 3) size := gocv.GetTextSize(label, gocv.FontHersheyPlain, 1.2, 2) pt := image.Pt(r.Min.X+(r.Min.X/2)-(size.X/2), r.Min.Y-2) gocv.PutText(img, label, pt, gocv.FontHersheyPlain, 1.2, fd.RectColor, 2) } } func (fd *FaceDetector) Close() { fd.classifier.Close() } <file_sep>## Udacity: Intro to Self-driving Car > Sat, 27 Apr 2018 at 2:00:23 MYT Preview link: https://classroom.udacity.com/courses/ud013-preview/lessons/06715629-363d-476c-b286-50909c109a3c/concepts/d8d00d85-38cb-45b8-b4f8-a511b535174e ### Lesson 5 - overall flow of data in self driving car, operating from fastest time (frequent update) to slowest: 1. motion control (updated most frequently) 2. sensor fusion 3. localization and trajectory 4. prediction 5. behavior planning (lowest update rate) - behavior planning get inputs from localization and precition. the output of behavior planning will then be used by trajectory which then passed to motion control (think of loopback) - **finite state machine**: a technique to implement behavior planner - **cost function**: used to make behavior level decision - **semantic segmentation**: the task of assigning meaning to part of an object - semantic segmentation helps us to derive valuable information about every pixel in the image - **scene understanding**: in contrast to object recognition, it attempts to analyze objects in context with respect to the 3D structure of the scene, its layout, and the spatial, functional, and semantic relationships between objects. - **Functional Safety**: reducing risk in electronic systems (ISO 26262) - **waypoints**: ordered set of coordinates that vehicle uses to plan a path around the track - **Carla**: udacity's self-driving car - **ROS framework**: Robot Operating System (ROS) framework, ie. collection of software frameworks for robot software development (hardware abstraction, low-level device control, etc.) <file_sep>package main import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) func do(s string) string { // your code here return s } // put the test case here. // comment this func before // submitting to codeforces func Test(t *testing.T) { a := assert.New(t) a.Equal("yo", do("yo")) } func main() { var s string fmt.Scan(&s) fmt.Println(do(s)) }
92adab7f98dc2e694739558e925dc4a408aa7da8
[ "SQL", "Ruby", "Markdown", "JavaScript", "Makefile", "Python", "PHP", "C", "Go", "C++", "Shell" ]
216
Python
wzulfikar/lab
2ef21c16150a88a15bfb7bf4ef0014fbee262ed3
a5c29d54baa111526032741a7850ebf9457148a3
refs/heads/master
<repo_name>BW-Team-Eagle/FE<file_sep>/README.md # CS Build Week - Team Eagle <file_sep>/frontend/src/components/forms.js import React from 'react'; import { Box, Flex, Button } from 'rebass'; import { H1 } from './headings'; import { Label, Input } from '@rebass/forms'; import { Formik, Form, Field } from 'formik'; const FormField = ({ name, placeholder }) => ( <Field as={Input} sx={{ width: '60%', my: 3, fontSize: 2 }} placeholder={placeholder} name={name} /> ); export const LoginForm = props => ( <Formik initialValues={{ username: '', password: '' }} onSubmit={values => { console.log(values); props.onSubmit(values); }} > <Flex as={Form} flexDirection='column' width='60%' mx='auto' alignItems='center' pb={5} > <H1>Login</H1> <FormField name='username' placeholder='Username' /> <FormField name='password' placeholder='<PASSWORD>' /> <Button type='submit' fontSize={3} color='muted' sx={{ ':hover': { cursor: 'pointer', color: 'white' } }} > Submit </Button> </Flex> </Formik> ); export const RegisterForm = props => ( <Formik initialValues={{ username: '', email: '', password1: '', password2: '' }} onSubmit={values => { console.log(values); props.onSubmit(values); }} > <Flex as={Form} flexDirection='column' width='60%' mx='auto' alignItems='center' pb={5} > <H1>Register</H1> <FormField name='username' placeholder='Username' /> <FormField name='email' placeholder='Email' /> <FormField name='password1' placeholder='Enter <PASSWORD>' /> <FormField name='password2' placeholder='Enter <PASSWORD>' /> <Button type='submit' fontSize={3} color='muted' sx={{ ':hover': { cursor: 'pointer', color: 'white' } }} > Submit </Button> </Flex> </Formik> ); <file_sep>/frontend/src/pages/login.js import React from 'react'; import { Flex } from 'rebass'; import { LoginForm } from '../components/forms'; import axios from 'axios'; import { Redirect } from 'react-router-dom'; const LoginPage = props => { console.log('comp props', props); return ( <Flex sx={{ flexDirection: 'column', justifyContent: 'center', pb: 4, px: 5, width: '100%', minHeight: '100vh' }} > <LoginForm onSubmit={values => { axios .post('http://localhost:8000/api/login/', values) .then(res => { console.log(props); props.history.push('/game'); }) .catch(err => { console.log(err); }); }} /> </Flex> ); }; export default LoginPage; <file_sep>/frontend/src/pages/landing.js import React from 'react'; import { Flex, Box, Button } from 'rebass'; import { Link } from 'react-router-dom'; import { H1 } from '../components/headings'; const LandingButton = ({ to, text }) => ( <Button as={Link} to={to} sx={{ display: 'block', fontSize: 4, bg: 'primary', color: 'muted', mt: 4, ':hover': { color: 'white' } }} > {text} </Button> ); const LandingPage = props => { return ( <Flex sx={{ flexDirection: 'column', justifyContent: 'center', pb: 6, px: 5, width: '100%', minHeight: '100vh' }} > <Box mx='auto'> <H1>Adventure Game</H1> <LandingButton to='/login' text='Login' /> <LandingButton to='/register' text='Register' /> </Box> </Flex> ); }; export default LandingPage; <file_sep>/frontend/src/components/text.js import React from 'react'; import { Text } from 'rebass'; //SIDEBAR export const SidebarItemText = props => ( <Text sx={{ color: 'white', fontFamily: 'heading', letterSpacing: '0.04rem' }} {...props} > {props.children} </Text> ); // MAIN SECTION export const RoomDescription = ({ sx, children }) => ( <Text as='p' sx={{ fontSize: 3, ...sx }} > {children} </Text> ); export const ItemName = ({ children }) => ( <Text sx={{ fontSize: 3, fontWeight: 600 }} > {children} </Text> );
62f376203f89d49442a4cf9730de7b2597387e32
[ "Markdown", "JavaScript" ]
5
Markdown
BW-Team-Eagle/FE
648e362452af2d6e00cc0ec79aaf10993525bc01
8bb4432b6c24cd7541ad5ed46cd5999743907952
refs/heads/master
<repo_name>deadjoker/llsif-cheater<file_sep>/plugins/cheater.py def proxy_mangle_request(req): print req return req <file_sep>/README.md # llsif-cheater It's a proxy server to modify request sent from client to sdo server. It won't change anything except song's result. original project link: https://code.google.com/p/proxpy/
4ebef1b38a1b3af812f5bef3802f14c6942c4955
[ "Markdown", "Python" ]
2
Python
deadjoker/llsif-cheater
99c13f0d2db7d433e68ecc3dee6dcf9bb3259bb7
92b9da89d9775c7ae30b34729b072cf4b93e0d27
refs/heads/master
<file_sep># Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "vibes-bj" s.version = "1.2.3" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["<NAME>", "<NAME>"] s.date = "2011-10-05" s.description = "Forked ahoward/bj because the way the bin/bj before_run method interacts with Main's logger= instance menthod breaks in Ruby 1.8.7" s.email = "<EMAIL>" s.executables = ["bj"] s.extra_rdoc_files = [ "LICENSE", "README", "TODO" ] s.files = [ "HISTORY", "LICENSE", "README", "Rakefile", "TODO", "VERSION", "bin/bj", "gemspec.rb", "init.rb", "install.rb", "lib/bj.rb", "lib/bj/api.rb", "lib/bj/bj.rb", "lib/bj/errors.rb", "lib/bj/joblist.rb", "lib/bj/logger.rb", "lib/bj/runner.rb", "lib/bj/stdext.rb", "lib/bj/table.rb", "lib/bj/util.rb", "plugin/HISTORY", "plugin/README", "plugin/Rakefile", "plugin/init.rb", "plugin/install.rb", "plugin/script/bj", "plugin/tasks/bj_tasks.rake", "plugin/test/bj_test.rb", "plugin/uninstall.rb", "spec/bj.rb", "spec/helper.rb", "spec/rails_root/README", "spec/rails_root/Rakefile", "spec/rails_root/app/controllers/application.rb", "spec/rails_root/app/helpers/application_helper.rb", "spec/rails_root/config/boot.rb", "spec/rails_root/config/database.yml", "spec/rails_root/config/environment.rb", "spec/rails_root/config/environments/development.rb", "spec/rails_root/config/environments/production.rb", "spec/rails_root/config/environments/test.rb", "spec/rails_root/config/initializers/inflections.rb", "spec/rails_root/config/initializers/mime_types.rb", "spec/rails_root/config/initializers/new_rails_defaults.rb", "spec/rails_root/config/routes.rb", "spec/rails_root/db/development.sqlite3", "spec/rails_root/db/migrate/20080909151517_bj_migration0.rb", "spec/rails_root/db/schema.rb", "spec/rails_root/doc/README_FOR_APP", "spec/rails_root/log/development.log", "spec/rails_root/log/production.log", "spec/rails_root/log/server.log", "spec/rails_root/log/test.log", "spec/rails_root/public/404.html", "spec/rails_root/public/422.html", "spec/rails_root/public/500.html", "spec/rails_root/public/dispatch.cgi", "spec/rails_root/public/dispatch.fcgi", "spec/rails_root/public/dispatch.rb", "spec/rails_root/public/favicon.ico", "spec/rails_root/public/images/rails.png", "spec/rails_root/public/index.html", "spec/rails_root/public/javascripts/application.js", "spec/rails_root/public/javascripts/controls.js", "spec/rails_root/public/javascripts/dragdrop.js", "spec/rails_root/public/javascripts/effects.js", "spec/rails_root/public/javascripts/prototype.js", "spec/rails_root/public/robots.txt", "spec/rails_root/script/about", "spec/rails_root/script/bj", "spec/rails_root/script/console", "spec/rails_root/script/dbconsole", "spec/rails_root/script/destroy", "spec/rails_root/script/generate", "spec/rails_root/script/performance/benchmarker", "spec/rails_root/script/performance/profiler", "spec/rails_root/script/performance/request", "spec/rails_root/script/plugin", "spec/rails_root/script/process/inspector", "spec/rails_root/script/process/reaper", "spec/rails_root/script/process/spawner", "spec/rails_root/script/runner", "spec/rails_root/script/server", "spec/rails_root/test/test_helper.rb", "spec/rails_root/vendor/plugins/bj/HISTORY", "spec/rails_root/vendor/plugins/bj/README", "spec/rails_root/vendor/plugins/bj/Rakefile", "spec/rails_root/vendor/plugins/bj/bin/bj", "spec/rails_root/vendor/plugins/bj/init.rb", "spec/rails_root/vendor/plugins/bj/install.rb", "spec/rails_root/vendor/plugins/bj/lib/arrayfields.rb", "spec/rails_root/vendor/plugins/bj/lib/attributes.rb", "spec/rails_root/vendor/plugins/bj/lib/bj.rb", "spec/rails_root/vendor/plugins/bj/lib/bj/api.rb", "spec/rails_root/vendor/plugins/bj/lib/bj/attributes.rb", "spec/rails_root/vendor/plugins/bj/lib/bj/bj.rb", "spec/rails_root/vendor/plugins/bj/lib/bj/errors.rb", "spec/rails_root/vendor/plugins/bj/lib/bj/joblist.rb", "spec/rails_root/vendor/plugins/bj/lib/bj/logger.rb", "spec/rails_root/vendor/plugins/bj/lib/bj/runner.rb", "spec/rails_root/vendor/plugins/bj/lib/bj/stdext.rb", "spec/rails_root/vendor/plugins/bj/lib/bj/table.rb", "spec/rails_root/vendor/plugins/bj/lib/bj/util.rb", "spec/rails_root/vendor/plugins/bj/lib/fattr.rb", "spec/rails_root/vendor/plugins/bj/lib/main.rb", "spec/rails_root/vendor/plugins/bj/lib/main/base.rb", "spec/rails_root/vendor/plugins/bj/lib/main/cast.rb", "spec/rails_root/vendor/plugins/bj/lib/main/factories.rb", "spec/rails_root/vendor/plugins/bj/lib/main/getoptlong.rb", "spec/rails_root/vendor/plugins/bj/lib/main/logger.rb", "spec/rails_root/vendor/plugins/bj/lib/main/mode.rb", "spec/rails_root/vendor/plugins/bj/lib/main/parameter.rb", "spec/rails_root/vendor/plugins/bj/lib/main/softspoken.rb", "spec/rails_root/vendor/plugins/bj/lib/main/stdext.rb", "spec/rails_root/vendor/plugins/bj/lib/main/usage.rb", "spec/rails_root/vendor/plugins/bj/lib/main/util.rb", "spec/rails_root/vendor/plugins/bj/lib/orderedautohash.rb", "spec/rails_root/vendor/plugins/bj/lib/orderedhash.rb", "spec/rails_root/vendor/plugins/bj/lib/systemu.rb", "spec/rails_root/vendor/plugins/bj/script/bj", "spec/rails_root/vendor/plugins/bj/tasks/bj_tasks.rake", "spec/rails_root/vendor/plugins/bj/test/bj_test.rb", "spec/rails_root/vendor/plugins/bj/uninstall.rb", "spec/rails_root/vendor/rails/actionmailer/CHANGELOG", "spec/rails_root/vendor/rails/actionmailer/MIT-LICENSE", "spec/rails_root/vendor/rails/actionmailer/README", "spec/rails_root/vendor/rails/actionmailer/Rakefile", "spec/rails_root/vendor/rails/actionmailer/install.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/adv_attr_accessor.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/base.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/helpers.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/mail_helper.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/part.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/part_container.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/quoting.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/test_case.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/test_helper.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/utils.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/vendor.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/vendor/text-format-0.6.3/text/format.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/address.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/attachments.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/base64.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/compat.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/config.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/core_extensions.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/encode.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/header.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/index.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/interface.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/loader.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mail.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mailbox.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/main.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/mbox.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/net.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/obsolete.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/parser.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/port.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/quoting.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/require_arch.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/scanner.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/scanner_r.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/stringio.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/utils.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/version.rb", "spec/rails_root/vendor/rails/actionmailer/lib/action_mailer/version.rb", "spec/rails_root/vendor/rails/actionmailer/lib/actionmailer.rb", "spec/rails_root/vendor/rails/actionmailer/test/abstract_unit.rb", "spec/rails_root/vendor/rails/actionmailer/test/delivery_method_test.rb", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/first_mailer/share.erb", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/helper_mailer/use_example_helper.erb", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/helper_mailer/use_helper.erb", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/helper_mailer/use_helper_method.erb", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/helper_mailer/use_mail_helper.erb", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/helpers/example_helper.rb", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/path.with.dots/funky_path_mailer/multipart_with_template_path_with_dots.erb", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/raw_email", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/raw_email10", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/raw_email12", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/raw_email13", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/raw_email2", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/raw_email3", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/raw_email4", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/raw_email5", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/raw_email6", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/raw_email7", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/raw_email8", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/raw_email9", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/raw_email_quoted_with_0d0a", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/raw_email_with_invalid_characters_in_content_type", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/raw_email_with_nested_attachment", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/raw_email_with_partially_quoted_subject", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/second_mailer/share.erb", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/templates/signed_up.erb", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/test_mailer/_subtemplate.text.plain.erb", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/test_mailer/custom_templating_extension.text.html.haml", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/test_mailer/custom_templating_extension.text.plain.haml", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.ignored.erb", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.text.html.erb", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.text.plain.erb", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.text.yaml.erb", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/test_mailer/included_subtemplate.text.plain.erb", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/test_mailer/rxml_template.builder", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/test_mailer/rxml_template.rxml", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/test_mailer/signed_up.erb", "spec/rails_root/vendor/rails/actionmailer/test/fixtures/test_mailer/signed_up_with_url.erb", "spec/rails_root/vendor/rails/actionmailer/test/mail_helper_test.rb", "spec/rails_root/vendor/rails/actionmailer/test/mail_render_test.rb", "spec/rails_root/vendor/rails/actionmailer/test/mail_service_test.rb", "spec/rails_root/vendor/rails/actionmailer/test/quoting_test.rb", "spec/rails_root/vendor/rails/actionmailer/test/test_helper_test.rb", "spec/rails_root/vendor/rails/actionmailer/test/tmail_test.rb", "spec/rails_root/vendor/rails/actionmailer/test/url_test.rb", "spec/rails_root/vendor/rails/actionpack/CHANGELOG", "spec/rails_root/vendor/rails/actionpack/MIT-LICENSE", "spec/rails_root/vendor/rails/actionpack/README", "spec/rails_root/vendor/rails/actionpack/RUNNING_UNIT_TESTS", "spec/rails_root/vendor/rails/actionpack/Rakefile", "spec/rails_root/vendor/rails/actionpack/install.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/assertions.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/assertions/dom_assertions.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/assertions/model_assertions.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/assertions/response_assertions.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/assertions/routing_assertions.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/assertions/selector_assertions.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/assertions/tag_assertions.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/base.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/benchmarking.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/caching.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/caching/actions.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/caching/fragments.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/caching/pages.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/caching/sql_cache.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/caching/sweeping.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/cgi_ext.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/cgi_ext/cookie.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/cgi_ext/query_extension.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/cgi_ext/session.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/cgi_ext/stdinput.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/cgi_process.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/components.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/cookies.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/dispatcher.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/filters.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/flash.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/headers.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/helpers.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/http_authentication.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/integration.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/layout.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/mime_responds.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/mime_type.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/mime_types.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/polymorphic_routes.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/record_identifier.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/request.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/request_forgery_protection.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/request_profiler.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/rescue.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/resources.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/response.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/routing.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/routing/builder.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/routing/optimisations.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/routing/recognition_optimisation.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/routing/route.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/routing/route_set.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/routing/routing_ext.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/routing/segments.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/session/active_record_store.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/session/cookie_store.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/session/drb_server.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/session/drb_store.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/session/mem_cache_store.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/session_management.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/status_codes.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/streaming.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/templates/rescues/_request_and_response.erb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/templates/rescues/_trace.erb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/templates/rescues/diagnostics.erb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/templates/rescues/layout.erb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/templates/rescues/missing_template.erb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/templates/rescues/routing_error.erb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/templates/rescues/template_error.erb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/templates/rescues/unknown_action.erb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/test_case.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/test_process.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/url_rewriter.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/vendor/html-scanner/html/document.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/vendor/html-scanner/html/node.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/vendor/html-scanner/html/selector.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/vendor/html-scanner/html/tokenizer.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/vendor/html-scanner/html/version.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_controller/verification.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_pack.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_pack/version.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/base.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/helpers/active_record_helper.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/helpers/asset_tag_helper.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/helpers/atom_feed_helper.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/helpers/benchmark_helper.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/helpers/cache_helper.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/helpers/capture_helper.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/helpers/date_helper.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/helpers/debug_helper.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/helpers/form_helper.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/helpers/form_options_helper.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/helpers/form_tag_helper.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/helpers/javascript_helper.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/helpers/javascripts/controls.js", "spec/rails_root/vendor/rails/actionpack/lib/action_view/helpers/javascripts/dragdrop.js", "spec/rails_root/vendor/rails/actionpack/lib/action_view/helpers/javascripts/effects.js", "spec/rails_root/vendor/rails/actionpack/lib/action_view/helpers/javascripts/prototype.js", "spec/rails_root/vendor/rails/actionpack/lib/action_view/helpers/number_helper.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/helpers/record_identification_helper.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/helpers/record_tag_helper.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/helpers/sanitize_helper.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/helpers/scriptaculous_helper.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/helpers/tag_helper.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/helpers/text_helper.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/helpers/url_helper.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/inline_template.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/partial_template.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/partials.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/template.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/template_error.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/template_finder.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/template_handler.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/template_handlers/builder.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/template_handlers/compilable.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/template_handlers/erb.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/template_handlers/rjs.rb", "spec/rails_root/vendor/rails/actionpack/lib/action_view/test_case.rb", "spec/rails_root/vendor/rails/actionpack/lib/actionpack.rb", "spec/rails_root/vendor/rails/actionpack/test/abstract_unit.rb", "spec/rails_root/vendor/rails/actionpack/test/active_record_unit.rb", "spec/rails_root/vendor/rails/actionpack/test/activerecord/active_record_store_test.rb", "spec/rails_root/vendor/rails/actionpack/test/activerecord/render_partial_with_record_identification_test.rb", "spec/rails_root/vendor/rails/actionpack/test/adv_attr_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/action_pack_assertions_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/addresses_render_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/assert_select_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/base_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/benchmark_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/caching_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/capture_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/cgi_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/components_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/content_type_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/controller_fixtures/app/controllers/admin/user_controller.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/controller_fixtures/app/controllers/user_controller.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/controller_fixtures/vendor/plugins/bad_plugin/lib/plugin_controller.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/cookie_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/custom_handler_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/deprecation/deprecated_base_methods_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/dispatcher_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/fake_controllers.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/fake_models.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/filter_params_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/filters_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/flash_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/header_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/helper_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/html-scanner/document_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/html-scanner/node_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/html-scanner/sanitizer_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/html-scanner/tag_node_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/html-scanner/text_node_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/html-scanner/tokenizer_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/http_authentication_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/integration_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/integration_upload_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/layout_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/mime_responds_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/mime_type_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/new_render_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/polymorphic_routes_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/record_identifier_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/redirect_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/render_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/request_forgery_protection_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/request_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/rescue_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/resources_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/routing_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/selector_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/send_file_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/session/cookie_store_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/session/mem_cache_store_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/session_fixation_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/session_management_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/test_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/url_rewriter_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/verification_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/view_paths_test.rb", "spec/rails_root/vendor/rails/actionpack/test/controller/webservice_test.rb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/addresses/list.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/bad_customers/_bad_customer.html.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/companies.yml", "spec/rails_root/vendor/rails/actionpack/test/fixtures/company.rb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/content_type/render_default_content_types_for_respond_to.rhtml", "spec/rails_root/vendor/rails/actionpack/test/fixtures/content_type/render_default_for_rhtml.rhtml", "spec/rails_root/vendor/rails/actionpack/test/fixtures/content_type/render_default_for_rjs.rjs", "spec/rails_root/vendor/rails/actionpack/test/fixtures/content_type/render_default_for_rxml.rxml", "spec/rails_root/vendor/rails/actionpack/test/fixtures/customers/_customer.html.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/db_definitions/sqlite.sql", "spec/rails_root/vendor/rails/actionpack/test/fixtures/developer.rb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/developers.yml", "spec/rails_root/vendor/rails/actionpack/test/fixtures/developers_projects.yml", "spec/rails_root/vendor/rails/actionpack/test/fixtures/fun/games/hello_world.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/functional_caching/_partial.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/functional_caching/fragment_cached.html.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/functional_caching/html_fragment_cached_with_partial.html.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/functional_caching/js_fragment_cached_with_partial.js.rjs", "spec/rails_root/vendor/rails/actionpack/test/fixtures/good_customers/_good_customer.html.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/helpers/abc_helper.rb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/helpers/fun/games_helper.rb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/helpers/fun/pdf_helper.rb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/layout_tests/alt/hello.rhtml", "spec/rails_root/vendor/rails/actionpack/test/fixtures/layout_tests/layouts/controller_name_space/nested.rhtml", "spec/rails_root/vendor/rails/actionpack/test/fixtures/layout_tests/layouts/item.rhtml", "spec/rails_root/vendor/rails/actionpack/test/fixtures/layout_tests/layouts/layout_test.rhtml", "spec/rails_root/vendor/rails/actionpack/test/fixtures/layout_tests/layouts/multiple_extensions.html.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/layout_tests/layouts/third_party_template_library.mab", "spec/rails_root/vendor/rails/actionpack/test/fixtures/layout_tests/views/hello.rhtml", "spec/rails_root/vendor/rails/actionpack/test/fixtures/layouts/block_with_layout.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/layouts/builder.builder", "spec/rails_root/vendor/rails/actionpack/test/fixtures/layouts/partial_with_layout.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/layouts/standard.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/layouts/talk_from_action.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/layouts/yield.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/mascot.rb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/mascots.yml", "spec/rails_root/vendor/rails/actionpack/test/fixtures/mascots/_mascot.html.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/multipart/binary_file", "spec/rails_root/vendor/rails/actionpack/test/fixtures/multipart/boundary_problem_file", "spec/rails_root/vendor/rails/actionpack/test/fixtures/multipart/bracketed_param", "spec/rails_root/vendor/rails/actionpack/test/fixtures/multipart/large_text_file", "spec/rails_root/vendor/rails/actionpack/test/fixtures/multipart/mixed_files", "spec/rails_root/vendor/rails/actionpack/test/fixtures/multipart/mona_lisa.jpg", "spec/rails_root/vendor/rails/actionpack/test/fixtures/multipart/single_parameter", "spec/rails_root/vendor/rails/actionpack/test/fixtures/multipart/text_file", "spec/rails_root/vendor/rails/actionpack/test/fixtures/override/test/hello_world.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/override2/layouts/test/sub.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/post_test/layouts/post.html.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/post_test/layouts/super_post.iphone.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/post_test/post/index.html.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/post_test/post/index.iphone.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/post_test/super_post/index.html.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/post_test/super_post/index.iphone.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/project.rb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/projects.yml", "spec/rails_root/vendor/rails/actionpack/test/fixtures/public/404.html", "spec/rails_root/vendor/rails/actionpack/test/fixtures/public/500.html", "spec/rails_root/vendor/rails/actionpack/test/fixtures/public/images/rails.png", "spec/rails_root/vendor/rails/actionpack/test/fixtures/public/javascripts/application.js", "spec/rails_root/vendor/rails/actionpack/test/fixtures/public/javascripts/bank.js", "spec/rails_root/vendor/rails/actionpack/test/fixtures/public/javascripts/controls.js", "spec/rails_root/vendor/rails/actionpack/test/fixtures/public/javascripts/dragdrop.js", "spec/rails_root/vendor/rails/actionpack/test/fixtures/public/javascripts/effects.js", "spec/rails_root/vendor/rails/actionpack/test/fixtures/public/javascripts/prototype.js", "spec/rails_root/vendor/rails/actionpack/test/fixtures/public/javascripts/robber.js", "spec/rails_root/vendor/rails/actionpack/test/fixtures/public/javascripts/version.1.0.js", "spec/rails_root/vendor/rails/actionpack/test/fixtures/public/stylesheets/bank.css", "spec/rails_root/vendor/rails/actionpack/test/fixtures/public/stylesheets/robber.css", "spec/rails_root/vendor/rails/actionpack/test/fixtures/public/stylesheets/version.1.0.css", "spec/rails_root/vendor/rails/actionpack/test/fixtures/replies.yml", "spec/rails_root/vendor/rails/actionpack/test/fixtures/reply.rb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/respond_to/all_types_with_layout.html.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/respond_to/all_types_with_layout.js.rjs", "spec/rails_root/vendor/rails/actionpack/test/fixtures/respond_to/custom_constant_handling_without_block.mobile.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/respond_to/iphone_with_html_response_type.html.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/respond_to/iphone_with_html_response_type.iphone.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/respond_to/layouts/missing.html.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/respond_to/layouts/standard.html.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/respond_to/layouts/standard.iphone.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/respond_to/using_defaults.html.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/respond_to/using_defaults.js.rjs", "spec/rails_root/vendor/rails/actionpack/test/fixtures/respond_to/using_defaults.xml.builder", "spec/rails_root/vendor/rails/actionpack/test/fixtures/respond_to/using_defaults_with_type_list.html.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/respond_to/using_defaults_with_type_list.js.rjs", "spec/rails_root/vendor/rails/actionpack/test/fixtures/respond_to/using_defaults_with_type_list.xml.builder", "spec/rails_root/vendor/rails/actionpack/test/fixtures/scope/test/modgreet.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/shared.html.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/symlink_parent/symlinked_layout.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/_customer.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/_customer_counter.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/_customer_greeting.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/_form.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/_hash_greeting.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/_hash_object.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/_hello.builder", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/_labelling_form.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/_layout_for_partial.html.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/_partial.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/_partial.html.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/_partial.js.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/_partial_for_use_in_layout.html.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/_partial_only.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/_person.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/_raise.html.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/action_talk_to_layout.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/block_content_for.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/calling_partial_with_layout.html.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/capturing.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/content_for.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/content_for_concatenated.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/content_for_with_parameter.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/delete_with_js.rjs", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/dot.directory/render_file_with_ivar.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/enum_rjs_test.rjs", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/erb_content_for.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/formatted_html_erb.html.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/formatted_xml_erb.builder", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/formatted_xml_erb.html.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/formatted_xml_erb.xml.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/greeting.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/greeting.js.rjs", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/hello.builder", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/hello_world.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/hello_world_container.builder", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/hello_world_from_rxml.builder", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/hello_world_with_layout_false.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/hello_xml_world.builder", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/list.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/non_erb_block_content_for.builder", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/potential_conflicts.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/render_file_with_ivar.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/render_file_with_locals.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/render_to_string_test.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/update_element_with_capture.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/test/using_layout_around_block.html.erb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/topic.rb", "spec/rails_root/vendor/rails/actionpack/test/fixtures/topics.yml", "spec/rails_root/vendor/rails/actionpack/test/fixtures/topics/_topic.html.erb", "spec/rails_root/vendor/rails/actionpack/test/template/active_record_helper_test.rb", "spec/rails_root/vendor/rails/actionpack/test/template/asset_tag_helper_test.rb", "spec/rails_root/vendor/rails/actionpack/test/template/atom_feed_helper_test.rb", "spec/rails_root/vendor/rails/actionpack/test/template/benchmark_helper_test.rb", "spec/rails_root/vendor/rails/actionpack/test/template/date_helper_test.rb", "spec/rails_root/vendor/rails/actionpack/test/template/erb_util_test.rb", "spec/rails_root/vendor/rails/actionpack/test/template/form_helper_test.rb", "spec/rails_root/vendor/rails/actionpack/test/template/form_options_helper_test.rb", "spec/rails_root/vendor/rails/actionpack/test/template/form_tag_helper_test.rb", "spec/rails_root/vendor/rails/actionpack/test/template/javascript_helper_test.rb", "spec/rails_root/vendor/rails/actionpack/test/template/number_helper_test.rb", "spec/rails_root/vendor/rails/actionpack/test/template/prototype_helper_test.rb", "spec/rails_root/vendor/rails/actionpack/test/template/record_tag_helper_test.rb", "spec/rails_root/vendor/rails/actionpack/test/template/sanitize_helper_test.rb", "spec/rails_root/vendor/rails/actionpack/test/template/scriptaculous_helper_test.rb", "spec/rails_root/vendor/rails/actionpack/test/template/tag_helper_test.rb", "spec/rails_root/vendor/rails/actionpack/test/template/template_finder_test.rb", "spec/rails_root/vendor/rails/actionpack/test/template/template_object_test.rb", "spec/rails_root/vendor/rails/actionpack/test/template/test_test.rb", "spec/rails_root/vendor/rails/actionpack/test/template/text_helper_test.rb", "spec/rails_root/vendor/rails/actionpack/test/template/url_helper_test.rb", "spec/rails_root/vendor/rails/actionpack/test/testing_sandbox.rb", "spec/rails_root/vendor/rails/activerecord/CHANGELOG", "spec/rails_root/vendor/rails/activerecord/README", "spec/rails_root/vendor/rails/activerecord/RUNNING_UNIT_TESTS", "spec/rails_root/vendor/rails/activerecord/Rakefile", "spec/rails_root/vendor/rails/activerecord/examples/associations.png", "spec/rails_root/vendor/rails/activerecord/install.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/aggregations.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/association_preload.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/associations.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/associations/association_collection.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/associations/association_proxy.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/associations/belongs_to_association.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/associations/has_many_association.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/associations/has_many_through_association.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/associations/has_one_association.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/associations/has_one_through_association.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/attribute_methods.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/base.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/calculations.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/callbacks.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/dirty.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/fixtures.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/locking/optimistic.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/locking/pessimistic.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/migration.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/named_scope.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/observer.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/query_cache.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/reflection.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/schema.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/schema_dumper.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/serialization.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/serializers/json_serializer.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/serializers/xml_serializer.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/test_case.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/timestamp.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/transactions.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/validations.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/vendor/db2.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/vendor/mysql.rb", "spec/rails_root/vendor/rails/activerecord/lib/active_record/version.rb", "spec/rails_root/vendor/rails/activerecord/lib/activerecord.rb", "spec/rails_root/vendor/rails/activerecord/test/assets/example.log", "spec/rails_root/vendor/rails/activerecord/test/assets/flowers.jpg", "spec/rails_root/vendor/rails/activerecord/test/cases/aaa_create_tables_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/active_schema_test_mysql.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/active_schema_test_postgresql.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/adapter_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/adapter_test_sqlserver.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/aggregations_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/ar_schema_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/associations/belongs_to_associations_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/associations/callbacks_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/associations/cascaded_eager_loading_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/associations/eager_load_nested_include_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/associations/eager_singularization_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/associations/eager_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/associations/extension_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/associations/has_many_associations_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/associations/has_many_through_associations_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/associations/has_one_associations_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/associations/has_one_through_associations_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/associations/inner_join_association_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/associations/join_model_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/associations_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/attribute_methods_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/base_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/binary_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/calculations_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/callbacks_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/class_inheritable_attributes_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/column_alias_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/connection_test_firebird.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/connection_test_mysql.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/copy_table_test_sqlite.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/datatype_test_postgresql.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/date_time_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/default_test_firebird.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/defaults_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/deprecated_finder_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/dirty_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/finder_respond_to_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/finder_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/fixtures_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/helper.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/inheritance_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/invalid_date_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/json_serialization_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/lifecycle_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/locking_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/method_scoping_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/migration_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/migration_test_firebird.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/mixin_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/modules_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/multiple_db_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/named_scope_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/pk_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/query_cache_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/readonly_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/reflection_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/reserved_word_test_mysql.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/schema_authorization_test_postgresql.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/schema_dumper_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/schema_test_postgresql.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/serialization_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/synonym_test_oracle.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/table_name_test_sqlserver.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/threaded_connections_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/transactions_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/unconnected_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/validations_test.rb", "spec/rails_root/vendor/rails/activerecord/test/cases/xml_serialization_test.rb", "spec/rails_root/vendor/rails/activerecord/test/config.rb", "spec/rails_root/vendor/rails/activerecord/test/connections/native_db2/connection.rb", "spec/rails_root/vendor/rails/activerecord/test/connections/native_firebird/connection.rb", "spec/rails_root/vendor/rails/activerecord/test/connections/native_frontbase/connection.rb", "spec/rails_root/vendor/rails/activerecord/test/connections/native_mysql/connection.rb", "spec/rails_root/vendor/rails/activerecord/test/connections/native_openbase/connection.rb", "spec/rails_root/vendor/rails/activerecord/test/connections/native_oracle/connection.rb", "spec/rails_root/vendor/rails/activerecord/test/connections/native_postgresql/connection.rb", "spec/rails_root/vendor/rails/activerecord/test/connections/native_sqlite/connection.rb", "spec/rails_root/vendor/rails/activerecord/test/connections/native_sqlite3/connection.rb", "spec/rails_root/vendor/rails/activerecord/test/connections/native_sqlite3/in_memory_connection.rb", "spec/rails_root/vendor/rails/activerecord/test/connections/native_sybase/connection.rb", "spec/rails_root/vendor/rails/activerecord/test/fixtures/accounts.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/all/developers.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/all/people.csv", "spec/rails_root/vendor/rails/activerecord/test/fixtures/all/tasks.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/author_addresses.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/author_favorites.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/authors.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/binaries.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/books.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/categories.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/categories/special_categories.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/categories/subsubdir/arbitrary_filename.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/categories_ordered.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/categories_posts.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/categorizations.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/clubs.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/comments.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/companies.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/computers.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/courses.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/customers.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/developers.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/developers_projects.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/edges.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/entrants.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/fk_test_has_fk.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/fk_test_has_pk.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/funny_jokes.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/items.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/jobs.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/legacy_things.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/mateys.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/members.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/memberships.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/minimalistics.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/mixed_case_monkeys.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/mixins.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/movies.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/naked/csv/accounts.csv", "spec/rails_root/vendor/rails/activerecord/test/fixtures/naked/yml/accounts.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/naked/yml/companies.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/naked/yml/courses.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/owners.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/parrots.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/parrots_pirates.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/people.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/pets.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/pirates.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/posts.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/price_estimates.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/projects.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/readers.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/references.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/reserved_words/distinct.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/reserved_words/distincts_selects.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/reserved_words/group.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/reserved_words/select.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/reserved_words/values.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/ships.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/sponsors.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/subscribers.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/subscriptions.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/taggings.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/tags.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/tasks.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/topics.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/treasures.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/vertices.yml", "spec/rails_root/vendor/rails/activerecord/test/fixtures/warehouse-things.yml", "spec/rails_root/vendor/rails/activerecord/test/migrations/decimal/1_give_me_big_numbers.rb", "spec/rails_root/vendor/rails/activerecord/test/migrations/duplicate/1_people_have_last_names.rb", "spec/rails_root/vendor/rails/activerecord/test/migrations/duplicate/2_we_need_reminders.rb", "spec/rails_root/vendor/rails/activerecord/test/migrations/duplicate/3_foo.rb", "spec/rails_root/vendor/rails/activerecord/test/migrations/duplicate/3_innocent_jointable.rb", "spec/rails_root/vendor/rails/activerecord/test/migrations/duplicate_names/20080507052938_chunky.rb", "spec/rails_root/vendor/rails/activerecord/test/migrations/duplicate_names/20080507053028_chunky.rb", "spec/rails_root/vendor/rails/activerecord/test/migrations/interleaved/pass_1/3_innocent_jointable.rb", "spec/rails_root/vendor/rails/activerecord/test/migrations/interleaved/pass_2/1_people_have_last_names.rb", "spec/rails_root/vendor/rails/activerecord/test/migrations/interleaved/pass_2/3_innocent_jointable.rb", "spec/rails_root/vendor/rails/activerecord/test/migrations/interleaved/pass_3/1_people_have_last_names.rb", "spec/rails_root/vendor/rails/activerecord/test/migrations/interleaved/pass_3/2_i_raise_on_down.rb", "spec/rails_root/vendor/rails/activerecord/test/migrations/interleaved/pass_3/3_innocent_jointable.rb", "spec/rails_root/vendor/rails/activerecord/test/migrations/missing/1000_people_have_middle_names.rb", "spec/rails_root/vendor/rails/activerecord/test/migrations/missing/1_people_have_last_names.rb", "spec/rails_root/vendor/rails/activerecord/test/migrations/missing/3_we_need_reminders.rb", "spec/rails_root/vendor/rails/activerecord/test/migrations/missing/4_innocent_jointable.rb", "spec/rails_root/vendor/rails/activerecord/test/migrations/valid/1_people_have_last_names.rb", "spec/rails_root/vendor/rails/activerecord/test/migrations/valid/2_we_need_reminders.rb", "spec/rails_root/vendor/rails/activerecord/test/migrations/valid/3_innocent_jointable.rb", "spec/rails_root/vendor/rails/activerecord/test/models/author.rb", "spec/rails_root/vendor/rails/activerecord/test/models/auto_id.rb", "spec/rails_root/vendor/rails/activerecord/test/models/binary.rb", "spec/rails_root/vendor/rails/activerecord/test/models/book.rb", "spec/rails_root/vendor/rails/activerecord/test/models/categorization.rb", "spec/rails_root/vendor/rails/activerecord/test/models/category.rb", "spec/rails_root/vendor/rails/activerecord/test/models/citation.rb", "spec/rails_root/vendor/rails/activerecord/test/models/club.rb", "spec/rails_root/vendor/rails/activerecord/test/models/column_name.rb", "spec/rails_root/vendor/rails/activerecord/test/models/comment.rb", "spec/rails_root/vendor/rails/activerecord/test/models/company.rb", "spec/rails_root/vendor/rails/activerecord/test/models/company_in_module.rb", "spec/rails_root/vendor/rails/activerecord/test/models/computer.rb", "spec/rails_root/vendor/rails/activerecord/test/models/contact.rb", "spec/rails_root/vendor/rails/activerecord/test/models/course.rb", "spec/rails_root/vendor/rails/activerecord/test/models/customer.rb", "spec/rails_root/vendor/rails/activerecord/test/models/default.rb", "spec/rails_root/vendor/rails/activerecord/test/models/developer.rb", "spec/rails_root/vendor/rails/activerecord/test/models/edge.rb", "spec/rails_root/vendor/rails/activerecord/test/models/entrant.rb", "spec/rails_root/vendor/rails/activerecord/test/models/guid.rb", "spec/rails_root/vendor/rails/activerecord/test/models/item.rb", "spec/rails_root/vendor/rails/activerecord/test/models/job.rb", "spec/rails_root/vendor/rails/activerecord/test/models/joke.rb", "spec/rails_root/vendor/rails/activerecord/test/models/keyboard.rb", "spec/rails_root/vendor/rails/activerecord/test/models/legacy_thing.rb", "spec/rails_root/vendor/rails/activerecord/test/models/matey.rb", "spec/rails_root/vendor/rails/activerecord/test/models/member.rb", "spec/rails_root/vendor/rails/activerecord/test/models/membership.rb", "spec/rails_root/vendor/rails/activerecord/test/models/minimalistic.rb", "spec/rails_root/vendor/rails/activerecord/test/models/mixed_case_monkey.rb", "spec/rails_root/vendor/rails/activerecord/test/models/movie.rb", "spec/rails_root/vendor/rails/activerecord/test/models/order.rb", "spec/rails_root/vendor/rails/activerecord/test/models/owner.rb", "spec/rails_root/vendor/rails/activerecord/test/models/parrot.rb", "spec/rails_root/vendor/rails/activerecord/test/models/person.rb", "spec/rails_root/vendor/rails/activerecord/test/models/pet.rb", "spec/rails_root/vendor/rails/activerecord/test/models/pirate.rb", "spec/rails_root/vendor/rails/activerecord/test/models/post.rb", "spec/rails_root/vendor/rails/activerecord/test/models/price_estimate.rb", "spec/rails_root/vendor/rails/activerecord/test/models/project.rb", "spec/rails_root/vendor/rails/activerecord/test/models/reader.rb", "spec/rails_root/vendor/rails/activerecord/test/models/reference.rb", "spec/rails_root/vendor/rails/activerecord/test/models/reply.rb", "spec/rails_root/vendor/rails/activerecord/test/models/ship.rb", "spec/rails_root/vendor/rails/activerecord/test/models/sponsor.rb", "spec/rails_root/vendor/rails/activerecord/test/models/subject.rb", "spec/rails_root/vendor/rails/activerecord/test/models/subscriber.rb", "spec/rails_root/vendor/rails/activerecord/test/models/subscription.rb", "spec/rails_root/vendor/rails/activerecord/test/models/tag.rb", "spec/rails_root/vendor/rails/activerecord/test/models/tagging.rb", "spec/rails_root/vendor/rails/activerecord/test/models/task.rb", "spec/rails_root/vendor/rails/activerecord/test/models/topic.rb", "spec/rails_root/vendor/rails/activerecord/test/models/treasure.rb", "spec/rails_root/vendor/rails/activerecord/test/models/vertex.rb", "spec/rails_root/vendor/rails/activerecord/test/models/warehouse_thing.rb", "spec/rails_root/vendor/rails/activerecord/test/schema/mysql_specific_schema.rb", "spec/rails_root/vendor/rails/activerecord/test/schema/postgresql_specific_schema.rb", "spec/rails_root/vendor/rails/activerecord/test/schema/schema.rb", "spec/rails_root/vendor/rails/activerecord/test/schema/schema2.rb", "spec/rails_root/vendor/rails/activerecord/test/schema/sqlite_specific_schema.rb", "spec/rails_root/vendor/rails/activerecord/test/schema/sqlserver_specific_schema.rb", "spec/rails_root/vendor/rails/activeresource/CHANGELOG", "spec/rails_root/vendor/rails/activeresource/README", "spec/rails_root/vendor/rails/activeresource/Rakefile", "spec/rails_root/vendor/rails/activeresource/lib/active_resource.rb", "spec/rails_root/vendor/rails/activeresource/lib/active_resource/base.rb", "spec/rails_root/vendor/rails/activeresource/lib/active_resource/connection.rb", "spec/rails_root/vendor/rails/activeresource/lib/active_resource/custom_methods.rb", "spec/rails_root/vendor/rails/activeresource/lib/active_resource/formats.rb", "spec/rails_root/vendor/rails/activeresource/lib/active_resource/formats/json_format.rb", "spec/rails_root/vendor/rails/activeresource/lib/active_resource/formats/xml_format.rb", "spec/rails_root/vendor/rails/activeresource/lib/active_resource/http_mock.rb", "spec/rails_root/vendor/rails/activeresource/lib/active_resource/validations.rb", "spec/rails_root/vendor/rails/activeresource/lib/active_resource/version.rb", "spec/rails_root/vendor/rails/activeresource/lib/activeresource.rb", "spec/rails_root/vendor/rails/activeresource/test/abstract_unit.rb", "spec/rails_root/vendor/rails/activeresource/test/authorization_test.rb", "spec/rails_root/vendor/rails/activeresource/test/base/custom_methods_test.rb", "spec/rails_root/vendor/rails/activeresource/test/base/equality_test.rb", "spec/rails_root/vendor/rails/activeresource/test/base/load_test.rb", "spec/rails_root/vendor/rails/activeresource/test/base_errors_test.rb", "spec/rails_root/vendor/rails/activeresource/test/base_test.rb", "spec/rails_root/vendor/rails/activeresource/test/connection_test.rb", "spec/rails_root/vendor/rails/activeresource/test/fixtures/beast.rb", "spec/rails_root/vendor/rails/activeresource/test/fixtures/person.rb", "spec/rails_root/vendor/rails/activeresource/test/fixtures/street_address.rb", "spec/rails_root/vendor/rails/activeresource/test/format_test.rb", "spec/rails_root/vendor/rails/activeresource/test/setter_trap.rb", "spec/rails_root/vendor/rails/activesupport/CHANGELOG", "spec/rails_root/vendor/rails/activesupport/README", "spec/rails_root/vendor/rails/activesupport/lib/active_support.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/base64.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/basic_object.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/buffered_logger.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/cache.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/cache/compressed_mem_cache_store.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/cache/drb_store.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/cache/file_store.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/cache/mem_cache_store.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/cache/memory_store.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/callbacks.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/clean_logger.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/array.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/array/access.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/array/conversions.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/array/extract_options.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/array/grouping.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/array/random_access.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/base64.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/base64/encoding.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/benchmark.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/bigdecimal.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/bigdecimal/conversions.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/blank.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/cgi.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/cgi/escape_skipping_slashes.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/class.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/class/attribute_accessors.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/class/delegating_attributes.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/class/removal.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/date.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/date/behavior.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/date/calculations.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/date/conversions.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/date_time.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/date_time/calculations.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/date_time/conversions.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/duplicable.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/enumerable.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/exception.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/file.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/float.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/float/rounding.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/hash.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/hash/conversions.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/hash/diff.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/hash/except.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/hash/indifferent_access.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/hash/keys.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/hash/reverse_merge.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/hash/slice.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/integer.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/integer/even_odd.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/integer/inflections.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/kernel.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/kernel/agnostics.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/kernel/daemonizing.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/kernel/debugger.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/kernel/reporting.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/kernel/requires.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/load_error.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/logger.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/module.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/module/aliasing.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/module/attr_accessor_with_default.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/module/attr_internal.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/module/attribute_accessors.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/module/delegation.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/module/inclusion.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/module/introspection.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/module/loading.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/name_error.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/numeric.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/numeric/bytes.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/numeric/conversions.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/numeric/time.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/object.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/object/conversions.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/object/extending.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/object/instance_variables.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/object/misc.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/pathname.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/pathname/clean_within.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/proc.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/process.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/process/daemon.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/range.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/range/blockless_step.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/range/conversions.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/range/include_range.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/range/overlaps.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/string.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/string/access.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/string/conversions.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/string/filters.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/string/inflections.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/string/iterators.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/string/starts_ends_with.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/string/unicode.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/string/xchar.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/symbol.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/test.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/test/unit/assertions.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/time.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/time/behavior.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/time/calculations.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/time/conversions.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/core_ext/time/zones.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/dependencies.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/deprecation.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/duration.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/gzip.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/inflections.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/inflector.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/json.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/json/decoding.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/json/encoders/date.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/json/encoders/date_time.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/json/encoders/enumerable.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/json/encoders/false_class.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/json/encoders/hash.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/json/encoders/nil_class.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/json/encoders/numeric.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/json/encoders/object.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/json/encoders/regexp.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/json/encoders/string.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/json/encoders/symbol.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/json/encoders/time.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/json/encoders/true_class.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/json/encoding.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/json/variable.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/multibyte.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/multibyte/chars.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/multibyte/generators/generate_tables.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/multibyte/handlers/passthru_handler.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/multibyte/handlers/utf8_handler.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/multibyte/handlers/utf8_handler_proc.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/option_merger.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/ordered_hash.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/ordered_options.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/test_case.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/testing/default.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/testing/setup_and_teardown.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/time_with_zone.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/values/time_zone.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/values/unicode_tables.dat", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/builder-2.1.2/blankslate.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/builder-2.1.2/builder.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/builder-2.1.2/builder/blankslate.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/builder-2.1.2/builder/css.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/builder-2.1.2/builder/xchar.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/builder-2.1.2/builder/xmlbase.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/builder-2.1.2/builder/xmlevents.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/builder-2.1.2/builder/xmlmarkup.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/memcache-client-1.5.0/memcache.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/data_timezone.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/data_timezone_info.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Africa/Algiers.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Africa/Cairo.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Africa/Casablanca.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Africa/Harare.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Africa/Johannesburg.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Africa/Monrovia.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Africa/Nairobi.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/America/Argentina/Buenos_Aires.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/America/Argentina/San_Juan.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/America/Bogota.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/America/Caracas.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/America/Chicago.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/America/Chihuahua.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/America/Denver.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/America/Godthab.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/America/Guatemala.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/America/Halifax.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/America/Indiana/Indianapolis.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/America/Juneau.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/America/La_Paz.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/America/Lima.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/America/Los_Angeles.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/America/Mazatlan.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/America/Mexico_City.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/America/Monterrey.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/America/New_York.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/America/Phoenix.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/America/Regina.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/America/Santiago.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/America/St_Johns.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/America/Tijuana.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Almaty.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Baghdad.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Baku.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Bangkok.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Chongqing.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Dhaka.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Hong_Kong.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Irkutsk.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Jakarta.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Jerusalem.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Kabul.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Kamchatka.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Karachi.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Katmandu.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Kolkata.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Krasnoyarsk.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Kuala_Lumpur.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Kuwait.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Magadan.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Muscat.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Novosibirsk.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Rangoon.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Riyadh.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Seoul.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Shanghai.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Singapore.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Taipei.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Tashkent.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Tbilisi.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Tehran.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Tokyo.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Ulaanbaatar.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Urumqi.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Vladivostok.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Yakutsk.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Yekaterinburg.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Asia/Yerevan.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Atlantic/Azores.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Atlantic/Cape_Verde.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Atlantic/South_Georgia.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Australia/Adelaide.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Australia/Brisbane.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Australia/Darwin.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Australia/Hobart.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Australia/Melbourne.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Australia/Perth.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Australia/Sydney.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Etc/UTC.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Europe/Amsterdam.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Europe/Athens.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Europe/Belgrade.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Europe/Berlin.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Europe/Bratislava.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Europe/Brussels.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Europe/Bucharest.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Europe/Budapest.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Europe/Copenhagen.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Europe/Dublin.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Europe/Helsinki.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Europe/Istanbul.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Europe/Kiev.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Europe/Lisbon.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Europe/Ljubljana.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Europe/London.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Europe/Madrid.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Europe/Minsk.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Europe/Moscow.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Europe/Paris.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Europe/Prague.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Europe/Riga.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Europe/Rome.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Europe/Sarajevo.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Europe/Skopje.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Europe/Sofia.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Europe/Stockholm.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Europe/Tallinn.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Europe/Vienna.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Europe/Vilnius.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Europe/Warsaw.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Europe/Zagreb.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Pacific/Auckland.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Pacific/Fiji.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Pacific/Guam.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Pacific/Honolulu.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Pacific/Majuro.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Pacific/Midway.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Pacific/Noumea.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Pacific/Pago_Pago.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Pacific/Port_Moresby.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/definitions/Pacific/Tongatapu.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/info_timezone.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/linked_timezone.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/linked_timezone_info.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/offset_rationals.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/time_or_datetime.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/timezone.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/timezone_definition.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/timezone_info.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/timezone_offset_info.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/timezone_period.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/tzinfo-0.3.8/tzinfo/timezone_transition_info.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/vendor/xml-simple-1.0.11/xmlsimple.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/version.rb", "spec/rails_root/vendor/rails/activesupport/lib/active_support/whiny_nil.rb", "spec/rails_root/vendor/rails/activesupport/lib/activesupport.rb", "spec/rails_root/vendor/rails/railties/CHANGELOG", "spec/rails_root/vendor/rails/railties/MIT-LICENSE", "spec/rails_root/vendor/rails/railties/README", "spec/rails_root/vendor/rails/railties/Rakefile", "spec/rails_root/vendor/rails/railties/bin/about", "spec/rails_root/vendor/rails/railties/bin/console", "spec/rails_root/vendor/rails/railties/bin/dbconsole", "spec/rails_root/vendor/rails/railties/bin/destroy", "spec/rails_root/vendor/rails/railties/bin/generate", "spec/rails_root/vendor/rails/railties/bin/performance/benchmarker", "spec/rails_root/vendor/rails/railties/bin/performance/profiler", "spec/rails_root/vendor/rails/railties/bin/performance/request", "spec/rails_root/vendor/rails/railties/bin/plugin", "spec/rails_root/vendor/rails/railties/bin/process/inspector", "spec/rails_root/vendor/rails/railties/bin/process/reaper", "spec/rails_root/vendor/rails/railties/bin/process/spawner", "spec/rails_root/vendor/rails/railties/bin/rails", "spec/rails_root/vendor/rails/railties/bin/runner", "spec/rails_root/vendor/rails/railties/bin/server", "spec/rails_root/vendor/rails/railties/builtin/rails_info/rails/info.rb", "spec/rails_root/vendor/rails/railties/builtin/rails_info/rails/info_controller.rb", "spec/rails_root/vendor/rails/railties/builtin/rails_info/rails/info_helper.rb", "spec/rails_root/vendor/rails/railties/builtin/rails_info/rails_info_controller.rb", "spec/rails_root/vendor/rails/railties/configs/apache.conf", "spec/rails_root/vendor/rails/railties/configs/databases/frontbase.yml", "spec/rails_root/vendor/rails/railties/configs/databases/mysql.yml", "spec/rails_root/vendor/rails/railties/configs/databases/oracle.yml", "spec/rails_root/vendor/rails/railties/configs/databases/postgresql.yml", "spec/rails_root/vendor/rails/railties/configs/databases/sqlite2.yml", "spec/rails_root/vendor/rails/railties/configs/databases/sqlite3.yml", "spec/rails_root/vendor/rails/railties/configs/empty.log", "spec/rails_root/vendor/rails/railties/configs/initializers/inflections.rb", "spec/rails_root/vendor/rails/railties/configs/initializers/mime_types.rb", "spec/rails_root/vendor/rails/railties/configs/initializers/new_rails_defaults.rb", "spec/rails_root/vendor/rails/railties/configs/lighttpd.conf", "spec/rails_root/vendor/rails/railties/configs/routes.rb", "spec/rails_root/vendor/rails/railties/dispatches/dispatch.fcgi", "spec/rails_root/vendor/rails/railties/dispatches/dispatch.rb", "spec/rails_root/vendor/rails/railties/dispatches/gateway.cgi", "spec/rails_root/vendor/rails/railties/doc/README_FOR_APP", "spec/rails_root/vendor/rails/railties/environments/boot.rb", "spec/rails_root/vendor/rails/railties/environments/development.rb", "spec/rails_root/vendor/rails/railties/environments/environment.rb", "spec/rails_root/vendor/rails/railties/environments/production.rb", "spec/rails_root/vendor/rails/railties/environments/test.rb", "spec/rails_root/vendor/rails/railties/fresh_rakefile", "spec/rails_root/vendor/rails/railties/helpers/application.rb", "spec/rails_root/vendor/rails/railties/helpers/application_helper.rb", "spec/rails_root/vendor/rails/railties/helpers/test_helper.rb", "spec/rails_root/vendor/rails/railties/html/404.html", "spec/rails_root/vendor/rails/railties/html/422.html", "spec/rails_root/vendor/rails/railties/html/500.html", "spec/rails_root/vendor/rails/railties/html/favicon.ico", "spec/rails_root/vendor/rails/railties/html/images/rails.png", "spec/rails_root/vendor/rails/railties/html/index.html", "spec/rails_root/vendor/rails/railties/html/javascripts/application.js", "spec/rails_root/vendor/rails/railties/html/javascripts/controls.js", "spec/rails_root/vendor/rails/railties/html/javascripts/dragdrop.js", "spec/rails_root/vendor/rails/railties/html/javascripts/effects.js", "spec/rails_root/vendor/rails/railties/html/javascripts/prototype.js", "spec/rails_root/vendor/rails/railties/html/robots.txt", "spec/rails_root/vendor/rails/railties/lib/code_statistics.rb", "spec/rails_root/vendor/rails/railties/lib/commands.rb", "spec/rails_root/vendor/rails/railties/lib/commands/about.rb", "spec/rails_root/vendor/rails/railties/lib/commands/console.rb", "spec/rails_root/vendor/rails/railties/lib/commands/dbconsole.rb", "spec/rails_root/vendor/rails/railties/lib/commands/destroy.rb", "spec/rails_root/vendor/rails/railties/lib/commands/generate.rb", "spec/rails_root/vendor/rails/railties/lib/commands/ncgi/listener", "spec/rails_root/vendor/rails/railties/lib/commands/ncgi/tracker", "spec/rails_root/vendor/rails/railties/lib/commands/performance/benchmarker.rb", "spec/rails_root/vendor/rails/railties/lib/commands/performance/profiler.rb", "spec/rails_root/vendor/rails/railties/lib/commands/performance/request.rb", "spec/rails_root/vendor/rails/railties/lib/commands/plugin.rb", "spec/rails_root/vendor/rails/railties/lib/commands/process/inspector.rb", "spec/rails_root/vendor/rails/railties/lib/commands/process/reaper.rb", "spec/rails_root/vendor/rails/railties/lib/commands/process/spawner.rb", "spec/rails_root/vendor/rails/railties/lib/commands/process/spinner.rb", "spec/rails_root/vendor/rails/railties/lib/commands/runner.rb", "spec/rails_root/vendor/rails/railties/lib/commands/server.rb", "spec/rails_root/vendor/rails/railties/lib/commands/servers/base.rb", "spec/rails_root/vendor/rails/railties/lib/commands/servers/lighttpd.rb", "spec/rails_root/vendor/rails/railties/lib/commands/servers/mongrel.rb", "spec/rails_root/vendor/rails/railties/lib/commands/servers/new_mongrel.rb", "spec/rails_root/vendor/rails/railties/lib/commands/servers/webrick.rb", "spec/rails_root/vendor/rails/railties/lib/commands/update.rb", "spec/rails_root/vendor/rails/railties/lib/console_app.rb", "spec/rails_root/vendor/rails/railties/lib/console_sandbox.rb", "spec/rails_root/vendor/rails/railties/lib/console_with_helpers.rb", "spec/rails_root/vendor/rails/railties/lib/dispatcher.rb", "spec/rails_root/vendor/rails/railties/lib/fcgi_handler.rb", "spec/rails_root/vendor/rails/railties/lib/initializer.rb", "spec/rails_root/vendor/rails/railties/lib/rails/gem_builder.rb", "spec/rails_root/vendor/rails/railties/lib/rails/gem_dependency.rb", "spec/rails_root/vendor/rails/railties/lib/rails/mongrel_server/commands.rb", "spec/rails_root/vendor/rails/railties/lib/rails/mongrel_server/handler.rb", "spec/rails_root/vendor/rails/railties/lib/rails/plugin.rb", "spec/rails_root/vendor/rails/railties/lib/rails/plugin/loader.rb", "spec/rails_root/vendor/rails/railties/lib/rails/plugin/locator.rb", "spec/rails_root/vendor/rails/railties/lib/rails/version.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/base.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/commands.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generated_attribute.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/applications/app/USAGE", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/applications/app/app_generator.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/controller/USAGE", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/controller/controller_generator.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/controller/templates/controller.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/controller/templates/functional_test.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/controller/templates/helper.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/controller/templates/view.html.erb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/integration_test/USAGE", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/integration_test/integration_test_generator.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/integration_test/templates/integration_test.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/mailer/USAGE", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/mailer/mailer_generator.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/mailer/templates/fixture.erb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/mailer/templates/fixture.rhtml", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/mailer/templates/mailer.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/mailer/templates/unit_test.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/mailer/templates/view.erb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/mailer/templates/view.rhtml", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/migration/USAGE", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/migration/migration_generator.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/migration/templates/migration.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/model/USAGE", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/model/model_generator.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/model/templates/fixtures.yml", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/model/templates/migration.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/model/templates/model.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/model/templates/unit_test.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/observer/USAGE", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/observer/observer_generator.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/observer/templates/observer.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/observer/templates/unit_test.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/plugin/USAGE", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/plugin/plugin_generator.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/plugin/templates/MIT-LICENSE", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/plugin/templates/README", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/plugin/templates/Rakefile", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/plugin/templates/USAGE", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/plugin/templates/generator.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/plugin/templates/init.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/plugin/templates/install.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/plugin/templates/plugin.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/plugin/templates/tasks.rake", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/plugin/templates/uninstall.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/plugin/templates/unit_test.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/resource/USAGE", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/resource/resource_generator.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/resource/templates/controller.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/resource/templates/functional_test.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/resource/templates/helper.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/scaffold/USAGE", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/scaffold/scaffold_generator.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/scaffold/templates/controller.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/scaffold/templates/functional_test.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/scaffold/templates/helper.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/scaffold/templates/layout.html.erb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/scaffold/templates/style.css", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/scaffold/templates/view_edit.html.erb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/scaffold/templates/view_index.html.erb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/scaffold/templates/view_new.html.erb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/scaffold/templates/view_show.html.erb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/session_migration/USAGE", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/session_migration/session_migration_generator.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/generators/components/session_migration/templates/migration.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/lookup.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/manifest.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/options.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/scripts.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/scripts/destroy.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/scripts/generate.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/scripts/update.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/secret_key_generator.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/simple_logger.rb", "spec/rails_root/vendor/rails/railties/lib/rails_generator/spec.rb", "spec/rails_root/vendor/rails/railties/lib/railties_path.rb", "spec/rails_root/vendor/rails/railties/lib/ruby_version_check.rb", "spec/rails_root/vendor/rails/railties/lib/rubyprof_ext.rb", "spec/rails_root/vendor/rails/railties/lib/source_annotation_extractor.rb", "spec/rails_root/vendor/rails/railties/lib/tasks/annotations.rake", "spec/rails_root/vendor/rails/railties/lib/tasks/databases.rake", "spec/rails_root/vendor/rails/railties/lib/tasks/documentation.rake", "spec/rails_root/vendor/rails/railties/lib/tasks/framework.rake", "spec/rails_root/vendor/rails/railties/lib/tasks/gems.rake", "spec/rails_root/vendor/rails/railties/lib/tasks/log.rake", "spec/rails_root/vendor/rails/railties/lib/tasks/misc.rake", "spec/rails_root/vendor/rails/railties/lib/tasks/rails.rb", "spec/rails_root/vendor/rails/railties/lib/tasks/routes.rake", "spec/rails_root/vendor/rails/railties/lib/tasks/statistics.rake", "spec/rails_root/vendor/rails/railties/lib/tasks/testing.rake", "spec/rails_root/vendor/rails/railties/lib/tasks/tmp.rake", "spec/rails_root/vendor/rails/railties/lib/test_help.rb", "spec/rails_root/vendor/rails/railties/lib/webrick_server.rb", "todo.yml" ] s.homepage = "http://github.com/vibes/bj" s.require_paths = ["lib"] s.rubygems_version = "1.8.10" s.summary = "Minor fork of ahoward/bj" if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<main>, [">= 2.6.0"]) s.add_runtime_dependency(%q<systemu>, [">= 1.2.0"]) s.add_runtime_dependency(%q<orderedhash>, [">= 0.0.3"]) else s.add_dependency(%q<main>, [">= 2.6.0"]) s.add_dependency(%q<systemu>, [">= 1.2.0"]) s.add_dependency(%q<orderedhash>, [">= 0.0.3"]) end else s.add_dependency(%q<main>, [">= 2.6.0"]) s.add_dependency(%q<systemu>, [">= 1.2.0"]) s.add_dependency(%q<orderedhash>, [">= 0.0.3"]) end end
e32b6dab414d9ab02cb8d1be7b972a5af1243ddf
[ "Ruby" ]
1
Ruby
vibes/bj
6099145a3936703cfc2549aa93e60256567415ad
3c3b5f682a86f6ade411474269655af873657df8
refs/heads/master
<file_sep>using Design_Patterns_Behavioral_Command_06.Command; using Design_Patterns_Behavioral_Command_06.Command.ConcreteCommands; using Design_Patterns_Behavioral_Command_06.Invoker; using Design_Patterns_Behavioral_Command_06.Receiver; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Behavioral_Command_06 { public class ProgramUI { private IAccount _newAccount; private ICommand _seeBalance, _withdraw, _deposit; private AccountInvoker _invoker; private decimal _clientBalance; public void Run() { Console.WriteLine("Please enter your name:"); var clientName = Console.ReadLine(); Console.Clear(); Console.WriteLine($"{clientName}, What is your initial deposit?"); _clientBalance = decimal.Parse(Console.ReadLine()); Console.WriteLine($"Are you a Gold member? y/n"); var memberResponse = Console.ReadLine(); if (memberResponse == "y" || memberResponse == "Y") _newAccount = new GoldLevelEmployee(); else _newAccount = new Employee(); _seeBalance = new SeeAccountBalance(_newAccount, _clientBalance); _withdraw = new WithdrawFromAccount(_newAccount, _clientBalance); _deposit = new DepositToAccount(_newAccount, _clientBalance); _invoker = new AccountInvoker(_seeBalance, _withdraw, _deposit); Console.WriteLine($"Welcome {clientName} To Account Manager!" + $"\n\nPress any key to continue..."); Console.ReadKey(); var response = true; while (response) { Console.WriteLine($"\nWhat would you like to do?\n\t" + "1. See funds.\n\t" + "2. Deposit funds.\n\t" + "3. Withdraw funds.\n\t" + "4. See Account History\n\t" + "5. Revert action\n\t" + "6. Exit."); var menuResponse = int.Parse(Console.ReadLine()); Console.Clear(); switch (menuResponse) { case 1: _invoker.SeeBalance(); break; case 2: decimal deposit = 0m; Console.WriteLine("How much will you be depositing?"); deposit = decimal.Parse(Console.ReadLine()); _invoker.Deposit(deposit); break; case 3: UIWithdraw(); break; case 4: Console.WriteLine("We apologize. This feature is not yet available."); break; case 5: Console.WriteLine("We apologize. This feature is not yet available."); break; case 6: response = false; break; } } } private void UIWithdraw() { Console.Write("How much will you be withdrawing?\n$"); decimal withdrawl = decimal.Parse(Console.ReadLine()); _invoker.Withdraw(withdrawl); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Creational_Factory_03 { //This is the Product Interface. It determines what properties and methods each Concrete Product will need to express. public interface IPatient { string Name { get; set; } int Age { get; set; } string Gender { get; set; } bool IsDiabetic { get; set; } void TakeMeds(); void TakeInsulin(); void VisitDoctor(); } } <file_sep>using Design_Patterns_Behavioral_Command_06.Command; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Behavioral_Command_06.Invoker { class AccountInvoker { private ICommand _seeBalance, _withdraw, _deposit; public AccountInvoker(ICommand seeBalance, ICommand withdraw, ICommand deposit) { _seeBalance = seeBalance; _withdraw = withdraw; _deposit = deposit; } //Invoker Methods public void SeeBalance() { _seeBalance.Execute(); } public void Withdraw(decimal _amt) { _withdraw.Amount = _amt; _withdraw.Execute(); } public void Deposit(decimal _amt) { _deposit.Amount = _amt; _deposit.Execute(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Behavioral_Command_05.Receiver { public class Motorcycle : IVehicle { public void Brake() { Console.WriteLine("You slow your motorbike."); } public void SpeedUp() { Console.WriteLine("Someone is on your tail. Speed up!"); } public void TurnOff() { Console.WriteLine("You've out run them and can rest. Turn off the bike."); } public void TurnOn() { Console.WriteLine("The game is afoot! Hop on your bike and go!"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Behavioral_Command_03 { public class Ignition { ICommand _turnOnCommand; ICommand _turnOffCommand; public Ignition(ICommand turnedOffCommand, ICommand turnedOnCommand) { this._turnOffCommand = turnedOffCommand; this._turnOnCommand = turnedOnCommand; } public void On() { this._turnOnCommand.Execute(); } public void Off() { this._turnOffCommand.Execute(); } } } <file_sep>using Design_Patterns_Behavioral_Command_06.Receiver; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Behavioral_Command_06.Command.ConcreteCommands { class WithdrawFromAccount : ICommand { private IAccount _account; public decimal Amount { get; set; } public WithdrawFromAccount(IAccount account, decimal amt) { _account = account; Amount = amt; } public WithdrawFromAccount(IAccount account) { _account = account; } public void Execute() { _account.Withdraw(Amount); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Creational_Factory_02 { public interface IAves { void WriteHabitat(string habitat); void Call(string sound); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Creational_Factory_04.ConcreteVehicles { class Truck : IVehicle { public string Name { get; set; } public string Color { get; set; } public DoorNumber DoorNumber { get; set; } public bool HasGas { get; set; } public Truck() { } public Truck(string name, string color, DoorNumber doorNumber, bool hasGas) { Name = name; Color = color; DoorNumber = doorNumber; HasGas = hasGas; } public void Brake() { Console.WriteLine("The truck slows down."); } public void FuelStatus() { if (HasGas) Console.WriteLine("The truck has gas in the tank."); else Console.WriteLine("The tank is empty."); } public void Move() { Console.WriteLine("The truck drives off the road."); } public void Start() { Console.WriteLine("The truck starts up."); } } } <file_sep>using Design_Patterns_Creational_Factory_04.ConcreteVehicles; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Creational_Factory_04 { class ConcreteVehicleFactory : VehicleFactory { public override IVehicle GetVehicle(string userInput, string name, string color, DoorNumber doorNumber, bool hasGas) { switch (userInput) { case "1": return new Car(name, color, doorNumber, hasGas); case "2": return new Boat(name, color, doorNumber, hasGas); case "3": return new Truck(name, color, doorNumber, hasGas); default: throw new ApplicationException("No valid input recieved."); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Creational_Factory_03 { //This is the Factory. It takes in the parameters from the user to give back a new Concrete Product, in this case a patient. //Think of the parameters as being the raw materials that the factory requires to produce. public abstract class NewPatientFactory { public abstract IPatient GetPatient(string name, int age, string gender, bool isDiabetic); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Creational_Factory_04.ConcreteVehicles { class Boat : IVehicle { public string Name { get; set; } public string Color { get; set; } public DoorNumber DoorNumber { get; set; } public bool HasGas { get; set; } public Boat() { } public Boat(string name, string color, DoorNumber doorNumber, bool hasGas) { Name = name; Color = color; DoorNumber = doorNumber; HasGas = hasGas; } public void Brake() { Console.WriteLine("The boat slowly slows down."); } public void FuelStatus() { if (HasGas) Console.WriteLine("The boat has gas in the tank."); else Console.WriteLine("The tank is empty. You take out the oars to paddle."); } public void Move() { Console.WriteLine("The boat zips across the water."); } public void Start() { Console.WriteLine("The boat sputters and starts up."); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Behavioral_Command_04 { class Program { static void Main(string[] args) { IReceiver receiver = new Receiver(); ICommand receiverFirst = new PerformActionOne(receiver); ICommand receiverSecond = new PerformActionTwo(receiver); Invoker invoker = new Invoker(receiverFirst, receiverSecond); var run = true; while (run) { Console.WriteLine("You have a receiver. What do you want to do?\n\t1. Perform First Action\n\t2. Perform Second Action"); var response = int.Parse(Console.ReadLine()); switch (response) { case 1: invoker.ActionOneComplete(); break; case 2: invoker.ActionTwoComplete(); break; default: Console.WriteLine("Please type 1 or 2"); break; } } Console.ReadLine(); } } } <file_sep>using Design_Patterns_Creational_Factory_03.ConcreteProductClasses; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Creational_Factory_03 { //This is the ConcreteCreator. It takes the parameters and methods from the Factory to produce a new Concrete Product. //This of this class as the factory worker that assembles the product. public class NewPatientSignUp : NewPatientFactory { public override IPatient GetPatient(string name, int age, string gender, bool isDiabetic) { if (age < 18) return new PatientTypeOne { Name = name, Age = age, Gender = gender, IsDiabetic = isDiabetic, }; else if (age >= 18 && age <= 65) return new PatientTypeTwo { Name = name, Age = age, Gender = gender, IsDiabetic = isDiabetic, }; else return new PatientTypeThree { Name = name, Age = age, Gender = gender, IsDiabetic = isDiabetic, }; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Creational_Factory_01 { public class Program { /// <summary> /// Demo /// </summary> /// <param name="args"></param> static void Main(string[] args) { VehicleFactory factory = new ConcreteVehicleFactory(); IVehicle scooter = factory.GetVehicle("Scooter"); scooter.Drive(10); IVehicle bike = factory.GetVehicle("Bike"); bike.Drive(20); //Throws Exception //IFactory car = factory.GetVehicle("Car"); //car.Drive(45); Console.ReadKey(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Behavioral_Command_03 { public class Program { static void Main(string[] args) { IIgnitable car = new Car(); ICommand carOn = new TurnIgnitionOn(car); ICommand carOff = new TurnIgnitionOff(car); Ignition ignition = new Ignition(carOff, carOn); var run = true; while (run) { Console.WriteLine("You have a car. What do you want to do?\n\t1. Turn it on\n\t2. Turn it off"); var response = int.Parse(Console.ReadLine()); switch (response) { case 1: ignition.On(); break; case 2: ignition.Off(); break; default: Console.WriteLine("Please type 1 or 2"); break; } } Console.ReadLine(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Behavioral_Command_06.Receiver { public class GoldLevelEmployee : IAccount { private decimal _balance; public GoldLevelEmployee(decimal balance) { AccountBalance = balance; } public GoldLevelEmployee() { } public decimal AccountBalance { get; set; } public void Deposit(decimal amt) { Employee employee = new Employee(_balance); employee.AccountBalance += amt; _balance = employee.AccountBalance; Console.WriteLine($"Beloved asset, you have made a contribution of ${amt} to your future. May you never step on a lego."); } public void SeeBalance(decimal amt) { Employee employee = new Employee(_balance); if (_balance == 0) _balance = amt; employee.AccountBalance = amt; Console.WriteLine($"Esteemed patron, you have ${_balance} in your account. I hope this news brings you peace."); } public void Withdraw(decimal amt) { Employee employee = new Employee(_balance); employee.AccountBalance -= amt; _balance = employee.AccountBalance; Console.WriteLine($"Kind soul, you have withdrawn ${amt} from your funds. Spend it wisely."); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Creational_Factory_02 { public class ConcreteBird : Bird { public override IAves GetAves(string bird) { switch (bird) { case "Chickadee": return new Chickadee(); case "Crow": return new Crow(); case "Cuckoo": return new Cuckoo(); default: throw new ApplicationException("Bird could not be identified"); } } } } <file_sep>using System; namespace Design_Patterns_Creational_Factory_03 { internal class ProgramUI { private NewPatientFactory _newSignUp = new NewPatientSignUp(); private IPatient _newPatient; internal void Run() { _newPatient = _newSignUp.GetPatient(GetPatientName(), GetPatientAge(), GetPatientGender(), GetPatientDiabetesInfo()); _newPatient.TakeMeds(); _newPatient.TakeInsulin(); _newPatient.VisitDoctor(); Console.ReadLine(); } #region Factory Resources //These methods retrieve parameters from the user to package and send to the factory. public string GetPatientName() { Console.Write("Enter patient name:"); var name = Console.ReadLine(); return name; } public int GetPatientAge() { Console.Write("Enter patient age:"); var age = int.Parse(Console.ReadLine()); return age; } public string GetPatientGender() { Console.Write("Enter patient gender (male/female):"); var gender = Console.ReadLine(); return gender; } public bool GetPatientDiabetesInfo() { bool isDiabetic; Console.WriteLine("Is the patient diabetic? y/n"); var response = Console.ReadLine(); if (response == "y" || response == "Y") isDiabetic = true; else isDiabetic = false; return isDiabetic; } #endregion } }<file_sep>using Design_Patterns_Behavioral_Command_05.Command; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Behavioral_Command_05.Invoker { class VehicleInvoker { private ICommand _turnOn, _turnOff, _speedUp, _brake; public VehicleInvoker(ICommand turnOn, ICommand turnOff, ICommand brake, ICommand speedUp) { _turnOn = turnOn; _turnOff = turnOff; _brake = brake; _speedUp = speedUp; } //Invoker Methods public void TurnOn() { _turnOn.Execute(); } public void TurnOff() { _turnOff.Execute(); } public void SpeedUp() { _speedUp.Execute(); } public void Brake() { _brake.Execute(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Behavioral_Command_01 { /* An interface that defines actions that the receiver can perform */ public interface ISwitchable { void PowerOn(); void PowerOff(); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Creational_Factory_01 { /// <summary> /// Product Interface /// </summary> public interface IVehicle { void Drive(int miles); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Behavioral_Command_04 { public class Receiver : IReceiver { public void ActionOne() { Console.WriteLine("Action one is performed."); } public void ActionTwo() { Console.WriteLine("Action two is performed."); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Behavioral_Command_04 { public class Invoker { private readonly ICommand _actionOne; private readonly ICommand _actionTwo; public Invoker(ICommand actionOne, ICommand actionTwo) { _actionOne = actionOne; _actionTwo = actionTwo; } public void ActionOneComplete() { _actionOne.Execute(); } public void ActionTwoComplete() { _actionTwo.Execute(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Behavioral_Command_03 { public class TurnIgnitionOn : ICommand { private IIgnitable _ingnitable; public TurnIgnitionOn(IIgnitable ignitable) { _ingnitable = ignitable; } public void Execute() { _ingnitable.TurnOn(); } } } <file_sep>using Design_Patterns_Behavioral_Command_06.Command; using Design_Patterns_Behavioral_Command_06.Command.ConcreteCommands; using Design_Patterns_Behavioral_Command_06.Invoker; using Design_Patterns_Behavioral_Command_06.Receiver; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Behavioral_Command_06 { class Program { static void Main(string[] args) { ProgramUI program = new ProgramUI(); program.Run(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Behavioral_Command_04 { public interface IReceiver { void ActionOne(); void ActionTwo(); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Creational_Factory_03.ConcreteProductClasses { class PatientTypeOne : IPatient { public string Name { get; set; } public int Age { get; set; } public string Gender { get; set; } public bool IsDiabetic { get; set; } public void TakeInsulin() { if (IsDiabetic) Console.WriteLine("Patient takes insulin."); else Console.WriteLine("Patient does not need insulin."); } public void TakeMeds() { Console.WriteLine("The patient's parent administers their prescribed medication"); } public void VisitDoctor() { Console.WriteLine("The patient visits their pediatritian."); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Creational_Factory_02 { public class Crow : IAves { public void Call(string sound) { Console.WriteLine("Crows make a " + sound + " sound."); } public void WriteHabitat(string habitat) { throw new NotImplementedException(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Behavioral_Command_06.Receiver { public interface IAccount { decimal AccountBalance { get; set; } void SeeBalance(decimal amt); void Withdraw(decimal amt); void Deposit(decimal amt); } } <file_sep>using System; using System.Diagnostics; namespace Design_Patterns_Behavioral_Command_02 { /// <summary> /// Houses all logging methods for various debug outputs. /// </summary> public static class Logging { /// <summary> /// Determines type of output to be generated. /// </summary> internal class StopwatchProxy { private readonly Stopwatch _stopwatch; private static readonly StopwatchProxy _stopwatchProxy = new StopwatchProxy(); private StopwatchProxy() { _stopwatch = new Stopwatch(); } public Stopwatch Stopwatch { get { return _stopwatch; } } public static StopwatchProxy Instance { get { return _stopwatchProxy; } } } public enum OutputType { /// <summary> /// Default output. /// </summary> Default, /// <summary> /// Output includes timestamp prefix. /// </summary> Timestamp } /// <summary> /// Outputs to <see cref="Debug.WriteLine(String)"/>. /// </summary> /// <param name="value">Value to be output to log.</param> /// <param name="outputType">Output type.</param> public static void Log(string value, OutputType outputType = OutputType.Default) { Debug.WriteLine(outputType == OutputType.Timestamp ? $"[{StopwatchProxy.Instance.Stopwatch.Elapsed}] {value}" : value); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Behavioral_Command_06.Receiver { public class Employee : IAccount { private decimal _balance; public Employee(decimal _balance) { AccountBalance = _balance; } public Employee() { } public decimal AccountBalance { get; set; } public void Deposit(decimal amt) { Employee employee = new Employee(_balance); employee.AccountBalance += amt; _balance = employee.AccountBalance; Console.WriteLine($"You deposited ${amt} to your account. You now have ${_balance}."); } public void SeeBalance(decimal amt) { Employee employee = new Employee(_balance); if (_balance == 0) _balance = amt; employee.AccountBalance = amt; Console.WriteLine($"You have ${_balance} in your account."); } public void Withdraw(decimal amt) { Employee employee = new Employee(_balance); employee.AccountBalance -= amt; _balance = employee.AccountBalance; Console.WriteLine($"You withdrew ${amt} from your account. You now have ${_balance}."); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Behavioral_Command_04 { public class PerformActionTwo : ICommand { private IReceiver _receiver; public PerformActionTwo(IReceiver receiver) { _receiver = receiver; } public void Execute() { _receiver.ActionTwo(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Creational_Factory_02 { public class Program { static void Main(string[] args) { Bird bird = new ConcreteBird(); IAves cuckoo = bird.GetAves("Cuckoo"); IAves crow = bird.GetAves("Crow"); IAves chickadee = bird.GetAves("Chickadee"); cuckoo.Call("Cuck-oo"); crow.Call("Caw caw caw"); chickadee.Call("Chicka-dee-dee-dee"); Console.ReadLine(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Behavioral_Command_04 { public class PerformActionOne : ICommand { private IReceiver _receiver; public PerformActionOne(IReceiver receiver) { _receiver = receiver; } public void Execute() { _receiver.ActionOne(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Behavioral_Command_02 { public enum StatisticType { Agility, Charisma, Strength } public interface IStatistic { decimal Value { get; set; } } public class Strength : IStatistic { public decimal Value { get; set; } = 0; } public class Agility : IStatistic { public decimal Value { get; set; } = 0; } public class Charisma : IStatistic { public decimal Value { get; set; } = 0; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Behavioral_Command_03 { public class Car : IIgnitable { public void TurnOff() { Console.WriteLine("The car turns off"); } public void TurnOn() { Console.WriteLine("The car turns on"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Behavioral_Command_01 { /* The Command for turning on the device - ConcreteCommand #2 */ public class OpenSwitchCommand : ICommand { private ISwitchable _switchable; public OpenSwitchCommand(ISwitchable switchable) { _switchable = switchable; } public void Execute() { _switchable.PowerOn(); } } } <file_sep>using System; namespace Design_Patterns_Creational_Factory_04 { internal class ProgramUI { VehicleFactory _factory = new ConcreteVehicleFactory(); IVehicle _vehicle; DoorNumber _doorNumber; internal void Run() { Console.WriteLine("What type of vehicle do you need?\n\n" + "1. Car\n" + "2. Boat\n" + "3. Truck"); var userInput = Console.ReadLine(); _vehicle = _factory.GetVehicle(userInput, GetName(), GetColor(), GetNumberOfDoors(), GetFuelStatus()); _vehicle.Start(); _vehicle.Move(); _vehicle.Brake(); PrintVehicle(); Console.ReadLine(); } public void PrintVehicle() { Console.WriteLine($"Vehicle Name: {_vehicle.Name}\n" + $"Vehicle Color: {_vehicle.Color}\n" + $"Number of Doors: {_vehicle.DoorNumber}\n" + $"Does it have fuel? {_vehicle.HasGas}\n"); } private bool GetFuelStatus() { bool hasGas; Console.WriteLine("Is there fuel in the tank? y/n"); var fuelResponse = Console.ReadLine(); if (fuelResponse == "y" || fuelResponse == "Y") hasGas = true; else hasGas = false; return hasGas; } private DoorNumber GetNumberOfDoors() { Console.WriteLine($"How many doors does the vehicle have?\n\t" + $"1. One\n\t" + $"2. Two\n\t" + $"3. Four\n\t" + $"4. Other\n\t"); var doorResponse = int.Parse(Console.ReadLine()); switch (doorResponse) { case 1: return _doorNumber = DoorNumber.One; case 2: return _doorNumber = DoorNumber.Two; case 3: return _doorNumber = DoorNumber.Four; default: return _doorNumber = DoorNumber.Other; } } public string GetName() { Console.Write("Enter the name of the vehicle: "); var name = Console.ReadLine(); return name; } public string GetColor() { Console.Write("Enter the color of the vehicle: "); var color = Console.ReadLine(); return color; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Behavioral_Command_03 { class TurnIgnitionOff : ICommand { private IIgnitable _ingnitable; public TurnIgnitionOff(IIgnitable ignitable) { _ingnitable = ignitable; } public void Execute() { _ingnitable.TurnOff(); } } } <file_sep>using Design_Patterns_Behavioral_Command_05.Command; using Design_Patterns_Behavioral_Command_05.Command.ConcreteCommands; using Design_Patterns_Behavioral_Command_05.Invoker; using Design_Patterns_Behavioral_Command_05.Receiver; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Behavioral_Command_05 { //Client class Program { static void Main(string[] args) { //Reciever IVehicle car = new Car(); IVehicle motorcycle = new Motorcycle(); //Concrete Commands ICommand turnOnCommand = new TurnOnVehicle(car); ICommand turnOffCommand = new TurnOffVehicle(car); ICommand speedUpCommand = new SpeedUpVehicle(car); ICommand brakeCommand = new BrakeVehicle(car); ICommand turnOnMotorcycle = new TurnOnVehicle(motorcycle); ICommand turnOffMotorcycle = new TurnOffVehicle(motorcycle); ICommand speedUpMotorcycle = new SpeedUpVehicle(motorcycle); ICommand brakeMotorcycle = new BrakeVehicle(motorcycle); //Invoker VehicleInvoker invoker = new VehicleInvoker(turnOnCommand, turnOffCommand, brakeCommand, speedUpCommand); VehicleInvoker motorcycleInvoker = new VehicleInvoker(turnOnMotorcycle, turnOffMotorcycle, brakeMotorcycle, speedUpMotorcycle); invoker.TurnOn(); invoker.SpeedUp(); invoker.Brake(); invoker.TurnOff(); Console.WriteLine(); motorcycleInvoker.TurnOn(); motorcycleInvoker.SpeedUp(); motorcycleInvoker.Brake(); motorcycleInvoker.TurnOff(); Console.ReadLine(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Creational_Factory_04.ConcreteVehicles { class Car : IVehicle { public string Name { get; set; } public string Color { get; set; } public DoorNumber DoorNumber { get; set; } public bool HasGas { get; set; } public Car() { } public Car(string name, string color, DoorNumber doorNumber, bool hasGas) { Name = name; Color = color; DoorNumber = doorNumber; HasGas = hasGas; } public void Brake() { Console.WriteLine("Car is braking"); } public void FuelStatus() { if (HasGas) Console.WriteLine("The car has gas in the tank."); else Console.WriteLine("The tank is empty."); } public void Move() { Console.WriteLine("Car is driving."); } public void Start() { Console.WriteLine("The car starts."); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Design_Patterns_Creational_Factory_02 { public abstract class Bird { public string Sound { get; set; } public string Habitat { get; set; } public abstract IAves GetAves(string bird); } }
e6805bf1f6e1550f238eecbdad7d028afab52434
[ "C#" ]
42
C#
ransfordw/CSharp-Library
de55e15d46232964918540bae428faa841da57ec
4b7c86183dd3d7ae565786df34edcdd81117dcbf
refs/heads/master
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package DataTier; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.LinkedList; /** * * @author Luca */ public class StudentDataAccess implements StudentDataAccessInterface{ private LinkedList <Student> students; private String addout,cout; public StudentDataAccess(){ this.students = new LinkedList<Student>(); try{ loadFromDB(); }catch(Exception e ){ e.printStackTrace(); } } public LinkedList getStudents(){ return students; } private void loadFromDB(){ try{ Class.forName("org.sqlite.JDBC"); Connection connessione = DriverManager.getConnection("jdbc:sqlite:students.db"); Statement stat = connessione.createStatement(); ResultSet result = stat.executeQuery("SELECT * FROM students"); Student add; while (result.next()) { add= new Student(result.getString("name"),result.getString("surname"), result.getString("id"),result.getString("dateofbirth"),result.getString("placeofbirth"), result.getString("gender"),result.getString("age")); this.students.add(add); } result.close(); connessione.close(); } catch ( Exception e ) { e.printStackTrace(); } } public void creaDb(){ try{ Class.forName("org.sqlite.JDBC"); Connection connessione = DriverManager.getConnection("jdbc:sqlite:students.db"); Statement stato = connessione.createStatement(); stato.executeUpdate("CREATE TABLE students (name,surname,id,dateofbirth,placeofbirth,gender,age)"); connessione.close(); cout="Database creato con successo"; } catch ( Exception e ) { e.printStackTrace(); cout=e.getMessage(); } } public void addStudent(String name,String surname,String id,String dateofbirth,String placeofbirth,String gender,String age){ Student newStud = new Student(name,surname,id,dateofbirth,placeofbirth,gender,age); students.add(newStud); try{ Class.forName("org.sqlite.JDBC"); Connection connessione = DriverManager.getConnection("jdbc:sqlite:students.db"); Statement stato = connessione.createStatement(); stato.executeUpdate("INSERT INTO students (name,surname,id,dateofbirth,placeofbirth,gender,age) " + "VALUES ('"+name+"', '"+surname+"', '"+id+"','"+dateofbirth+"','"+placeofbirth+"','"+gender+"','"+age+"')"); connessione.close(); addout="Studente aggiunto con successo al database"; } catch ( Exception e ) { e.printStackTrace(); addout=e.getMessage(); } } public String getCout(){ return this.cout; } public String getAddOut(){ return this.addout; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package DataTier; import java.util.LinkedList; /** * * @author Luca */ public interface StudentDataAccessInterface { public void creaDb(); public void addStudent(String name,String surname,String id,String dateofbirth,String placeofbirth,String gender,String age); public LinkedList getStudents(); public String getCout(); public String getAddOut(); } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package DataTier; /** * * @author Luca */ public class Student { public String name; public String surname; public String id; public String dateofbirth; public String placeofbirth; public String gender; public String age; public Student(String name,String surname,String id,String dateofbirth,String placeofbirth,String gender,String age){ this.name=name; this.surname=surname; this.id=id; this.dateofbirth= dateofbirth; this.placeofbirth= placeofbirth; this.gender=gender; this.age= age; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package BusinessTier; import DataTier.Student; import DataTier.StudentDataAccess; import java.util.LinkedList; /** * * @author Luca */ public class StudentBusinessLogic implements StudentBusinessLogicInterface{ private LinkedList <Student> students; private StudentDataAccess studentDt; public StudentBusinessLogic(){ this.studentDt = new StudentDataAccess(); this.students= studentDt.getStudents(); } public void creaDb(){ studentDt.creaDb(); } public void addStudent(String name,String surname,String id,String dateofbirth,String placeofbirth,String gender,String age){ this.studentDt.addStudent(name,surname,id,dateofbirth,placeofbirth,gender,age); } public String getCout(){ return this.studentDt.getCout(); } public String getAddOut(){ return this.studentDt.getAddOut(); } public String toString(int i){ return "<p>"+this.students.get(i).name+ " - " + this.students.get(i).surname+ " - " + this.students.get(i).id + " - " + this.students.get(i).dateofbirth+ " - " + this.students.get(i).dateofbirth+ " - " + this.students.get(i).gender+ " - " + this.students.get(i).age +"</p>"; } public String toString(){ String out="I dati richiesti sono:"; for(int i=0;i<this.students.size();i++){ out+="<p>"+this.students.get(i).name+ " - " + this.students.get(i).surname+ " - " + this.students.get(i).id + " - " + this.students.get(i).dateofbirth+ " - " + this.students.get(i).dateofbirth+ " - " + this.students.get(i).gender+ " - " + this.students.get(i).age +"</p>"; } return out; } public int searchStudentByName(String name,String surname){ int index = 0; while (index <=this.students.size()){ if(this.students.get(index).name.equals(name) && this.students.get(index).surname.equals(surname)) return index; index++; } index=-1; return index; } public int searchById(String id){ int index = 0; while (index <=this.students.size()){ if(this.students.get(index).id.equals(id)) return index; index++; } index=-1; return index; } public LinkedList searchByPlaceOfBirth(String place){ LinkedList indexList = new LinkedList(); int index = 0; while (index <=this.students.size()){ if(this.students.get(index).placeofbirth.equals(place)) indexList.add(index); index++; } return indexList; } } <file_sep># DatabaseProject Simple project with Java Servlet and SQLite <file_sep>package ViewTier; // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import BusinessTier.StudentBusinessLogic; // Extend HttpServlet class public class AddPage extends HttpServlet { StudentBusinessLogic studentL; // Method to handle GET method request. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ studentL= new StudentBusinessLogic(); studentL.addStudent(request.getParameter("name"), request.getParameter("surname"),request.getParameter("id"), request.getParameter("dateofbirth"), request.getParameter("placeofbirth"), request.getParameter("gender"), request.getParameter("age")); PrintWriter out = response.getWriter(); String title = "Result Adding Page"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n "+ request.getParameter("name") +"</ul>\n" + "<ul>\n "+ request.getParameter("surname") +"</ul>\n" + "<ul>\n "+ request.getParameter("id") +"</ul>\n" + "<ul>\n "+ request.getParameter("dateofbirth") +"</ul>\n" + "<ul>\n "+ request.getParameter("placeofbirth") +"</ul>\n" + "<ul>\n "+ request.getParameter("gender") +"</ul>\n" + "<ul>\n "+ request.getParameter("age") +"</ul>\n" + "<ul>\n "+ studentL.getAddOut()+"</ul>\n" + "<a href=\"index.html\">Back</a></body></html>"); } // Method to handle POST method request. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
a9053b7e4f9183cf296aef13851e2016cd92d13b
[ "Markdown", "Java" ]
6
Java
LucaSarge4/DatabaseProject
f0697b5920d5fbea194e62c898d0ae14cb528200
0167f8dcaae534fda18f47a0929666620492dc5e
refs/heads/master
<repo_name>CianteJones/muddhacks2018<file_sep>/README.md This is our 2018 muddhacks project.<file_sep>/app.py from flask import Flask, request, jsonify from motorshield import Motor app =Flask(__name__) leftm = None ritem = None def initial(): global leftm,ritem leftm = Motor("MOTOR2",1) ritem = Motor("MOTOR1",1) @app.route("/",methods=["GET","POST"]) def index(): if request.args.get("accel") == None: return "Hey" x_accel= float(request.args.get("x_accel")) y_accel= float(request.args.get("y_accel")) z_accel= float(request.args.get("z_accel")) accel= float(request.args.get("accel")) x_mag= float(request.args.get("x_mag")) y_mag= float(request.args.get("y_mag")) z_mag= float(request.args.get("z_mag")) x_rot= float(request.args.get("x_rot")) y_rot= float(request.args.get("y_rot")) z_rot= float(request.args.get("z_rot")) lum= float(request.args.get("lumens")) lat= float(request.args.get("lat")) lon= float(request.args.get("lon")) #150 lumens is the normal lighting if lum < 25: leftm.forward(100) ritem.forward(100) if lum > 100: leftm.stop() ritem.stop() if accel > 2: jsonify({ "face":":O", "color":"yellow" }) if abs(x_mag) > 60 or abs(y_mag) > 60 or abs(z_mag) > 60: testing= { "face" : ":(", "brightness": 100, "color": "yellow" } return jsonify(testing) if abs(x_rot) > 7 or abs(y_rot) > 7 or abs(z_rot) > 7 : testing= { "face" : ":)", "brightness" : 75, "color" : "cyan" } return jsonify(testing) testing = { "face": ":-)", "color":"white" } return jsonify(testing) if __name__ == "__main__": initial() app.debug = True app.run(host="0.0.0.0")
146fa3a3919462b062e8022f9575d43ce87254dc
[ "Markdown", "Python" ]
2
Markdown
CianteJones/muddhacks2018
e1560876ca2b34dc354fb3f6a812b49c5df14957
75a49b857610be611d06dd04319aceaf665e4d60
refs/heads/master
<file_sep><?php $Estado = 0; $Dep = $_POST['centro']; $Tipo = $_POST['Tipo']; $idEmp = $_POST['idEmp']; /*$file = fopen("datos/DepOsup.txt", "w"); if(fwrite($file, $Tipo)){ $Estado++; } fclose($file);*/ $bd1 = new ConexionM(); $bd1->__constructM(); if($Tipo == 9){ $InsertarCP = "UPDATE config SET IDEmpresa = '$idEmp' WHERE IDUser = '".$_SESSION['IDUser']."';"; $_SESSION['IDEmpresa'] = $idEmp; if($bd1->query($InsertarCP)){ $Estado = 2; }else { echo $bd1->errno. ' '.$bd1->error; } }else { $InsertarCP = "UPDATE config SET centro = '$Dep', IDEmpresa = '$idEmp', DoS = '$Tipo' WHERE IDUser = '".$_SESSION['IDUser']."';"; $_SESSION['centro'] = $Dep; $_SESSION['DepOsub'] = $Tipo; $_SESSION['IDEmpresa'] = $idEmp; if($bd1->query($InsertarCP)){ $Estado = 2; }else { echo $bd1->errno. ' '.$bd1->error; } } $bd1->close(); echo $Estado; ?> <file_sep><?php $BDS = constructS(); $codigo = $_POST['codigo']; $consulta = "SELECT TOP(5) L.empresa AS empresa, L.codigo AS codigo, E.nombre + ' ' + E.ap_paterno + ' ' + E.ap_materno AS nombre, D.entra1 AS entra1, D.sale1 AS sale1 FROM Llaves AS L INNER JOIN detalle_horarios AS D ON D.horario = L.horario AND D.empresa = L.empresa INNER JOIN empleados AS E ON L.codigo = E.codigo WHERE L.codigo LIKE '".$codigo."%' AND (D.dia_Semana = 1 AND D.entra1 <> '') AND E.activo = 'S' "; $rs = odbc_exec($BDS, $consulta); while (odbc_fetch_row($rs)) { echo ' <div class="chip" style="cursor: pointer;" onclick="agregartap('.odbc_result($rs,"codigo").', '.odbc_result($rs,"empresa").', \''.odbc_result($rs,"entra1").'\', \''.odbc_result($rs,"sale1").'\')"> '.odbc_result($rs,"nombre").' <i class="close material-icons">close</i> </div> '; } ?> <file_sep><?php $objBDSQL = new ConexionSRV(); $objBDSQL->conectarBD(); $Periodo = $_POST["periodo"]; $Tn = $_POST["TN"]; $codigo = $_POST["codigo"]; $numr = ""; if($Periodo <= 24){ $_fechas = periodo($Periodo); list($fecha1, $fecha2, $fecha3, $fecha4) = explode(',', $_fechas); } if($Periodo > 24 || $Tn == 1){ $_queryFechas = "SELECT CONVERT (VARCHAR (10), inicio, 103) AS 'FECHA1', CONVERT (VARCHAR (10), cierre, 103) AS 'FECHA2' FROM Periodos WHERE tiponom = 1 AND periodo = $Periodo AND ayo_operacion = $ayoA AND empresa = $IDEmpresa ;"; $_resultados = $objBDSQL->consultaBD($_queryFechas); if($_resultados === false) { die(print_r(sqlsrv_errors(), true)); exit(); }else { $_datos = $objBDSQL->obtenResult(); } $fecha1 = $_datos['FECHA1']; $fecha2 = $_datos['FECHA2']; $fecha3 = $_datos['FECHA1']; $fecha4 = $_datos['FECHA2']; $objBDSQL->liberarC(); } if($DepOsub == 1) { $ComSql = "LEFT (Centro, ".$MascaraEm.") = LEFT ('".$centro."', ".$MascaraEm.")"; }else { $ComSql = "Centro = '".$centro."'"; } $fechaSuma = ""; $ff = str_replace('/', '-', $fecha1); $ConsultaConfirm = "SELECT codigo FROM Llaves WHERE codigo = '".$codigo."' AND tiponom = ".$Tn." AND ".$ComSql.""; $objBDSQL->consultaBD($ConsultaConfirm); $codigoConfirm = $objBDSQL->obtenResult(); $objBDSQL->liberarC(); if(empty($codigoConfirm['codigo'])){ echo "El empleado $codigoConfirm no exite con los datos ingresados"; }else { for ($i=0; $i <= 40; $i++) { if($fechaSuma != $fecha2){ $fechaSuma = date("d/m/Y", strtotime($ff." +".$i." day")); $ff2 = str_replace('/', '-', $fechaSuma); $nombre = "fecha".$ff2; if(empty($_POST[$nombre])){ }else { $queryM = "SELECT valor FROM datosanti WHERE codigo = '".$codigo."' AND nombre = 'fecha".$ff2."' AND periodoP = '".$Periodo."' AND tipoN = '".$Tn."' and IDEmpresa = '".$IDEmpresa."' and ".$ComSql.";"; $numr = $objBDSQL->obtenfilas($queryM); if($numr <= 0){ if(strtoupper($_POST[$nombre]) == "PG"){ $Minsert = "INSERT INTO datosanti VALUES ('".$codigo."', 'fecha".$ff2."', '".strtoupper($_POST[$nombre])."', '".$Periodo."', '".$Tn."', '".$IDEmpresa."', '".$centro."', 0, 0, 0);"; $objBDSQL->consultaBD($Minsert); }else { $Minsert = "INSERT INTO datosanti VALUES ('".$codigo."', 'fecha".$ff2."', '".strtoupper($_POST[$nombre])."', '".$Periodo."', '".$Tn."', '".$IDEmpresa."', '".$centro."', 1, 1, 1);"; $objBDSQL->consultaBD($Minsert); } }else{ $Minsert = "UPDATE datosanti SET valor = '".strtoupper($_POST[$nombre])."' WHERE codigo = '".$codigo."' and nombre = 'fecha".$ff2."' and periodoP = '".$Periodo."' and tipoN = '".$Tn."' and IDEmpresa = '".$IDEmpresa."' and Centro = '".$centro."';"; $objBDSQL->consultaBD($Minsert); } } }else { } } if($numr > 0) { echo "1"; } else { echo "2"; } } ?> <file_sep><?php $objBDSQL = new ConexionSRV(); $objBDSQL->conectarBD(); $objBDSQL2 = new ConexionSRV(); $objBDSQL2->conectarBD(); $script = ""; if($DepOsub == 1) { $ComSql = "LEFT (llaves.centro, ".$MascaraEm.") = LEFT ('".$centro."', ".$MascaraEm.")"; $ComSql2 = "LEFT (centro, ".$MascaraEm.") = LEFT ('".$centro."', ".$MascaraEm.")"; }else { $ComSql = "llaves.centro = '".$centro."'"; $ComSql2 = "centro = '".$centro."'"; } $query = " select all (empleados.codigo) AS 'codigo', ltrim (empleados.ap_paterno)+' '+ltrim (empleados.ap_materno)+' '+ltrim (empleados.nombre) AS 'nombre', llaves.ocupacion AS 'ocupacion', tabulador.actividad AS 'actividad', llaves.horario AS 'horario', MAx (convert(varchar(10),empleados.fchantigua,103)) AS 'fechaAnti', max(convert(varchar(10),contratos.fchAlta ,103)) AS 'fechaAlta', max(convert(varchar(10),contratos.fchterm ,103)) AS 'fechaTer', SUM(contratos.dias) AS 'dias' from empleados LEFT join contratos on contratos.empresa = empleados.empresa and contratos.codigo = empleados.codigo INNER JOIN llaves on llaves.empresa = empleados.empresa and llaves.codigo = empleados.codigo INNER JOIN tabulador on tabulador.empresa = llaves.empresa and tabulador.ocupacion = llaves.ocupacion where empleados.activo = 'S' AND llaves.supervisor = '".$supervisor."' AND ".$ComSql." and llaves.empresa = '".$IDEmpresa."' group by empleados.codigo, empleados.ap_paterno, empleados.ap_materno, empleados.nombre, empleados.fchantigua, llaves.ocupacion, tabulador.actividad, llaves.horario "; $numCol = $objBDSQL->obtenfilas($query); if($numCol >= 1){ echo '<form method="post" id="frmContratos"> <input type="hidden" name="Emp9" value="'.$NombreEmpresa.'" /> <input type="hidden" name="NomDep" value="'.$NomDep.'" /> <input type="hidden" name="centro" value="'.$centro.'" /> <input type="hidden" name="TNomina" value="'.$TN.'" /> <table id="tablaContra" class="responsive-table striped highlight centered" style="border: 1px solid #000080;"> <thead> <tr id="CdMas"> <th colspan="10" style="background-color: white; border-top: hidden;"></th> <th colspan="2" style="text-aling: center; background-color: #0091ea;">Contrato</th> </tr> <tr style="background-color: #00b0ff; border-top: 1px solid #000"> <th>Codigo</th> <th>Nombre</th> <th>Ocupación</th> <th>Actividad</th> <th>horario</th> <th>Antigüedad</th> <th>Inicio de Contrato</th> <th>Termino de Contrato</th> <th>Ds A</th> <th class="Line35">Observacion</th> <th class="Line45">SI</th> <th class="Line45">NO</th> </tr> </thead> <tbody> '; $objBDSQL->consultaBD($query); while ( $row = $objBDSQL->obtenResult() ) { echo ' <tr ondblclick="seleccion('.$row["codigo"].')" id="'.$row["codigo"].'"> <td>'.$row["codigo"].'</td> <td style="text-align: left;">'.utf8_encode($row["nombre"]).'</td> <td>'.$row["ocupacion"].'</td> <td>'.$row["actividad"].'</td> <td>'.$row["horario"].'</td> <td>'.$row["fechaAnti"].'</td> <td>'.$row["fechaAlta"].'</td> <td>'.$row["fechaTer"].'</td> <td>'.$row["dias"].'</td>'; $consultaI = "SELECT Observacion, Contrato FROM contrato WHERE IDEmpleado = '".$row["codigo"]."' AND IDEmpresa = '".$IDEmpresa."' AND ".$ComSql2; $valorC = ""; $valorA = ""; $valorB = ""; $objBDSQL2->consultaBD2($consultaI); $valorM = $objBDSQL2->obtenResult2(); if(empty($valorM)){ echo '<td><input type="text" name="'.$row["codigo"].'" id="obser" size="100%"></td> <td><p><input class="with-gap" type="radio" id="A'.$row["codigo"].'" name="NC'.$row["codigo"].'" value="SI"><label for="A'.$row["codigo"].'"></label></p></td> <td ondblclick="quitar'.$row["codigo"].'()"><p><input class="with-gap" type="radio" id="B'.$row["codigo"].'" name="NC'.$row["codigo"].'" value="NO"><label for="B'.$row["codigo"].'"></label></p></td>'; }else { $valorC = ""; $valorA = ""; $valorB = ""; if ($valorM['Observacion'] != ''){ $valorC = $valorM['Observacion']; if($valorM['Contrato'] == "SI"){ echo '<td><input type="text" name="'.$row["codigo"].'" id="obser" size="100%" value="'.$valorC.'"></td> <td><p><input class="with-gap" type="radio" id="A'.$row["codigo"].'" name="NC'.$row["codigo"].'" value="SI" checked><label for="A'.$row["codigo"].'"></label></p></td> <td ondblclick="quitar'.$row["codigo"].'()"><p><input class="with-gap" type="radio" id="B'.$row["codigo"].'" name="NC'.$row["codigo"].'" value="NO"><label for="B'.$row["codigo"].'"></label></p></td> '; } if($valorM['Contrato'] == "NO"){ echo '<td><input type="text" name="'.$row["codigo"].'" id="obser" size="100%" value="'.$valorC.'"></td> <td><p><input class="with-gap" type="radio" id="A'.$row["codigo"].'" name="NC'.$row["codigo"].'" value="SI"><label for="A'.$row["codigo"].'"></label></p></td> <td ondblclick="quitar'.$row["codigo"].'()"><p><input class="with-gap" type="radio" id="B'.$row["codigo"].'" name="NC'.$row["codigo"].'" value="NO" checked><label for="B'.$row["codigo"].'"></label></p></p></td>'; } if($valorM['Contrato'] == "vacio"){ echo '<td><input type="text" name="'.$row["codigo"].'" id="obser" size="100%" value="'.$valorC.'"></td> <td><p><input class="with-gap" type="radio" id="A'.$row["codigo"].'" name="NC'.$row["codigo"].'" value="SI"><label for="A'.$row["codigo"].'"></label></p></td> <td ondblclick="quitar'.$row["codigo"].'()"><p><input class="with-gap" type="radio" id="B'.$row["codigo"].'" name="NC'.$row["codigo"].'" value="NO"><label for="B'.$row["codigo"].'"></label></p></td>'; } }else { $valorC = ""; if($valorM['Contrato'] == "SI"){ echo '<td><input type="text" name="'.$row["codigo"].'" id="obser" size="100%"></td> <td><p><input class="with-gap" type="radio" id="A'.$row["codigo"].'" name="NC'.$row["codigo"].'" value="SI" checked><label for="A'.$row["codigo"].'"></label></p></p></td> <td ondblclick="quitar'.$row["codigo"].'()"><p><input class="with-gap" type="radio" id="B'.$row["codigo"].'" name="NC'.$row["codigo"].'" value="NO"><label for="B'.$row["codigo"].'"></label></p></p></td>'; } if ($valorM['Contrato'] == "NO"){ echo '<td><input type="text" name="'.$row["codigo"].'" id="obser" size="100%"></td> <td><p><input class="with-gap" type="radio" id="A'.$row["codigo"].'" name="NC'.$row["codigo"].'" value="SI"><label for="A'.$row["codigo"].'"></label></p></p></td> <td ondblclick="quitar'.$row["codigo"].'()"><p><input class="with-gap" type="radio" id="B'.$row["codigo"].'" name="NC'.$row["codigo"].'" value="NO" checked><label for="B'.$row["codigo"].'"></label></p></p></td>'; } if($valorM['Contrato'] == "vacio"){ echo '<td><input type="text" name="'.$row["codigo"].'" id="obser" size="100%"></td> <td><p><input class="with-gap" type="radio" id="A'.$row["codigo"].'" name="NC'.$row["codigo"].'" value="SI"><label for="A'.$row["codigo"].'"></label></p></p></td> <td ondblclick="quitar'.$row["codigo"].'()"><p><input class="with-gap" type="radio" id="B'.$row["codigo"].'" name="NC'.$row["codigo"].'" value="NO"><label for="B'.$row["codigo"].'"></label></p></p></td>'; } } } echo '</tr>'; } echo ' </tbody> </table> <input type="hidden" name="Centro" value="'.$centro.'"> </form> <button class="waves-effect waves-light btn" onclick="Gcontratos()" id="btnGuardar">GUARDAR</button> <button class="waves-effect waves-light btn" onclick="EnviarContrato()" id="btnEnviar" >GENERAR</button>'; }else { echo '<div style="width: 100%" class="deep-orange accent-4"><h6 class="center-align" style="padding-top: 5px; padding-bottom: 5px; color: white;">No se encotro resultado !</h6></div>'; } ?> <file_sep> $( function() { $( ".controlgroup" ).controlgroup() $( ".controlgroup-vertical" ).controlgroup({ "direction": "vertical" }); } ); $(document).ready(function(){ //VerRol(); $("form").keypress(function(e){ if(e.which == 13){ return false; } }); $('#pie').css("position", "inherit"); }); // # verificar en tiempo real cada 1seg. /* function notiReal(){ var noti = $.ajax({ url : 'notificaciones.php', dataType : 'text', async : false }).responseText; document.getElementById('noti').innerHTML = noti; } setInterval(notiReal, 1000); */ function Rol(){ var conexion, variables, Dia, Dia2, Mes, Ayo; Dia = $('#Dia').val(); Dia2 = $('#Dia2').val(); Mes = $('#Mes').val(); Ayo = $('#Ayo').val(); if(Dia != "" && Dia2 != "" && Mes != "" && Ayo != ""){ variables = $("#frmRol").serialize(); variables += "&Dia="+Dia+"&Dia2="+Dia2+"&Mes="+Mes+"&Ayo="+Ayo; conexion = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); conexion.onreadystatechange = function() { if(conexion.readyState == 4 && conexion.status == 200){ conexion.responseText = conexion.responseText.replace(/\ufeff/g, ''); if(conexion.responseText == 1){ document.getElementById('textCargado').innerHTML = "ROL ACTUALIZADOS"; setTimeout(function(){ $("#modal1").modal('close'); document.getElementById('textCargado').innerHTML = "Procesando..."; }, 1500); }else { document.getElementById('textCargado').innerHTML = conexion.responseText; setTimeout(function(){ $("#modal1").modal('close'); }, 2000); } }else if(conexion.readyState != 4){ document.getElementById('textCargado').innerHTML = "Procesando..."; $("#modal1").modal('open'); } } conexion.open('POST', 'ajax.php?modo=ActRol', true); conexion.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); conexion.send(variables); }else { if(Dia == ""){ $('#Dia').focus(); }else if(Dia2 == ""){ $('#Dia2').focus(); }else if(Mes == ""){ $('#Mes').focus(); }else { $('#Ayo').focus(); } } } <file_sep><?php ///Periodos administrativos $A = array ("26/12/2017", "10/01/2018", "01/01/2018", "15/01/2018");//1 $B = array ("11/01/2018", "25/01/2018", "16/01/2018", "31/01/2018");//2 $C = array ("26/01/2018", "10/02/2018", "01/02/2018", "15/02/2018");//3 $D = array ("11/02/2018", "25/02/2018", "16/02/2018", "29/02/2018");//4 $E = array ("26/02/2018", "10/03/2018", "01/03/2018", "15/03/2018");//5 $F = array ("11/03/2018", "25/03/2018", "16/03/2018", "31/03/2018");//6 $G = array ("26/03/2018", "10/04/2018", "01/04/2018", "15/04/2018");//7 $H = array ("11/04/2018", "25/04/2018", "16/04/2018", "30/04/2018");//8 $I = array ("26/04/2018", "10/05/2018", "01/05/2018", "15/05/2018");//9 $J = array ("11/05/2018", "25/05/2018", "16/05/2018", "31/05/2018");//10 $K = array ("26/05/2018", "10/06/2018", "01/06/2018", "15/06/2018");//11 $L = array ("11/06/2018", "25/06/2018", "16/06/2018", "30/06/2018");//12 $M = array ("26/06/2018", "10/07/2018", "01/07/2018", "15/07/2018");//13 $N = array ("11/07/2018", "25/07/2018", "16/07/2018", "31/07/2018");//14 $O = array ("26/07/2018", "10/08/2018", "01/08/2018", "15/08/2018");//15 $P = array ("11/08/2018", "25/08/2018", "16/08/2018", "31/08/2018");//16 $Q = array ("26/08/2018", "10/09/2018", "01/09/2018", "15/09/2018");//17 $R = array ("11/09/2018", "25/09/2018", "16/09/2018", "30/09/2018");//18 $S = array ("26/09/2018", "10/10/2018", "01/10/2018", "15/10/2018");//19 $T = array ("11/10/2018", "25/10/2018", "16/10/2018", "31/10/2018");//20 $U = array ("26/10/2018", "10/11/2018", "01/11/2018", "15/11/2018");//21 $V = array ("11/11/2018", "25/11/2018", "16/11/2018", "30/11/2018");//22 $W = array ("26/11/2018", "10/12/2018", "01/12/2018", "15/12/2018");//23 $X = array ("11/12/2018", "25/12/2018", "16/12/2018", "31/12/2018");//24 function periodo($p){ switch ($p) { case 1: $fecha1 = $GLOBALS['A'][0]; $fecha2 = $GLOBALS['A'][1]; $fecha3 = $GLOBALS['A'][2]; $fecha4 = $GLOBALS['A'][3]; break; case 2: $fecha1 = $GLOBALS['B'][0]; $fecha2 = $GLOBALS['B'][1]; $fecha3 = $GLOBALS['B'][2]; $fecha4 = $GLOBALS['B'][3]; break; case 3: $fecha1 = $GLOBALS['C'][0]; $fecha2 = $GLOBALS['C'][1]; $fecha3 = $GLOBALS['C'][2]; $fecha4 = $GLOBALS['C'][3]; break; case 4: $fecha1 = $GLOBALS['D'][0]; $fecha2 = $GLOBALS['D'][1]; $fecha3 = $GLOBALS['D'][2]; $fecha4 = $GLOBALS['D'][3]; break; case 5: $fecha1 = $GLOBALS['E'][0]; $fecha2 = $GLOBALS['E'][1]; $fecha3 = $GLOBALS['E'][2]; $fecha4 = $GLOBALS['E'][3]; break; case 6: $fecha1 = $GLOBALS['F'][0]; $fecha2 = $GLOBALS['F'][1]; $fecha3 = $GLOBALS['F'][2]; $fecha4 = $GLOBALS['F'][3]; break; case 7: $fecha1 = $GLOBALS['G'][0]; $fecha2 = $GLOBALS['G'][1]; $fecha3 = $GLOBALS['G'][2]; $fecha4 = $GLOBALS['G'][3]; break; case 8: $fecha1 = $GLOBALS['H'][0]; $fecha2 = $GLOBALS['H'][1]; $fecha3 = $GLOBALS['H'][2]; $fecha4 = $GLOBALS['H'][3]; break; case 9: $fecha1 = $GLOBALS['I'][0]; $fecha2 = $GLOBALS['I'][1]; $fecha3 = $GLOBALS['I'][2]; $fecha4 = $GLOBALS['I'][3]; break; case 10: $fecha1 = $GLOBALS['J'][0]; $fecha2 = $GLOBALS['J'][1]; $fecha3 = $GLOBALS['J'][2]; $fecha4 = $GLOBALS['J'][3]; break; case 11: $fecha1 = $GLOBALS['K'][0]; $fecha2 = $GLOBALS['K'][1]; $fecha3 = $GLOBALS['K'][2]; $fecha4 = $GLOBALS['K'][3]; break; case 12: $fecha1 = $GLOBALS['L'][0]; $fecha2 = $GLOBALS['L'][1]; $fecha3 = $GLOBALS['L'][2]; $fecha4 = $GLOBALS['L'][3]; break; case 13: $fecha1 = $GLOBALS['M'][0]; $fecha2 = $GLOBALS['M'][1]; $fecha3 = $GLOBALS['M'][2]; $fecha4 = $GLOBALS['M'][3]; break; case 14: $fecha1 = $GLOBALS['N'][0]; $fecha2 = $GLOBALS['N'][1]; $fecha3 = $GLOBALS['N'][2]; $fecha4 = $GLOBALS['N'][3]; break; case 15: $fecha1 = $GLOBALS['O'][0]; $fecha2 = $GLOBALS['O'][1]; $fecha3 = $GLOBALS['O'][2]; $fecha4 = $GLOBALS['O'][3]; break; case 16: $fecha1 = $GLOBALS['P'][0]; $fecha2 = $GLOBALS['P'][1]; $fecha3 = $GLOBALS['P'][2]; $fecha4 = $GLOBALS['P'][3]; break; case 17: $fecha1 = $GLOBALS['Q'][0]; $fecha2 = $GLOBALS['Q'][1]; $fecha3 = $GLOBALS['Q'][2]; $fecha4 = $GLOBALS['Q'][3]; break; case 18: $fecha1 = $GLOBALS['R'][0]; $fecha2 = $GLOBALS['R'][1]; $fecha3 = $GLOBALS['R'][2]; $fecha4 = $GLOBALS['R'][3]; break; case 19: $fecha1 = $GLOBALS['S'][0]; $fecha2 = $GLOBALS['S'][1]; $fecha3 = $GLOBALS['S'][2]; $fecha4 = $GLOBALS['S'][3]; break; case 20: $fecha1 = $GLOBALS['T'][0]; $fecha2 = $GLOBALS['T'][1]; $fecha3 = $GLOBALS['T'][2]; $fecha4 = $GLOBALS['T'][3]; break; case 21: $fecha1 = $GLOBALS['U'][0]; $fecha2 = $GLOBALS['U'][1]; $fecha3 = $GLOBALS['U'][2]; $fecha4 = $GLOBALS['U'][3]; break; case 22: $fecha1 = $GLOBALS['V'][0]; $fecha2 = $GLOBALS['V'][1]; $fecha3 = $GLOBALS['V'][2]; $fecha4 = $GLOBALS['V'][3]; break; case 23: $fecha1 = $GLOBALS['W'][0]; $fecha2 = $GLOBALS['W'][1]; $fecha3 = $GLOBALS['W'][2]; $fecha4 = $GLOBALS['W'][3]; break; case 24: $fecha1 = $GLOBALS['X'][0]; $fecha2 = $GLOBALS['X'][1]; $fecha3 = $GLOBALS['X'][2]; $fecha4 = $GLOBALS['X'][3]; break; } return $fecha1.",".$fecha2.",".$fecha3.",".$fecha4; } ?> <file_sep><?php $objBDSQL = new ConexionSRV(); $objBDSQL->conectarBD(); $BDM = new ConexionM(); $BDM->__constructM(); $codigo = $_POST["codigo"]; $frente = $_POST["frente"]; $fecha = $_POST["fecha"]; $PRio = $_POST["periodo"]; $Ttn = $_POST["tn"]; if($DepOsub == 1){ $ComSql2 = "LEFT (CENTRO, ".$MascaraEm.") = LEFT ('".$centro."', ".$MascaraEm.")"; $ComSql3 = "LEFT (Centro, ".$MascaraEm.") = LEFT ('".$centro."', ".$MascaraEm.")"; }else { $ComSql2 = "CENTRO = '".$centro."'"; $ComSql3 = "Centro = '".$centro."'"; } if($frente == 'F' || $frente == 'f' || empty($frente) || $frente == ' '){ }else { $Fecha0 = date('Y-m-d', strtotime($fecha)); $dias = array('','LUN','MAR','MIE','JUE','VIE','SAB','DOM'); $fechaDias = $dias[date('N', strtotime($Fecha0))]; $RelacionEmpFrente = "SELECT ".$fechaDias." FROM relacionempfrente WHERE Codigo = '$codigo' AND CENTRO = '$centro' AND IDEmpresa = '$IDEmpresa';"; $rsultadoM1 = $BDM->query($RelacionEmpFrente); $consulta = $objBDSQL->consultaBD($RelacionEmpFrente); if($consulta === false){ $errorS = sqlsrv_errors(); var_dump($errorS[0]['message']); exit(); } if(empty($objBDSQL->obtenResult())){ switch ($fechaDias) { case 'LUN': $INSERTRELACION = "INSERT INTO relacionempfrente VALUES ('$codigo', '$frente', '', '', '', '', '', '', '$centro', '$IDEmpresa');"; break; case 'MAR': $INSERTRELACION = "INSERT INTO relacionempfrente VALUES ('$codigo', '', '$frente','','','','','', '$centro', '$IDEmpresa');"; break; case 'MIE': $INSERTRELACION = "INSERT INTO relacionempfrente VALUES ('$codigo', '', '','$frente','','','','', '$centro', '$IDEmpresa');"; break; case 'JUE': $INSERTRELACION = "INSERT INTO relacionempfrente VALUES ('$codigo', '', '','','$frente','','','', '$centro', '$IDEmpresa');"; break; case 'VIE': $INSERTRELACION = "INSERT INTO relacionempfrente VALUES ('$codigo', '', '','','','$frente','','', '$centro', '$IDEmpresa');"; break; case 'SAB': $INSERTRELACION = "INSERT INTO relacionempfrente VALUES ('$codigo', '', '','','','','$frente','', '$centro', '$IDEmpresa');"; break; case 'DOM': $INSERTRELACION = "INSERT INTO relacionempfrente VALUES ('$codigo', '', '','','','','','$frente', '$centro', '$IDEmpresa');"; break; default: # code... break; } $insertar = $objBDSQL->consultaBD($INSERTRELACION); if($insertar === false){ die(print_r(sqlsrv_errors(), true)); exit(); } $objBDSQL->liberarC(); }else { if($frente == '-n' || $frente == '-N'){ $UPDATERELACION = "UPDATE relacionempfrente SET ".$fechaDias." = '' WHERE Codigo = '$codigo' AND CENTRO = '$centro' AND IDEmpresa = '$IDEmpresa';"; }else { $UPDATERELACION = "UPDATE relacionempfrente SET ".$fechaDias." = '$frente' WHERE Codigo = '$codigo' AND CENTRO = '$centro' AND IDEmpresa = '$IDEmpresa';"; } $insertar = $objBDSQL->consultaBD($UPDATERELACION); if($insertar === false){ die(print_r(sqlsrv_errors(), true)); exit(); } $objBDSQL->liberarC(); } } $consultaD = "SELECT valor FROM datos WHERE codigo = '$codigo' AND nombre = '$fecha' AND periodoP = '$PRio' AND tipoN = '$Ttn' AND IDEmpresa = '$IDEmpresa' AND Centro = '$centro';"; echo $consultaD; $consulta = $objBDSQL->consultaBD($consultaD); if($consulta === false){ $errorS = sqlsrv_errors(); var_dump($errorS[0]['message']); exit(); } $row = $objBDSQL->obtenResult(); if(!empty($row)){ echo $row['valor']; if($row['valor'] == "F"){ $consCodigo = "SELECT ID FROM usuarios WHERE User = '".Autoriza1."';"; echo $consCodigo; $RUSER = $BDM->query($consCodigo); $datoUser = $BDM->recorrer($RUSER); $INSERALERTA = "INSERT INTO notificaciones VALUES (NULL, '".$_SESSION['IDUser']."', '$datoUser[0]', 'SE ELIMINO FALTA DE ".$codigo."', '', '0');"; if($BDM->query($INSERALERTA)){ }else { echo $BDM->errno. ' '.$BDM->error; } $consultaAnti = "SELECT valor FROM datosanti WHERE codigo = '$codigo' AND nombre = 'fecha".$fecha."' AND periodoP = '$PRio' AND tipoN = '$Ttn' AND IDEmpresa = '$IDEmpresa' AND Centro = '$centro';"; echo $consultaAnti; $consulta = $objBDSQL->consultaBD($consultaD); $resultados = $objBDSQL->obtenResult(); $objBDSQL->liberarC(); if(empty($resultados)){ $insert = "INSERT INTO datosanti VALUES ('$codigo', 'fecha".$fecha."', '$frente', '$PRio', '$Ttn', '$IDEmpresa', '$centro', 0, 0, 0);"; echo $insert; $consulta = $objBDSQL->consultaBD($insert); if($consulta === false){ die(print_r(sqlsrv_errors(), true)); } $objBDSQL->liberarC(); }else { $update = "UPDATE datosanti SET valor = '$frente' WHERE codigo = '$codigo' AND nombre = 'fecha".$fecha."' AND periodoP = '$PRio' AND tipoN = '$Ttn' AND IDEmpresa = '$IDEmpresa' AND Centro = '$centro';"; echo $update; $consulta = $objBDSQL->consultaBD($update); if($consulta === false){ die(print_r(sqlsrv_errors(), true)); } $objBDSQL->liberarC(); } }else { if(empty($row)){ $insert = "INSERT INTO datos VALUES ('$codigo', '$fecha', '$frente', '$PRio', '$Ttn', '$IDEmpresa', '$centro');"; echo $insert; $consulta = $objBDSQL->consultaBD($insert); if($consulta === false){ die(print_r(sqlsrv_errors(), true)); } $objBDSQL->liberarC(); }else { $update = "UPDATE datos SET valor = '$frente' WHERE codigo = '$codigo' AND nombre = '$fecha' AND periodoP = '$PRio' AND tipoN = '$Ttn' AND IDEmpresa = '$IDEmpresa' AND Centro = '$centro';"; echo $update; $consulta = $objBDSQL->consultaBD($update); if($consulta === false){ die(print_r(sqlsrv_errors(), true)); } $objBDSQL->liberarC(); } } } try { $BDM->close(); $objBDSQL->cerrarBD(); } catch (Exception $e) { echo 'ERROR al cerrar la conexion con SQL SERVER', $e->getMessage(), "\n"; } ?> <file_sep><?php $objBDSQL = new ConexionSRV(); $objBDSQL->conectarBD(); $objBDSQL2 = new ConexionSRV(); $objBDSQL2->conectarBD(); $modo = $_POST['modo']; if($DepOsub == 1) { $ComSql = "LEFT (Llaves.centro, ".$MascaraEm.") = LEFT ('".$centro."', ".$MascaraEm.")"; }else { $ComSql = "Llaves.centro = '".$centro."'"; } $query = " select empleados.codigo, empleados.ap_paterno+' '+empleados.ap_materno+' '+empleados.nombre as Nombre, tabulador.actividad from empleados INNER JOIN Llaves on Llaves.codigo = empleados.codigo INNER JOIN tabulador on tabulador.ocupacion = Llaves.ocupacion and tabulador.empresa = Llaves.empresa where ".$ComSql." AND Llaves.empresa = '".$IDEmpresa."' and empleados.activo = 'S' order by ap_paterno, ap_materno, nombre "; $objBDSQL->consultaBD($query); if($modo == "G"){ while($row = $objBDSQL->obtenResult()){ $nombreA = $row["codigo"]; if(empty($_POST[$nombreA])){ $Minsert = "INSERT INTO ajusteempleado values ('".$nombreA."', '0', '0', '0', '0', '".$centro."', ".$IDEmpresa." );"; $objBDSQL2->consultaBD2($Minsert); }else { $array = array($_POST[$nombreA]); if(empty($array[0][0])){ $A1 = 0; }else { $A1 = $array[0][0]; } if(empty($array[0][1])){ $A2 = 0; }else { $A2 = $array[0][1]; } if(empty($array[0][2])){ $A3 = 0; }else { $A3 = $array[0][2]; } if(empty($array[0][3])){ $A4 = 0; }else { $A4 = $array[0][3]; } $Minsert = "INSERT INTO ajusteempleado values ('".$nombreA."', '".$A1."', '".$A2."', '".$A3."', '".$A4."', '".$centro."', ".$IDEmpresa." );"; $objBDSQL2->consultaBD2($Minsert); } } echo "1"; }else { while ($row = $objBDSQL->obtenResult()) { $nombreA = $row["codigo"]; if(empty($_POST[$nombreA])){ $Minsert = "UPDATE ajusteempleado SET PDOM = 0, DLaborados = 0, PA = 0, PP = 0, centro = '".$centro."', IDEmpresa = ".$IDEmpresa." WHERE IDEmpleado = '".$nombreA."' AND centro = '".$centro."' AND IDEmpresa = ".$IDEmpresa.";"; $objBDSQL2->consultaBD2($Minsert); }else { $array = array($_POST[$nombreA]); if(empty($array[0][0])){ $A1 = 0; }else { $A1 = $array[0][0]; } if(empty($array[0][1])){ $A2 = 0; }else { $A2 = $array[0][1]; } if(empty($array[0][2])){ $A3 = 0; }else { $A3 = $array[0][2]; } if(empty($array[0][3])){ $A4 = 0; }else { $A4 = $array[0][3]; } $Minsert = "UPDATE ajusteempleado SET PDOM = '".$A1."', DLaborados = '".$A2."', PA = '".$A3."', PP = '".$A4."', centro = '".$centro."', IDEmpresa = ".$IDEmpresa." WHERE IDEmpleado = '".$nombreA."' AND centro = '".$centro."' AND IDEmpresa = ".$IDEmpresa.";"; $objBDSQL2->consultaBD2($Minsert); } } echo "1"; } $objBDSQL->cerrarBD(); $objBDSQL2->cerrarBD(); ?> <file_sep><?php $codigo = $_POST['codigo']; $fecha = $_POST['fecha']; $CenT = $_POST['centro']; $Peri = $_POST['periodo']; $TiN = $_POST['TN']; $IDEmp = $_POST['IDEmp']; $bd1 = new ConexionM(); $bd1->__constructM(); $CsDescansoL = "SELECT valor FROM dobTurno WHERE codigo = ".$codigo." AND fecha = '".$fecha."' AND periodo = ".$Peri." AND tipoN = ".$TiN." AND IDEmpresa = $IDEmpresa AND Centro = '".$CenT."' LIMIT 1;"; $sql1 = $bd1->query($CsDescansoL); if($bd1->rows($sql1) > 0){ $datos = $bd1->recorrer($sql1); $CsValor = $datos[0]; if($CsValor == 0){ $Update = "UPDATE dobTurno SET valor = 1 WHERE codigo = $codigo AND fecha = '".$fecha."' AND periodo = $Peri AND tipoN = $TiN AND IDEmpresa = $IDEmp AND Centro = '".$CenT."';"; }else { $Update = "UPDATE dobTurno SET valor = 0 WHERE codigo = $codigo AND fecha = '".$fecha."' AND periodo = $Peri AND tipoN = $TiN AND IDEmpresa = $IDEmp AND Centro = '".$CenT."';"; } if($bd1->query($Update)){ }else { echo $bd1->errno. ' '.$bd1->error; } }else { $CSInsert = "INSERT INTO dobTurno VALUES(NULL, ".$codigo.", '".$fecha."', 1, ".$Peri.", ".$TiN.", ".$IDEmp.", '".$CenT."')"; if($bd1->query($CSInsert)){ }else { echo $bd1->errno. ' '.$bd1->error; } } ?> <file_sep><?php $periodo = $_POST['periodo']; $TN = $_POST['TN']; $objBDSQL = new ConexionSRV(); $objBDSQL->conectarBD(); $fecha1 = ""; $fecha2 = ""; $fecha3 = ""; $fecha4 = ""; if($PC <= 24){ $_fechas = periodo($periodo); list($fecha1, $fecha2, $fecha3, $fecha4) = explode(',', $_fechas); $fecha3 = $fecha1; $fecha4 = $fecha2; } if($TN == 1 || $PC > 24) { $_queryFechas = "SELECT CONVERT (VARCHAR (10), inicio, 103) AS 'FECHA1', CONVERT (VARCHAR (10), cierre, 103) AS 'FECHA2' FROM Periodos WHERE tiponom = 1 AND periodo = $periodo AND ayo_operacion = $ayoA AND empresa = $IDEmpresa ;"; $_resultados = $objBDSQL->consultaBD($_queryFechas); if($_resultados === false) { die(print_r(sqlsrv_errors(), true)); break; } $_datos = $objBDSQL->obtenResult(); $fecha1 = $_datos['FECHA1']; $fecha2 = $_datos['FECHA2']; $fecha3 = $fecha1; $fecha4 = $fecha2; $objBDSQL->liberarC(); } if(empty($fecha3)){ echo "Error"; }else { $fechas = array( "fecha1" => $fecha1, "fecha2" => $fecha2, "fecha3" => $fecha3, "fecha4" => $fecha4 ); echo json_encode($fechas); try { $objBDSQL->cerrarBD(); } catch (Exception $e) { echo 'ERROR al cerrar la conexion con SQL SERVER', $e->getMessage(), "\n"; } } ?> <file_sep><?php $ihidden = ""; $objBDSQL = new ConexionSRV(); $objBDSQL->conectarBD(); if($DepOsub == 1) { $querySQL = "[dbo].[roldehorarioEmp] '".$IDEmpresa."', '".$centro."', '1'"; }else { $querySQL = "[dbo].[roldehorarioEmp] '".$IDEmpresa."', '".$centro."', '0'"; } $numCol = $objBDSQL->obtenfilas($querySQL); if($numCol > 0){ echo ' <form id="frmRol" method="POST"> <input type="hidden" name="centro" value="'.$centro.'" > <table id="tRH" class="responsive-table striped highlight centered" style="border: 1px solid #000080;"> <thead> <tr> <th style="border-right: 1px solid black; background-color: #0091ea; color: white; border-bottom: 1px solid #696666;">Codigo</th> <th style="border-right: 1px solid black; background-color: #0091ea; color: white; border-bottom: 1px solid #696666;">Nombre</th> <th style="border-right: 1px solid black; background-color: #0091ea; color: white; border-bottom: 1px solid #696666;">Horario</th> <th style="border-right: 1px solid black; background-color: #0091ea; color: white; border-bottom: 1px solid #696666;">Descripcion</th> <th style="border-right: 1px solid black; background-color: #0091ea; color: white; border-bottom: 1px solid #696666;">Lunes</th> <th style="border-right: 1px solid black; background-color: #0091ea; color: white; border-bottom: 1px solid #696666;">Martes</th> <th style="border-right: 1px solid black; background-color: #0091ea; color: white; border-bottom: 1px solid #696666;">Miercoles</th> <th style="border-right: 1px solid black; background-color: #0091ea; color: white; border-bottom: 1px solid #696666;">Jueves</th> <th style="border-right: 1px solid black; background-color: #0091ea; color: white; border-bottom: 1px solid #696666;">Viernes</th> <th style="border-right: 1px solid black; background-color: #0091ea; color: white; border-bottom: 1px solid #696666;">Sabado</th> <th style="background-color: #0091ea; color: white;">Domingo</th> </tr> </thead><tbody>'; $objBDSQL->consultaBD($querySQL); $lr = 0; while ( $row = $objBDSQL->obtenResult() ) { $lr++; $ihidden .= '<input type="hidden" name="c'.$lr.'" value="'.$row["codigo"].'">'; echo '<tr> <td style="border-left: 1px solid #696666; border-bottom: 1px solid #696666;" >'.$row["codigo"].'</td> <td style="border-left: 1px solid #696666; border-bottom: 1px solid #696666;" >'.utf8_encode($row["nomE"]).'</td> <td style="text-align: center; border-left: 1px solid #696666; border-bottom: 1px solid #696666;"><div onclick="cambiar'.$lr.'()" class="controlgroup"><input style="width: 100%; margin: 0;" min="1" class="ui-spinner-input" value ="'.$row["Horario"].'" name="inp'.$lr.'" id="'.$lr.'" onclick="cambiar'.$lr.'()"></div></td> <td style="border-left: 1px solid #696666; border-bottom: 1px solid #696666;" id="des'.$lr.'">'.utf8_encode($row["Nombre"]).'</td> '; if($row["LUN"] == "DESCANSO"){ echo '<td style="background-color: #f9ff00; border-left: 1px solid #696666; border-bottom: 1px solid #696666;" id="l'.$lr.'">'.odbc_result($rs,"LUN").'</td>'; }else { echo '<td style="border-left: 1px solid #696666; border-bottom: 1px solid #696666;" id="l'.$lr.'">'.odbc_result($rs,"LUN").'</td>'; } if($row["MAR"] == "DESCANSO"){ echo '<td style="background-color: #f9ff00; border-left: 1px solid #696666; border-bottom: 1px solid #696666;" id="m'.$lr.'">'.odbc_result($rs,"MAR").'</td>'; }else { echo '<td style="border-left: 1px solid #696666; border-bottom: 1px solid #696666;" id="m'.$lr.'">'.odbc_result($rs,"MAR").'</td>'; } if($row["MIE"] == "DESCANSO"){ echo '<td style="background-color: #f9ff00; border-left: 1px solid #696666; border-bottom: 1px solid #696666;" id="i'.$lr.'">'.odbc_result($rs,"MIE").'</td>'; }else { echo '<td style="border-left: 1px solid #696666; border-bottom: 1px solid #696666;" id="i'.$lr.'">'.odbc_result($rs,"MIE").'</td>'; } if($row["JUE"] == "DESCANSO"){ echo '<td style="background-color: #f9ff00; border-left: 1px solid #696666; border-bottom: 1px solid #696666;" id="j'.$lr.'">'.odbc_result($rs,"JUE").'</td>'; }else { echo '<td style="border-left: 1px solid #696666; border-bottom: 1px solid #696666;" id="j'.$lr.'">'.odbc_result($rs,"JUE").'</td>'; } if($row["VIE"] == "DESCANSO"){ echo '<td style="background-color: #f9ff00; border-left: 1px solid #696666; border-bottom: 1px solid #696666;" id="v'.$lr.'">'.odbc_result($rs,"VIE").'</td>'; }else { echo '<td style="border-left: 1px solid #696666; border-bottom: 1px solid #696666;" id="v'.$lr.'">'.odbc_result($rs,"VIE").'</td>'; } if($row["SAB"] == "DESCANSO"){ echo '<td style="background-color: #f9ff00; border-left: 1px solid #696666; border-bottom: 1px solid #696666;" id="s'.$lr.'">'.odbc_result($rs,"SAB").'</td>'; }else { echo '<td style="border-left: 1px solid #696666; border-bottom: 1px solid #696666;" id="s'.$lr.'">'.odbc_result($rs,"SAB").'</td>'; } if($row["DOM"] == "DESCANSO"){ echo '<td style="background-color: #f9ff00; border-left: 1px solid #696666; border-bottom: 1px solid #696666;" id="d'.$lr.'">'.odbc_result($rs,"DOM").'</td>'; }else { echo '<td style="border-left: 1px solid #696666; border-bottom: 1px solid #696666;" id="d'.$lr.'">'.odbc_result($rs,"DOM").'</td>'; } echo '</tr>'; } echo '</tbody></table><input type="hidden" name="cantidad" value="'.$lr.'">'.$ihidden.'</form>'; echo '<button class="waves-effect waves-light btn" style="margin: 10px;" onclick="Rol()">GUARDAR</button>'; echo '<script type="text/javascript">'; for($jh=1; $jh<=$lr; $jh++){ echo 'function cambiar'.$jh.'() { var numero; numero = document.getElementById("'.$jh.'").value; numero = Number(numero); switch (numero) { '; for ($j=1; $j<=$iDH; $j++){ echo' case '.$j.': document.getElementById("des'.$jh.'").innerHTML = "'.$DesHora[$j].'"; document.getElementById("l'.$jh.'").innerHTML = "'.$Lun[$j].'";'; if($Lun[$j] == "DESCANSO"){ echo 'document.getElementById("l'.$jh.'").style.background = \'#f9ff00\';'; }else { //echo 'document.getElementById("l'.$jh.'").style.background = \'#ffffff\';'; } echo 'document.getElementById("m'.$jh.'").innerHTML = "'.$Mar[$j].'";'; if($Mar[$j] == "DESCANSO"){ echo 'document.getElementById("m'.$jh.'").style.background = \'#f9ff00\';'; }else { //echo 'document.getElementById("m'.$jh.'").style.background = \'#ffffff\';'; } echo 'document.getElementById("i'.$jh.'").innerHTML = "'.$Mie[$j].'";'; if($Mie[$j] == "DESCANSO"){ echo 'document.getElementById("i'.$jh.'").style.background = \'#f9ff00\';'; }else { //echo 'document.getElementById("i'.$jh.'").style.background = \'#ffffff\';'; } echo 'document.getElementById("j'.$jh.'").innerHTML = "'.$Jue[$j].'";'; if($Jue[$j] == "DESCANSO"){ echo 'document.getElementById("j'.$jh.'").style.background = \'#f9ff00\';'; }else { //echo 'document.getElementById("j'.$jh.'").style.background = \'#ffffff\';'; } echo 'document.getElementById("v'.$jh.'").innerHTML = "'.$Vie[$j].'";'; if($Vie[$j] == "DESCANSO"){ echo 'document.getElementById("v'.$jh.'").style.background = \'#f9ff00\';'; }else { //echo 'document.getElementById("v'.$jh.'").style.background = \'#ffffff\';'; } echo 'document.getElementById("s'.$jh.'").innerHTML = "'.$Sab[$j].'";'; if($Sab[$j] == "DESCANSO"){ echo 'document.getElementById("s'.$jh.'").style.background = \'#f9ff00\';'; }else { //echo 'document.getElementById("s'.$jh.'").style.background = \'#ffffff\';'; } echo 'document.getElementById("d'.$jh.'").innerHTML = "'.$Dom[$j].'";'; if($Dom[$j] == "DESCANSO"){ echo 'document.getElementById("d'.$jh.'").style.background = \'#f9ff00\';'; }else { //echo 'document.getElementById("d'.$jh.'").style.background = \'#ffffff\';'; } echo ' break;'; } echo ' default: alert ("Horario no valido"); document.getElementById("des'.$jh.'").innerHTML = "'.$DesHora[1].'"; document.getElementById("l'.$jh.'").innerHTML = "'.$Lun[1].'";'; if($Lun[1] == "DESCANSO"){ echo 'document.getElementById("l'.$jh.'").style.background = \'#f9ff00\';'; }else { //echo 'document.getElementById("l'.$jh.'").style.background = \'#ffffff\';'; } echo 'document.getElementById("m'.$jh.'").innerHTML = "'.$Mar[1].'";'; if($Mar[1] == "DESCANSO"){ echo 'document.getElementById("m'.$jh.'").style.background = \'#f9ff00\';'; }else { //echo 'document.getElementById("m'.$jh.'").style.background = \'#ffffff\';'; } echo 'document.getElementById("i'.$jh.'").innerHTML = "'.$Mie[1].'";'; if($Mie[1] == "DESCANSO"){ echo 'document.getElementById("i'.$jh.'").style.background = \'#f9ff00\';'; }else { //echo 'document.getElementById("i'.$jh.'").style.background = \'#ffffff\';'; } echo 'document.getElementById("j'.$jh.'").innerHTML = "'.$Jue[1].'";'; if($Jue[1] == "DESCANSO"){ echo 'document.getElementById("j'.$jh.'").style.background = \'#f9ff00\';'; }else { //echo 'document.getElementById("j'.$jh.'").style.background = \'#ffffff\';'; } echo 'document.getElementById("v'.$jh.'").innerHTML = "'.$Vie[1].'";'; if($Vie[1] == "DESCANSO"){ echo 'document.getElementById("v'.$jh.'").style.background = \'#f9ff00\';'; }else { //echo 'document.getElementById("v'.$jh.'").style.background = \'#ffffff\';'; } echo 'document.getElementById("s'.$jh.'").innerHTML = "'.$Sab[1].'";'; if($Sab[1] == "DESCANSO"){ echo 'document.getElementById("s'.$jh.'").style.background = \'#f9ff00\';'; }else { //echo 'document.getElementById("s'.$jh.'").style.background = \'#ffffff\';'; } echo 'document.getElementById("d'.$jh.'").innerHTML = "'.$Dom[1].'";'; if($Dom[1] == "DESCANSO"){ echo 'document.getElementById("d'.$jh.'").style.background = \'#f9ff00\';'; }else { //echo 'document.getElementById("d'.$jh.'").style.background = \'#ffffff\';'; } echo ' document.getElementById("'.$jh.'").value = "1"; break; } }; '; } echo '</script>'; }else { //echo 'No se encontraron resultados'; echo '<div style="width: 100%" class="deep-orange accent-4"><h6 class="center-align" style="padding-top: 5px; padding-bottom: 5px; color: white;">No se encotro resultado !</h6></div>'; } $objBDSQL->liberarC(); $objBDSQL->cerrarBD(); ?> <file_sep>$(document).ready(function() { verContratos(); }); function verContratos(){ var Dimensiones = AHD(); var conexion, resultado, variable, ancho; ancho = Dimensiones[0]; variable = "valor="+ancho; conexion = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); conexion.onreadystatechange = function() { if(conexion.readyState == 4 && conexion.status == 200){ document.getElementById('estado_consulta_ajax').innerHTML = conexion.responseText; var Dimensiones = AHD(); if(Dimensiones[3] > Dimensiones[1]){ $('#pie').css("position", "inherit"); }else { $('#pie').css("position", "absolute"); } }else if(conexion.readyState != 4){ resultado = '<div class="progress">'; resultado += '<div class="indeterminate"></div>'; resultado += '</div>'; document.getElementById('estado_consulta_ajax').innerHTML = resultado; } } conexion.open('POST', 'ajax.php?modo=contratosVence', true); conexion.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); conexion.send(variable); } <file_sep><?php //----------------------------------------------------- //----------------------------------------------------- /** * CONEXION MYSQL */ class ConexionM extends mysqli { public $conexionInfo=""; public $enlace=""; public $resultado=""; public $consulta=""; public function __constructM() { parent::__construct(M_DB_SERVER,M_DB_USER,M_DB_PASS,M_DB_NOMBRE); $this->connect_errno ? die('Error en la Conexión a la base de datos') : null; $this->set_charset("utf8"); } public function rows($query) { return mysqli_num_rows($query); } public function liberar($query){ return mysqli_free_result($query); } public function recorrer($query){ return mysqli_fetch_array($query); } } //----------------------------------------------------- //----------------------------------------------------- /** * CONEXION SQL LIBRERIA SRV */ class ConexionSRV { public $conexionInfo=""; public $enlace=""; public $resultado=""; public $resultado2=""; public $consulta=""; public $consulta2=""; public function ConexionSRV() { $this->conexionInfo = array("Database" => S_DB_NOMBRE, "UID" => S_DB_USER, "PWD" => <PASSWORD>, "CharacterSet" => "UTF-8"); } public function conectarBD() { $this->enlace = sqlsrv_connect( S_DB_SERVER, $this->conexionInfo); if( $this->enlace === false ) { foreach(sqlsrv_errors() as $error){ echo "<h1 style='text-align: center'>OCURRIO UN ERROR EN LA CONEXION CON LA BD.</h1><br/>"; echo "SQLSTATE: ".$error['SQLSTATE']."<br/>"; echo "CODIGO: ".$error['code']."<br/>"; echo "MENSAJE: ".$error['message']."<br/>"; } //die( print_r( sqlsrv_errors(), true)); exit(); } } public function consultaBD($sentenciaSQL) { $this->consulta = sqlsrv_query($this->enlace, $sentenciaSQL); if($this->consulta === false || empty($this->consulta)) { if(($errors = sqlsrv_errors()) != null) { $file = fopen("log/log".date("d-m-Y").".txt", "a"); fwrite($file, ":::::::::::::::::::::::CONSULTA BD:::::::::::::::::::::::".PHP_EOL); foreach($errors as $error){ fwrite($file, '['.date('d/m/Y h:i:s A').']'.' SQLSTATE: '.$error['SQLSTATE'].PHP_EOL); fwrite($file, '['.date('d/m/Y h:i:s A').']'.' CODIGO: '.$error['code'].PHP_EOL); fwrite($file, '['.date('d/m/Y h:i:s A').']'.' MENSAJE: '.$error['message'].PHP_EOL); } fwrite($file, '['.date('d/m/Y h:i:s A').']'.' CONSULTA: '.$sentenciaSQL.PHP_EOL); fclose($file); return 1; } } return 0; } public function consultaBD2($sentenciaSQL){ $this->consulta2 = sqlsrv_query($this->enlace, $sentenciaSQL); if($this->consulta2 === false || empty($this->consulta2)) { if(($errors = sqlsrv_errors()) != null) { $file = fopen("log/log".date("d-m-Y").".txt", "a"); fwrite($file, ":::::::::::::::::::::::CONSULTA BD:::::::::::::::::::::::".PHP_EOL); foreach($errors as $error){ fwrite($file, '['.date('d/m/Y h:i:s A').']'.' SQLSTATE: '.$error['SQLSTATE'].PHP_EOL); fwrite($file, '['.date('d/m/Y h:i:s A').']'.' CODIGO: '.$error['code'].PHP_EOL); fwrite($file, '['.date('d/m/Y h:i:s A').']'.' MENSAJE: '.$error['message'].PHP_EOL); } fwrite($file, '['.date('d/m/Y h:i:s A').']'.' CONSULTA: '.$sentenciaSQL.PHP_EOL); fclose($file); return 1; } } return 0; } public function returnConsulta(){ return $this->consulta; } public function returnConsulta2(){ return $this->consulta2; } public function obtenResult(){ $this->resultado=sqlsrv_fetch_array($this->consulta, SQLSRV_FETCH_ASSOC); return $this->resultado; } public function obtenResultNum(){ $this->resultado=sqlsrv_fetch_array($this->consulta, SQLSRV_FETCH_NUMERIC); return $this->resultado; } public function obtenResult2(){ $this->resultado2=sqlsrv_fetch_array($this->consulta2, SQLSRV_FETCH_ASSOC); return $this->resultado2; } public function obtenfilas($sentenciaSQL) { $this->resultado=sqlsrv_num_rows(sqlsrv_query($this->enlace, $sentenciaSQL, array(), array("Scrollable" => "buffered"))); return $this->resultado; } public function liberarC() { sqlsrv_free_stmt($this->consulta); } public function liberarC2(){ sqlsrv_free_stmt($this->consulta2); } public function cerrarBD() { sqlsrv_close( $this->enlace ); } } ?> <file_sep><?php require_once('ClassImpFormatos.php'); $bd1 = new ConexionM(); $bd1->__constructM(); $bdS = constructS(); $Carpeta = "quincenal"; if($TN == 1){ $Carpeta = "semanal"; } $ID = $_POST['ID']; $CodEmp = $_POST['codEmp']; $fechhh = $_POST['FF']; if(!empty($_POST['AU'])){ $AU = $_POST['AU']; if($AU == 2){ $AU = 0; } $InsertarTNT = "UPDATE datosanti SET Autorizo1 = $AU WHERE ID = $ID ;"; } if(!empty($_POST['AU2'])){ $AU2 = $_POST['AU2']; if($AU2 == 2){ $AU2 = 0; } $InsertarTNT = "UPDATE datosanti SET Autorizo2 = $AU2 WHERE ID = $ID ;"; } if($bd1->query($InsertarTNT)){ $consultaMs = "SELECT valor FROM datosanti WHERE Autorizo1 = 1 AND Autorizo2 = 1 AND valor = 'PG' AND ID = $ID ;"; if($resulll = $bd1->query($consultaMs)){ $contar = $resulll->num_rows; if($contar == 1){ $querySS = "SELECT E.nombre + ' ' + E.ap_paterno + ' ' + E.ap_materno AS Nombre, E.codigo, C.nomdepto FROM empleados AS E INNER JOIN Llaves AS L ON L.codigo = E.codigo INNER JOIN centros AS C ON C.centro = L.centro AND C.empresa = L.empresa WHERE E.codigo = '".$CodEmp."' AND E.empresa = $IDEmpresa;"; $rs = odbc_exec($bdS, $querySS); //$consultaFechas = "SELECT nombre FROM datosanti WHERE Autorizo1 = 1 AND Autorizo2 = 1 AND valor = 'PG' AND codigo = $CodEmp AND ;"; $pdfImp = new PDF('P', 'mm', 'Letter'); $pdfImp->AliasNbPages(); $pdfImp->SetFont('Arial', '', 8); $pdfImp->AddPage(); $pdfImp->tablePermiso($NombreEmpresa, utf8_encode(odbc_result($rs,"Nombre")), odbc_result($rs,"codigo"), utf8_encode(odbc_result($rs,"nomdepto")), $fechhh); //$pdfImp->Output('F', Unidad.'E'.$IDEmpresa.'\\'.$Carpeta.'\pdf\PruebaPermiso.pdf'); $pdfImp->Output('F', "Temp/tempPP.pdf"); echo "1"; } } }else { echo $bd1->errno. ' '.$bd1->error; } ?> <file_sep> <?php set_time_limit(6000); //////////////// VARIABLES /////////////// $_periodo = $_POST['periodo']; $_tipoNom = $_POST['tipoNom']; $diasAnteO = false; if(isset($_POST['obtenDiasAnt'])){ if(!empty($_POST['obtenDiasAnt']) && $_POST['obtenDiasAnt'] == 'true'){ $diasAnteO = true; } } $_permisoT = $_SESSION["Permiso"]; $_dias = array('', 'LUN', 'MAR', 'MIE', 'JUE', 'VIE', 'SAB', 'DOM'); $objBDSQL = new ConexionSRV(); $objBDSQL->conectarBD(); $objBDSQL2 = new ConexionSRV(); $objBDSQL2->conectarBD(); $BDM = new ConexionM(); $BDM->__constructM(); $_HTML = ""; $_BTNS = ''; $_nResultados = 1; $_cabecera = "<tr>"; $_cabeceraD = "<tr><th></th><th></th><th></th><th></th>"; $_cabeceraD = '<tr> <th colspan="4" id="CdMas" style="background-color: white; border-top: 1px solid transparent; border-left: 1px solid transparent;"></th>'; $_cuerpo = ""; $_Fecha0 = ""; $_FechaPar = ""; $_DiaNumero = ""; $_FechaND = ""; $_FechaCol = ""; $_date = ""; $_FechaNDQ = ""; $_queryDatos = ""; $_NumColumnas = 0; $_NumResultado = 0; $_tmp_E_valor = ""; $_valorC = ""; $_colorF = ""; $_arrayCabeceraD = ""; $_arrayCabeceraF = ""; $_PPPA = explode('|', "0|0"); $_PPPAempleado = explode('|', "0|0"); ///////////////////////////////////////// /////////////// PERIODOS /////////////// if($_periodo <= 24){ $_fechas = periodo($_periodo); list($_fecha1, $_fecha2, $_fecha3, $_fecha4) = explode(',', $_fechas); } if($_tipoNom == 1 || $_periodo > 24) { $_queryFechas = "SELECT CONVERT (VARCHAR (10), inicio, 103) AS 'FECHA1', CONVERT (VARCHAR (10), cierre, 103) AS 'FECHA2' FROM Periodos WHERE tiponom = 1 AND periodo = $_periodo AND ayo_operacion = $ayoA AND empresa = $IDEmpresa ;"; $_resultados = $objBDSQL->consultaBD($_queryFechas); if($_resultados === false) { die(print_r(sqlsrv_errors(), true)); exit(); }else { $_datos = $objBDSQL->obtenResult(); } $_fecha1 = $_datos['FECHA1']; $_fecha2 = $_datos['FECHA2']; $objBDSQL->liberarC(); } ///////////////CONSULTA GENERAL //////// list($_dia, $_mes, $_ayo) = explode('/', $_fecha1); list($_diaB, $_mesB, $_ayoB) = explode('/', $_fecha2); $_fecha1 = $_ayo.$_mes.$_dia; $_fecha2 = $_ayoB.$_mesB.$_diaB; ///////////////INCRUSTRAR CHECADAS////////// $Jcodigos = file_get_contents("datos/empleados.json"); $datosJSON = json_decode($Jcodigos, true); $contarJSON = count($datosJSON["empleados"]); $dateInc = $_ayo.'/'.$_mes.'/'.$_dia; $varificarIns = true; for($j = 0; $j <= $contarJSON - 1; $j++){ if($datosJSON["empleados"][$j]["estado"] == 1){ $randon = rand(0, 15); $hora = strtotime($datosJSON["empleados"][$j]["hora"]); $horaParse = (date('H:i:s', $hora)); $hora2 = strtotime($datosJSON["empleados"][$j]["hora2"]); $hora2Parse = (date('H:i:s', $hora2)); //RECORRER DOS FECHAS for($i=0; $i<=31; $i++){ $fechaS = date("d/m/Y", strtotime($dateInc." + ".$i." day")); list($dia, $mes, $ayo) = explode('/', $fechaS); $fConsulta = $ayo.$mes.$dia; $fComp = explode('/', $fechaS); $FMK = mktime(0,0,0,$fComp[1],$fComp[0],$fComp[2]); $FMK2 = mktime(0,0,0,$_mesB, $_diaB, $_ayoB); if($FMK <= $FMK2){ //CONFIRMAR QUE NO EXISTE ENTRADA $consultaChecada = "SELECT R.checada FROM relch_registro AS R WHERE R.fecha = '".$fConsulta."' AND R.codigo = ".$datosJSON["empleados"][$j]["codigo"]." AND R.empresa = ".$datosJSON["empleados"][$j]["empresa"]." AND R.checada <> '00:00:00' AND (R.EoS = '1' OR R.EoS = 'E' OR R.EoS IS NULL);"; $_resultados = $objBDSQL->consultaBD($consultaChecada); if($_resultados === false) { die(print_r(sqlsrv_errors(), true)); break; }else { $objBDSQL->liberarC(); $_datos = $objBDSQL->obtenResult(); if(empty($_datos)){ $fechaInst = date("Ymd", $FMK); $fchora = strtotime('+'.rand(0, 15).' minute', strtotime($horaParse)); $horainsert = date('H:s:i', $fchora); $checadaEntrada = "ObtenRelojDatosEmps ".$datosJSON["empleados"][$j]["empresa"].", ".$datosJSON["empleados"][$j]["codigo"].", '".$fechaInst."', '".$horainsert."', 'N', ' ', ' '"; try { $insertChecada = $objBDSQL->consultaBD($checadaEntrada); if($insertChecada){ $file = fopen("datos/insertSS.txt", "w"); fwrite($file, 1); fclose($file); }else { $verificacion = false; } }catch(Exception $e){ var_dump($e->getMessage()); } //$objBDSQL->liberarC(); } } ////////////////////CONFIRMAR QUE NO EXISTE UNA SALIDA $consultaChecada0 = "SELECT R.checada FROM relch_registro AS R WHERE R.fecha = '".$fConsulta."' AND R.codigo = ".$datosJSON["empleados"][$j]["codigo"]." AND R.empresa = ".$datosJSON["empleados"][$j]["empresa"]." AND R.checada <> '00:00:00' AND (R.EoS = '2' OR R.EoS = 'S' OR R.EoS IS NULL);"; $_resultados = $objBDSQL->consultaBD($consultaChecada); if($_resultados === false) { die(print_r(sqlsrv_errors(), true)); break; }else { $objBDSQL->liberarC(); $_datos = $objBDSQL->obtenResult(); if(empty($_datos)){ $fechaInst = date("Ymd", $FMK2); $fchora = strtotime('+'.rand(0, 15).' minute', strtotime($hora2Parse)); $horainsert = date('H:s:i', $fchora); $checadaEntrada = "ObtenRelojDatosEmps ".$datosJSON["empleados"][$j]["empresa"].", ".$datosJSON["empleados"][$j]["codigo"].", '".$fechaInst."', '".$horainsert."', 'N', ' ', ' '"; try { $insertChecada = $objBDSQL->consultaBD($checadaEntrada); if($insertChecada){ $file = fopen("datos/insertSS.txt", "w"); fwrite($file, 1); fclose($file); }else { $verificacion = false; } }catch(Exception $e){ var_dump($e->getMessage()); } //$objBDSQL->liberarC(); } } } } } } if($varificarIns == false){ echo "<script >alert ('ERROR - Verifica los parametros de los empleados(cargarChecadas)');</script>"; } /////////////////////////////////////////// if($DepOsub == 1) { $queryGeneral = " [dbo].[reporte_checadas_excel_ctro] '".$_fecha1."', '".$_fecha2."', '".$centro."', '".$supervisor."', '".$IDEmpresa."', '".$_tipoNom."', 'LEFT (Llaves.centro, ".$MascaraEm.") = LEFT (''".$centro."'', ".$MascaraEm.")', '1'"; $ComSql = "LEFT (Centro, ".$MascaraEm.") = LEFT ('".$centro."', ".$MascaraEm.")"; }else { $queryGeneral = " [dbo].[reporte_checadas_excel_ctro] '".$_fecha1."', '".$_fecha2."', '".$centro."', '".$supervisor."', '".$IDEmpresa."', '".$_tipoNom."', 'Llaves.centro = ''".$centro."''', '0'"; $ComSql = "Centro = '".$centro."'"; } /////////////Periodo y TipoNomina///////// $_UPDATEPYT = "UPDATE config SET PC = $_periodo, TN = $_tipoNom WHERE IDUser = '".$_SESSION['IDUser']."';"; try{ if($BDM->query($_UPDATEPYT)){ }else { echo $BDM->errno.' '.$BDM->error; } }catch (\Exception $e){ echo $e; } $_SESSION['TN'] = $_tipoNom; $_SESSION['PC'] = $_periodo; //////////ACTUALIZAR FRENTES //////////////// if(date($_fecha1) >= date("Ymd")){ $SELECTJUEVES = "SELECT Codigo, JUE FROM relacionempfrente"; $queryJueves = $objBDSQL->consultaBD($SELECTJUEVES); while ($row = $objBDSQL->obtenResult()) { $codigoJue = $row["Codigo"]; $Juev = ltrim(rtrim($row["JUE"])); $UPDATEFRENTES = "UPDATE relacionempfrente SET LUN = '".$Juev."', MAR = '".$Juev."', MIE = '".$Juev."', VIE = '".$Juev."', SAB = '".$Juev."', DOM = '".$Juev."' WHERE Codigo = '".$codigoJue."';"; $result = $objBDSQL->consultaBD($UPDATEFRENTES); if($result === false){ die(print_r(sqlsrv_errors(), true)); break; } } //$objBDSQL->liberarC(); } ////////////BOTONES DE GUARDAR EDITAR GENERAR ETC.////////////// $consultaEstatus = "SELECT estado FROM estatusPeriodo WHERE periodo = $_periodo AND tipoNom = $_tipoNom"; $bloquear = ''; $objBDSQL->consultaBD($consultaEstatus); if(!empty(sqlsrv_errors()[0]['message'])){ echo "Error Capturado: ".sqlsrv_errors()[0]['message']; } $estadoP = $objBDSQL->obtenResult(); $objBDSQL->liberarC(); if($estadoP['estado'] == 1){ $bloquear = 'disabled="disabled"'; $_BTNS = '<button name="generar" id="btnGenerar" class="waves-effect waves-light btn" onclick="GTasistencia()" style="margin: 20px;">GENERAR</button> <button name="cierre" class="waves-effect waves-light btn" style="margin: 20px;" onclick="CerrarT(0)">HABILITAR</button>'; if($_permisoT == 0){ $_BTNS = '<button name="generar" id="btnGenerar" class="waves-effect waves-light btn" onclick="GTasistencia()" style="margin: 20px;">GENERAR</button> <button name="cierre" disabled="disabled" class="waves-effect waves-light btn" style="margin: 20px;">HABILITAR</button>'; } }else if($estadoP['estado'] == 0 || empty($estadoP['estado'])){ $_BTNS = '<button name="generar" id="btnGenerar" class="waves-effect waves-light btn" onclick="GTasistencia()" style="margin: 20px;">GENERAR</button> <button name="cierre" class="waves-effect waves-light btn" style="margin: 20px;" onclick="CerrarT(1)">CERRAR</button>'; $bloquear = ''; } /* if($_permisoT == 0){ $_BTNS = '<button name="generar" id="btnGenerar" class="waves-effect waves-light btn" onclick="GTasistencia()" style="margin: 20px;">GENERAR</button>'; }*/ /* $_queryNumeroR = "SELECT valor FROM datos WHERE periodoP = $_periodo AND tipoN = $_tipoNom AND ".$ComSql." ;"; $_nResultados = $BDS->nFilas($_conn, $_queryNumeroR); if($_nResultados > 0){ if($_permisoT == 0){ $BTNT = ''; }else if($_permisoT == 1) { } }*/ /////////////////////////////////////////////////////////////// $_HTML = '<form method="POST" id="frmTasis"> <div id="Sugerencias" style="position: fixed; left: 0; top: -3px; padding-top: 15px; margin-bottom: 0; z-index: 998;"></div> <table id="t01" class="responsive-table striped highlight centered" > <thead id="Thfija">'; /*$serverName = "DESKTOP-2POHOQ5\\JUAN"; $connectionInfo = array( "Database"=>"VISTA", "UID"=>"sa", "PWD"=>"<PASSWORD>"); $conn = sqlsrv_connect( $serverName, $connectionInfo); if( $conn === false ) { die( print_r( sqlsrv_errors(), true)); } $_consultaS = sqlsrv_query($conn, $queryGeneral);*/ $objBDSQL->consultaBD($queryGeneral); while ($row=$objBDSQL->obtenResult()) { $_NumResultado++; $_cuerpo .= "<tr>"; foreach (array_keys($row) as $value) { if($_nResultados==1){ if($value == 'codigo' || $value == 'Nombre' || $value == 'Sueldo' || $value == 'Tpo'){ }else { $_date = str_ireplace('/', '-', $value); $_Fecha0 = date('Y-m-d', strtotime($_date)); $_FechaND = $_dias[date('N', strtotime($_Fecha0))]; $_cabeceraD .= "<th>".$_FechaND."</th>"; $_NumColumnas++; $_arrayCabeceraD .= '<input type = "hidden" name="CabeceraD[]" value="'.$_FechaND.'">'; } $_cabecera .= "<th>".$value."</th>"; $_arrayCabeceraF .= '<input type = "hidden" name="Cabecera[]" value="'.$value.'">'; } if($value == 'codigo' || $value == 'Nombre' || $value == 'Sueldo' || $value == 'Tpo'){ $_cuerpo .= "<td>".$row[$value]."</td>"; }else { $tmp_valorC = ""; $_FechaCol = str_replace("/", "-", $value); $_FechaPar = date('Y-m-d', strtotime($_FechaCol)); $_DiaNumero = date('N', strtotime($_FechaPar)); if($_DiaNumero == 1){ $_FechaNDQ = $_dias[6]; }else { $_FechaNDQ = $_dias[$_DiaNumero-1]; } $_queryDatos = " SELECT (SELECT TOP(1) valor FROM datosanti WHERE codigo = '".$row['codigo']."' AND nombre = 'fecha".str_replace("/", "-", $value)."' and periodoP = '".$_periodo."' and tipoN = '".$_tipoNom."' and IDEmpresa = '".$IDEmpresa."' and ".$ComSql.") AS 'A', (SELECT TOP(1) valor FROM datos WHERE codigo = '".$row['codigo']."' AND nombre = '".str_replace("/", "-", $value)."' and periodoP = '".$_periodo."' and tipoN = '".$_tipoNom."' and IDEmpresa = '".$IDEmpresa."' and ".$ComSql.") AS 'B', (SELECT TOP(1) valor FROM datosanti WHERE codigo = '".$row['codigo']."' AND nombre = 'fecha".str_replace("/", "-", $value)."' and periodoP = '".$_periodo."' and tipoN = '".$_tipoNom."' and IDEmpresa = '".$IDEmpresa."' and ".$ComSql." and Autorizo1 = 1) AS 'C', (SELECT TOP(1) ".$_FechaNDQ." FROM relacionempfrente WHERE Codigo = '".$row['codigo']."' AND ".$ComSql." AND IDEmpresa = '".$IDEmpresa."') AS 'D', (SELECT TOP(1) valor FROM deslaborado WHERE codigo = ".$row['codigo']." AND fecha = '".str_replace("/", "-", $value)."' AND periodo = $_periodo AND tipoN = $_tipoNom AND IDEmpresa = '".$IDEmpresa."' AND ".$ComSql.") AS 'E', (SELECT TOP(1) (Convert(varchar(5), PP)+'|'+Convert(varchar(5), PA)) as 'B' FROM premio WHERE codigo = '".$row['codigo']."' and Periodo = '".$_periodo."' and TN = '".$_tipoNom."' and ".$ComSql." and IDEmpresa = '".$IDEmpresa."') AS 'F', (SELECT TOP(1) (Convert(varchar(5), PP)+'|'+Convert(varchar(5), PA)) as 'B' FROM ajusteempleado WHERE IDEmpleado = '".$row['codigo']."' and ".$ComSql." and IDEmpresa = '".$IDEmpresa."') AS 'G' "; $consultaMedi = $objBDSQL2->consultaBD2($_queryDatos); if($consultaMedi === false){ die(print_r(sqlsrv_errors(), true)); exit(); }else { $row2=$objBDSQL2->obtenResult2(); $objBDSQL2->liberarC2(); } ################################################## //VERIFICAR LOS DATOS EN LAS TABLAS EXTRAS ################################################## $_colorF = 0; $_valorC = ""; $_PPPAempleado = explode('|', '0|0'); $_PPPA = explode('|', '0|0'); if(!empty($row2['A'])){ $_colorF = 1; } if(!empty($row2['B'])){ if($row2['B'] == '-n' || $row2['B'] == '-N'){ }else { $_valorC = $row2['B']; } } if(!empty($row2['C'])){ if($row2['C'] == '-n' || $row2['C'] == '-N'){ }else { $_valorC = $row2['C']; } } if(!empty($row2['F'])){ $_PPPA = explode('|', $row2['F']); } if(!empty($row2['G'])){ $_PPPAempleado = explode('|', $row2['G']); } ################################################## //Condiciones para insertar datos encuanto a fecha ################################################## if($diasAnteO == true){ if(date($_FechaCol) == date("d-m-Y")){ if($_valorC != ""){ if($row2['D'] != 'F'){ $UPDATERELACIONDT = "UPDATE relacionempfrente SET ".$_dias[$_DiaNumero]." = '".$row2['D']."' WHERE Codigo = '".$row['codigo']."' AND ".$ComSql." AND IDEmpresa = '".$IDEmpresa."';"; $updaRelaFrente = $objBDSQL2->consultaBD2($UPDATERELACIONDT); if($updaRelaFrente === false){ die(print_r(sqlsrv_errors(), true)); break; } //$objBDSQL2->liberarC2(); } } } if(empty($_valorC)){ $fechaHOY = date("d-m-Y"); $_valorC = $row2['D']; if(!empty($_valorC) && (date($_FechaCol) <= $fechaHOY)){ if($_valorC != 'F'){ $INSERTRELACIONDT = "INSERT INTO datos (codigo, nombre, valor, periodoP, tipoN, IDEmpresa, Centro) VALUES ('".$row['codigo']."', '".$_FechaCol."', '".$_valorC."', '".$_periodo."', '".$_tipoNom."', '".$IDEmpresa."', '".$centro."');"; $InsertD = $objBDSQL2->consultaBD2($INSERTRELACIONDT); if($InsertD === false){ die(print_r(sqlsrv_errors(), true)); break; } //$objBDSQL2->liberarC2(); } } } } ################################################## ################################################## if(empty($row[$value])){ $_cuerpo .= '<td style="height: 74px;">'; if($_tipoNom == 1){ $evento = 'onkeyup="ConsultaFrente('.$row["codigo"].', \''.$_FechaCol.'\', \''.$row["codigo"].$_FechaCol.'\', )"'; }else { $evento = 'onkeyup="GuardarRegistro('.$row["codigo"].', \''.$_FechaCol.'\')"'; } if($_colorF == 1){ $_cuerpo .= '<input type="text" '.$bloquear.' style="background-color: #f57c7c;" id="'.$row['codigo'].$_FechaCol.'" value="'.$_valorC.'" '.$evento.' >'; }else { $_cuerpo .= '<input type="text" '.$bloquear.' id="'.$row['codigo'].$_FechaCol.'" value="'.$_valorC.'" '.$evento.' >'; } $_cuerpo .= '</td>'; }else { if($row2['E'] == 1){ $_cuerpo .= '<td class="Aline" style="height: 74px;"> <p style="padding: 0; margin: 0; text-align: center;"> <input type="checkbox" '.$bloquear.' checked="checked" id="'.$row['codigo'].$_FechaCol.'DL" /> <label for="'.$row['codigo'].$_FechaCol.'DL" onclick="DLaborados(\''.$row['codigo'].'\', \''.$_FechaCol.'\', \''.$centro.'\', \''.$_periodo.'\', \''.$_tipoNom.'\', \''.$IDEmpresa.'\')" title="Descanso Laborado" style="padding: 6px; margin-left: 17px; position: absolute; margin-top: -25px;"></label> </p>'; if($_tipoNom == 1){ $_cuerpo .= '<input type="text" '.$bloquear.' value="'.$_valorC.'" id="'.$row['codigo'].$_FechaCol.'" onkeyup="ConsultaFrente('.$row['codigo'].', \''.$_FechaCol.'\', \''.$row['codigo'].$_FechaCol.'\')">'; }else { $_cuerpo .= $row[$value]; } $_cuerpo .= '</td>'; }else{ $_cuerpo .= '<td class="Aline" style="height: 74px;"> <p style="padding: 0; margin: 0; text-align: center;"> <input type="checkbox" '.$bloquear.' id="'.$row['codigo'].$_FechaCol.'DL" /> <label for="'.$row['codigo'].$_FechaCol.'DL" onclick="DLaborados(\''.$row['codigo'].'\', \''.$_FechaCol.'\', \''.$centro.'\', \''.$_periodo.'\', \''.$_tipoNom.'\', \''.$IDEmpresa.'\')" title="Descanso Laborado" style="padding: 6px; margin-left: 17px; position: absolute; margin-top: -25px;"></label> </p>'; if($_tipoNom == 1){ $_cuerpo .= '<input type="text" '.$bloquear.' value="'.$_valorC.'" id="'.$row['codigo'].$_FechaCol.'" onkeyup="ConsultaFrente('.$row['codigo'].', \''.$_FechaCol.'\', \''.$row['codigo'].$_FechaCol.'\')">'; }else { $_cuerpo .= $row[$value]; } $_cuerpo .= '</td>'; } } } } if($row['Tpo'] == "E"){ $tmp_PPC = ""; $tmp_PAC = ""; $tmp_APPC = ""; $tmp_APAC = ""; if($_PPPAempleado[0] == 0){ if($_PPPA[0] == 0){ $_cuerpo .= '<td><input type="number" '.$bloquear.' style="width: 70px;" min="0" name="pp'.$row['codigo'].'" placeholder="P.P" step="0.01" value=""></td>'; }else { $_cuerpo .= '<td><input type="number" '.$bloquear.' style="width: 70px;" min="0" name="pp'.$row['codigo'].'" placeholder="P.P" step="0.01" value="'.$_PPPA[0].'"></td>'; } }else { $_cuerpo .= '<td class="Aline"></td>'; } if($_PPPAempleado[1] == 0){ if($_PPPA[1] == 0){ $_cuerpo .= '<td><input type="number" '.$bloquear.' style="width: 70px; min="0" name="pa'.$row['codigo'].'" placeholder="P.A" step="0.01" value=""></td>'; }else { $_cuerpo .= '<td><input type="number" '.$bloquear.' style="width: 70px; min="0" name="pa'.$row['codigo'].'" placeholder="P.A" step="0.01" value="'.$_PPPA[1].'"></td>'; } }else { $_cuerpo .= '<td class="Aline"></td>'; } }else { $_cuerpo .= '<td class="Aline"></td>'; $_cuerpo .= '<td class="Aline"></td>'; } $_nResultados++; $_cuerpo .= '<td></td></tr>'; } $_cabecera .= "<th>P.P</th><th>P.A</th><th>Firma</th></tr>"; $_cabeceraD .= "</tr>"; if(strlen($_cabeceraD) == 148){ echo '<div style="width: 100%;" class="deep-orange accent-4"><h4 class="center-align" style="padding: 10px; color: white;">No se encontraron resultados !</h4></div>'; }else { echo $_HTML.$_cabeceraD.' '.$_cabecera.' </thead> <tbody> '.$_cuerpo.' </tbody> </table>'; $Fd = substr($_fecha1, 6, 2); $Fm = substr($_fecha1, 4, 2); $Fa = substr($_fecha1, 0, 4); $F2d = substr($_fecha2, 6, 2); $F2m = substr($_fecha2, 4, 2); $F2a = substr($_fecha2, 0, 4); $fecha1 = $Fd."/".$Fm."/".$Fa; $fecha2 = $F2d."/".$F2m."/".$F2a; echo '<input type="hidden" name="Nresul" value="'.$_NumResultado.'"/>'; echo '<input type="hidden" name="f1" value="'.$fecha1.'"/>'; echo '<input type="hidden" name="f2" value="'.$fecha2.'"/>'; echo '<input type="hidden" name="f3" value="'.$fecha1.'"/>'; echo '<input type="hidden" name="f4" value="'.$fecha2.'"/>'; echo '<input type="hidden" name="Ncabecera" value="'.$_NumColumnas.'"/>'; echo '<input type="hidden" name="periodo" value="'.$_periodo.'" id="periodo"/>'; echo '<input type="hidden" name="multiplo" value="'.$FactorA.'"/>'; echo '<input type="hidden" name="pp" value="'.$_PPPA[0].'" id="hPP"/>'; echo '<input type="hidden" name="pa" value="'.$_PPPA[1].'" id="hPA"/>'; echo '<input type="hidden" name="tipoNom" value="'.$_tipoNom.'"/>'; echo $_arrayCabeceraD; echo $_arrayCabeceraF; echo '</form>'; echo $_BTNS; echo '<a class="modal-trigger waves-effect waves-light btn" onclick="modal()" style="margin: 20px;">Conceptos Extras</a>'; } try{ $objBDSQL->liberarC(); $objBDSQL2->cerrarBD(); $objBDSQL->cerrarBD(); }catch(Exception $e){ echo "Error con la BD: ".$e; } ?> <file_sep><?php $objBDSQL = new ConexionSRV(); $objBDSQL->conectarBD(); $objBDSQL2 = new ConexionSRV(); $objBDSQL2->conectarBD(); $bdM = new ConexionM(); $bdM->__constructM(); $BTN = '<button class="btn" id="btnAjusEmp" onclick="GajusteEmple()" style="margin: 20px;">GUARDAR</button>'; if($DepOsub == 1) { $ComSql = "LEFT (Llaves.centro, ".$MascaraEm.") = LEFT ('".$centro."', ".$MascaraEm.")"; $ComSql2 = "LEFT (centro, ".$MascaraEm.") = LEFT ('".$centro."', ".$MascaraEm.")"; }else { $ComSql = "Llaves.centro = '".$centro."'"; $ComSql2 = "centro = '".$centro."'"; } $queryS = " select empleados.codigo, empleados.ap_paterno+' '+empleados.ap_materno+' '+empleados.nombre as Nombre, tabulador.actividad from empleados INNER JOIN Llaves on Llaves.codigo = empleados.codigo INNER JOIN tabulador on tabulador.ocupacion = Llaves.ocupacion and tabulador.empresa = Llaves.empresa where ".$ComSql." AND Llaves.empresa = '".$IDEmpresa."' and empleados.activo = 'S' order by ap_paterno, ap_materno, nombre "; $numCol = $objBDSQL->obtenfilas($queryS); if($numCol > 0){ $queryM = "SELECT * FROM ajusteempleado WHERE ".$ComSql2.";"; $numr = $objBDSQL->obtenfilas($queryM); if($numr >= 1){ $BTN = '<button class="btn" id="btnAjusEmp" onclick="MajusteEmple()" style="margin: 20px;">ACTUALIZAR</button>'; } echo ' <form method="POST" id="frmAjusEmp"> <table class="responsive-table striped highlight centered"> <thead style="background-color: #00b0ff;"> <tr id="CdMas"> <th colspan="3" style="background-color: white;"></th> <th colspan="4" >Omitir Siempre En </th> </tr> <tr> <th>Codigo</th> <th>Nombre</th> <th>Actividad</th> <th class="alTH">PDOM</th> <th class="alTH">DLaborados</th> <th class="alTH">P.A</th> <th class="alTH">P.P</th </tr> </thead> <tbody>'; $objBDSQL->consultaBD($queryS); while ($row = $objBDSQL->obtenResult()){ echo ' <tr> <td>'.$row["codigo"].'</td> <td>'.utf8_decode($row["Nombre"]).'</td> <td>'.$row["actividad"].'</td>'; $consultM = "SELECT PDOM, DLaborados, PA, PP FROM ajusteempleado WHERE IDEmpleado = '".$row["codigo"]."';"; $c1 = ""; $c2 = ""; $c3 = ""; $c4 = ""; $objBDSQL2->consultaBD2($consultM); while ($valorM = $objBDSQL2->obtenResult2()) { if($valorM['PDOM'] == 1){ $c1 = 'checked="checked"'; } else { $c1 = ""; } if($valorM['DLaborados'] == 1){ $c2 = 'checked="checked"'; }else { $c2 = ""; } if($valorM['PA'] == 1){ $c3 = 'checked="checked"'; }else { $c3 = ""; } if($valorM['PP'] == 1){ $c4 = 'checked="checked"'; }else { $c4 = ""; } } echo ' <td><p style="text-align: center;"><input type="checkbox" name="'.$row["codigo"].'[0]" value="1" '.$c1.' id="Q1'.$row["codigo"].'"><label for="Q1'.$row["codigo"].'"></label></p></td> <td><p style="text-align: center;"><input type="checkbox" name="'.$row["codigo"].'[1]" value="1" '.$c2.' id="Q2'.$row["codigo"].'"><label for="Q2'.$row["codigo"].'"></label></p></td> <td><p style="text-align: center;"><input type="checkbox" name="'.$row["codigo"].'[2]" value="1" '.$c3.' id="Q3'.$row["codigo"].'"><label for="Q3'.$row["codigo"].'"></label></p></td> <td><p style="text-align: center;"><input type="checkbox" name="'.$row["codigo"].'[3]" value="1" '.$c4.' id="Q4'.$row["codigo"].'"><label for="Q4'.$row["codigo"].'"></label></p></td> </tr> '; } echo' </tbody> </table> </form> '.$BTN; }else { //echo "NO SE ENCONTRATON RESULTADOS"; echo '<div style="width: 100%" class="deep-orange accent-4"><h6 class="center-align" style="padding-top: 5px; padding-bottom: 5px; color: white;">No se encotro resultado !</h6></div>'; } $objBDSQL->liberarC(); $objBDSQL2->liberarC2(); $objBDSQL->cerrarBD(); $objBDSQL2->cerrarBD(); ?> <file_sep><?php //ConseptosExt $BDM = new ConexionM(); $BDM->__constructM(); $objBDSQL = new ConexionSRV(); $objBDSQL->conectarBD(); $tnomina = $_POST["TN"]; $arrayConExt = array(); $cabExtCon = "<table><thead><tr>"; if($PC <= 24){ $fechas = periodo($PC); list($fecha1,$fecha2,$fecha3,$fecha4) = explode(',', $fechas); } if($tnomina == 1 || $PC > 24){ $_queryFechas = "SELECT CONVERT (VARCHAR (10), inicio, 103) AS 'FECHA1', CONVERT (VARCHAR (10), cierre, 103) AS 'FECHA2' FROM Periodos WHERE tiponom = 1 AND periodo = $PC AND ayo_operacion = $ayoA AND empresa = $IDEmpresa ;"; $_resultados = $objBDSQL->consultaBD($_queryFechas); if($_resultados === false) { die(print_r(sqlsrv_errors(), true)); exit(); }else { $_datos = $objBDSQL->obtenResult(); } $fecha1 = $_datos['FECHA1']; $fecha2 = $_datos['FECHA1']; $objBDSQL->liberarC(); } list($dia, $mes, $ayo) = explode('/', $fecha1); list($dia2, $mes2, $ayo2) = explode('/', $fecha2); $fecha1 = $ayo.$mes.$dia; $fecha2 = $ayo2.$mes2.$dia2; $querySQL1 = "select L.codigo AS Codigo, E.nombre + ' '+E.ap_paterno + ' '+E.ap_materno AS Nombre, E.sueldo,"; $querySQL2 = ""; if($DepOsub == 1){ if($supervisor == 0){ $querySQL3 = " from Llaves AS L INNER JOIN empleados AS E ON E.codigo = L.codigo AND E.empresa = L.empresa LEFT JOIN destajo AS D ON D.Codigo = L.codigo AND D.IDEmpresa = L.empresa AND D.Centro = L.centro AND D.fecha = '".date("Y")."' WHERE L.empresa = ".$IDEmpresa." AND LEFT (L.centro, ".$MascaraEm.") = LEFT ('".$centro."', ".$MascaraEm.") AND L.tiponom = '".$tnomina."' AND E.activo = 'S'"; }else { $querySQL3 = " from Llaves AS L INNER JOIN empleados AS E ON E.codigo = L.codigo AND E.empresa = L.empresa LEFT JOIN destajo AS D ON D.Codigo = L.codigo AND D.IDEmpresa = L.empresa AND D.Centro = L.centro AND D.fecha = '".date("Y")."' WHERE L.empresa = ".$IDEmpresa." AND LEFT (L.centro, ".$MascaraEm.") = LEFT ('".$centro."', ".$MascaraEm.") AND L.supervisor = '".$supervisor."' AND L.tiponom = '".$tnomina."' AND E.activo = 'S'"; } $ComSql2 = "LEFT (Centro, ".$MascaraEm.") = LEFT ('".$centro."', ".$MascaraEm.")"; }else { if($supervisor == 0){ $querySQL3 = " from Llaves AS L INNER JOIN empleados AS E ON E.codigo = L.codigo AND E.empresa = L.empresa LEFT JOIN destajo AS D ON D.Codigo = L.codigo AND D.IDEmpresa = L.empresa AND D.Centro = L.centro AND D.fecha = '".date("Y")."' WHERE L.empresa = ".$IDEmpresa." AND L.centro = '".$centro."' AND L.tiponom = '".$tnomina."' AND E.activo = 'S'"; }else { $querySQL3 = " from Llaves AS L INNER JOIN empleados AS E ON E.codigo = L.codigo AND E.empresa = L.empresa LEFT JOIN destajo AS D ON D.Codigo = L.codigo AND D.IDEmpresa = L.empresa AND D.Centro = L.centro AND D.fecha = '".date("Y")."' WHERE L.empresa = ".$IDEmpresa." AND L.centro = '".$centro."' AND L.supervisor = '".$supervisor."' AND L.tiponom = '".$tnomina."' AND E.activo = 'S' "; } $ComSql2 = "Centro = '".$centro."'"; } $consultaCa = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'destajo'"; $reultadoo = $objBDSQL->consultaBD($consultaCa); //$row = $objBDSQL->obtenResult(); $cabExtCon .= "<th>Codigo</th>"; $cabExtCon .= "<th>Nombre</th>"; $cabExtCon .= "<th>sueldo</th>"; while($datos = $objBDSQL->obtenResult()){ if($datos['COLUMN_NAME'] != "ID" && $datos['COLUMN_NAME'] != "Codigo" && $datos['COLUMN_NAME'] != "Periodo" && $datos['COLUMN_NAME'] != "IDEmpresa" && $datos['COLUMN_NAME'] != "Centro" && $datos['COLUMN_NAME'] != "fecha" ){ $arrayConExt[] = $datos['COLUMN_NAME']; $querySQL2 .= "D.".$datos['COLUMN_NAME'].","; $cabExtCon .= '<th>'.$datos['COLUMN_NAME'].'<i class="close material-icons" style="display: contents; color: red; cursor: pointer;" title="Eliminar" onclick="eliminarColumna(\''.$datos['COLUMN_NAME'].'\')">close</i></th>'; } } $querySQL2 = substr($querySQL2, 0, -1); $cabExtCon .= "</tr></thead>"; $cabExtCon .= "<tbody>"; $objBDSQL->liberarC(); $objBDSQL->consultaBD($querySQL1.$querySQL2.$querySQL3); while ( $row = $objBDSQL->obtenResult() ) { $cabExtCon .= "<tr>"; $cabExtCon .= "<td>".$row['Codigo']."</td>"; $cabExtCon .= "<td>".utf8_encode($row['Nombre'])."</td>"; $cabExtCon .= "<td>".$row['sueldo']."</td>"; foreach ($arrayConExt as $valor) { //$cabExtCon .= "<td>".$row[$valor]."</td>"; if(!empty($row[$valor])){ $cabExtCon .= '<td><input type="text" id="'.$row['Codigo'].$valor.'" value="'.$row[$valor].'" onkeyup="InserConExt(\''.$row['Codigo'].'\', \''.$valor.'\', \''.$row['Codigo'].$valor.'\')" ></td>'; }else { $cabExtCon .= '<td><input type="text" id="'.$row['Codigo'].$valor.'" onkeyup="InserConExt(\''.$row['Codigo'].'\', \''.$valor.'\', \''.$row['Codigo'].$valor.'\')" ></td>'; } } $cabExtCon .= "</tr>"; } $cabExtCon .= "</tbody></table>"; echo $cabExtCon; echo '<input type="hidden" value="1" id="OCV" >'; $objBDSQL->liberarC(); $objBDSQL->cerrarBD(); ?> <file_sep><?php $Mupdate = ""; $Select = ""; $objBDSQL = new ConexionSRV(); $objBDSQL->conectarBD(); $objBDSQL2 = new ConexionSRV(); $objBDSQL2->conectarBD(); $bdM = new ConexionM(); $bdM->__constructM(); if($DepOsub == 1) { $ComSql = "LEFT (llaves.centro, ".$MascaraEm.") = LEFT ('".$centro."', ".$MascaraEm.")"; $ComSql2 = "LEFT (centro, ".$MascaraEm.") = LEFT ('".$centro."', ".$MascaraEm.")"; }else { $ComSql = "llaves.centro = '".$centro."'"; $ComSql2 = "centro = '".$centro."'"; } $query = " select all (empleados.codigo), ltrim (empleados.ap_paterno)+' '+ltrim (empleados.ap_materno)+' '+ltrim (empleados.nombre) , llaves.ocupacion, tabulador.actividad, llaves.horario, MAx (convert(varchar(10),empleados.fchantigua,103)), max(convert(varchar(10),contratos.fchAlta ,103)) , max(convert(varchar(10),contratos.fchterm ,103)) , SUM(contratos.dias) from empleados LEFT join contratos on contratos.empresa = empleados.empresa and contratos.codigo = empleados.codigo INNER JOIN llaves on llaves.empresa = empleados.empresa and llaves.codigo = empleados.codigo INNER JOIN tabulador on tabulador.empresa = llaves.empresa and tabulador.ocupacion = llaves.ocupacion where empleados.activo = 'S' AND ".$ComSql." and llaves.empresa = '".$IDEmpresa."' AND llaves.supervisor = '".$supervisor."' group by empleados.codigo, empleados.ap_paterno, empleados.ap_materno, empleados.nombre, empleados.fchantigua, llaves.ocupacion, tabulador.actividad, llaves.horario "; $objBDSQL->consultaBD($query); while ($row = $objBDSQL->obtenResult()) { $consultaI = "SELECT ID FROM contrato WHERE IDEmpleado = '".$row["codigo"]."' AND IDEmpresa = '".$IDEmpresa."' AND ".$ComSql2.";"; $objBDSQL2->consultaBD2($consultaI); $valorM = $objBDSQL2->obtenResult2(); $objBDSQL2->liberarC2(); if(empty($valorM)){ $name = $row["codigo"]; $option = "NC".$row["codigo"]; if(empty($_POST[$option])){ $Select = "INSERT INTO contrato VALUES ('".$row["codigo"]."', '".$_POST[$name]."', 'vacio', ".$IDEmpresa.", '".$centro."');"; }else { $Select = "INSERT INTO contrato VALUES ('".$row["codigo"]."', '".$_POST[$name]."', '".$_POST[$option]."', ".$IDEmpresa.", '".$centro."');"; } $objBDSQL2->consultaBD2($Select); }else { $consultaII = "SELECT ID FROM contrato WHERE IDEmpleado = '".$row["codigo"]."' AND IDEmpresa = '".$IDEmpresa."' AND ".$ComSql2.";"; $objBDSQL2->consultaBD2($consultaII); while ($valorM = $objBDSQL2->obtenResult2()) { $name = $row["codigo"]; $option = "NC".$row["codigo"]; if($valorM['ID']){ if(empty($_POST[$option])){ $Mupdate = "UPDATE contrato SET IDEmpleado = '".$row["codigo"]."', Observacion = '".$_POST[$name]."', Contrato = 'vacio', IDEmpresa = ".$IDEmpresa.", centro = '".$centro."' WHERE ID = ".$valorM['ID']." AND IDEmpleado = '".$row["codigo"]."' AND IDEmpresa = '".$IDEmpresa."' AND centro = '".$centro."';"; }else { $Mupdate = "UPDATE contrato SET IDEmpleado = '".$row["codigo"]."', Observacion = '".$_POST[$name]."', Contrato = '".$_POST[$option]."', IDEmpresa = ".$IDEmpresa.", centro = '".$centro."' WHERE ID = ".$valorM['ID']." AND IDEmpleado = '".$row["codigo"]."' AND IDEmpresa = '".$IDEmpresa."' AND centro = '".$centro."';"; } $objBDSQL2->consultaBD2($Mupdate); } } } } $Minsert = "UPDATE config SET correo = '".$_POST["correo"]."' WHERE IDUser = '".$_SESSION['IDUser']."'"; $bdM->query($Minsert); $objBDSQL->cerrarBD(); $objBDSQL2->cerrarBD(); echo "1"; ?> <file_sep><?php $objBDSQL = new ConexionSRV(); $objBDSQL->conectarBD(); $objBDSQL2 = new ConexionSRV(); $objBDSQL2->conectarBD(); $NoInsertados = array(); $arcNoinsertaron = "NoInsertaron.txt"; $contarExito = 0; $contarError = 0; $error = $_FILES['Archivo']['error'][0]; if($error == 0){ if(substr($_FILES['Archivo']['name'][0], 0, 12) == substr($arcNoinsertaron, 0, 12)){ move_uploaded_file($_FILES['Archivo']['tmp_name'][0], 'img/' . 'NoInsertaron.txt'); //echo "<script>alert('El archivo es de revicion');</script>"; $ArchivoTxt0 = fopen("img/NoInsertaron.txt", "r"); while(!feof($ArchivoTxt0)){ $linea = fgets($ArchivoTxt0); $lnk = explode(",", $linea); if(isset($lnk[1])){ $consulta = "SELECT L.empresa FROM Llaves AS L INNER JOIN empleados AS E ON E.codigo = L.codigo WHERE L.codigo = ".$lnk[1]." AND E.activo = 'S'"; $resultado = $objBDSQL->consultaBD($consulta); $datos = $objBDSQL->obtenResult(); if(!empty($datos)){ $NumEmpresa = $datos['empresa']; $FLNK = str_replace('-', '', $lnk[2]); //$checadaEntrada = "ObtenRelojDatosEmps ".$NumEmpresa.", ".$lnk[1].", ".$FLNK.", ".$lnk[3].", 'N', ' ', ' '"; $checadaEntrada = "ObtenRelojDatosEmps 2, ".$lnk[1].", ".$FLNK.", ".$lnk[3].", 'N', ' ', ' '"; try { $insertChecada = $objBDSQL2->consultaBD2($checadaEntrada); } catch (Exception $e){ var_dump($e->getMessage()); $contarError++; } $contarExito++; }else { $NoInsertados[$lnk[1].$lnk[2].$lnk[3]] = "ObtenRelojDatosEmps X, ".$lnk[1].", '".$lnk[2]."', '".$lnk[3]."', 'N', ' ', ' '"; $contarError++; } $objBDSQL->liberarC(); } } echo "SE IMPORTARON ".$contarExito." REGISTROS EXITOSAMENTE"; echo "<br>"; if(count($NoInsertados)>0){ $file = fopen($arcNoinsertaron, "w") or die("Error al abrir el archivo"); echo "NO SE INPORTARON ALGUNOS REGISTROS(".$contarError.") (cambiar la 'X' por el numero de empresa) <a href='".$arcNoinsertaron."' download='".$arcNoinsertaron."'>Descargar Archivo</a>"; echo "<br>"; foreach ($NoInsertados as $Valor) { fwrite($file, $Valor.PHP_EOL); } fclose($file); } }else { move_uploaded_file($_FILES['Archivo']['tmp_name'][0], 'img/' . 'checadas.txt'); $ArchivoTxt0 = fopen("img/checadas.txt", "r"); while(!feof($ArchivoTxt0)){ $linea = fgets($ArchivoTxt0); $ln = trim($linea); //echo $ln."<br>"; //$lnk = explode("\t", $ln); ///ARCHIVO DE AYUNTAMIENTO $lnk = explode(",", $ln); $array = array(); for ($i=0; $i < count($lnk); $i++) { $array[$i] = $lnk[$i]; //echo $lnk[$i]."<br>"; } if(isset($array[1]) && isset($array[0])){ $ln1 = explode(" ", $array[1]); $consulta = "SELECT L.empresa FROM Llaves AS L INNER JOIN empleados AS E ON E.codigo = L.codigo WHERE L.codigo = ".$array[0]." AND E.activo = 'S'"; $resultado = $objBDSQL->consultaBD($consulta); $datos = $objBDSQL->obtenResult(); if(!empty($datos)){ //$NumEmpresa = $datos['empresa']; $FLNK = str_replace('/', '', $ln1[0]); //$checadaEntrada = "ObtenRelojDatosEmps ".$NumEmpresa.", ".$array[0].", '".$FLNK."', '".$ln1[1]."', 'N', ' ', ' '"; $checadaEntrada = "ObtenRelojDatosEmps 2, ".$array[0].", '".$FLNK."', '".$ln1[1]."', 'N', ' ', ' '"; try { $insertChecada = $objBDSQL2->consultaBD2($checadaEntrada); } catch (Exception $e){ var_dump($e->getMessage()); $contarError++; } $contarExito++; }else { $NoInsertados[$array[0].$ln1[0].$ln1[1]] = "ObtenRelojDatosEmps X, ".$array[0].", '".$ln1[0]."', '".$ln1[1]."', 'N', ' ', ' '"; $contarError++; } $objBDSQL->liberarC(); } } echo "SE IMPORTARON ".$contarExito." REGISTROS EXITOSAMENTE"; echo "<br>"; if(count($NoInsertados)>0){ $file = fopen($arcNoinsertaron, "w") or die("Error al abrir el archivo"); echo "NO SE INPORTARON ALGUNOS REGISTROS(".$contarError.") (cambiar la 'X' por el numero de empresa) <a href='".$arcNoinsertaron."' download='".$arcNoinsertaron."'>Descargar Archivo</a>"; echo "<br>"; foreach ($NoInsertados as $Valor) { fwrite($file, $Valor.PHP_EOL); //echo $Valor; //echo "<br>"; } fclose($file); } } echo "<br>"; echo "<br>"; echo "<br>"; //echo "<h3 class='center'>El archivos se ha subidos correctamente</h3>"; }else { echo "<h3 class='center'>Error al subir el archivo</h3>"; } try{ $objBDSQL->cerrarBD(); $objBDSQL2->cerrarBD(); }catch(Exception $e){ echo "Error con la BD: ".$e; } ?> <file_sep><?php $objBDSQL = new ConexionSRV(); $objBDSQL->conectarBD(); $BDM = new ConexionM(); $BDM->__constructM(); $codigo = $_POST["codigo"]; $valor = $_POST["valor"]; $fecha = $_POST["fecha"]; $PRio = $_POST["periodo"]; $Ttn = $_POST["tn"]; $centroE = $centro; $valor = strtoupper($valor); $result = array(); $result['error'] = 0; if($DepOsub == 1){ $ComSql = "LEFT (Centro, ".$MascaraEm.") = LEFT('".$centro."', ".$MascaraEm.")"; }else { $ComSql = "Centro = '".$centro."'"; } $consulta = "SELECT valor FROM datos WHERE codigo = '$codigo' AND nombre = '$fecha' AND periodoP = '$PRio' AND tipoN = '$Ttn' AND IDEmpresa = '$IDEmpresa' AND $ComSql;"; if($objBDSQL->consultaBD($consulta) == 1){ $result['error'] = 1; $objBDSQL->cerrarBD(); echo json_encode($result); exit(); } $row = $objBDSQL->obtenResult(); $objBDSQL->liberarC(); /** * Consultar centro del empleado */ $consultaCentroEmp = "SELECT TOP 1 LTRIM(RTRIM(centro)) AS centro FROM Llaves WHERE codigo = '$codigo' AND empresa = '$IDEmpresa' AND tiponom = '$Ttn'"; if($objBDSQL->consultaBD($consultaCentroEmp) == 1){ $result['error'] = 1; $objBDSQL->cerrarBD(); echo json_encode($result); exit(); } $rowCentro = $objBDSQL->obtenResult(); if(!empty($rowCentro)){ $centroE = $rowCentro['centro']; } $objBDSQL->liberarC(); /** * Verificar si existen datos en la consulta */ if(!empty($row)){ if($row['valor'] == "F"){ $consultaUser = "SELECT ID FROM usuarios WHERE User = '".Autoriza1."';"; $queryUser = $BDM->query($consultaUser); $resultUser = $BDM->recorrer($queryUser); /** * Insertar registro en notificacion, se ha modificado una falta */ $inserAlert = "INSERT INTO notificaciones VALUES (NULL, '".$_SESSION['IDUser']."', '$resultUser[0]', 'SE ELIMINO FALTA DE ".$codigo."', '', '0');"; if(!$BDM->query($inserAlert)){ $file = fopen("log/log".date("d-m-Y").".txt", "a"); fwrite($file, ":::::::::::::::::ERROR MYSQL:::::::::::::::::::::".PHP_EOL); fwrite($file, '['.date('d/m/Y h:i:s A').']'.' - '.$BDM->errno. ' '.$BDM->error.PHP_EOL); fwrite($file, '['.date('d/m/Y h:i:s A').']'.' - CONSULTA: '.$INSERALERTA); fclose($file); } } /** * Actualizar Datos en la Tabla Datos */ $update = "UPDATE datos SET valor = '$valor' WHERE codigo = '$codigo' AND nombre = '$fecha' AND periodoP = '$PRio' AND tipoN = '$Ttn' AND IDEmpresa = '$IDEmpresa' AND Centro = '$centroE';"; $consulta = $objBDSQL->consultaBD($update); if($consulta == 1){ $result['error'] = 1; $objBDSQL->cerrarBD(); echo json_encode($result); exit(); } }else { /** * Insertar registro en la tabla Datos */ $insert = "INSERT INTO datos VALUES ('$codigo', '$fecha', '$valor', '$PRio', '$Ttn', '$IDEmpresa', '$centroE');"; if($objBDSQL->consultaBD($insert) == 1){ $result['error'] = 1; $objBDSQL->cerrarBD(); echo json_encode($result); exit(); } } try{ $BDM->close(); $objBDSQL->cerrarBD(); }catch(Exception $e){ $resultV['error'] = 1; $file = fopen("log/log".date("d-m-Y").".txt", "a"); fwrite($file, ":::::::::::::::::::::::ERROR BD:::::::::::::::::::::::".PHP_EOL); fwrite($file, '['.date('d/m/Y h:i:s A').']'.' - ERROR al cerrar la conexion con SQL SERVER'.PHP_EOL); fwrite($file, '['.date('d/m/Y h:i:s A').']'.' - '.$e->getMessage().PHP_EOL); fclose($file); } echo json_encode($result); exit(); ?><file_sep><?php $periodo = $PC; $objBDSQL = new ConexionSRV(); $objBDSQL->conectarBD(); if($periodo <= 24){ $_fechas = periodo($periodo); list($fecha1, $fecha2, $fecha3, $fecha4) = explode(',', $_fechas); } if($TN == 1 || $periodo > 24){ $_queryFechas = "SELECT CONVERT (VARCHAR (10), inicio, 103) AS 'FECHA1', CONVERT (VARCHAR (10), cierre, 103) AS 'FECHA2' FROM Periodos WHERE tiponom = 1 AND periodo = $periodo AND ayo_operacion = $ayoA AND empresa = $IDEmpresa ;"; $_resultados = $objBDSQL->consultaBD($_queryFechas); if($_resultados === false) { die(print_r(sqlsrv_errors(), true)); exit(); }else { $_datos = $objBDSQL->obtenResult(); } $fecha1 = $_datos['FECHA1']; $fecha2 = $_datos['FECHA2']; $fecha3 = $_datos['FECHA1']; $fecha4 = $_datos['FECHA2']; $objBDSQL->liberarC(); } ?> <h4 style="text-align: center;"><?php echo $NomDep; ?></h4> <h5 style="text-align: center;">ROL DE HORARIO</h5> <div> <center> <?php $numMESS = substr($fecha2, 3, 2); if($numMESS < 9){ $numMESS = substr($fecha2, 4, 1); } $ayoF = substr($fecha2, 6, 4); $mesF = substr($fecha2, 3, 2); $diaF = substr($fecha2, 0, 2); ?> <p>DEL <input style="width: 64px; background-color: white; text-align: center;" id="Dia" type="number" min="1" max="31" value="<?php echo substr($fecha1, 0, 2);?>" /> AL <input style="width: 64px; background-color: white; text-align: center;" id="Dia2" type="number" min="1" max="31" value="<?php echo substr($fecha2, 0, 2); ?>" /> DE <select style="width: auto;" id="Mes"> <option value="<?php echo $MESES[$numMESS];?>"><?php echo $MESES[$numMESS];?></option> <option value="<?php $diamas = date($ayoF."/".$mesF."/".$diaF); echo $MESES[date("n", strtotime($diamas." + 1 month"))]; ?>"><?php echo $MESES[date("n", strtotime($diamas." + 1 month"))]; ?></option> <option value="<?php echo $MESES[date("n", strtotime($diamas." + 2 month"))]; ?>"><?php echo $MESES[date("n", strtotime($diamas." + 2 month"))]; ?></option> <option value="<?php echo $MESES[date("n", strtotime($diamas." + 3 month"))]; ?>"><?php echo $MESES[date("n", strtotime($diamas." + 3 month"))]; ?></option> <option value="<?php echo $MESES[date("n", strtotime($diamas." + 4 month"))]; ?>"><?php echo $MESES[date("n", strtotime($diamas." + 4 month"))]; ?></option> <option value="<?php echo $MESES[date("n", strtotime($diamas." + 5 month"))]; ?>"><?php echo $MESES[date("n", strtotime($diamas." + 5 month"))]; ?></option> <option value="<?php echo $MESES[date("n", strtotime($diamas." + 6 month"))]; ?>"><?php echo $MESES[date("n", strtotime($diamas." + 6 month"))]; ?></option> <option value="<?php echo $MESES[date("n", strtotime($diamas." + 7 month"))]; ?>"><?php echo $MESES[date("n", strtotime($diamas." + 7 month"))]; ?></option> <option value="<?php echo $MESES[date("n", strtotime($diamas." + 8 month"))]; ?>"><?php echo $MESES[date("n", strtotime($diamas." + 8 month"))]; ?></option> <option value="<?php echo $MESES[date("n", strtotime($diamas." + 9 month"))]; ?>"><?php echo $MESES[date("n", strtotime($diamas." + 9 month"))]; ?></option> <option value="<?php echo $MESES[date("n", strtotime($diamas." + 10 month"))]; ?>"><?php echo $MESES[date("n", strtotime($diamas." + 10 month"))]; ?></option> <option value="<?php echo $MESES[date("n", strtotime($diamas." + 11 month"))]; ?>"><?php echo $MESES[date("n", strtotime($diamas." + 11 month"))]; ?></option> </select> DEL <input style="width: 64px; background-color: white; text-align: center;" id="Ayo" type="number" value="<?php echo $ayoA;?>" /> </p> </center> </div> <div class="modal " id="modal1" style="text-align: center; padding-top: 10px;"> <h4 id="textCargado">Procesando...</h4> <div class="progress"> <div class="indeterminate"></div> </div> </div> <div id="estado_consulta_ajax"> <?php $ihidden = ""; if($DepOsub == 1) { $querySQL = "[dbo].[roldehorarioEmp] '".$IDEmpresa."', '".$centro."', '1'"; }else { $querySQL = "[dbo].[roldehorarioEmp] '".$IDEmpresa."', '".$centro."', '0'"; } $numCol = $objBDSQL->obtenfilas($querySQL); if($numCol > 0){ echo ' <form id="frmRol" method="POST"> <input type="hidden" name="centro" value="'.$centro.'" > <table id="tRH" class="responsive-table striped highlight centered" style="border: 1px solid #000080;"> <thead> <tr> <th style="border-right: 1px solid black; background-color: #0091ea; color: white; border-bottom: 1px solid #696666;">Codigo</th> <th style="border-right: 1px solid black; background-color: #0091ea; color: white; border-bottom: 1px solid #696666;">Nombre</th> <th id="TRolH" style="border-right: 1px solid black; background-color: #0091ea; color: white; border-bottom: 1px solid #696666;">Horario</th> <th style="border-right: 1px solid black; background-color: #0091ea; color: white; border-bottom: 1px solid #696666;">Descripcion</th> <th style="border-right: 1px solid black; background-color: #0091ea; color: white; border-bottom: 1px solid #696666;">Lunes</th> <th style="border-right: 1px solid black; background-color: #0091ea; color: white; border-bottom: 1px solid #696666;">Martes</th> <th style="border-right: 1px solid black; background-color: #0091ea; color: white; border-bottom: 1px solid #696666;">Miercoles</th> <th style="border-right: 1px solid black; background-color: #0091ea; color: white; border-bottom: 1px solid #696666;">Jueves</th> <th style="border-right: 1px solid black; background-color: #0091ea; color: white; border-bottom: 1px solid #696666;">Viernes</th> <th style="border-right: 1px solid black; background-color: #0091ea; color: white; border-bottom: 1px solid #696666;">Sabado</th> <th style="background-color: #0091ea; color: white;">Domingo</th> </tr> </thead><tbody>'; $objBDSQL->consultaBD($querySQL); $lr = 0; while ( $row = $objBDSQL->obtenResult() ) { $lr++; $ihidden .= '<input type="hidden" name="c'.$lr.'" value="'.$row["codigo"].'">'; echo '<tr> <td style="border-left: 1px solid #696666; border-bottom: 1px solid #696666;" >'.$row["codigo"].'</td> <td style="border-left: 1px solid #696666; border-bottom: 1px solid #696666;" >'.utf8_encode($row["nomE"]).'</td> <td style="text-align: center; border-left: 1px solid #696666; border-bottom: 1px solid #696666;"><div onclick="cambiar'.$lr.'()" class="controlgroup"><input style="width: 100%; margin: 0;" min="1" class="ui-spinner-input" value ="'.$row["Horario"].'" name="inp'.$lr.'" id="'.$lr.'" onkeyup="cambiar'.$lr.'()" onclick="cambiar'.$lr.'()"></div></td> <td style="border-left: 1px solid #696666; border-bottom: 1px solid #696666;" id="des'.$lr.'">'.utf8_encode($row["Nombre"]).'</td> '; if($row["LUN"] == "DESCANSO"){ echo '<td style="background-color: #f9ff00; border-left: 1px solid #696666; border-bottom: 1px solid #696666;" id="l'.$lr.'">'.$row["LUN"].'</td>'; }else { echo '<td style="border-left: 1px solid #696666; border-bottom: 1px solid #696666;" id="l'.$lr.'">'.$row["LUN"].'</td>'; } if($row["MAR"] == "DESCANSO"){ echo '<td style="background-color: #f9ff00; border-left: 1px solid #696666; border-bottom: 1px solid #696666;" id="m'.$lr.'">'.$row["LUN"].'</td>'; }else { echo '<td style="border-left: 1px solid #696666; border-bottom: 1px solid #696666;" id="m'.$lr.'">'.$row["MAR"].'</td>'; } if($row["MIE"] == "DESCANSO"){ echo '<td style="background-color: #f9ff00; border-left: 1px solid #696666; border-bottom: 1px solid #696666;" id="i'.$lr.'">'.$row["LUN"].'</td>'; }else { echo '<td style="border-left: 1px solid #696666; border-bottom: 1px solid #696666;" id="i'.$lr.'">'.$row["MIE"].'</td>'; } if($row["JUE"] == "DESCANSO"){ echo '<td style="background-color: #f9ff00; border-left: 1px solid #696666; border-bottom: 1px solid #696666;" id="j'.$lr.'">'.$row["LUN"].'</td>'; }else { echo '<td style="border-left: 1px solid #696666; border-bottom: 1px solid #696666;" id="j'.$lr.'">'.$row["JUE"].'</td>'; } if($row["VIE"] == "DESCANSO"){ echo '<td style="background-color: #f9ff00; border-left: 1px solid #696666; border-bottom: 1px solid #696666;" id="v'.$lr.'">'.$row["LUN"].'</td>'; }else { echo '<td style="border-left: 1px solid #696666; border-bottom: 1px solid #696666;" id="v'.$lr.'">'.$row["VIE"].'</td>'; } if($row["SAB"] == "DESCANSO"){ echo '<td style="background-color: #f9ff00; border-left: 1px solid #696666; border-bottom: 1px solid #696666;" id="s'.$lr.'">'.$row["LUN"].'</td>'; }else { echo '<td style="border-left: 1px solid #696666; border-bottom: 1px solid #696666;" id="s'.$lr.'">'.$row["SAB"].'</td>'; } if($row["DOM"] == "DESCANSO"){ echo '<td style="background-color: #f9ff00; border-left: 1px solid #696666; border-bottom: 1px solid #696666;" id="d'.$lr.'">'.$row["LUN"].'</td>'; }else { echo '<td style="border-left: 1px solid #696666; border-bottom: 1px solid #696666;" id="d'.$lr.'">'.$row["DOM"].'</td>'; } echo '</tr>'; } echo '</tbody></table><input type="hidden" name="cantidad" value="'.$lr.'">'.$ihidden.'</form>'; echo '<button class="waves-effect waves-light btn" style="margin: 10px;" onclick="Rol()">GUARDAR</button>'; echo '<script type="text/javascript">'; for($jh=1; $jh<=$lr; $jh++){ echo 'function cambiar'.$jh.'() { var numero; numero = document.getElementById("'.$jh.'").value; numero = Number(numero); switch (numero) { '; for ($j=1; $j<=$iDH; $j++){ echo' case '.$j.': document.getElementById("des'.$jh.'").innerHTML = "'.$DesHora[$j].'"; document.getElementById("l'.$jh.'").innerHTML = "'.$Lun[$j].'";'; if($Lun[$j] == "DESCANSO"){ echo 'document.getElementById("l'.$jh.'").style.background = \'#f9ff00\';'; }else { echo 'document.getElementById("l'.$jh.'").style.background = \'#ffffff\';'; } echo 'document.getElementById("m'.$jh.'").innerHTML = "'.$Mar[$j].'";'; if($Mar[$j] == "DESCANSO"){ echo 'document.getElementById("m'.$jh.'").style.background = \'#f9ff00\';'; }else { echo 'document.getElementById("m'.$jh.'").style.background = \'#ffffff\';'; } echo 'document.getElementById("i'.$jh.'").innerHTML = "'.$Mie[$j].'";'; if($Mie[$j] == "DESCANSO"){ echo 'document.getElementById("i'.$jh.'").style.background = \'#f9ff00\';'; }else { echo 'document.getElementById("i'.$jh.'").style.background = \'#ffffff\';'; } echo 'document.getElementById("j'.$jh.'").innerHTML = "'.$Jue[$j].'";'; if($Jue[$j] == "DESCANSO"){ echo 'document.getElementById("j'.$jh.'").style.background = \'#f9ff00\';'; }else { echo 'document.getElementById("j'.$jh.'").style.background = \'#ffffff\';'; } echo 'document.getElementById("v'.$jh.'").innerHTML = "'.$Vie[$j].'";'; if($Vie[$j] == "DESCANSO"){ echo 'document.getElementById("v'.$jh.'").style.background = \'#f9ff00\';'; }else { echo 'document.getElementById("v'.$jh.'").style.background = \'#ffffff\';'; } echo 'document.getElementById("s'.$jh.'").innerHTML = "'.$Sab[$j].'";'; if($Sab[$j] == "DESCANSO"){ echo 'document.getElementById("s'.$jh.'").style.background = \'#f9ff00\';'; }else { echo 'document.getElementById("s'.$jh.'").style.background = \'#ffffff\';'; } echo 'document.getElementById("d'.$jh.'").innerHTML = "'.$Dom[$j].'";'; if($Dom[$j] == "DESCANSO"){ echo 'document.getElementById("d'.$jh.'").style.background = \'#f9ff00\';'; }else { echo 'document.getElementById("d'.$jh.'").style.background = \'#ffffff\';'; } echo ' break;'; } echo ' default: alert ("Horario no valido"); document.getElementById("des'.$jh.'").innerHTML = "'.$DesHora[1].'"; document.getElementById("l'.$jh.'").innerHTML = "'.$Lun[1].'";'; if($Lun[1] == "DESCANSO"){ echo 'document.getElementById("l'.$jh.'").style.background = \'#f9ff00\';'; }else { echo 'document.getElementById("l'.$jh.'").style.background = \'#ffffff\';'; } echo 'document.getElementById("m'.$jh.'").innerHTML = "'.$Mar[1].'";'; if($Mar[1] == "DESCANSO"){ echo 'document.getElementById("m'.$jh.'").style.background = \'#f9ff00\';'; }else { echo 'document.getElementById("m'.$jh.'").style.background = \'#ffffff\';'; } echo 'document.getElementById("i'.$jh.'").innerHTML = "'.$Mie[1].'";'; if($Mie[1] == "DESCANSO"){ echo 'document.getElementById("i'.$jh.'").style.background = \'#f9ff00\';'; }else { echo 'document.getElementById("i'.$jh.'").style.background = \'#ffffff\';'; } echo 'document.getElementById("j'.$jh.'").innerHTML = "'.$Jue[1].'";'; if($Jue[1] == "DESCANSO"){ echo 'document.getElementById("j'.$jh.'").style.background = \'#f9ff00\';'; }else { echo 'document.getElementById("j'.$jh.'").style.background = \'#ffffff\';'; } echo 'document.getElementById("v'.$jh.'").innerHTML = "'.$Vie[1].'";'; if($Vie[1] == "DESCANSO"){ echo 'document.getElementById("v'.$jh.'").style.background = \'#f9ff00\';'; }else { echo 'document.getElementById("v'.$jh.'").style.background = \'#ffffff\';'; } echo 'document.getElementById("s'.$jh.'").innerHTML = "'.$Sab[1].'";'; if($Sab[1] == "DESCANSO"){ echo 'document.getElementById("s'.$jh.'").style.background = \'#f9ff00\';'; }else { echo 'document.getElementById("s'.$jh.'").style.background = \'#ffffff\';'; } echo 'document.getElementById("d'.$jh.'").innerHTML = "'.$Dom[1].'";'; if($Dom[1] == "DESCANSO"){ echo 'document.getElementById("d'.$jh.'").style.background = \'#f9ff00\';'; }else { echo 'document.getElementById("d'.$jh.'").style.background = \'#ffffff\';'; } echo ' document.getElementById("'.$jh.'").value = "1"; break; } }; '; } echo '</script>'; }else { //echo 'No se encontraron resultados'; echo '<div style="width: 100%" class="deep-orange accent-4"><h6 class="center-align" style="padding-top: 5px; padding-bottom: 5px; color: white;">No se encotro resultado !</h6></div>'; } $objBDSQL->liberarC(); $objBDSQL->cerrarBD(); ?> </div> <script src="js/procesos/Rol.js"></script> <file_sep>$(document).ready(function () { Retardos(); }); function cambiarPeriodo(){ var conexion, variables, Periodo, tn; Periodo = document.getElementById('periodo').value; tn = document.getElementById('tiponom').value; if(Periodo != ''){ variables = 'periodo='+Periodo+'&TN='+tn; conexion = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); conexion.onreadystatechange = function() { if(conexion.readyState == 4 && conexion.status == 200){ conexion.responseText = conexion.responseText.replace(/\ufeff/g, ''); if(conexion.responseText == 'Error'){ document.getElementById('estado_consulta_ajax').innerHTML = '<div style="width: 100%" class="deep-orange accent-4"><h6 class="center-align" style="padding-top: 5px; padding-bottom: 5px; color: white;">No hay fecha de este periodo !</h6></div>'; } else { var fechaJSON = JSON.parse(conexion.responseText); document.getElementById('fchI').value = fechaJSON.fecha1; document.getElementById('fchF').value = fechaJSON.fecha2; document.getElementById('fchP_I').value = fechaJSON.fecha3; document.getElementById('fchP_F').value = fechaJSON.fecha4; document.getElementById('btnT').disabled = false; } }else if(conexion.readyState != 4){ document.getElementById('btnT').disabled = true; } } conexion.open('POST', 'ajax.php?modo=periodo', true); conexion.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); conexion.send(variables); }else { document.getElementById('estado_consulta_ajax').innerHTML = '<div style="width: 100%" class="deep-orange accent-4"><h6 class="center-align" style="padding-top: 5px; padding-bottom: 5px; color: white;">Todos los datos deben estar llenos !</h6></div>'; } } function Retardos() { var conexion, variables, Periodo, Tn, resultado; Periodo = document.getElementById('periodo').value; Tn = document.getElementById('tiponom').value; variables = "Pr="+Periodo+"&Tn="+Tn; conexion = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); conexion.onreadystatechange = function() { if(conexion.readyState == 4 && conexion.status == 200) { document.getElementById('estado_consulta_ajax').innerHTML = conexion.responseText; var Dimensiones = AHD(); if(Dimensiones[3] > Dimensiones[1]){ $('#pie').css("position", "inherit"); }else { $('#pie').css("position", "absolute"); } }else if(conexion.readyState != 4){ resultado = '<div class="progress">'; resultado += '<div class="indeterminate"></div>'; resultado += '</div>'; document.getElementById('pie').style.position = 'absolute'; document.getElementById('estado_consulta_ajax').innerHTML = resultado; } } conexion.open('POST', 'ajax.php?modo=Retardos', true); conexion.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); conexion.send(variables); } function GRetardos() { var conexion, variables, Tn, Periodo; Tn = document.getElementById('tiponom').value; Periodo = document.getElementById('periodo').value; variables = $('#frmRetardos').serialize(); variables += "&Tn="+Tn+"&Periodo="+Periodo; conexion = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); conexion.onreadystatechange = function() { if(conexion.readyState == 4 && conexion.status == 200) { conexion.responseText = conexion.responseText.replace(/\ufeff/g, ''); if(conexion.responseText == 1) { document.getElementById('textCargado').innerHTML = "EL ARCHIVO SE HA GENERADO CON EXITO"; setTimeout(function() { $("#modal1").modal('close'); document.getElementById('textCargado').innerHTML = "Procesando..."; }, 1500); }else { document.getElementById('textCargado').innerHTML = conexion.responseText; /*setTimeout(function() { $("#modal1").modal('close'); document.getElementById('textCargado').innerHTML = "Procesando..."; }, 2000);*/ } }else if(conexion.readyState != 4) { document.getElementById('textCargado').innerHTML = "Procesando..."; $("#modal1").modal('open'); } } conexion.open('POST', 'ajax.php?modo=GRetardos', true); conexion.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); conexion.send(variables); } function GenerarExcel(){ var fecha1 = document.getElementById('fchI').value; var fecha2 = document.getElementById('fchF').value; $.ajax({ method: 'POST', url: 'ajax.php?modo=GenerarExcel', data: "tipo=retardos&"+"fecha1="+fecha1+"&fecha2="+fecha2, beforeSend: function(){ $('#textCargado').html("Procesando..."); $('#modal1').modal('open'); } }).done(function(datosC){ datosC = datosC.replace(/\ufeff/g, ''); if(datosC == '1'){ $('#textCargado').html("ARCHIVO GENERADO"); }else{ $('#textCargado').html("ERROR AL GENERAR EL ARCHIVO"); } }).fail(function(retorno){ $('#textCargado').html(retorno); }).always(function(){ setTimeout(function(){ $('#textCargado').html("Procesando..."); $('#modal1').modal('close'); }, 1500); }); } <file_sep>ALTER TABLE config ADD FoC SMALLINT(1) NOT NULL AFTER `supervisor`;
091d4f8d0d7f97b246dc527bb0e19db238d5b523
[ "JavaScript", "SQL", "PHP" ]
23
PHP
adicto969/PrenominaWeb
9082db4439a21eb4d96c114c7959d01abe8e855d
eb4c5e1bafcc849105851f9ae75260f1f0a86241
refs/heads/main
<repo_name>wany0530/Programmers_Algorithm<file_sep>/src/main/java/K번째수/K_number.java package main.java.K번째수; import java.util.ArrayList; public class K_number { int array[] = { 1, 5, 2, 6, 3, 7, 4 }; int commands[][] = { { 2, 5, 3 }, { 4, 4, 1 }, { 1, 7, 3 } }; public static void main(String[] args) { K_number a = new K_number(); // 결과가 몇개인지. int i; // 결과 갯수만큼 돌리기 for (i = 0; i < a.commands.length; i++) { int first = a.commands[i][0] - 1; int last = a.commands[i][1] - 1; int pick = a.commands[i][2] - 1; for (int x = first; x <= last; x++) { System.out.print(a.array[x]); } System.out.println(""); } } } <file_sep>/README.md # Programmers 100문제 도전 src/java/main에 위치 #### 2021-05-09 15:41 첫번째 문제 : 폰켓몬 문제(완료)
8223dbd5f0ba2dd7d12589aa4a1456f874df94dd
[ "Markdown", "Java" ]
2
Java
wany0530/Programmers_Algorithm
5ae4660cb721219be0e415afd1972d67c49b2ce4
ed5ccdc6d454a2b5385fa0dbf21c216af19f8271
refs/heads/master
<repo_name>peizhouyu/twchat<file_sep>/src/main/java/cn/mrpei/App.java package cn.mrpei; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.context.annotation.Bean; /** * @author peizhouyu (大数据与智能供应链事业部-大数据平台部-平台产品研发部) * @version V1.0.0 * @description * @date 2019/4/9 * @last-modified: * @class cn.mrpei.controller * @copyright Copyright © 2004-2019 京东JD.com ALL Right Reserved * @see */ @SpringBootApplication public class App { // @Bean // public TomcatServletWebServerFactory servletContainer(){ // return new TomcatServletWebServerFactory(80) ; // } public static void main(String[] args) { SpringApplication.run(App.class, args); } }
e0cdf150956fede4998205f8197974b9e27383c6
[ "Java" ]
1
Java
peizhouyu/twchat
f4cd20fcaff1ec277dc192c2d710f3073657f374
e942ddb69caf61a185b00f1375fc551749b827d9
refs/heads/master
<repo_name>beemfx/Beem.Media<file_sep>/games/Explor2002/Source_Old/ExplorED DOS/dosexplored/Readme.txt ===================================================== === ExplorED: Copyright (c) 2001, <NAME> === ===================================================== This folder contains: Binread.exe: Dumps a copy of Binary int's on the screen Explored.exe: Explor Map Editor Find.exe: Nothing Egavga.bgi: Graphics Drivers Binread.c: source for binread explor.c: nothing find.c: nothing explored.h: header for explored fcopy.h: obsolete graph.h: graphic driver loader for explor explored.ico: icon for explored explor.ide: nothing explored.ide: program project for explored find.ide: nothing getimage.c: nothing *.map: maps generated by ExplorED readme.txt: your looking at it This is ExplorED the map editor for explor. It is completely useless unless you have the game explor. Even then I don't know why you'd make a custom map. Leave map making to the game designers. This software is still in development anyway. For more technical details about explor and explorED look at teh source code.<file_sep>/games/Legacy-Engine/Source/lc_sys2/lc_sys2_ANSI.cpp #include <stdarg.h> #include <stdio.h> #include <string.h> #include "lc_con.h" #include "common.h" #include "lg_string.h" lg_char CConsole::s_szTemp[LC_MAX_LINE_LEN+1]; lg_char CConsole::s_szTemp2[LC_MAX_LINE_LEN+1]; //lg_char CConsole::s_szArgs[sizeof(lg_char)*(LC_MAX_CMD_ARGS+1)+LC_MAX_LINE_LEN+1]; CConsole::LC_ARGS CConsole::s_Args; CConsole::CConsole(): m_pNewestLine(LG_NULL), m_pOldestLine(LG_NULL), m_nLineCount(0), m_nGetLineMode(GET_NONE), m_pGetLine(LG_NULL), m_pCmdExtra(LG_NULL), m_pfnCmd(LG_NULL), m_nActiveCursorPos(0) { m_szActiveLine[0]=0; } CConsole::~CConsole() { Clear(); } const lg_char* CConsole::GetActiveLine() { return m_szActiveLine; } void CConsole::OnChar(lg_char c) { switch(c) { case '\r': SendCommand(m_szActiveLine); m_szActiveLine[0]=0; m_nActiveCursorPos=0; break; case '\b': if(m_nActiveCursorPos==0) break; m_szActiveLine[--m_nActiveCursorPos]=0; break; case '\n': break; case '\t': OnChar(' '); OnChar(' '); OnChar(' '); break; default: m_szActiveLine[m_nActiveCursorPos++]=c; if(m_nActiveCursorPos>=LC_MAX_LINE_LEN) m_nActiveCursorPos=LC_MAX_LINE_LEN-1; m_szActiveLine[m_nActiveCursorPos]=0; break; } } void CConsole::ListCommands() { Print("Registered commands:"); for(lg_dword i=0; i<LC_DEF_HASH_SIZE; i++) { if(!m_Commands.m_pHashList[i].bDefined) continue; CDefs::DEF* pDef=&m_Commands.m_pHashList[i]; while(pDef) { Printf(" %s", pDef->szDef); pDef=pDef->pHashNext; } } } lg_bool CConsole::RegisterCommand(const lg_char* szCommand, lg_dword nID, const lg_char* szHelpString) { if(!m_Commands.AddDef(szCommand, nID, LC_DEF_NOREDEFINE)) { Printf("LC WARNING: \"%s\" is already a registered command.", szCommand); return LG_FALSE; } return LG_TRUE; } void CConsole::SetCommandFunc(LC_CMD_FUNC pfn, lg_void* pExtra) { m_pfnCmd=pfn; m_pCmdExtra=pExtra; } const lg_char* CConsole::GetLine(lg_dword nRef, const lg_bool bStartWithNew) { m_pGetLine=bStartWithNew?m_pNewestLine:m_pOldestLine; m_nGetLineMode=bStartWithNew?GET_OLDER:GET_NEWER; for(lg_dword i=0; m_pGetLine; i++) { if(i==nRef) return m_pGetLine->szLine; m_pGetLine=bStartWithNew?m_pGetLine->pOlder:m_pGetLine->pNewer; } return LG_NULL; } const lg_char* CConsole::GetNewestLine() { if(!m_pNewestLine) return LG_NULL; m_pGetLine=m_pNewestLine; m_nGetLineMode=GET_OLDER; return m_pGetLine->szLine; } const lg_char* CConsole::GetOldestLine() { if(!m_pOldestLine) return LG_NULL; m_pGetLine=m_pOldestLine; m_nGetLineMode=GET_NEWER; return m_pGetLine->szLine; } const lg_char* CConsole::GetNextLine() { if(!m_pGetLine) return LG_NULL; if(m_nGetLineMode==GET_NEWER) { m_pGetLine=m_pGetLine->pNewer; if(m_pGetLine) return m_pGetLine->szLine; else { m_nGetLineMode=GET_NONE; return LG_NULL; } } else if(m_nGetLineMode==GET_OLDER) { m_pGetLine=m_pGetLine->pOlder; if(m_pGetLine) return m_pGetLine->szLine; else { m_nGetLineMode=GET_NONE; return LG_NULL; } } return LG_NULL; } void CConsole::AddEntry(lg_char* szText) { LC_LINE* pNew=new LC_LINE; if(!pNew) return; if(szText) strncpy(pNew->szLine, szText, LC_MAX_LINE_LEN); else strncpy(pNew->szLine, "", LC_MAX_LINE_LEN); pNew->pOlder=pNew->pNewer=LG_NULL; if(!m_pNewestLine) { m_pNewestLine=m_pOldestLine=pNew; } else { pNew->pOlder=m_pNewestLine; m_pNewestLine->pNewer=pNew; m_pNewestLine=pNew; } m_nLineCount++; return; } void CConsole::Clear() { for(LC_LINE* pLine=m_pNewestLine; pLine; ) { LC_LINE* pTemp=pLine->pOlder; delete pLine; pLine=pTemp; } m_pNewestLine=m_pOldestLine=LG_NULL; m_nLineCount=0; } void CConsole::Print(lg_char* szText) { if(szText) AddEntry(szText); } void CConsole::Printf(lg_char* szFormat, ...) { va_list arglist; va_start(arglist, szFormat); _vsnprintf(s_szTemp, LC_MAX_LINE_LEN, szFormat, arglist); va_end(arglist); Print(s_szTemp); } void CConsole::SendCommand(lg_char* szCmd) { lg_dword nCurrent=0; strncpy(s_szTemp, szCmd, LC_MAX_LINE_LEN); s_szTemp[LC_MAX_LINE_LEN]=0; lg_char* szTemp=L_strtokA(s_szTemp, " \t\r\n", '"'); while(szTemp[0]!=0) { strncpy(s_Args.szArg[nCurrent], &szTemp[szTemp[0]=='"'?1:0], LC_MAX_LINE_LEN); lg_dword nLen=strlen(s_Args.szArg[nCurrent]); if(s_Args.szArg[nCurrent][nLen-1]=='"') { s_Args.szArg[nCurrent][nLen-1]=0; } nCurrent++; if(nCurrent>LC_MAX_CMD_ARGS) break; szTemp=L_strtokA(0, 0, 0); } s_Args.nArgCount=nCurrent; //If no arguments were found then the command //wasn't found so we just print a blank //line and that's it. if(s_Args.nArgCount<1) { Print(""); return; } #if 0 for(lg_dword i=0; i<s_Args.nArgCount; i++) { printf("Arg[%d]=\"%s\"\n", i, s_Args.szArg[i]); } #endif lg_bool bResult; lg_dword nCmdID=m_Commands.GetDefUnsigned(s_Args.szArg[0], &bResult); if(!bResult) { Printf("\"%s\" is not recognized as a valid command.", s_Args.szArg[0]); return; } if(m_pfnCmd) bResult=m_pfnCmd(nCmdID, (lg_void*)&s_Args, m_pCmdExtra); else Printf("No command function specified."); } const lg_char* CConsole::GetArg(lg_dword nParam, lg_void* pParams) { LC_ARGS* pArgs=(LC_ARGS*)pParams; if(nParam>=pArgs->nArgCount) return LG_NULL; return pArgs->szArg[nParam]; } lg_bool CConsole::CheckArg(const lg_char* string, lg_void* args) { LC_ARGS* pArgs=(LC_ARGS*)args; for(lg_dword i=0; i<pArgs->nArgCount; i++) { if(LG_StrNcCmpA(string, pArgs->szArg[i], -1)==0) return LG_TRUE; } return LG_FALSE; } void CConsole::SendCommandf(lg_char* szFormat, ...) { va_list arglist; va_start(arglist, szFormat); _vsnprintf(s_szTemp, LC_MAX_LINE_LEN, szFormat, arglist); va_end(arglist); SendCommand(s_szTemp); }<file_sep>/games/Explor2002/Source/Game/bmp.h #ifndef __BMP_H__ #define __BMP_H__ #include <ddraw.h> #include <windows.h> #include <windowsx.h> #include "defines.h" class CBitmapReader{ protected: HBITMAP m_hBitmap; int m_nFileWidth, m_nFileHeight; public: CBitmapReader(); ~CBitmapReader(); BOOL draw(LPDIRECTDRAWSURFACE surface); BOOL draw(LPDIRECTDRAWSURFACE surface, int w, int h, int x, int y); BOOL draw(LPDIRECTDRAWSURFACE surface, int w1, int h1, int w2, int h2, int x, int y); BOOL load(char *filename); }; #endif<file_sep>/games/Legacy-Engine/Source/game/lw_ai_test.cpp #include "lw_ent_sdk.h" #include "lg_func.h" #include "lw_ai_test.h" #include <memory.h> extern GAME_AI_GLOBALS g_Globals; /*************************** *** The Test Jack AI class *** ***************************/ lg_dword CLWAIJack::PhysFlags() { return AI_PHYS_INT|AI_PHYS_DIRECT_ANGULAR; } void CLWAIJack::Init(LEntitySrv *pEnt) { AIJACK_DATA* pData=(AIJACK_DATA*)pEnt->m_pData; pEnt->m_fLook[1]=0.0f; LWAI_SetAnim(pEnt->m_nAnimFlags1, 0, 0, 0, 1.0f, 0.0f); pData->nMode=0; } void CLWAIJack::PrePhys(LEntitySrv *pEnt) { AIJACK_DATA* pData=(AIJACK_DATA*)pEnt->m_pData; lg_float fThrust=pEnt->m_fMass*3.0f; //AI_DATA* pAIData=(AI_DATA*)pAIDataArg; //Technically a server ai should not take input, but //this is strictly for development testing. ML_VEC3 v3Temp; if(LWAI_CmdActive(pEnt, 0)) { //The general idea for movement is to create a vector //in the direction of movement, note that the vector //is a force so to get it to be acceleration we need //to multiply it by the object's mass, that way 2.0f //will be 2 m/s^2. ML_Vec3Scale(&v3Temp, &pEnt->m_v3Face[0], fThrust); ML_Vec3Add(&pEnt->m_v3Thrust, &pEnt->m_v3Thrust, &v3Temp); } if(LWAI_CmdActive(pEnt, 1)) { ML_Vec3Scale(&v3Temp, &pEnt->m_v3Face[0], -fThrust); ML_Vec3Add(&pEnt->m_v3Thrust, &pEnt->m_v3Thrust, &v3Temp); } if(LWAI_CmdActive(pEnt, 2)) { ML_Vec3Scale(&v3Temp, &pEnt->m_v3Face[2], fThrust); ML_Vec3Add(&pEnt->m_v3Thrust, &pEnt->m_v3Thrust, &v3Temp); } if(LWAI_CmdActive(pEnt, 3)) { ML_Vec3Scale(&v3Temp, &pEnt->m_v3Face[2], -fThrust); ML_Vec3Add(&pEnt->m_v3Thrust, &pEnt->m_v3Thrust, &v3Temp); } #if 0 if(cInput.s_pCmds[COMMAND_MOVEUP].IsActive()) { ML_Vec3Scale(&v3Temp, &pEnt->m_v3Face[1], fThrust); ML_Vec3Add(&pEnt->m_v3Thrust, &pEnt->m_v3Thrust, &v3Temp); } #else if(LWAI_CmdPressed(pEnt, 6)) { ML_Vec3Scale(&v3Temp, &pEnt->m_v3Face[1], 5.0f*pEnt->m_fMass); ML_Vec3Add(&pEnt->m_v3Impulse, &pEnt->m_v3Impulse, &v3Temp); } #endif if(LWAI_CmdActive(pEnt, 7)) { ML_Vec3Scale(&v3Temp, &pEnt->m_v3Face[1], -fThrust); ML_Vec3Add(&pEnt->m_v3Thrust, &pEnt->m_v3Thrust, &v3Temp); } //This AI is setup so that it will rotate directly, //that means that the object will rotate by the amount //specified as the torque, for that reason the number should //be either attached to the mouse, or very small (and time adjusted) so //the transition apears smooth. lg_float fRot = pEnt->m_fAxis[0]; pEnt->m_v3Torque.y=fRot; pEnt->m_fLook[1]-=pEnt->m_fAxis[1]; pEnt->m_fLook[1]=LG_Clamp(pEnt->m_fLook[1], -ML_HALFPI, ML_HALFPI); ML_VEC3 v3Look[3]={ 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f}; ML_MAT matTemp; ML_MatRotationX(&matTemp, pEnt->m_fLook[1]); ML_Vec3TransformNormalArray( v3Look, sizeof(ML_VEC3), v3Look, sizeof(ML_VEC3), &matTemp, 3); //memcpy(pEnt->m_v3Look, pEnt->m_v3Face, sizeof(ML_VEC3)*3); ML_Vec3TransformNormalArray( pEnt->m_v3Look, sizeof(ML_VEC3), v3Look, sizeof(ML_VEC3), &pEnt->m_matPos, 3); //Setup the animation if(ML_Vec3LengthSq(&pEnt->m_v3Thrust)>0.0f) { if(pData->nMode!=1) { LWAI_SetAnim(pEnt->m_nAnimFlags1, 0, 1, 0, 1.0f, 0.3f); pData->nMode=1; } } else { if(pData->nMode!=0) { LWAI_SetAnim(pEnt->m_nAnimFlags1, 0, 0, 0, 2.0f, 0.3f); pData->nMode=0; } } } void CLWAIJack::PostPhys(LEntitySrv *pEnt) { } /******************************* *** The Test Blaine AI class *** *******************************/ void CLWAIBlaine::Init(LEntitySrv *pEnt) { AIBLAINE_DATA* pData=(AIBLAINE_DATA*)pEnt->m_pData; pData->fElapsedTime=0.0f; pData->bForward=LG_TRUE; pData->fCurThrust=0.0f; pData->fRotSpeed=0.0f; pData->nTicks=0; } lg_dword CLWAIBlaine::PhysFlags() { return AI_PHYS_INT|AI_PHYS_DIRECT_ANGULAR; } void CLWAIBlaine::PrePhys(LEntitySrv *pEnt) { AIBLAINE_DATA* pData=(AIBLAINE_DATA*)pEnt->m_pData; pData->fElapsedTime+=g_Globals.fTimeStep; //Err_MsgPrintf("%f", pData->fElapsedTime); LG_UnsetFlag(pEnt->m_nAnimFlags1, LWAI_ANIM_CHANGE); if(pData->fElapsedTime>5.0f) { pData->fCurThrust=pEnt->m_fMass*3.0f;; pData->fRotSpeed=LG_RandomFloat(-1.0f, 1.0f); pData->fElapsedTime=0.0f; LWAI_SetAnim(pEnt->m_nAnimFlags1, 0, 1, 0, 1.0f, 0.5f); pData->nTicks++; //Esentially cuase the entity to kill itself after //15 seconds of existence. if(pData->nTicks>2) { LWAI_QueueFunc(pEnt, AI_FUNC_DELETE); } } ml_vec3 v3Temp={0.0f, 0.0f, 0.0f}; ML_Vec3Scale(&v3Temp, &pEnt->m_v3Face[0], pData->fCurThrust); ML_Vec3Add(&pEnt->m_v3Thrust, &pEnt->m_v3Thrust, &v3Temp); pEnt->m_v3Torque.y=pData->fRotSpeed*g_Globals.fTimeStep; } void CLWAIBlaine::PostPhys(LEntitySrv *pEnt) { }<file_sep>/games/Explor2002/Source_Old/ExplorED DOS/borland/Mapboard.cpp #include "mapboard.h" #include <stdio.h> #include <windows.h> //The following definition should be removed once I get the map files to //load into ram correctly. //#define NOTLOADING unsigned short ExplorMap::getMapWidth(void)const { return fileHeader.mapWidth; } unsigned short ExplorMap::getMapHeight(void)const { return fileHeader.mapHeight; } unsigned short ExplorMap::tbase(int tx, int ty)const { return tx + fileHeader.mapWidth*(ty-1)-1; } int ExplorMap::getTileStat(int x, int y, int propnum)const { return prop[propnum][TBASE]; } int ExplorMap::getTileStat(int x, int y)const { return tiles[tbase(x, y)]; } int ExplorMap::boardEdit(int x, int y, unsigned int propedit, unsigned int newvalue) { if(propedit>fileHeader.mapNumProperty) return 210; prop[propedit][TBASE] = newvalue; if((prop[propedit][TBASE] < 0) || ((prop[propedit][TBASE] < 0))) prop[propedit][TBASE] = 0;//reset if value less than 0 return 0; } int ExplorMap::boardEdit(int x, int y) { switch (tiles[tbase(x, y)]){ case 0: tiles[tbase(x, y)] = 10; return 10; case 10: tiles[tbase(x, y)] = 20; return 20; case 20: tiles[tbase(x, y)] = 0; return 0; default: tiles[tbase(x, y)] = 0; return 201; } } int ExplorMap::resetBoard(void) { int i; int j; for(i=0; i<NUMTILES; i++){ tiles[i]=0; for(j=0;j<fileHeader.mapNumProperty; j++) prop[j][i]=0; } return 0; } int ExplorMap::openMap(char openmap[FNAMELEN]) { FILE *openfile; //char buf[100]; int i; if((openfile = fopen(openmap, "rb"))==NULL) return 101; fread(&fileHeader, sizeof(fileHeader),1,openfile); //Check Map statistics to make sure it is valid // if not return error code. if(!strcmp("EM", fileHeader.mapType)){ fclose(openfile); return 110; } if(fileHeader.mapVersion != 3){ fclose(openfile); return 115; } fread(&tiles, fileHeader.mapTileDataSize, 1, openfile); //sprintf(buf, "Number of properties is: %i", fileHeader.mapNumProperty); //MessageBox(NULL, buf, "Notice", MB_OK); for (i=0; i<fileHeader.mapNumProperty; i++){ fread(&prop[i], fileHeader.mapPropertyDataSize, 1, openfile); } //MessageBox(NULL, "All Done", "Done", MB_OK); fclose(openfile); return 0; } int ExplorMap::saveMap(char openmap[FNAMELEN]) { FILE *savefile; int i; if((savefile = fopen(openmap, "wb"))==NULL) return 101; //strcpy(fileHeader.mapType, "EM"); fileHeader.mapPropertyDataSize = sizeof(prop[0])*fileHeader.mapNumProperty; fileHeader.mapTileDataSize = sizeof(tiles); fileHeader.mapDataSize = fileHeader.mapTileDataSize + fileHeader.mapPropertyDataSize*fileHeader.mapNumProperty; fileHeader.mapFileSize = fileHeader.mapDataSize + sizeof(fileHeader); fwrite(&fileHeader, sizeof(fileHeader), (size_t)1, savefile); fwrite(&tiles, fileHeader.mapTileDataSize, (size_t)1, savefile); for(i=0; i<fileHeader.mapNumProperty; i++) fwrite(&prop[i], fileHeader.mapTileDataSize, (size_t)1, savefile); fclose(savefile); return 0; }<file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/lv_tex.c /* lv_tex.c texture loading functions. */ #include <d3d9.h> #include <d3dx9.h> #include <lf_sys.h> #include "lv_tex.h" #include "lg_err.h" #include "lg_sys.h" #include "lv_init.h" L_bool Tex_SysToVid( IDirect3DDevice9* lpDevice, IDirect3DTexture9** lppTex, L_dword Flags) /* L_bool bAutoGenMipMap, D3DTEXTUREFILTERTYPE AutoGenFilter) */ { IDirect3DTexture9* lpTexSys=*lppTex; IDirect3DTexture9* lpTexVid=L_null; L_result nResult=0; D3DSURFACE_DESC sysdesc; L_dword nLevelCount=0; if(!lpTexSys || !lpDevice) return L_false; /* Get the description of the system texture. Make sure that the source is actually in system memory. Also get the level count.*/ memset(&sysdesc, 0, sizeof(sysdesc)); nResult=IDirect3DTexture9_GetLevelDesc(lpTexSys, 0, &sysdesc); if(L_failed(nResult)) return L_false; if(sysdesc.Pool!=D3DPOOL_SYSTEMMEM) return L_false; nLevelCount=IDirect3DTexture9_GetLevelCount(lpTexSys); /* Create the new texture in video memory. */ nResult=lpDevice->lpVtbl->CreateTexture( lpDevice, sysdesc.Width, sysdesc.Height, L_CHECK_FLAG(Flags, SYSTOVID_AUTOGENMIPMAP)?0:nLevelCount, L_CHECK_FLAG(Flags, SYSTOVID_AUTOGENMIPMAP)?D3DUSAGE_AUTOGENMIPMAP:0, sysdesc.Format, D3DPOOL_DEFAULT, &lpTexVid, L_null); if(L_failed(nResult)) { Err_Printf("Tex_Load Error: Could not open texture."); Err_PrintDX(" IDirect3DDevice9::CreateTexture", nResult); return L_false; } /* Use the device function to update the surface in video memory, with the data in system memory, then release the system memory texture, and adjust the pointer to point at the video memory texture. */ if(L_CHECK_FLAG(Flags, SYSTOVID_AUTOGENMIPMAP) && nLevelCount==1) { D3DTEXTUREFILTERTYPE nFilter=0; nFilter=L_CHECK_FLAG(Flags, SYSTOVID_LINEARMIPFILTER)?D3DTEXF_LINEAR:D3DTEXF_POINT; lpTexVid->lpVtbl->SetAutoGenFilterType(lpTexVid, nFilter); } lpTexVid->lpVtbl->AddDirtyRect(lpTexVid, L_null); lpDevice->lpVtbl->UpdateTexture(lpDevice, (void*)lpTexSys, (void*)lpTexVid); lpTexSys->lpVtbl->Release(lpTexSys); *lppTex=lpTexVid; return L_true; } L_bool Tex_LoadD3D( IDirect3DDevice9* lpDevice, L_lpstr szFilename, D3DPOOL Pool, L_dword Flags, L_dword nSizeLimit, IDirect3DTexture9** lppTex) { LF_FILE2 fin=L_null; L_result nResult=0; L_uint nMipLevels=0; L_dword dwTexFilter=0; L_dword dwTexFormat=0; L_dword dwWidth=0, dwHeight=0; fin=File_Open(szFilename, 0, LF_ACCESS_READ|LF_ACCESS_MEMORY, LFCREATE_OPEN_EXISTING); if(!fin) { Err_Printf("Tex_Load Error: Could not create texture from \"%s\".", szFilename); Err_Printf(" Could not open source file."); return L_false; } if(L_CHECK_FLAG(Flags, TEXLOAD_GENMIPMAP)) nMipLevels=0; else nMipLevels=1; if(L_CHECK_FLAG(Flags, TEXLOAD_LINEARMIPFILTER)) dwTexFilter=D3DX_FILTER_TRIANGLE|D3DX_FILTER_DITHER; else dwTexFilter=D3DX_FILTER_POINT; if(nSizeLimit) { dwWidth=dwHeight=nSizeLimit; } else { dwWidth=dwHeight=D3DX_DEFAULT; } if(L_CHECK_FLAG(Flags, TEXLOAD_FORCE16BIT)) { if(L_CHECK_FLAG(Flags, TEXLOAD_16BITALPHA)) dwTexFormat=D3DFMT_A1R5G5B5; else dwTexFormat=D3DFMT_R5G6B5; } else { dwTexFormat=D3DFMT_UNKNOWN; } /* Because we opened the file in membuf mode, we can just pas the pFileData member, and the File Size member to create the file in memory. */ nResult=D3DXCreateTextureFromFileInMemoryEx( lpDevice, File_GetMemPointer(fin, L_null), File_GetSize(fin), dwWidth, dwHeight, nMipLevels, 0, dwTexFormat, Pool, dwTexFilter, dwTexFilter, 0, L_null, L_null, lppTex); File_Close(fin); if(L_failed(nResult)) { Err_Printf("Tex_Load Error: Could not create texture from \"%s\".", szFilename); Err_PrintDX(" D3DXCreateTextureFromFileInMemoryEx", nResult); return L_false; } return L_true; } L_bool Tex_Load( IDirect3DDevice9* lpDevice, L_lpstr szFilename, D3DPOOL Pool, L_dword dwTransparent, L_bool bForceNoMip, IDirect3DTexture9** lppTex) { L3DGame* lpGame=LG_GetGame(); L_dword nFlags=0; L_bool (*pTexLoadCB)( IDirect3DDevice9* lpDevice, L_lpstr szFilename, D3DPOOL Pool, L_dword Flags, L_dword SizeLimit, IDirect3DTexture9** lppTex)=L_null; L_bool bGenMipMap=L_false; LV_TEXFILTER_MODE nMipFilter=FILTER_POINT; L_dword dwSizeLimit=0; char* szExt=L_null; L_dword nLen=L_strlen(szFilename); L_dword i=0; if(!lpDevice || !szFilename) { Err_Printf("Tex_Load Error: Could not open \"%s\".", szFilename); Err_Printf(" No device or no filename specified."); return L_false; } nFlags=0; if(lpGame) { if(CVar_GetValue(lpGame->m_cvars, "v_UseMipMaps", L_null) && !bForceNoMip) nFlags|=TEXLOAD_GENMIPMAP; if(CVar_GetValue(lpGame->m_cvars, "v_MipGenFilter", L_null)>=FILTER_LINEAR) nFlags|=TEXLOAD_LINEARMIPFILTER; dwSizeLimit=(L_dword)CVar_GetValue(lpGame->m_cvars, "v_TextureSizeLimit", L_null); if(CVar_GetValue(lpGame->m_cvars, "v_HWMipMaps", L_null)) nFlags|=TEXLOAD_HWMIPMAP; if(CVar_GetValue(lpGame->m_cvars, "v_Force16BitTextures", L_null)) nFlags|=TEXLOAD_FORCE16BIT; if(CVar_GetValue(lpGame->m_cvars, "v_16BitTextureAlpha", L_null)) nFlags|=TEXLOAD_16BITALPHA; } else { if(!bForceNoMip) nFlags|=TEXLOAD_GENMIPMAP; nFlags|=TEXLOAD_LINEARMIPFILTER; dwSizeLimit=0; } for(i=nLen; i>0; i--) { if(szFilename[i]=='.') { szExt=&szFilename[i+1]; break; } } if(L_strnicmp(szExt, "tga", 0) || L_strnicmp(szExt, "bmp", 0) || L_strnicmp(szExt, "dib", 0)) pTexLoadCB=Tex_LoadIMG2; else pTexLoadCB=Tex_LoadD3D; return pTexLoadCB( lpDevice, szFilename, Pool, nFlags, dwSizeLimit, lppTex); } L_bool Tex_CanAutoGenMipMap(IDirect3DDevice9* lpDevice, D3DFORMAT Format) { D3DCAPS9 Caps; D3DDEVICE_CREATION_PARAMETERS d3ddc; D3DDISPLAYMODE d3ddm; IDirect3D9* lpD3D=L_null; L_result nResult=0; if(!lpDevice) return L_false; memset(&Caps, 0, sizeof(D3DCAPS9)); lpDevice->lpVtbl->GetDeviceCaps(lpDevice, &Caps); if(!L_CHECK_FLAG(Caps.Caps2, D3DCAPS2_CANAUTOGENMIPMAP)) return L_false; lpDevice->lpVtbl->GetDirect3D(lpDevice, &lpD3D); memset(&d3ddc, 0, sizeof(d3ddc)); lpDevice->lpVtbl->GetCreationParameters(lpDevice, &d3ddc); memset(&d3ddm, 0, sizeof(d3ddm)); nResult=lpD3D->lpVtbl->CheckDeviceFormat( lpD3D, d3ddc.AdapterOrdinal, d3ddc.DeviceType, D3DFMT_R5G6B5, D3DUSAGE_AUTOGENMIPMAP, D3DRTYPE_TEXTURE, Format); L_safe_release(lpD3D); if(L_succeeded(nResult)) return L_true; else return L_false; }<file_sep>/games/Legacy-Engine/Source/engine/lv_sys.h #ifndef __LV_SYS_H__ #define __LV_SYS_H__ #include <d3d9.h> #include "lg_types.h" class CElementD3D { protected: static IDirect3D9* s_pD3D; static IDirect3DDevice9* s_pDevice; static IDirect3DSurface9* s_pBackSurface; static lg_uint s_nAdapterID; static D3DDEVTYPE s_nDeviceType; static D3DFORMAT s_nBackBufferFormat; static lg_dword s_nDisplayWidth; static lg_dword s_nDisplayHeight; }; typedef enum _TEXFILTER_MODE{ FILTER_UNKNOWN = 0, FILTER_NONE = 0, FILTER_POINT = 1, FILTER_LINEAR = 2, FILTER_BILINEAR = 2, FILTER_TRILINEAR = 3, FILTER_ANISOTROPIC = 4, FILTER_FORCE_DWORD = 0xFFFFFFFF }TEXFILTER_MODE; //#endif FILTER_MODE class CLVideo: private CElementD3D { friend class CLGame; //Will remove this friend when completely implemented. private: HWND m_hwnd; public: CLVideo(); ~CLVideo(); lg_bool Init(HWND hwnd); void Shutdown(); lg_bool SetStates(); lg_bool SetFilterMode(lg_int nFilterMode, lg_dword dwStage); private: lg_bool SetPPFromCVars(D3DPRESENT_PARAMETERS* pp); //void LV_SetTexLoadModes(); //static lg_bool SupportedTexFormats(); static lg_bool CorrectWindowSize(HWND hWnd, DWORD nWidth, DWORD nHeight); static void PrintPP(D3DPRESENT_PARAMETERS* pp); static lg_dword D3DFMTToBitDepth(D3DFORMAT fmt); static lg_dword StringToD3DFMT(lg_cstr szfmt); static lg_cstr D3DFMTToString(D3DFORMAT fmt); //Video reset stuff: //lg_result LV_ValidateDevice(); //lg_result LV_ValidateGraphics(); //lg_result LV_InvalidateGraphics(); lg_bool Restart(); }; #endif __LV_SYS_H__<file_sep>/games/Legacy-Engine/Source/engine/lp_newton2.h #ifndef __NEWTON2_H__ #define __NEWTON2_H__ #include "lp_sys2.h" #include "Newton/Newton.h" class CLPhysNewton: CLPhys { private: NewtonWorld* m_pNewtonWorld; NewtonBody* m_pWorldBody; lg_int MTR_DEFAULT; lg_int MTR_LEVEL; lg_int MTR_CHARACTER; lg_int MTR_OBJECT; ML_VEC3 m_v3Grav; lg_float m_fTimeStep; public: virtual void Init(lg_dword nMaxBodies); virtual void Shutdown(); virtual lg_void* AddBody(lg_void* pEnt, lp_body_info* pInfo); virtual void RemoveBody(lg_void* pBody); virtual void SetupWorld(lg_void* pWorldMap); virtual void SetGravity(ML_VEC3* pGrav); virtual void Simulate(lg_float fTimeStepSec); virtual void SetBodyFlag(lg_void* pBody, lg_dword nFlagID, lg_dword nValue); virtual void SetBodyVector(lg_void* pBody, lg_dword nVecID, ML_VEC3* pVec); virtual void SetBodyFloat(lg_void* pBody, lg_dword nFloatID, lg_float fValue); virtual void SetBodyPosition(lg_void* pBody, ML_MAT* pMat); virtual lg_void* GetBodySaveInfo(lg_void* pBody, lg_dword* pSize); virtual lg_void* LoadBodySaveInfo(lg_void* pData, lg_dword nSize); private: static void UpdateFromSrv(const NewtonBody* body); static void UpdateToSrv(const NewtonBody* body, const dFloat* matrix); /*typedef void (*NewtonBodyIterator) (const NewtonBody* body);*/ static CLPhysNewton* s_pPhys; }; #endif __NEWTON2_H__<file_sep>/games/Legacy-Engine/Source/engine/lw_ai.h #ifndef __LW_AI_H__ #define __LW_AI_H__ #include "lg_types.h" #include "lw_ai_sdk.h" #include <windows.h> struct LEntitySrv; #define LWAI_DEC_LIB_FUNC(return_type, name) TYPE_##name##_FUNC name; \ static return_type GAME_FUNC DEF_##name class CLWAIDefault: public CLWAIBase{ public: virtual void Init(LEntitySrv* pEnt); virtual void PrePhys(LEntitySrv* pEnt); virtual void PostPhys(LEntitySrv* pEnt); virtual lg_dword PhysFlags(); }; class CLWAIMgr { private: static CLWAIDefault s_DefaultAI; //CLWAIBase* m_pJackAI; //CLWAIBase* m_pBlaineAI; HMODULE m_hDllFile; LWAI_DEC_LIB_FUNC(CLWAIBase*, Game_ObtainAI)(lg_cstr szName); LWAI_DEC_LIB_FUNC(void, Game_Init)(); LWAI_DEC_LIB_FUNC(void, Game_UpdateGlobals)(const GAME_AI_GLOBALS* pIn); public: CLWAIMgr(); ~CLWAIMgr(); void LoadAI(lg_path szFilename); void CloseAI(); void SetGlobals(const GAME_AI_GLOBALS* pGlobals); CLWAIBase* GetAI(lg_cstr szName); }; #define LWAI_OBTAIN_FUNC(name) name=(TYPE_##name##_FUNC)GetProcAddress(m_hDllFile, #name); \ if(!name){\ Err_Printf(#name" function could not be loaded, using default."); \ name=DEF_##name;} #endif __LW_AI_H__<file_sep>/games/Legacy-Engine/Scrapped/old/lv_font.c #include <d3d9.h> #include <d3dx9.h> #include "common.h" #include "lf_sys.h" #include "lv_font.h" LVFONT* Font_Create( IDirect3DDevice9* lpDevice, char* szFilename, float fCharWidth, float fCharHeight, L_dword dwFontWidth, L_dword dwFontHeight) { LVFONT* lpNewFont=L_null; LF_FILE* fin=L_null; L_result nResult=0; D3DSURFACE_DESC TexDesc; if(!lpDevice || !szFilename) return L_null; /* Allocate memory for the font. */ lpNewFont=malloc(sizeof(LVFONT)); if(!lpNewFont) return L_null; memset(&TexDesc, 0, sizeof(TexDesc)); memset(lpNewFont, 0, sizeof(LVFONT)); lpNewFont->fCharHeight=(float)dwFontHeight; lpNewFont->fCharWidth=(float)dwFontWidth; /* Attempt to load the texture. */ fin=File_Open(szFilename, 0, LFF_READ); if(!fin) return L_null; /* Load the texture. Because of the way the Legacy Filesystem works we can pass the data directly to the function. */ nResult=D3DXCreateTextureFromFileInMemoryEx( lpDevice, fin->pFileData, fin->FileSize, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_FILTER_POINT, D3DX_FILTER_POINT, 0xFFFF00FF, L_null, L_null, &lpNewFont->lpTexture); File_Close(fin); if(L_failed(nResult)) { L_safe_free(lpNewFont); return L_null; } /* Save a copy of the device, and add a reference to it. */ lpNewFont->lpDevice=lpDevice; lpNewFont->lpDevice->lpVtbl->AddRef(lpNewFont->lpDevice); lpNewFont->lpTexture->lpVtbl->GetLevelDesc(lpNewFont->lpTexture, 0, &TexDesc); { float fCharsPerLine=0.0f; float fNumLines=0.0f; int i=0, j=0, a=0; L_rect rcSrc={0, 0, 0, 0}; fCharsPerLine=(float)TexDesc.Width/fCharWidth; rcSrc.right=(L_long)fCharWidth; rcSrc.bottom=(L_long)fCharHeight; for(i=0, a=0; i<fNumLines, a<96; i++) { for(j=0; j<fCharsPerLine && a<96; j++, a++) { rcSrc.left=j*(L_long)fCharWidth; rcSrc.top=i*(L_long)fCharHeight; lpNewFont->lpChars[a]=L2DI_CreateFromTexture( lpDevice, &rcSrc, dwFontWidth, dwFontHeight, lpNewFont->lpTexture, L_null); } } } return lpNewFont; } L_bool Font_Delete(LVFONT* lpFont) { int i=0; if(!lpFont) return L_false; for(i=0; i<96; i++) { L2DI_Delete(lpFont->lpChars[i]); } lpFont->lpTexture->lpVtbl->Release(lpFont->lpTexture); lpFont->lpDevice->lpVtbl->Release(lpFont->lpDevice); L_safe_free(lpFont); return L_true; } L_bool Font_DrawChar( LVFONT* lpFont, IDirect3DDevice9* lpDevice, char c, float x, float y) { /* Make sure the character is renderable. */ if(!lpFont || !lpDevice) return L_false; if(c<' ' || c>'~') c=' '; L2DI_Render(lpFont->lpChars[c-' '], lpDevice, x, y); return L_true; } L_bool Font_DrawString( LVFONT* lpFont, IDirect3DDevice9* lpDevice, char* szString, float x, float y) { L_dword dwLen=0; L_dword i=0; if(!lpFont) return L_false; if(!szString) return L_false; dwLen=L_strlen(szString); for(i=0; i<dwLen; i++) { Font_DrawChar(lpFont, lpDevice, szString[i], x+(i*lpFont->fCharWidth), y); } return L_true; } L_bool Font_Validate(LVFONT* lpFont, IDirect3DDevice9* lpDevice) { int i=0; if(!lpFont) return L_false; for(i=0; i<96; i++) { L2DI_Validate(lpFont->lpChars[i]); } return L_true; } L_bool Font_Invalidate(LVFONT* lpFont) { int i=0; if(!lpFont) return L_false; for(i=0; i<96; i++) { L2DI_Invalidate(lpFont->lpChars[i]); } return L_true; }<file_sep>/tools/fs_sys2/fs_bdio_ex.c /********************************************************************** *** fs_bdio_ex.c - Includes extra functions for basic input output *** **********************************************************************/ #include "fs_bdio.h" #include "fs_internal.h" #include <zlib.h> voidpf ZLIB_Alloc(voidpf opaque, uInt items, uInt size) { return FS_Malloc(items*size, LF_ALLOC_REASON_SCRATCH, "FS_ZLIB",__FILE__,__LINE__); } void ZLIB_Free(voidpf opaque, voidpf address) { FS_Free(address, LF_ALLOC_REASON_SCRATCH); } fs_dword BDIO_WriteCompressed(BDIO_FILE File, fs_dword nSize, void* pInBuffer) { fs_dword nWritten=0; z_stream stream; int err; fs_byte* pCmpBuffer=FS_Malloc(nSize, LF_ALLOC_REASON_SCRATCH, "FS", __FILE__, __LINE__); if(!pCmpBuffer) return 0; stream.next_in=(Bytef*)pInBuffer; stream.avail_in=(uInt)nSize; stream.next_out=pCmpBuffer; stream.avail_out=nSize; stream.zalloc=ZLIB_Alloc; stream.zfree=ZLIB_Free; stream.opaque=(voidpf)0; err=deflateInit(&stream, Z_DEFAULT_COMPRESSION); if(err!=Z_OK) { FS_Free(pCmpBuffer, LF_ALLOC_REASON_SCRATCH); return 0; } err=deflate(&stream, Z_FINISH); if(err!=Z_STREAM_END) { deflateEnd(&stream); FS_Free(pCmpBuffer, LF_ALLOC_REASON_SCRATCH); return 0; } nWritten=stream.total_out; deflateEnd(&stream); nWritten=BDIO_Write(File, nWritten, pCmpBuffer); FS_Free(pCmpBuffer, LF_ALLOC_REASON_SCRATCH); return nWritten; } fs_dword BDIO_ReadCompressed(BDIO_FILE File, fs_dword nSize, void* pInBuffer) { //The BDIO_ReadCompressed function is somewhat complicated. Unlike the //BDIO_WriteCompressed method. Also note that this function returns the //size of the data that was decompressed, and not the actual amount of //data read from the file. z_stream in_stream; int err; fs_dword nRead; fs_dword nPos; fs_byte* pCmpBuffer=FS_Malloc(nSize, LF_ALLOC_REASON_SCRATCH, "FS", __FILE__, __LINE__); if(!pCmpBuffer) return 0; nPos=BDIO_Tell(File); nRead=BDIO_Read(File, nSize, pCmpBuffer); in_stream.zalloc=ZLIB_Alloc; in_stream.zfree=ZLIB_Free; in_stream.opaque=(voidpf)0; in_stream.next_out=pInBuffer; in_stream.avail_out=nSize; in_stream.next_in=pCmpBuffer; in_stream.avail_in=nRead; err=inflateInit(&in_stream); if(Z_OK != err) { FS_Free(pCmpBuffer, LF_ALLOC_REASON_SCRATCH); BDIO_Seek(File, nPos, LF_SEEK_BEGIN); return 0; } err=inflate(&in_stream, Z_FINISH); nRead=in_stream.total_out; BDIO_Seek(File, nPos+in_stream.total_in, LF_SEEK_BEGIN); inflateEnd(&in_stream); FS_Free(pCmpBuffer, LF_ALLOC_REASON_SCRATCH); return nRead; } fs_dword BDIO_CopyData(BDIO_FILE DestFile, BDIO_FILE SourceFile, fs_dword nSize) { fs_dword i=0; fs_byte byte=0; fs_dword nWritten=0; fs_byte* pData=FS_Malloc(nSize, LF_ALLOC_REASON_SCRATCH, "FS", __FILE__,__LINE__); if(!pData) return 0; nWritten=BDIO_Read(SourceFile, nSize, pData); nWritten=BDIO_Write(DestFile, nWritten, pData); FS_Free(pData, LF_ALLOC_REASON_SCRATCH); return nWritten; } <file_sep>/tools/fs_sys2/fs_fs2.cpp #include <stdlib.h> #include <stdio.h> #include <string.h> #include "fs_fs2.h" #include "fs_bdio.h" #include "fs_lpk.h" #if defined(DEBUG) #include <ctype.h> #endif //NOTES: The file system is fairly simply, but most of the methods have a //wide character and multibyte method that way the file system is compatible //both with Windows 98 and unicode operating systems. The file system stores //information about all files in a partition table that uses hash indexes to //quickly access information about each of the files. //TODO: Testing on windows 98 //Inusuring complete testing, and better support for the multi-byte methods. //Typical mounting procedure. //1) The first thing that needs to be done is to have the base get mounted. //eg. // MountBase(".\"); //This would mount the current directory. //This will get the base file system mounted. //2) Mount any subdirectories. //eg. // Mount("base", "/base1/", MOUNT_FILE_OVERWRITE|MOUNT_FILE_SUBDIRS); // Mount("expansionbase", "/base2/", MOUNT_FILE_OVERWRITE|MOUNT_FILE_SUBDIRS); // This will get the main folders mounted for the application. Note that // You could do something as follows: // Mount("base", "/base1/", MOUNT_FILE_OVERWRITE|MOUNT_FILE_SUBDIRS); // Mount("expansionbase", "/base1/", MOUNT_FILE_OVERWRITE|MOUNT_FILE_SUBDIRS); // And that all files in the OS folder expansionbase would take precedence over // any files in base, but the same mount path would be used no matter what. //3) Mount any LPK files. //eg. // MountLPK("/base1/pak0.lpk", MOUNT_FILE_OVERWRITELPKONLY); // MountLPK("/base1/pak1.lpk", MOUNT_FILE_OVERWRITELPKONLY); // MountLPK("/base1/pak2.lpk", MOUNT_FILE_OVERWTITELPKONLY); // Note that by specifying MOUNT_FILE_OVERWRITELPKONLY any files // in pak1 would overwrite files in pak0, but not any files that // are directly on the hard drive. //4) Proceed to open, close, read, and write files as necessary. CLFileSystem::CLFileSystem() : m_PrtTableList(FS_NULL) , m_bBaseMounted(FS_FALSE) { m_szBasePath[0]=0; } CLFileSystem::~CLFileSystem() { UnMountAll(); } void CLFileSystem::PrintMountInfo(FS_PRINT_MOUNT_INFO_TYPE Type) { if( PRINT_MOUNT_INFO_FULL == Type ) { FS_ErrPrintW(L"Base mounted at \"%s\"", ERR_LEVEL_ALWAYS, this->m_szBasePath); FS_ErrPrintW(L"Mounted Files:", ERR_LEVEL_ALWAYS); } for( CPartTable* Table = m_PrtTableList; FS_NULL != Table; Table = Table->GetNext() ) { Table->PrintMountInfo(Type); } } CLFileSystem::MOUNT_FILE* CLFileSystem::GetFileInfoW( fs_cstr16 szMountPath , CPartTable** OwnerTable ) { fs_pathW sFixed; FS_FixCaseW(sFixed, szMountPath); MOUNT_FILE* FoundFile = FS_NULL; for( CPartTable* Table = m_PrtTableList; FS_NULL != Table && FS_NULL == FoundFile; Table = Table->GetNext() ) { FoundFile = Table->FindFile(sFixed); if( FS_NULL != FoundFile && FS_NULL != OwnerTable ) { *OwnerTable = Table; } } return FoundFile; } CLFileSystem::MOUNT_FILE* CLFileSystem::GetFileInfoA( fs_cstr8 szMountPath , CPartTable** OwnerTable ) { fs_pathW szMountedFileW; mbstowcs(szMountedFileW, szMountPath, FS_MAX_PATH); return GetFileInfoW( szMountedFileW , OwnerTable ); } //Mount base must be called before any other mounting operations are called. //Mount base basically sets the current directory. From there on out any //calls to mount don't need full path names they only need path names //relative to the OS path that was mounted at the base. When MountBase is //called any files immediately in the base directory are mounted, but not //subdirectories. Note that even if a base is mounted, files outside the //base may still be mounted (for example a CD-ROM drive can be mounted). //The path to the base is always /. Note that any files that are created //are always created relatvie to the base, and not other paths that may //be mounted. I want to change that, however, so that a path can be mounted //to where files should be saved. fs_dword CLFileSystem::MountBaseW(fs_cstr16 szOSPath) { if(m_bBaseMounted) { FS_ErrPrintW(L"MountBase Error 1: The base file system is already mounted. Call UnMountAll before mounting the base.", ERR_LEVEL_ERROR); return 0; } if(!BDIO_ChangeDirW(szOSPath)) { FS_ErrPrintW(L"MountBase Error 2: Could not mount base file system.", ERR_LEVEL_ERROR); return 0; } BDIO_GetCurrentDirW(m_szBasePath, FS_MAX_PATH); m_bBaseMounted=FS_TRUE; fs_dword nMountCount=MountW(L".", L"/", 0); FS_ErrPrintW(L"Mounted \"%s\" to \"/\"", ERR_LEVEL_DETAIL, m_szBasePath); return nMountCount; } fs_dword CLFileSystem::MountBaseA(fs_cstr8 szOSPath) { if(m_bBaseMounted) { FS_ErrPrintW(L"MountBase Error 3: The base file system is already mounted. Call UnMountAll before mounting the base.", ERR_LEVEL_ERROR); return 0; } if(!BDIO_ChangeDirA(szOSPath)) { FS_ErrPrintW(L"MountBase Error 4: Could not mount base file system.", ERR_LEVEL_ERROR); return 0; } fs_pathA szBasePath; BDIO_GetCurrentDirA(szBasePath, FS_MAX_PATH); mbstowcs(m_szBasePath, szBasePath, FS_MAX_PATH); m_bBaseMounted=FS_TRUE; fs_dword nMountCount=MountA(".", "/", 0); FS_ErrPrintW(L"Mounted \"%s\" to \"/\"", ERR_LEVEL_DETAIL, m_szBasePath); return nMountCount; } //MountLPK mounts a Legacy PaKage file into the file system. Note that before //an LPK can be mounted the actually LPK file must be within the file system. //Then when MountLPK is called the path to the mounted file (e.g. /base1/pak0.lpk) //should be specifed as a parameter, and not the os path (e.g. NOT .\base\pak0.lpk). //This method will expand the archive file into the current directory, so if //a file was stored in the LPK as Credits.txt it would now be /base1/Credits.txt //and Textures/Tex1.tga would be /base1/Textures/Tex1.tga. //Note that for the flags either MOUNT_FILE_OVERWRITE or MOUNT_FILE_OVERWRITELPKONLY //may be specifed. // //MOUNT_FILE_OVERWRITE: If any file with the same mout path as the new file //already exists, then the new file will take precedence over the old file //that is to say that when calls to open a file with the specified name //are made the file most recently mounted file will be opened (it doens't //mean that the OS file will be overwritten, because it won't). // //MOUNT_FILE_OVERWRITELPKONLY: Is similar to the above flag, but a newer file //will only take precedence over other archived files. So fore example if two //LPK files have a file with the same name stored in them, the most recently //mounted LPK file will take precedence, but if there was a file directly on //the hard drive, the hard drive file will take precedence, whether or not //the archive was mounted first or second. // //If neither flag is specified files will never get overwritten and the first //file to be mounted will always take precidence. fs_dword CLFileSystem::MountLPKW(fs_cstr16 szMountedFileOrg, fs_dword Flags) { fs_pathW szMountedFile; FS_FixCaseW(szMountedFile, szMountedFileOrg); MOUNT_FILE* pMountFile=GetFileInfoW(szMountedFile,FS_NULL); if(!pMountFile) { FS_ErrPrintW(L"MountLPK Error 5: The archive file \"%s\" has not been mounted.", ERR_LEVEL_ERROR, szMountedFile); return 0; } fs_pathW szMountDir; FS_GetDirFromPathW(szMountDir, szMountedFile); FS_ErrPrintW(L"Expanding \"%s\" to \"%s\"", ERR_LEVEL_NOTICE, szMountedFile, szMountDir); CLArchive lpkFile; if(!lpkFile.OpenW(pMountFile->szOSFileW)) { FS_ErrPrintW(L"Could not mount \"%s\". Possibly not a valid archive.", ERR_LEVEL_ERROR, szMountedFile); return 0; } pMountFile->Flags |= MOUNT_FILE::MOUNT_FILE_READONLY; fs_dword dwMounted=0; for(fs_dword i=0; i<lpkFile.GetNumFiles(); i++) { LPK_FILE_INFO fileInfo; if(!lpkFile.GetFileInfo(i, &fileInfo)) continue; MOUNT_FILE mountFile; swprintf(mountFile.szMountFileW, FS_MAX_PATH, L"%s%s", szMountDir, fileInfo.szFilename); swprintf(mountFile.szOSFileW, FS_MAX_PATH, L"%s", pMountFile->szOSFileW); mountFile.nSize=fileInfo.nSize; mountFile.nCmpSize=fileInfo.nCmpSize; mountFile.nOffset=fileInfo.nOffset; mountFile.Flags=MOUNT_FILE::MOUNT_FILE_ARCHIVED|MOUNT_FILE::MOUNT_FILE_READONLY; if(fileInfo.nType==LPK_FILE_TYPE_ZLIBCMP) mountFile.Flags|=MOUNT_FILE::MOUNT_FILE_ZLIBCMP; if(MountFile(&mountFile, Flags)) dwMounted++; else { FS_ErrPrintW( L"Mount Error 6: Could not mount \"%s\" (%s).", ERR_LEVEL_ERROR, mountFile.szMountFileW, mountFile.szOSFileW); } } return dwMounted; } fs_dword CLFileSystem::MountLPKA(fs_cstr8 szMountedFileOrg, fs_dword Flags) { fs_pathA szMountedFile; FS_FixCaseA(szMountedFile, szMountedFileOrg); fs_pathW szMountedFileW; mbstowcs(szMountedFileW, szMountedFile, FS_MAX_PATH); MOUNT_FILE* pMountFile=GetFileInfoW( szMountedFileW , FS_NULL ); if(!pMountFile) { FS_ErrPrintW(L"MountLPK Error 7: The archive file \"%s\" has not been mounted.", ERR_LEVEL_ERROR, szMountedFileW); return 0; } fs_pathW szMountDir; FS_GetDirFromPathW(szMountDir, szMountedFileW); FS_ErrPrintW(L"Expanding \"%s\" to \"%s\"", ERR_LEVEL_NOTICE, szMountedFileW, szMountDir); fs_pathA szOSFileA; wcstombs(szOSFileA, pMountFile->szOSFileW, FS_MAX_PATH); CLArchive lpkFile; if(!lpkFile.OpenA(szOSFileA)) { FS_ErrPrintW(L"Could not mount \"%s\". Possibly not a valid archive.", ERR_LEVEL_ERROR, szMountedFile); return 0; } pMountFile->Flags |= MOUNT_FILE::MOUNT_FILE_READONLY; fs_dword dwMounted=0; for(fs_dword i=0; i<lpkFile.GetNumFiles(); i++) { LPK_FILE_INFO fileInfo; if(!lpkFile.GetFileInfo(i, &fileInfo)) continue; MOUNT_FILE mountFile; swprintf(mountFile.szMountFileW, FS_MAX_PATH, L"%s%s", szMountDir, fileInfo.szFilename); swprintf(mountFile.szOSFileW, FS_MAX_PATH, L"%s", pMountFile->szOSFileW); mountFile.nSize=fileInfo.nSize; mountFile.nCmpSize=fileInfo.nCmpSize; mountFile.nOffset=fileInfo.nOffset; mountFile.Flags=MOUNT_FILE::MOUNT_FILE_ARCHIVED|MOUNT_FILE::MOUNT_FILE_READONLY; if(fileInfo.nType==LPK_FILE_TYPE_ZLIBCMP) mountFile.Flags|=MOUNT_FILE::MOUNT_FILE_ZLIBCMP; if(MountFile(&mountFile, Flags)) dwMounted++; else { FS_ErrPrintW( L"Mount Error 6: Could not mount \"%s\" (%s).", ERR_LEVEL_ERROR, mountFile.szMountFileW, mountFile.szOSFileW); } } return dwMounted; } fs_dword CLFileSystem::MountDirW(fs_cstr16 szOSPath, fs_cstr16 szMount, fs_dword Flags) { fs_dword nMountCount=0; fs_bool bRes=0; fs_pathW szSearchPath; _snwprintf(szSearchPath, FS_MAX_PATH, L"%s%c*", szOSPath, BDIO_GetOsPathSeparator()); //Recursivley mount all files... BDIO_FIND_DATAW sData; BDIO_FIND hFind=BDIO_FindFirstFileW(szSearchPath, &sData); if(!hFind) { FS_ErrPrintW( L"Mount Error 9: Could not mount any files. \"%s\" may not exist.", ERR_LEVEL_ERROR, szOSPath); return 0; } //Mount the directory, itself... MOUNT_FILE mountInfo; mountInfo.nCmpSize=mountInfo.nOffset=mountInfo.nSize=0; mountInfo.Flags=MOUNT_FILE::MOUNT_FILE_DIRECTORY; wcsncpy(mountInfo.szOSFileW, szOSPath, FS_MAX_PATH); wcsncpy(mountInfo.szMountFileW, szMount, FS_MAX_PATH); //Directories take the same overwrite priority, so overwritten //directories will be used when creating new files. bRes=MountFile(&mountInfo, Flags); if(!bRes) { FS_ErrPrintW(L"Mount Error 10: Could not mount \"%s\".", ERR_LEVEL_ERROR, mountInfo.szOSFileW); BDIO_FindClose(hFind); return nMountCount; } do { //Generate the mounted path and OS path.. MOUNT_FILE sMountFile; _snwprintf(sMountFile.szOSFileW, FS_MAX_PATH, L"%s%c%s", szOSPath, BDIO_GetOsPathSeparator(), sData.szFilename); _snwprintf(sMountFile.szMountFileW, FS_MAX_PATH, L"%s%s", szMount, sData.szFilename); FS_FixCaseW(sMountFile.szMountFileW, sMountFile.szMountFileW); //If a directory was found mount that directory... if(sData.bDirectory) { //Ignore . and .. directories. if(sData.szFilename[0]=='.') continue; if(FS_CheckFlag(Flags, MOUNT_MOUNT_SUBDIRS)) { wcsncat(sMountFile.szMountFileW, L"/", FS_min<fs_long>(1, FS_MAX_PATH-wcslen(sMountFile.szMountFileW))); nMountCount+=MountDirW(sMountFile.szOSFileW, sMountFile.szMountFileW, Flags); } } else { if(sData.nFileSize.dwHighPart) { FS_ErrPrintW(L"\"%s\" is too large to mount!", ERR_LEVEL_ERROR, sMountFile.szOSFileW); continue; } sMountFile.nSize=sData.nFileSize.dwLowPart; sMountFile.nCmpSize=sMountFile.nSize; sMountFile.nOffset=0; sMountFile.Flags=0; if(sData.bReadOnly) sMountFile.Flags|=MOUNT_FILE::MOUNT_FILE_READONLY; if(MountFile(&sMountFile, Flags)) nMountCount++; else FS_ErrPrintW(L"Mount Error 11: Could not mount \"%s\".", ERR_LEVEL_ERROR, mountInfo.szOSFileW); } }while(BDIO_FindNextFileW(hFind, &sData)); BDIO_FindClose(hFind); return nMountCount; } fs_dword CLFileSystem::MountDirA(fs_cstr8 szOSPath, fs_cstr8 szMount, fs_dword Flags) { fs_dword nMountCount=0; fs_bool bRes=0; fs_pathA szSearchPath; _snprintf(szSearchPath, FS_MAX_PATH, "%s\\*", szOSPath); //Recursivley mount all files... BDIO_FIND_DATAA sData; BDIO_FIND hFind=BDIO_FindFirstFileA(szSearchPath, &sData); if(!hFind) { FS_ErrPrintA( "Mount Error 12: Could not mount any files. \"%s\" may not exist.", ERR_LEVEL_ERROR, szOSPath); return 0; } //Mount the directory, itself... MOUNT_FILE mountInfo; mountInfo.nCmpSize=mountInfo.nOffset=mountInfo.nSize=0; mountInfo.Flags=MOUNT_FILE::MOUNT_FILE_DIRECTORY; mbstowcs(mountInfo.szOSFileW, szOSPath, FS_MAX_PATH); mbstowcs(mountInfo.szMountFileW, szMount, FS_MAX_PATH); //Directories take the same overwrite priority, so overwritten //directories will be used when creating new files. bRes=MountFile(&mountInfo, Flags); if(!bRes) { FS_ErrPrintW(L"Mount Error 13: Could not mount \"%s\".", ERR_LEVEL_ERROR, mountInfo.szOSFileW); BDIO_FindClose(hFind); return nMountCount; } do { //Generate the mounted path and OS path.. MOUNT_FILE sMountFile; fs_pathA szOSFileA, szMountFileA; _snprintf(szOSFileA, FS_MAX_PATH, "%s\\%s", szOSPath, sData.szFilename); _snprintf(szMountFileA, FS_MAX_PATH, "%s%s", szMount, sData.szFilename); mbstowcs(sMountFile.szOSFileW, szOSFileA, FS_MAX_PATH); mbstowcs(sMountFile.szMountFileW, szMountFileA, FS_MAX_PATH); FS_FixCaseW(sMountFile.szMountFileW, sMountFile.szMountFileW); //If a directory was found mount that directory... if(sData.bDirectory) { //Ignore . and .. directories. if(sData.szFilename[0]=='.') continue; if(FS_CheckFlag(Flags, MOUNT_MOUNT_SUBDIRS)) { strncat(szMountFileA, "/", FS_min<fs_long>(1, FS_MAX_PATH-strlen(szMountFileA))); nMountCount+=MountDirA(szOSFileA, szMountFileA, Flags); } } else { if(sData.nFileSize.dwHighPart) { FS_ErrPrintW(L"\"%s\" is too large to mount!", ERR_LEVEL_ERROR, sMountFile.szOSFileW); continue; } sMountFile.nSize=sData.nFileSize.dwLowPart; sMountFile.nCmpSize=sMountFile.nSize; sMountFile.nOffset=0; sMountFile.Flags=0; if(sData.bReadOnly) sMountFile.Flags|=MOUNT_FILE::MOUNT_FILE_READONLY; if(MountFile(&sMountFile, Flags)) nMountCount++; else FS_ErrPrintW(L"Mount Error 14: Could not mount \"%s\".", ERR_LEVEL_ERROR, mountInfo.szOSFileW); } }while(BDIO_FindNextFileA(hFind, &sData)); BDIO_FindClose(hFind); return nMountCount; } //The Mount method mounts a directory to the file //system. If the MOUNT_MOUNT_SUBDIRS flag is specifed //then all subdirectories will be mounted as well. fs_dword CLFileSystem::MountW(fs_cstr16 szOSPathToMount, fs_cstr16 szMountToPathOrg, fs_dword Flags) { fs_pathW szMountToPath; FS_FixCaseW(szMountToPath, szMountToPathOrg); fs_dword nMountCount=0; fs_pathW szMount; fs_pathW szOSPath; //Get the full path to the specified directory... BDIO_GetFullPathNameW(szOSPath, szOSPathToMount); //Insure that the mounting path does not have a / or \. size_t nLast=wcslen(szOSPath)-1; if(szOSPath[nLast]==L'/' || szOSPath[nLast]==L'\\') szOSPath[nLast]=0; if(szMountToPath[0]!='/') { FS_ErrPrintW( L"The path must be mounted at least to the base. Try mount \"%s\" \"/%s\" instead.", ERR_LEVEL_WARNING, szOSPathToMount, szMountToPath); return 0; } //Insure that the mount path has a / at the end of it if(szMountToPath[wcslen(szMountToPath)-1]!=L'/') _snwprintf(szMount, FS_MAX_PATH, L"%s/", szMountToPath); else _snwprintf(szMount, FS_MAX_PATH, L"%s", szMountToPath); FS_ErrPrintW(L"Mounting \"%s\" to \"%s\"...", ERR_LEVEL_NOTICE, szOSPath, szMount); return MountDirW(szOSPath, szMount, Flags); } fs_dword CLFileSystem::MountA(fs_cstr8 szOSPathToMount, fs_cstr8 szMountToPathOrg, fs_dword Flags) { fs_pathA szMountToPath; FS_FixCaseA(szMountToPath, szMountToPathOrg); fs_dword nMountCount=0; fs_pathA szMount; fs_pathA szOSPath; //Get the full path to the specified directory... BDIO_GetFullPathNameA(szOSPath, szOSPathToMount); //Insure that the mountine path does not have a / or \. size_t nLast=strlen(szOSPath)-1; if(szOSPath[nLast]=='/' || szOSPath[nLast]=='\\') szOSPath[nLast]=0; if(szMountToPath[0]!='/') { FS_ErrPrintW( L"The path must be mounted at least to the base. Try mount \"%s\" \"/%s\" instead.", ERR_LEVEL_WARNING, szOSPathToMount, szMountToPath); return 0; } //Insure that the mount path has a / at the end of it if(szMountToPath[strlen(szMountToPath)-1]!=L'/') _snprintf(szMount, FS_MAX_PATH, "%s/", szMountToPath); else _snprintf(szMount, FS_MAX_PATH, "%s", szMountToPath); fs_pathW szOSPathW, szMountW; mbstowcs(szOSPathW, szOSPath, FS_MAX_PATH); mbstowcs(szMountW, szMount, FS_MAX_PATH); FS_ErrPrintW(L"Mounting \"%s\" to \"%s\"...", ERR_LEVEL_NOTICE, szOSPathW, szMountW); return MountDirA(szOSPath, szMount, Flags); } fs_bool CLFileSystem::ExistsA(fs_cstr8 szFilename) { //Case is fixed by GetFileInfoA const MOUNT_FILE* pMountInfo=GetFileInfoA( szFilename , FS_NULL ); return pMountInfo!=FS_NULL; } fs_bool CLFileSystem::ExistsW(fs_cstr16 szFilename) { //Case is fixed by GetFileInfoW const MOUNT_FILE* pMountInfo=GetFileInfoW( szFilename , FS_NULL ); return pMountInfo!=FS_NULL; } fs_bool CLFileSystem::UnMountAll() { FS_ErrPrintW(L"Clearing partition table...", ERR_LEVEL_NOTICE); while( FS_NULL != m_PrtTableList ) { CPartTable* OldTable = m_PrtTableList; m_PrtTableList = OldTable->GetNext(); OldTable->Clear(); delete OldTable; } FS_ErrPrintW(L"Unmounting the base...", ERR_LEVEL_NOTICE); m_bBaseMounted=FS_FALSE; m_szBasePath[0]=0; return FS_TRUE; } fs_bool CLFileSystem::MountFile(MOUNT_FILE* pFile, fs_dword dwFlags) { #if defined(DEBUG) { for(int i=0; i<FS_MAX_PATH; i++) { if(0 == pFile->szMountFileW[i]) break; if( isupper(pFile->szMountFileW[i]) ) __debugbreak(); } } #endif FS_ErrPrintW(L"Mounting \"%s\"", ERR_LEVEL_SUPERDETAIL, pFile->szMountFileW); //If the current partition table doesn't exist, or if it is full, //create a new one for this file. if( FS_NULL == m_PrtTableList || m_PrtTableList->IsFull() ) { m_PrtTableList = new CPartTable( m_PrtTableList , PART_TABLE_SIZE ); } return FS_NULL != m_PrtTableList ? m_PrtTableList->MountFile(pFile, dwFlags) : false; } /********************************************************* File opening code, note that files are opened and closed using the file system, but they are accessed (read and written to) using the CLFile class. *********************************************************/ CLFile* CLFileSystem::OpenFileW(fs_cstr16 szFilename, fs_dword Access, fs_dword CreateMode) { fs_bool bOpenExisting=FS_TRUE; fs_bool bNew=FS_FALSE; //Check the flags to make sure they are compatible. if(FS_CheckFlag(Access, LF_ACCESS_WRITE) && FS_CheckFlag(Access, LF_ACCESS_MEMORY)) { FS_ErrPrintW(L"OpenFile Error: Cannot open a file with memory access and write access.", ERR_LEVEL_ERROR); return FS_NULL; } //Note that if creating a new file, then we shouldn't end here. const MOUNT_FILE* pMountInfo=GetFileInfoW(szFilename,FS_NULL); if(CreateMode==LF_OPEN_EXISTING) { if(!pMountInfo) { FS_ErrPrintW(L"OpenFile Warning: \"%s\" could not be found in the file system.", ERR_LEVEL_WARNING, szFilename); return FS_NULL; } bOpenExisting=FS_TRUE; bNew=FS_FALSE; } else if(CreateMode==LF_OPEN_ALWAYS) { bOpenExisting=pMountInfo?FS_TRUE:FS_FALSE; bNew=FS_FALSE; } else if(CreateMode==LF_CREATE_NEW) { if(pMountInfo) { FS_ErrPrintW(L"OpenFile Error: Cannot create \"%s\", it already exists.", ERR_LEVEL_ERROR, szFilename); return FS_NULL; } bOpenExisting=FS_FALSE; bNew=FS_TRUE; } else if(CreateMode==LF_CREATE_ALWAYS) { if(pMountInfo) { bOpenExisting=FS_TRUE; bNew=FS_TRUE; } else { bOpenExisting=FS_FALSE; bNew=FS_TRUE; } } else { FS_ErrPrintW(L"OpenFile Error: Invalid creation mode specifed.", ERR_LEVEL_ERROR); return FS_NULL; } //If the file is mounted then we are opening an existing file. if(bOpenExisting) { if(FS_CheckFlag(pMountInfo->Flags, MOUNT_FILE::MOUNT_FILE_DIRECTORY)) { FS_ErrPrintW(L"OpenFile Error: \"%s\" is a directory, not a file.", ERR_LEVEL_ERROR, pMountInfo->szMountFileW); return FS_NULL; } //If we're trying to create a new file, and the existing file is read //only then we can't. if(FS_CheckFlag(pMountInfo->Flags, MOUNT_FILE::MOUNT_FILE_READONLY) && bNew) { FS_ErrPrintW(L"OpenFile Error: \"%s\" cannot be created, because an existing file is read only.", ERR_LEVEL_ERROR, szFilename); return FS_NULL; } BDIO_FILE bdioFile=BDIO_OpenW(pMountInfo->szOSFileW, bNew?LF_CREATE_ALWAYS:LF_OPEN_EXISTING, Access); if(!bdioFile) { FS_ErrPrintW(L"Could not open the OS file: \"%s\".", ERR_LEVEL_ERROR, pMountInfo->szOSFileW); return FS_NULL; } return OpenExistingFile(pMountInfo, bdioFile, Access, bNew); } else { //TODO: Should also check to see if it is likely that the //file exists (because some OSs are not case sensitive //in which case the file may exist, but the path specified //may be a mounted file. //If it is necessary to create a new file, then we need to prepare //the mount info for the new file, as well as create an OS file. MOUNT_FILE mountInfo; //Get the specifie directory for the file, //then find the information about that directory in //the partition table. fs_pathW szDir; FS_GetDirFromPathW(szDir, szFilename); //The mount filename will be the same wcsncpy(mountInfo.szMountFileW, szFilename, FS_MAX_PATH); const MOUNT_FILE* pDirInfo=GetFileInfoW(szDir,FS_NULL); if(!pDirInfo || !FS_CheckFlag(pDirInfo->Flags, MOUNT_FILE::MOUNT_FILE_DIRECTORY)) { FS_ErrPrintW( L"OpenFile Error: Cannot create the specified file, the directory \"%s\" does not exist.", ERR_LEVEL_ERROR, szDir); return FS_NULL; } //Get just the filename for the file, //this will be used to create the OS file. fs_pathW szFile; FS_GetFileNameFromPathW(szFile, szFilename); FS_FixCaseW(szFile, szFile); //The OS filename is the information from the dir + the filename //Note that the OS separator must be inserted. _snwprintf(mountInfo.szOSFileW, FS_MAX_PATH, L"%s%c%s", pDirInfo->szOSFileW, BDIO_GetOsPathSeparator(), szFile); //The initial file information is all zeroes. mountInfo.Flags=0; mountInfo.nCmpSize=0; mountInfo.nSize=0; mountInfo.nOffset=0; //Create the OS file. BDIO_FILE bdioFile=BDIO_OpenW(mountInfo.szOSFileW, LF_CREATE_NEW, Access); if(!bdioFile) { FS_ErrPrintW( L"OpenFile Error: Could not create new file: \"%s\".", ERR_LEVEL_ERROR, mountInfo.szMountFileW); return FS_NULL; } //If the OS file was created, then we can mount the new file //and open the existing file. MountFile(&mountInfo, MOUNT_FILE_OVERWRITE); return OpenExistingFile(&mountInfo, bdioFile, Access, FS_TRUE); } } CLFile* CLFileSystem::OpenFileA(fs_cstr8 szFilename, fs_dword Access, fs_dword CreateMode) { fs_bool bOpenExisting=FS_TRUE; fs_bool bNew=FS_FALSE; //fs_pathW szFilenameW; //mbstowcs(szFilenameW, szFilename, FS_MAX_PATH); //Check the flags to make sure they are compatible. if(FS_CheckFlag(Access, LF_ACCESS_WRITE) && FS_CheckFlag(Access, LF_ACCESS_MEMORY)) { FS_ErrPrintA("OpenFile Error: Cannot open a file with memory access and write access.", ERR_LEVEL_ERROR); return FS_NULL; } //Note that if creating a new file, then we shouldn't end here. const MOUNT_FILE* pMountInfo=GetFileInfoA(szFilename,FS_NULL); if(CreateMode==LF_OPEN_EXISTING) { if(!pMountInfo) { FS_ErrPrintA("OpenFile Warning: \"%s\" could not be found in the file system.", ERR_LEVEL_WARNING, szFilename); return FS_NULL; } bOpenExisting=FS_TRUE; bNew=FS_FALSE; } else if(CreateMode==LF_OPEN_ALWAYS) { bOpenExisting=pMountInfo?FS_TRUE:FS_FALSE; bNew=FS_FALSE; } else if(CreateMode==LF_CREATE_NEW) { if(pMountInfo) { FS_ErrPrintA("OpenFile Error: Cannot create \"%s\", it already exists.", ERR_LEVEL_ERROR, szFilename); return FS_NULL; } bOpenExisting=FS_FALSE; bNew=FS_TRUE; } else if(CreateMode==LF_CREATE_ALWAYS) { if(pMountInfo) { bOpenExisting=FS_TRUE; bNew=FS_TRUE; } else { bOpenExisting=FS_FALSE; bNew=FS_TRUE; } } else { FS_ErrPrintA("OpenFile Error: Invalid creation mode specifed.", ERR_LEVEL_ERROR); return FS_NULL; } //If the file is mounted then we are opening an existing file. if(bOpenExisting) { if(FS_CheckFlag(pMountInfo->Flags, MOUNT_FILE::MOUNT_FILE_DIRECTORY)) { FS_ErrPrintW(L"OpenFile Error: \"%s\" is a directory, not a file.", ERR_LEVEL_ERROR, pMountInfo->szMountFileW); return FS_NULL; } //If we're trying to create a new file, and the existing file is read //only then we can't. if(FS_CheckFlag(pMountInfo->Flags, MOUNT_FILE::MOUNT_FILE_READONLY) && bNew) { FS_ErrPrintA("OpenFile Error: \"%s\" cannot be created, because an existing file is read only.", ERR_LEVEL_ERROR, szFilename); return FS_NULL; } fs_pathA szOSFileA; wcstombs(szOSFileA, pMountInfo->szOSFileW, FS_MAX_PATH); BDIO_FILE bdioFile=BDIO_OpenA(szOSFileA, bNew?LF_CREATE_ALWAYS:LF_OPEN_EXISTING, Access); if(!bdioFile) { FS_ErrPrintW(L"Could not open the OS file: \"%s\".", ERR_LEVEL_ERROR, pMountInfo->szOSFileW); return FS_NULL; } return OpenExistingFile(pMountInfo, bdioFile, Access, bNew); } else { //Should also check to see if it is likely that the //file exists (because some OSs are not case sensitive //in which case the file may exist, but the path specified //may be a mounted file. //If it is necessary to create a new file, then we need to prepare //the mount info for the new file, as well as create an OS file. MOUNT_FILE mountInfo; //Get the specifie directory for the file, //then find the information about that directory in //the partition table. fs_pathA szDir; FS_GetDirFromPathA(szDir, szFilename); //The mount filename will be the same mbstowcs(mountInfo.szMountFileW, szFilename, FS_MAX_PATH); const MOUNT_FILE* pDirInfo=GetFileInfoA(szDir,FS_NULL); if(!pDirInfo || !FS_CheckFlag(pDirInfo->Flags, MOUNT_FILE::MOUNT_FILE_DIRECTORY)) { FS_ErrPrintA( "OpenFile Error: Cannot create the specified file, the directory \"%s\" does not exist.", ERR_LEVEL_ERROR, szDir); return FS_NULL; } //Get just the filename for the file, //this will be used to create the OS file. fs_pathA szFile; fs_pathW szFileW; FS_GetFileNameFromPathA(szFile, szFilename); mbstowcs(szFileW, szFile, FS_MAX_PATH); FS_FixCaseW(szFileW, szFileW); //The OS filename is the information from the dir + the filename //Note that the OS separator must be inserted. _snwprintf(mountInfo.szOSFileW, FS_MAX_PATH, L"%s%c%s", pDirInfo->szOSFileW, BDIO_GetOsPathSeparator(), szFileW); //The initial file information is all zeroes. mountInfo.Flags=0; mountInfo.nCmpSize=0; mountInfo.nSize=0; mountInfo.nOffset=0; //Create the OS file. fs_pathA szOSFileA; wcstombs(szOSFileA, mountInfo.szOSFileW, FS_MAX_PATH); BDIO_FILE bdioFile=BDIO_OpenA(szOSFileA, LF_CREATE_NEW, Access); if(!bdioFile) { FS_ErrPrintW( L"OpenFile Error: Could not create new file: \"%s\".", ERR_LEVEL_ERROR, mountInfo.szMountFileW); return FS_NULL; } //If the OS file was created, then we can mount the new file //and open the existing file. MountFile(&mountInfo, MOUNT_FILE_OVERWRITE); return OpenExistingFile(&mountInfo, bdioFile, Access, FS_TRUE); } } CLFile* CLFileSystem::OpenExistingFile(const MOUNT_FILE* pMountInfo, BDIO_FILE File, fs_dword Access, fs_bool bNew) { //First thing's first, allocate memory for the file. CLFile* pFile=new CLFile; if(!pFile) { FS_ErrPrintW(L"OpenFile Error: Could not allocate memory for file.", ERR_LEVEL_ERROR); return FS_NULL; } //Initialize the file. pFile->m_BaseFile=File; pFile->m_bEOF=FS_FALSE; pFile->m_nAccess=Access; pFile->m_nBaseFileBegin=pMountInfo->nOffset; pFile->m_nFilePointer=0; //If creating a new file, the size needs to be set to 0. pFile->m_nSize=bNew?0:pMountInfo->nSize; pFile->m_pData=FS_NULL; wcsncpy(pFile->m_szPathW, pMountInfo->szMountFileW, FS_MAX_PATH); if(FS_CheckFlag(pMountInfo->Flags, MOUNT_FILE::MOUNT_FILE_READONLY) && bNew) { FS_ErrPrintW(L"OpenFile Error: \"%s\" cannot be created, because an existing file is read only.", ERR_LEVEL_ERROR, pFile->m_szPathW); BDIO_Close(pFile->m_BaseFile); delete pFile; return FS_NULL; } //Check infor flags again. if(FS_CheckFlag(pFile->m_nAccess, LF_ACCESS_WRITE) && FS_CheckFlag(pMountInfo->Flags, MOUNT_FILE::MOUNT_FILE_READONLY)) { FS_ErrPrintW(L"OpenFile Error: \"%s\" is read only, cannot open for writing.", ERR_LEVEL_ERROR, pFile->m_szPathW); BDIO_Close(pFile->m_BaseFile); delete pFile; return FS_NULL; } FS_ErrPrintW(L"Opening \"%s\"...", ERR_LEVEL_DETAIL, pFile->m_szPathW); //If the file is in an archive and is compressed it needs to be opened as a //memory file. if(FS_CheckFlag(pMountInfo->Flags, MOUNT_FILE::MOUNT_FILE_ARCHIVED) && FS_CheckFlag(pMountInfo->Flags, MOUNT_FILE::MOUNT_FILE_ZLIBCMP)) { pFile->m_nAccess|=LF_ACCESS_MEMORY; } //If the file is a memory file then we just open it, //allocate memory for it, and copy the file data into //the buffer. if(FS_CheckFlag(pFile->m_nAccess, LF_ACCESS_MEMORY)) { //Allocate memory... pFile->m_pData=static_cast<fs_byte*>(FS_Malloc(pFile->m_nSize, LF_ALLOC_REASON_FILE, "FS", __FILE__, __LINE__)); if(!pFile->m_pData) { FS_ErrPrintW(L"OpenFile Error: Could not allocte memory for \"%s\".", ERR_LEVEL_ERROR, pFile->m_szPathW); BDIO_Close(pFile->m_BaseFile); delete pFile; return FS_NULL; } //Read the file data... fs_dword nRead=0; //Seek to the beginning of the file... BDIO_Seek(pFile->m_BaseFile, pFile->m_nBaseFileBegin, LF_SEEK_BEGIN); //Then read either the compress data, or the uncompressed data. if(FS_CheckFlag(pMountInfo->Flags, MOUNT_FILE::MOUNT_FILE_ZLIBCMP)) { FS_ErrPrintW( L"Reading and uncompressing \"%s\"...", ERR_LEVEL_DETAIL, pFile->m_szPathW); nRead=BDIO_ReadCompressed(pFile->m_BaseFile, pFile->m_nSize, pFile->m_pData); } else { FS_ErrPrintW( L"Reading \"%s\"...", ERR_LEVEL_DETAIL, pFile->m_szPathW); nRead=BDIO_Read(pFile->m_BaseFile, pFile->m_nSize, pFile->m_pData); } if(nRead!=pFile->m_nSize) { FS_ErrPrintW( L"OpenFile Warning: Only read %d out of %d bytes in \"%s\".", ERR_LEVEL_WARNING, nRead, pFile->m_nSize, pFile->m_szPathW); pFile->m_nSize=nRead; } //We have the file open in memory so we no longer need to keep the //BDIO file open. BDIO_Close(pFile->m_BaseFile); pFile->m_BaseFile=FS_NULL; } else { //The file is not being opened as a memory file. //So we just leave it as it is and all file //reading/seeking functions will take care of everything. } pFile->m_bEOF=pFile->m_nFilePointer>=pFile->m_nSize; return pFile; } fs_bool CLFileSystem::CloseFile(CLFile* pFile) { fs_dword nSize=0; if(!pFile) return FS_FALSE; FS_ErrPrintW(L"Closing \"%s\"...", ERR_LEVEL_DETAIL, pFile->m_szPathW); if(pFile->m_BaseFile) { nSize=BDIO_GetSize(pFile->m_BaseFile); BDIO_Close(pFile->m_BaseFile); } FS_SAFE_DELETE_ARRAY(pFile->m_pData, LF_ALLOC_REASON_FILE); //If the file was writeable we need to update the data in the //partition table. if(FS_CheckFlag(pFile->m_nAccess, LF_ACCESS_WRITE)) { CPartTable* OwnerTable = FS_NULL; const MOUNT_FILE* pMountInfo=GetFileInfoW(pFile->m_szPathW,&OwnerTable); if(!pMountInfo) { FS_ErrPrintW(L"CloseFile Error: Could not update partition table.", ERR_LEVEL_ERROR); } else { MOUNT_FILE mountInfo=*pMountInfo; mountInfo.nSize=nSize; mountInfo.nCmpSize=nSize; OwnerTable->MountFile(&mountInfo, MOUNT_FILE_OVERWRITE); } } FS_SAFE_DELETE(pFile, LF_ALLOC_REASON_FILE); return FS_TRUE; } void CLFileSystem::EnumerateFilesOfTypeA( fs_cstr8 Ext , FS_ENUMERATE_FUNCA EnumerateFunc , void* Data ) { for( CPartTable* Table = m_PrtTableList; FS_NULL != Table; Table = Table->GetNext() ) { Table->EnumerateFilesOfTypeA( Ext , EnumerateFunc , Data ); } } void CLFileSystem::EnumerateFilesOfTypeW( fs_cstr16 Ext , FS_ENUMERATE_FUNCW EnumerateFunc , void* Data ) { for( CPartTable* Table = m_PrtTableList; FS_NULL != Table; Table = Table->GetNext() ) { Table->EnumerateFilesOfTypeW( Ext , EnumerateFunc , Data ); } } /******************************************************** *** The Partition Table Code *** A partition table keeps track of mounted files *** the table stores information about each file. *** *** The partition table stores all the file information *** in a hash table with HASH_SIZE entries. If a filename *** has a duplicate hash value then the table points *** to a linked list with all the filenames. ********************************************************/ CLFileSystem::CPartTable::CPartTable( CPartTable* Next , fs_dword nMaxFiles ) : m_nMaxFiles(nMaxFiles) , m_pMasterList(FS_NULL) , m_Next( Next ) { for(fs_dword i=0; i<HASH_SIZE; i++) { m_HashList[i]=FS_NULL; } //Create an initialize the master list m_pMasterList=static_cast<MOUNT_FILE_EX*>(FS_Malloc(sizeof(MOUNT_FILE_EX)*nMaxFiles, LF_ALLOC_REASON_SYSTEM, "FS", __FILE__, __LINE__)); if(!m_pMasterList) { return; } m_UnusedFiles.Init(m_pMasterList, nMaxFiles, sizeof(MOUNT_FILE_EX)); } CLFileSystem::CPartTable::~CPartTable() { Clear(); //Delete the hash table (note that the Clear method has already //deleted any linked lists that may exist, so the array can //safely be deleted without memory leaks. FS_SAFE_DELETE_ARRAY(m_pMasterList, LF_ALLOC_REASON_SYSTEM); } void CLFileSystem::CPartTable::Clear() { m_UnusedFiles.Init(m_pMasterList, m_nMaxFiles, sizeof(MOUNT_FILE_EX)); for(fs_dword i=0; i<HASH_SIZE; i++) { m_HashList[i]=FS_NULL; } } fs_bool CLFileSystem::CPartTable::IsFull()const { return m_UnusedFiles.IsEmpty(); } //FindFile finds a file in the partition table with the specified path. //If not file exists it returns NULL, also note that //this is CASE SENSITIVE so /base1/Tex.tga and /base1/tex.tga are not //the same file. CLFileSystem::MOUNT_FILE* CLFileSystem::CPartTable::FindFile(fs_cstr16 szFile) { //To find a file just get the hash value for the specified filename //and check to see if a file is at that hash entry, not that //the linked list should be checked at that hash entry. fs_dword nHash=GetHashValue1024(szFile); //Loop through the linked list (usually 1-3 items long) and find //the filename. for(MOUNT_FILE_EX* pItem=m_HashList[nHash]; pItem; pItem=pItem->pNext) { //Note that if a file is empty we don't need to worry //about it (we actually NEED to continue, becuase if a file //was mounted in that spot and was then unmounted all the //data is still there, only the Flags value has been changed.) if(pItem->Flags==MOUNT_FILE::MOUNT_FILE_EMPTY) continue; //If the string matches then return the file info. if(pItem->Flags!=MOUNT_FILE::MOUNT_FILE_ARCHIVED && (wcscmp(pItem->szMountFileW, szFile)==0)) return pItem; } return FS_NULL; } fs_bool CLFileSystem::CPartTable::MountFile(CLFileSystem::MOUNT_FILE* pFile, fs_dword Flags) { //Get the hash value for the mounted filename //note that we always use the mounted filename for the //hash table and not the OS filename. fs_dword nHash=GetHashValue1024(pFile->szMountFileW); //Figure out what the file extension is. (It'll be null terminated if there isn't one) fs_dword NameLen = wcslen( pFile->szMountFileW ); pFile->ExtOffset = NameLen; for( fs_dword i=0;i<NameLen;i++) { if( pFile->szMountFileW[i] == '.' ) { pFile->ExtOffset = i+1; } } //If the file at that hash entry is empty and there is no //linked list attached we can simply add the file to that spot. if( (m_HashList[nHash]==FS_NULL)) { //Create a new files; MOUNT_FILE_EX* pNewFile=(MOUNT_FILE_EX*)m_UnusedFiles.Pop(); if(!pNewFile) return FS_FALSE; pNewFile->pNext=FS_NULL; pNewFile->nHashValue=nHash; //Copy over the information for the file: memcpy(pNewFile, pFile, sizeof(MOUNT_FILE)); ////Copy just the MOUNT_FILE data, that way we don't overwrite the pNext value. //memcpy(m_pHashList[nHash], pFile, sizeof(MOUNT_FILE)); m_HashList[nHash]=pNewFile; return FS_TRUE; } else { //The same filename may already exist. So loop through the table and find //out if it does, if it does either skip the file or overwrite it based on //the flag, if the file doesn't exist add it on the end. for(MOUNT_FILE_EX* pItem=m_HashList[nHash]; pItem; pItem=pItem->pNext) { if(wcscmp(pItem->szMountFileW, pFile->szMountFileW)==0) { //The same file already exists, check flags and act appropriately. //If we need to overwrite an old file then we just copy the info if(FS_CheckFlag(Flags, MOUNT_FILE_OVERWRITELPKONLY)) { if(FS_CheckFlag(pItem->Flags, MOUNT_FILE::MOUNT_FILE_ARCHIVED)) { FS_ErrPrintW(L"Copying %s over old archive file.", ERR_LEVEL_DETAIL, pFile->szMountFileW); memcpy(pItem, pFile, sizeof(MOUNT_FILE)); return FS_TRUE; } else { FS_ErrPrintW(L"Cannot mount %s. A file with the same name has already been mounted.", ERR_LEVEL_DETAIL, pFile->szMountFileW); return FS_FALSE; } } else if(FS_CheckFlag(Flags, MOUNT_FILE_OVERWRITE)) { FS_ErrPrintW(L"Copying %s over old file.", ERR_LEVEL_DETAIL, pFile->szMountFileW); memcpy(pItem, pFile, sizeof(MOUNT_FILE)); return FS_TRUE; } else { FS_ErrPrintW(L"Cannot mount %s. A file with the same name has already been mounted.", ERR_LEVEL_DETAIL, pFile->szMountFileW); return FS_FALSE; } } if(pItem->pNext==FS_NULL) { //We got to the end of the list and the file wasn't found, //so we proceed to add the new file onto the end of the list. MOUNT_FILE_EX* pNew=(MOUNT_FILE_EX*)m_UnusedFiles.Pop(); if(!pNew) return FS_FALSE; memcpy(pNew, pFile, sizeof(MOUNT_FILE)); pNew->nHashValue=nHash; pNew->pNext=FS_NULL; pItem->pNext=pNew; return FS_TRUE; } //^^^...Loop to the next item in the list...^^^ } } //Shoul never actually get here. return FS_FALSE; } fs_dword CLFileSystem::CPartTable::GetHashValue1024(fs_cstr16 szString) { //This is basically <NAME>' One-At-A-Time-Hash. //http://www.burtleburtle.net/bob/hash/doobs.html fs_dword nLen=wcslen(szString); fs_dword nHash=0; fs_dword i=0; for(i=0; i<nLen; i++) { nHash+=szString[i]; nHash+=(nHash<<10); nHash^=(nHash>>6); } nHash+=(nHash<<3); nHash^=(nHash>>11); nHash+=(nHash<<15); //We'll limit our hash value from 0 to HASH_SIZE-1. return nHash%HASH_SIZE; } void CLFileSystem::CPartTable::PrintMountInfo(FS_PRINT_MOUNT_INFO_TYPE Type) { //Loop through all hash indexes and if the file exists //then print out the information about it. if( PRINT_MOUNT_INFO_FULL == Type ) { FS_ErrPrintA("FLAGS SIZE PACKED PATH", ERR_LEVEL_ALWAYS); FS_ErrPrintA("----- ---- ------ ----", ERR_LEVEL_ALWAYS); } fs_dword nFiles=0; for(fs_dword i=0; i<HASH_SIZE; i++) { for(MOUNT_FILE_EX* pItem=m_HashList[i]; pItem; pItem=pItem->pNext) { nFiles++; if( PRINT_MOUNT_INFO_FILENAME ==Type ) { fs_pathW szOutput; _snwprintf(szOutput, FS_MAX_PATH, L"%s", pItem->szMountFileW); szOutput[FS_MAX_PATH]=0; FS_ErrPrintW(szOutput, ERR_LEVEL_ALWAYS); } else { PrintFileInfo(pItem); } } } if( PRINT_MOUNT_INFO_FULL == Type ) { FS_ErrPrintA("Totals: %d files", ERR_LEVEL_ALWAYS, nFiles); } } void CLFileSystem::CPartTable::PrintFileInfo(MOUNT_FILE_EX* pFile) { //If there was not file in that table position we'll simply return. if(pFile->Flags==MOUNT_FILE::MOUNT_FILE_EMPTY) return; fs_char16 szOutput[29+FS_MAX_PATH]; szOutput[5]=' '; //First thing print all the file flags. if(FS_CheckFlag(pFile->Flags, MOUNT_FILE::MOUNT_FILE_DIRECTORY)) szOutput[0]=('d'); else szOutput[0]=('-'); if(FS_CheckFlag(pFile->Flags, MOUNT_FILE::MOUNT_FILE_ARCHIVED)) szOutput[1]=('a'); else szOutput[1]=('-'); if(FS_CheckFlag(pFile->Flags, MOUNT_FILE::MOUNT_FILE_READONLY)) { szOutput[2]=('r'); szOutput[3]=('-'); } else { szOutput[2]=('r'); szOutput[3]=('w'); } if(FS_CheckFlag(pFile->Flags, MOUNT_FILE::MOUNT_FILE_ZLIBCMP)) szOutput[4]=('z'); else szOutput[4]=('-'); _snwprintf(&szOutput[6], 10, L"%10u", pFile->nSize); szOutput[16]=' '; _snwprintf(&szOutput[17], 10, L"%10u", pFile->nCmpSize); szOutput[27]=' '; _snwprintf(&szOutput[28], FS_MAX_PATH, L"%s", pFile->szMountFileW); szOutput[28+FS_MAX_PATH]=0; FS_ErrPrintW(szOutput, ERR_LEVEL_ALWAYS); _snwprintf(szOutput, FS_MAX_PATH+27, L"%4u: %10u (%s)", pFile->nHashValue, pFile->nOffset, pFile->szOSFileW); FS_ErrPrintW(szOutput, ERR_LEVEL_DETAIL); } void CLFileSystem::CPartTable::EnumerateFilesOfTypeA( fs_cstr8 _Ext , FS_ENUMERATE_FUNCA EnumerateFunc , void* Data ) { fs_pathW Ext; mbstowcs(Ext, _Ext, FS_MAX_PATH); for(fs_dword HashPos=0; HashPos<HASH_SIZE; HashPos++) { for(MOUNT_FILE_EX* pItem=m_HashList[HashPos]; pItem; pItem=pItem->pNext) { fs_cstr16 FileExt = &pItem->szMountFileW[pItem->ExtOffset]; if( 0 == _wcsicmp( FileExt , Ext ) ) { fs_pathA FilenameA; wcstombs( FilenameA , pItem->szMountFileW , FS_MAX_PATH ); EnumerateFunc( FilenameA , Data ); } } } } void CLFileSystem::CPartTable::EnumerateFilesOfTypeW( fs_cstr16 Ext , FS_ENUMERATE_FUNCW EnumerateFunc , void* Data ) { for(fs_dword HashPos=0; HashPos<HASH_SIZE; HashPos++) { for(MOUNT_FILE_EX* pItem=m_HashList[HashPos]; pItem; pItem=pItem->pNext) { fs_cstr16 FileExt = &pItem->szMountFileW[pItem->ExtOffset]; if( 0 == _wcsicmp( FileExt , Ext ) ) { EnumerateFunc( pItem->szMountFileW , Data ); } } } } <file_sep>/samples/NASMDemo/NASMDemo.c #include <stdio.h> /* Declarations for the ASM within NASM functions. */ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ int __cdecl power2_ASM(unsigned long num, char power); int __stdcall power2_ASMSTD(unsigned long num, char power); #ifdef __cplusplus } #endif /* __cplusplus */ /* power2C power2 C version. */ int __cdecl power2_C(unsigned long num, char power) { return num<<power; } /* power2C power2 ASM within C version. */ int __cdecl power2_CASM(unsigned long num, char power) { __asm { mov eax, num /* Get first argument. */ mov cl, power /* Get second argument. */ shl eax, cl /* EAX = EAX * ( 2 to the power of CL ) */ } /* Return with result in EAX. */ } int __cdecl main(int argc, char** argv, char** envp) { int nResult=0; printf("The function is power2(3, 5)...\n\n"); printf("Doing assembly (__cdecl): %i\n", power2_ASM(3, 5)); printf("Doing assembly (__stdcall): %i\n", power2_ASMSTD(3, 5)); printf("Doing C (__cdecl): %i\n", power2_C(3, 5)); printf("Doing assembly within C (__cdecl): %i\n", power2_CASM(3, 5)); /* Calling C function within assembly, as __cdecl */ __asm { /* Push the params onto the stack. */ push 5 /* We push a 32-bit value because all parameters are passed as 32-bit. */ push 3 /* " " */ /* Call the function now that the params are in place. */ call power2_C /* Save the result. */ mov nResult, eax /* Pop the parameters off the stack. Becuase call is __cdecl. */ pop ebx /* Pop the parameters off the stack. */ pop ebx /* " " */ } printf("Calling C within assembly (__cdecl): %i\n", nResult); return 0; } <file_sep>/games/Legacy-Engine/Source/engine/lg_tmgr.h /* lg_tmgr.h - The texture manager. Copryight (c) 2008 <NAME> */ #ifndef __LG_TMGR_H__ #define __LG_TMGR_H__ #include <d3d9.h> #include "lg_types.h" #include "lg_hash_mgr.h" //All textures are represented by tm_tex, in this way they //are not specifically Direct3D based. Rather they are a //reference. Only the Texture manager itself sets the texture. //Should probably do something similar for vertex and index //buffers. typedef hm_item tm_tex; class CLTMgr: public CLHashMgr<IDirect3DTexture9>{ public: //Flags: const static lg_dword TM_FORCENOMIP=0x00000010; private: //Internal data, strictly initialized in the constructor. D3DPOOL m_nPool; IDirect3DDevice9* m_pDevice; //The device. public: /* Constructor PRE: Direct3D must be initialized. POST: The instance is created. */ CLTMgr(IDirect3DDevice9* pDevice, lg_dword nMaxTex); /* PRE: N/A. POST: Destroys everything, unloads all textures, and deallocates all memory associated. Note that after the manager is destroyed, any textures that have been obtained are still usable as only the reference count is decreased. Any textures obtained must still be released. */ ~CLTMgr(); /* PRE: See above, this is for lightmaps. POST: See above, but note that textures loaded from memory are not stored in the texture manager, and cannot be reobtained. This method should only be used to load lightmaps, or other textures that there is certainly only going to be one copy of. */ tm_tex LoadTextureMem(lg_void* pData, lg_dword nSize, lg_dword nFlags); /* PRE: N/A POST: Sets the specified texture for rendering in the specified stage. */ void SetTexture(tm_tex texture, lg_dword nStage); /* PRE: Called if device was lost. POST: Prepares the texture manager for a reset. */ void Invalidate(); /* PRE: Device must be reset. POST: Validates all textures. */ void Validate(); private: virtual IDirect3DTexture9* DoLoad(lg_path szFilename, lg_dword nFlags); virtual void DoDestroy(IDirect3DTexture9* pItem); private: //The static texture manager is so textures can be loaded on demand //without having acces to teh established texture manager within //the game class. static CLTMgr* s_pTMgr; public: /* PRE: The CLTMgr must be initialized. POST: If the specified texture is available it is loaded, see the public member LoadTexture for more details. */ static tm_tex TM_LoadTex(lg_path szFilename, lg_dword nFlags); /* PRE: The CLTMgr must be initialized. POST: If the specified texture is available it is loaded, see the public member LoadTextureMem for more details. */ static tm_tex TM_LoadTexMem(lg_void* pData, lg_dword nSize, lg_dword nFlags); /* PRE: texture must be a texture obtained with TM_LoadTex*, or 0 for no texture. POST: The texture set will be used for rendering. */ static void TM_SetTexture(tm_tex texture, lg_dword nStage); }; #endif __LG_TMGR_H__<file_sep>/games/Legacy-Engine/Scrapped/plugins/lw3DWS/lw3DWS.h // lw3DWS.h : main header file for the lw3DWS DLL // #pragma once #ifndef __AFXWIN_H__ #error "include 'stdafx.h' before including this file for PCH" #endif #include "resource.h" // main symbols // Clw3DWSApp // See lw3DWS.cpp for the implementation of this class // class Clw3DWSApp : public CWinApp { public: Clw3DWSApp(); // Overrides public: virtual BOOL InitInstance(); DECLARE_MESSAGE_MAP() }; <file_sep>/games/Legacy-Engine/Source/sdk/lw_ai_sdk.h /***************************************************** *** lw_ai_sdk.h - Copyright (c) 2008 Beem Software *** *** *** *** DO NOT MODIFY *** *** This file is a template for structures and *** *** items, that are used within the game, if these *** *** structures are modified in this file, then *** *** they will be incompatible with the game, and *** *** it is likely that the software will crash. *** *****************************************************/ #ifndef __LW_AI_SDK_H__ #define __LW_AI_SDK_H__ #include "lg_types.h" struct LEntitySrv; #define GAME_EXPORT extern "C" __declspec(dllexport) #define GAME_FUNC __cdecl /* AI Functions - These functions can be called within the PrePhys methods of an entity, the result (if any) will be avaialable in the post phys method. */ #define LWAI_QueueFunc(ent, func) LG_SetFlag(ent->m_nFuncs, func) //Do a ray trace, based on the look vector (the ray trace is carried //out from the objects center of gravity. The result is the UEID of //the entity that was hit (or level geometry, or null if nothing was //hit), and the coordinates of the trace. const lg_dword AI_FUNC_RAY_TRACE_LOOK=0x00000001; //Spawn entity, spawns an entity, based on the input given (useful for //missles being fired, etc. const lg_dword AI_FUNC_SPAWN_ENT=0x00000002; //Delete's the current entity, useful if the entity was killed, blown //up, or has expired. const lg_dword AI_FUNC_DELETE=0x00000004; const lg_dword AI_FUNC_REMOVE=0x00000004; //Do a ground trace, which gets the results of what the entity //is standing on (surface plane, in the air etc.) const lg_dword AI_FUNC_GROUND_TRACE=0x00000008; //Here are the physics flags, they are gotten by the physics engine to //decide certain things about how the body reacts. //The object is intelligent. const lg_dword AI_PHYS_INT=0x00000001; //m_v3Thrust represents and actual //movement distance and not a force. const lg_dword AI_PHYS_DIRECT_LINEAR=0x00000002; //m_v3Torque represents an actual //rotation and not a torque. const lg_dword AI_PHYS_DIRECT_ANGULAR=0x00000004; class CLWAIBase { public: virtual void Init(LEntitySrv* pEnt)=0; virtual void PrePhys(LEntitySrv* pEnt)=0; virtual void PostPhys(LEntitySrv* pEnt)=0; virtual lg_dword PhysFlags()=0; }; typedef struct _GAME_AI_GLOBAL{ lg_float fTimeStep; //Time step in seconds (since the last update). }GAME_AI_GLOBALS; #define LWAI_LIB_FUNC(return_type, name) typedef return_type (GAME_FUNC * TYPE_##name##_FUNC) LWAI_LIB_FUNC(CLWAIBase*, Game_ObtainAI)(lg_cstr szName); LWAI_LIB_FUNC(void, Game_Init)(); LWAI_LIB_FUNC(void, Game_UpdateGlobals)(const GAME_AI_GLOBALS* pIn); /* Command macros, translates flags into commands: */ #define LWAI_CmdActive(ent, cmd) LG_CheckFlag(pEnt->m_nCmdsActive, 1<<cmd) #define LWAI_CmdPressed(ent, cmd) LG_CheckFlag(pEnt->m_nCmdsPressed, 1<<cmd) /* Animation information: The infomation for an animation changes is stored within a single 32 bit dword, that way it can transfer over the network more quickly. Use the LWAI_SetAnim macro to set the animation: flag: value: Needs to be the entity's animation flag. node: value range: 0 to 15 notes: specifies which node the animation will effect. skel: value range: 0 to 15 notes: specifies which skeleton will be used for the animation. anim: value range: 0 to 31 notes: specifes which animation within the skel will be used. speed: value range: 0.0f to 10.0f notes: specifies the speed of the animation, the value represents how many seconds it takes to complete the animation (0 to 10 seconds). trans: value range: 0f to 10.0f notes: computed as above, but represents the time it takes to transition from the current animation to the next. */ const lg_dword LWAI_ANIM_CHANGE=0x00000001; #define LWAI_SetAnim(flag, node, skel, anim, speed, trans) { \ flag=0x00000001; \ flag|=(0xF&(node))<<1;\ flag|=(0xF&(skel))<<5;\ flag|=(0x1F&(anim))<<9; \ flag|=(0x1FF&((lg_dword)((speed)*51.1f)))<<14;\ flag|=(0x1FF&((lg_dword)((trans)*51.1f)))<<23;\ } //Checks to see if the animation is as specified. #define LWAI_IsAnim(flag, node, skel, anim) \ (flag&((node<<1)|(skel<<5)|(anim<<9)))\ //These are used internally and probably don't need to be //called for ai functions. #define LWAI_GetAnimNode(flag) ((0x0000001E&flag)>>1) #define LWAI_GetAnimSkel(flag) ((0x000001E0&flag)>>5) #define LWAI_GetAnimAnim(flag) ((0x00003E00&flag)>>9) #define LWAI_GetAnimSpeed(flag) (((0x007FC000&flag)>>14)/51.1f) #define LWAI_GetAnimTrans(flag) (((0xFF800000&flag)>>23)/51.1f) #endif __LW_AI_SDK_H__<file_sep>/tools/ListingGen/ListingGen/Main.cpp #include <stdio.h> #include <windows.h> #include "Lister.h" #include "resource.h" BOOL GetLister(CLister ** lppLister, HMODULE hListerDll) { FPOBTAINLISTER fpObtainLister=NULL; if(lppLister==NULL || hListerDll==NULL) return FALSE; fpObtainLister=(FPOBTAINLISTER)GetProcAddress(hListerDll, "ObtainLister"); if(fpObtainLister==NULL) { MessageBox(NULL, "Invalid Lister Plugin!", "Listing Generator", MB_OK|MB_ICONERROR); return FALSE; } (*lppLister)=fpObtainLister(); if((*lppLister)==NULL) { MessageBox(NULL, "Could not obtain lister!", "Listing Generator", MB_OK|MB_ICONERROR); return FALSE; } return TRUE; } BOOL DoListing(char szPlugin[MAX_PATH], HWND hwndParent) { HMODULE hListerDll=NULL; CLister * lpLister=NULL; hListerDll=LoadLibraryA(szPlugin); if(hListerDll==NULL) { MessageBox(hwndParent, "Could not load the specified plugin!", "Listing Generator", MB_OK|MB_ICONERROR); return FALSE; } if(!GetLister(&lpLister, hListerDll)) { MessageBox(hwndParent, "Unable to obtain lister!", "Listing Generator", MB_OK|MB_ICONERROR); FreeLibrary(hListerDll); return 0; } if(lpLister->RunDialog(hwndParent)) { OPENFILENAME of; char szFilename[MAX_PATH]; szFilename[0]=NULL; ZeroMemory(&of, sizeof(OPENFILENAME)); of.lStructSize=sizeof(OPENFILENAME); of.hwndOwner=hwndParent; of.lpstrFilter="HTML File (*.html)\0*.html\0All Files (*.*)\0*.*\0"; of.lpstrFile=szFilename; of.nMaxFile=MAX_PATH; of.lpstrTitle="Generate Listing"; of.lpstrDefExt="html"; if(GetSaveFileName(&of)) lpLister->CreateListing(szFilename); } delete lpLister; FreeLibrary(hListerDll); hListerDll=NULL; return TRUE; } BOOL PopulateListboxWithPlugins(HWND hwnd, int nIDDlgItem) { HANDLE hFind=NULL; WIN32_FIND_DATA FindData; ZeroMemory(&FindData, sizeof(WIN32_FIND_DATA)); hFind=FindFirstFile("plugins\\*.dll", &FindData); if(hFind==INVALID_HANDLE_VALUE) return FALSE; do { SendDlgItemMessage(hwnd, nIDDlgItem, CB_ADDSTRING, 0, (LPARAM)(LPCSTR)FindData.cFileName); }while(FindNextFile(hFind, &FindData)); FindClose(hFind); return TRUE; } BOOL CALLBACK PluginSelect( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch(uMsg) { case WM_INITDIALOG: { //Populat dialog box with available plugins. PopulateListboxWithPlugins(hwnd, IDC_LISTINGTYPE); break; } case WM_COMMAND: { switch(LOWORD(wParam)) { case IDC_GENERATE: { char szPath[MAX_PATH]; char szTemp[MAX_PATH]; GetDlgItemText(hwnd, IDC_LISTINGTYPE, szTemp, MAX_PATH); sprintf(szPath, "plugins\\%s", szTemp); if(!DoListing(szPath, hwnd)) { MessageBox(hwnd, "Could Not Generate Listing!", "Listing Generator", MB_OK|MB_ICONERROR); } else { MessageBox(hwnd, "Successfully Ran Listing Wizard!", "Listing Generator", MB_OK|MB_ICONINFORMATION); } break; } case IDC_QUIT: EndDialog(hwnd, 0); break; default: break; } break; } case WM_CLOSE: EndDialog(hwnd, 0); break; default: return FALSE; } return TRUE; } int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE, LPSTR lpCmdLine, int nShowCmd) { DialogBox(hInstance, MAKEINTRESOURCE(IDD_LISTING), NULL, PluginSelect); //DoListing("plugins\\gamelister.dll", NULL); return 0; }<file_sep>/games/Legacy-Engine/Scrapped/old/lm_mesh_old.cpp #if 0 #include "lm_mesh_lg.h" #include "lm_skin.h" class CLMeshNode { friend class CLMeshNode; public: CLMeshLG* m_pMesh; //The mesh for this node CLSkelLG* m_pDefSkel; //The default skeleton for this mesh. CLSkin m_Skin; //The skin for this node. private: CLSkelLG* m_pSkel; //The current skel for this node lg_dword m_nAnim; //The animation to use in the current skel float m_fTime; //The time for the animation (0.0f to 100.0f). lg_long m_nAnimSpeed; //How many milliseconds it takes to cycle through the animation lg_dword m_nTime; //The saved time for animation purposes lg_dword m_nLastUpdate;//The last time the animation was updated //The following info is used for transition animations CLSkelLG* m_pPrevSkel; //The previous skeleton lg_dword m_nPrevAnim; //The previous animation within the previous skeleton float m_fPrevTime; //The previous time for the previous animation lg_dword m_nTransTime; //How many milliseconds it should take to transition to the new animation private: CLMeshNode* m_pNext; //The next node in the list. CLMeshNode* m_pChildren; //The children of this node CLMeshNode* m_pParent; //The parent of the current node (not used) lg_dword m_nParentJoint; //The reference of the joint to which the child is attached. public: CLMeshNode(); ~CLMeshNode(); //Load a node. Note that the nodes are only used for frame and animation purposes, //they don't allocate or deallocate any memory. For this reason the load //method takes a preexisting mesh, the SetAnimation method takes a preexisting skeleton. //For this reason it is necessary that skeletons and meshes are not unloaded while //a mesh node still contains a reference to them. void Load(CLMeshLG* pMesh); void SetCompatibleWith(CLSkelLG* pSkel); void AddChild(CLMeshNode* pNode, lg_cstr szJoint); void Unload(); //It is only necessary to call Render on the topmost parent node, all child nodes //will be render according to the necessary joint transform. void Render(const ML_MAT* matTrans); //UpdateTime should be called once a frame, this sets all the time parameters //necessary for setting up the animation. Update time will update all child //nodes times as well so it is only necessary to call update time for the topmost //node in a set. void UpdateTime(lg_dword nTime); //SetAnimation changes the current animation to a new one, if the same animation //is specified the animation will not change. It is only necessary to call this //method when changing to a different animation, however calling it every frame //with the same paramters will not change anything, but it will waste processor //time. void SetAnimation(CLSkelLG* pSkel, lg_dword nAnim, lg_long nSpeed, lg_dword nTransTime); const CLMeshNode* GetParent(); }; //We can only use the mesh loading functions if FS2 is being used, //as fs2 is used for opening the xml file. CLMeshNode* LM_LoadMeshNodes(lg_path szXMLScriptFile, lg_dword* nNumMeshes); void LM_DeleteMeshNodes(CLMeshNode* pNodes); #endif typedef struct _LMESH_VERTEX{ float x, y, z; //Vertex Coordinates. float nx, ny, nz; //Vertex Normals. float tu, tv; //Texture Coordinates. }LMESH_VERTEX, *PLMESH_VERTEX; #define LMESH_VERTEX_FORMAT (D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX1) typedef struct _LMESH_SET{ LMESH_NAME szName; //Name of the mesh. lg_dword nFirstIndex; //Index of the first vertex in the mesh. lg_dword nNumTriangles; //Number of triangles in the mesh. lg_dword nMaterialIndex; //Index of the mesh material. }LMESH_SET, *PLMESH_SET; typedef struct _LMESH_MATERIAL{ LMESH_NAME szMaterialName; LMESH_PATH szTexture; }LMESH_MATERIAL, *PLMESH_MATERIAL; class CLMesh { friend class CLSkin; #ifdef LM_USE_LF2 public: static lg_uint ReadLF2(void* buffer, lg_uint size, lg_uint count, void* stream); static lg_uint WriteLF2(void* buffer, lg_uint size, lg_uint count, void* stream); #endif LM_USE_LF2 public: CLMesh(); virtual ~CLMesh(); lg_bool Load(void* file, LM_RW_FN read, char* szModelPath); lg_bool Save(void* file, LM_RW_FN write); #ifdef LM_USE_LF2 lg_bool Load(lf_path szFilename); #endif LM_USE_LF2 virtual lg_bool Unload(); const ML_AABB* GetBoundingBox(); lg_dword GetJointRef(lg_cstr szJoint); lg_bool IsLoaded(); protected: lg_bool AllocateMemory(); void DeallocateMemory(); lg_bool Serialize( void* file, LM_RW_FN read_or_write, lg_bool bLoading); void BuildFullTexPath(LMESH_PATH szOut, LMESH_PATH szTexPath); protected: lg_dword m_ID; lg_dword m_nVersion; LMESH_NAME m_szMeshName; lg_dword m_nNumVertices; lg_dword m_nNumTriangles; lg_dword m_nNumMeshes; lg_dword m_nNumMaterials; lg_dword m_nNumBones; LMESH_VERTEX* m_pVertices; lg_word* m_pIndexes; //Should be sized 3*m_nNumTriangles*sizeof(lg_word) in size; lg_dword* m_pVertexBoneList; LMESH_NAME* m_pBoneNameList; LMESH_SET* m_pMeshes; LMESH_MATERIAL* m_pMaterials; ML_AABB m_AABB; //The bounding box for the static mesh (note that skeletal bounding boxes are used for animated objects). LMESH_PATH m_szModelPath; //Stores the model path information. lg_bool m_bLoaded; }; //lm_mesh.cpp - Source Code for the Legacy Mesh (CLMesh). //Note that the loading code is compatible with Legacy //File System 2, but that loading code will only be available //if LM_USE_LF2 is defined (this should be a project wide definition). #include <memory.h> #include <stdio.h> #include "lm_sys.h" #include "ML_lib.h" #include "lg_func.h" ////////////////////////////// /// The Legacy Mesh Class /// ////////////////////////////// CLMesh::CLMesh(): m_ID(0), m_nVersion(0), m_nNumVertices(0), m_nNumTriangles(0), m_nNumMeshes(0), m_nNumMaterials(0), m_nNumBones(0), m_pVertices(LG_NULL), m_pIndexes(LG_NULL), m_pVertexBoneList(LG_NULL), m_pBoneNameList(LG_NULL), m_pMeshes(LG_NULL), m_pMaterials(LG_NULL), m_bLoaded(LG_FALSE) { m_szMeshName[0]=0; memset(&m_AABB, 0, sizeof(ML_AABB)); } CLMesh::~CLMesh() { this->Unload(); } lg_bool CLMesh::AllocateMemory() { //Before this function is called //m_nNumVertices, m_nNumMeshes, m_nNumMaterials should be set. //Call deallocate memory, just in case memory is already allocated: DeallocateMemory(); m_pVertices=new LMESH_VERTEX[m_nNumVertices]; m_pIndexes=new lg_word[m_nNumTriangles*3]; m_pMeshes=new LMESH_SET[m_nNumMeshes]; m_pMaterials=new LMESH_MATERIAL[m_nNumMaterials]; m_pVertexBoneList=new lg_dword[m_nNumVertices]; m_pBoneNameList=new LMESH_NAME[m_nNumBones]; if(!m_pVertices || !m_pIndexes || !m_pMeshes || !m_pMaterials || !m_pVertexBoneList || !m_pBoneNameList) { //If all the memory necessary can't be allocated then... //Deallocate any memory that has been allocated... DeallocateMemory(); //And return false for failure... return LG_FALSE; } return LG_TRUE; } void CLMesh::DeallocateMemory() { L_safe_delete_array(m_pVertices); L_safe_delete_array(m_pIndexes); L_safe_delete_array(m_pMeshes); L_safe_delete_array(m_pMaterials); L_safe_delete_array(m_pVertexBoneList); L_safe_delete_array(m_pBoneNameList); } lg_dword CLMesh::GetJointRef(lg_cstr szJoint) { for(lg_dword i=0; i<m_nNumBones; i++) { if(L_strnicmp(m_pBoneNameList[i], szJoint, 0)) return i; } return 0xFFFFFFFF; } const ML_AABB* CLMesh::GetBoundingBox() { return &m_AABB; } void CLMesh::BuildFullTexPath(LMESH_PATH szOut, LMESH_PATH szTexPath) { lg_byte nStart=L_strnicmp(szTexPath, ".\\", 2) || L_strnicmp(szTexPath, "./", 2)?2:0; LG_strncpy(szOut, m_szModelPath, LMESH_MAX_PATH-1); L_strncat(szOut, &szTexPath[nStart], LMESH_MAX_PATH); } #ifdef LM_USE_LF2 //The read and write LF2 functions are used for the legacy mesh //and legacy skel serialize methods when the LF2 file system is in //use. lg_uint CLMesh::ReadLF2(void* buffer, lg_uint size, lg_uint count, void* stream) { return LF_Read((LF_FILE3)stream, buffer, size*count); } lg_uint WriteLF2(void* buffer, lg_uint size, lg_uint count, void* stream) { return LF_Write((LF_FILE3)stream, buffer, size*count); } lg_bool CLMesh::Load(lf_path szFilename) { Unload(); LF_FILE3 fIn=LF_Open(szFilename, LF_ACCESS_READ, LF_OPEN_EXISTING); if(!fIn) return LG_FALSE; lg_bool bResult=Serialize(fIn, ReadLF2, LG_TRUE); LF_Close(fIn); if(!bResult) return LG_FALSE; //Because the LF2 file system always specifies the //full path name to open a file, we only need to //use the GetDirFromPath function to get the path //to the model. The path to the model is used //when loading textures. LF_GetDirFromPath(m_szModelPath, szFilename); m_bLoaded=LG_TRUE; return LG_TRUE; } #endif lg_bool CLMesh::Load(void* file, LM_RW_FN read, char* szModelPath) { //First unload the file. Unload(); if(!Serialize(file, read, LG_TRUE)) { return LG_FALSE; } LG_strncpy(m_szModelPath, szModelPath, LMESH_MAX_PATH-1); m_bLoaded=LG_TRUE; return LG_TRUE; } lg_bool CLMesh::Unload() { if(!m_bLoaded) return LG_TRUE; //Deallocate model's memory. DeallocateMemory(); m_ID=0; m_nVersion=0; m_nNumVertices=0; m_nNumMeshes=0; m_nNumMaterials=0; m_pVertices=LG_NULL; m_pVertexBoneList=LG_NULL; m_pMeshes=LG_NULL; m_pMaterials=LG_NULL; m_bLoaded=LG_FALSE; return LG_TRUE; } lg_bool CLMesh::IsLoaded() { return m_bLoaded; } lg_bool CLMesh::Serialize( void* file, lg_uint (__cdecl * read_or_write)(void* buffer, lg_uint size, lg_uint count, void* stream), lg_bool bLoading) { //Read or Write the file header. read_or_write(&m_ID, 4, 1, file); read_or_write(&m_nVersion, 4, 1, file); read_or_write(m_szMeshName, LMESH_MAX_NAME, 1, file); read_or_write(&m_nNumVertices, 4, 1, file); read_or_write(&m_nNumTriangles, 4, 1, file); read_or_write(&m_nNumMeshes, 4, 1, file); read_or_write(&m_nNumMaterials, 4, 1, file); read_or_write(&m_nNumBones, 4, 1, file); if(m_ID!=LMESH_ID || m_nVersion!=LMESH_VERSION) { return LG_FALSE; } //Allocate memory if we are loading. if(bLoading) if(!AllocateMemory())return LG_FALSE; //Read or Write the vertexes. lg_dword i=0; for(i=0; i<m_nNumVertices; i++) { read_or_write(&this->m_pVertices[i], sizeof(LMESH_VERTEX), 1, file); } for(i=0; i<m_nNumTriangles; i++) { read_or_write(&this->m_pIndexes[i*3], sizeof(lg_word)*3, 1, file); } //Read or Write the bone indexes. read_or_write(this->m_pVertexBoneList, sizeof(lg_dword), m_nNumVertices, file); //Write the bone names: for(i=0; i<m_nNumBones; i++) { read_or_write(this->m_pBoneNameList[i], sizeof(LMESH_NAME), 1, file); } //Read or Write the meses. for(i=0; i<m_nNumMeshes; i++) { read_or_write(&this->m_pMeshes[i], sizeof(LMESH_SET), 1, file); } //Read or Write the materials. for(i=0; i<m_nNumMaterials; i++) { read_or_write(&this->m_pMaterials[i], sizeof(LMESH_MATERIAL), 1, file); } //Read or write the bounding box. read_or_write(&this->m_AABB, 24, 1, file); return LG_TRUE; } lg_bool CLMesh::Save(void* file, LM_RW_FN write) { if(!m_bLoaded) return LG_FALSE; return Serialize(file, write, LG_FALSE); } class CLMeshD3D: public CLMesh { friend class CLMeshNode; public: CLMeshD3D(); ~CLMeshD3D(); //lg_bool Create(char* szFilename, IDirect3DDevice9* lpDevice); lg_bool CreateD3DComponents();//IDirect3DDevice9* lpDevice); lg_bool Validate(); lg_bool Invalidate(); lg_bool Render(CLSkin* pSkin=LG_NULL); lg_bool RenderNormals(); void SetRenderTexture(lg_bool b); void SetCompatibleWithSkel(CLSkel* pSkel); lg_bool PrepareFrame(lg_dword dwFist, lg_dword dwSecond, float fTime, CLSkel* pSkel, lg_bool bSetupVerts=LG_TRUE); lg_bool PrepareFrame(lg_dword nAnim, float fTime, CLSkel* pSkel, lg_bool bSetupVerts=LG_TRUE); void PrepareDefaultFrame(); lg_bool TransitionTo(lg_dword nAnim, float fTime, CLSkel* pSkel); lg_bool IsD3DReady(); virtual lg_bool Unload(); const ML_MAT* GetJointTransform(lg_dword nRef); const ML_MAT* GetJointAttachTransform(lg_dword nRef); private: //IDirect3DDevice9* m_lpDevice; IDirect3DVertexBuffer9* m_lpVB; IDirect3DIndexBuffer9* m_lpIB; tm_tex* m_lppTexs; lg_bool m_bD3DValid; lg_bool m_bD3DReady; lg_bool m_bRenderTexture; //Some structures to hold the stuff that is used every //frame but is only temporary. ML_MAT* m_pAnimMats; ML_MAT* m_pAttachMats; //The joint reference coordination array. lg_dword* m_pBoneRef; void TransformVerts(); public: static void SetRenderStates(); static void SetSkyboxRenderStates(); static lg_bool InitMeshDevice(IDirect3DDevice9* pDevice); static void UnInitMeshDevice(); private: static IDirect3DDevice9* s_pDevice; }; IDirect3DDevice9* CLMeshLG::s_pDevice=LG_NULL; lg_bool CLMeshLG::InitMeshDevice(IDirect3DDevice9* pDevice) { s_pDevice=pDevice; if(!s_pDevice) return LG_FALSE; s_pDevice->AddRef(); return LG_TRUE; } void CLMeshLG::UnInitMeshDevice() { if(s_pDevice) { lg_ulong nRef=s_pDevice->Release(); s_pDevice=nRef?s_pDevice:LG_NULL; } } void CLMeshLG::SetRenderStates() { if(!s_pDevice) return; s_pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); s_pDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); s_pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); s_pDevice->SetRenderState(D3DRS_NORMALIZENORMALS, TRUE); s_pDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); s_pDevice->SetRenderState(D3DRS_ZENABLE, TRUE); s_pDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE); s_pDevice->SetSamplerState( 0, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP); s_pDevice->SetSamplerState( 0, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP); } void CLMeshLG::SetSkyboxRenderStates() { ML_MAT m2; ML_MatIdentity((ML_MAT*)&m2); s_pDevice->SetTransform(D3DTS_WORLD, (D3DMATRIX*)&m2); SetRenderStates(); s_pDevice->SetRenderState(D3DRS_ZENABLE, FALSE); s_pDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE); s_pDevice->SetRenderState(D3DRS_LIGHTING, FALSE); s_pDevice->SetSamplerState( 0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP); s_pDevice->SetSamplerState( 0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP); } CLMeshLG::CLMeshLG(): CLMesh() { //m_lpDevice=LG_NULL; m_lpVB=LG_NULL; m_lpIB=LG_NULL; m_lppTexs=LG_NULL; m_bD3DValid=LG_FALSE; m_pAnimMats=LG_NULL; m_bRenderTexture=LG_TRUE; m_pBoneRef=LG_NULL; m_bD3DReady=LG_FALSE; } CLMeshLG::~CLMeshLG() { Unload(); } lg_bool CLMeshLG::CreateD3DComponents()//IDirect3DDevice9* lpDevice) { if(!m_bLoaded) return LG_FALSE; if(!s_pDevice) return LG_FALSE; if(m_bD3DReady) return LG_TRUE; //Allocate memory for textures. m_lppTexs=new tm_tex[m_nNumMaterials]; //Prepare the joints for rendering. m_pAnimMats=new ML_MAT[m_nNumBones*2]; m_pAttachMats=&m_pAnimMats[m_nNumBones]; //Set up the bone references m_pBoneRef=new lg_dword[m_nNumBones]; for(lg_dword i=0; i<m_nNumBones; i++) m_pBoneRef[i]=i; lg_dword i=0; for(i=0; i<m_nNumBones; i++) { ML_MatIdentity(&m_pAnimMats[i]); } //Load the textures. for(i=0; i<m_nNumMaterials; i++) { LMESH_PATH szFullTexPath; BuildFullTexPath(szFullTexPath, m_pMaterials[i].szTexture); m_lppTexs[i]=CLTMgr::TM_LoadTex(szFullTexPath, 0);//Tex_Load2(szFullTexPath); } if(!Validate()) { LG_SafeDeleteArray(m_lppTexs); LG_SafeDeleteArray(m_pAnimMats); return LG_FALSE; } m_bD3DReady=LG_TRUE; return LG_TRUE; } lg_bool CLMeshLG::Unload() { if(!m_bLoaded) return LG_TRUE; lg_dword i=0; Invalidate(); L_safe_delete_array(m_lppTexs); L_safe_delete_array(m_pAnimMats); L_safe_delete_array(m_pBoneRef); this->CLMesh::Unload(); m_lpVB=LG_NULL; m_lpIB=LG_NULL; m_lppTexs=LG_NULL; m_bD3DValid=LG_FALSE; return LG_TRUE; } lg_bool CLMeshLG::IsD3DReady() { return m_bD3DReady; } lg_bool CLMeshLG::Validate() { //If the device has not been set, then we can't validate. if(!s_pDevice) return LG_FALSE; //If we are already valid we don't need to revalidate the object. if(m_bD3DValid) return LG_TRUE; //Create the vertex buffer and fill it with the default information. lg_result nResult=0; nResult=s_pDevice->CreateVertexBuffer( m_nNumVertices*sizeof(LMESH_VERTEX), D3DUSAGE_WRITEONLY, LMESH_VERTEX_FORMAT, D3DPOOL_DEFAULT, &m_lpVB, LG_NULL); if(LG_FAILED(nResult)) { return LG_FALSE; } nResult=s_pDevice->CreateIndexBuffer( m_nNumTriangles*3*sizeof(*m_pIndexes), D3DUSAGE_WRITEONLY, D3DFMT_INDEX16, D3DPOOL_DEFAULT, &m_lpIB, LG_NULL); if(LG_FAILED(nResult)) { m_lpVB->Release(); return LG_FALSE; } // Now fill the vertex buffer with the default vertex data. // Note that animation data will be created and filled into // the vertex buffer on the fly. void* lpBuffer=LG_NULL; //Fill in the vertex buffer (note that this is the only time //that texture coords are written, but the vertex and normal //data gets rewritten when PrepareFrame is called. nResult=m_lpVB->Lock(0, m_nNumVertices*sizeof(LMESH_VERTEX), &lpBuffer, 0); if(LG_FAILED(nResult)) { L_safe_release(m_lpVB); L_safe_release(m_lpIB); return LG_FALSE; } memcpy(lpBuffer, m_pVertices, m_nNumVertices*sizeof(LMESH_VERTEX)); m_lpVB->Unlock(); //Now fill the index buffer: nResult=m_lpIB->Lock(0, m_nNumTriangles*3*sizeof(*m_pIndexes), &lpBuffer, 0); if(LG_FAILED(nResult)) { L_safe_release(m_lpVB); L_safe_release(m_lpIB); return LG_FALSE; } memcpy(lpBuffer, m_pIndexes, m_nNumTriangles*3*sizeof(*m_pIndexes)); m_lpIB->Unlock(); m_bD3DValid=LG_TRUE; return LG_TRUE; } lg_bool CLMeshLG::Invalidate() { if(!m_bD3DValid) return LG_FALSE; lg_dword i=0; L_safe_release(m_lpVB); L_safe_release(m_lpIB); m_bD3DValid=LG_FALSE; return LG_TRUE; } void CLMeshLG::PrepareDefaultFrame() { for(lg_dword i=0; i<m_nNumBones*2; i++) ML_MatIdentity(&m_pAnimMats[i]); TransformVerts(); } /********************************************************************** *** Technically the prepare frame functions should *** get a compatible skeleton, not all skeleton's are compatible *** with every model so in the future there will be a method to *** check compatibility, but this should not be called every frame *** as it would only use unecessary processor power, instead *** it is up to the the programmer to make sure a skeleton is *** compatible before using it for rendering, as the function stands *** right now the PrepareFrame functions simply try to prepare a *** frame based off joint references ***********************************************************************/ lg_bool CLMeshLG::PrepareFrame(lg_dword dwFrame1, lg_dword dwFrame2, float t, CLSkel* pSkel, lg_bool bSetupVerts) { if(!pSkel || !pSkel->IsLoaded()) { PrepareDefaultFrame(); return LG_FALSE; } ML_MAT* pJointTrans=(ML_MAT*)m_pAnimMats; //Prepare each joints final transformation matrix. for(lg_dword i=0; i<m_nNumBones; i++) { //To calculate the interpolated transform matrix //we need only call MCSkel's GenerateJointTransform method. pSkel->GenerateJointTransform(&pJointTrans[i], m_pBoneRef[i], dwFrame1, dwFrame2, t); //We don't necessarily need to setup attachment matrices for every bone (only for the //ones that actually get objects attached to them), but for now we set them up for //all bone anyway. ML_MatMultiply(&m_pAttachMats[i], pSkel->GetBaseTransform(m_pBoneRef[i]), &pJointTrans[i]); } //Transform all the vertices. if(bSetupVerts) TransformVerts(); return LG_TRUE; } //TransformVerts is called to actually transform //all the vertices in the mesh based upon the joint transforms. void CLMeshLG::TransformVerts() { if(!m_bD3DValid) return; //Lock the vertex buffer to prepare to write the data. LMESH_VERTEX* pVerts=LG_NULL; if(LG_FAILED(m_lpVB->Lock(0, m_nNumVertices*sizeof(LMESH_VERTEX), (void**)&pVerts, 0))) return; //Now that the transformations are all set up, //all we have to do is multiply each vertex by the //transformation matrix for it's joint. Note that //the texture coordinates have already been established //so they are not recopyed here. for(lg_dword i=0; i<m_nNumVertices; i++) { //Copy the vertex we want. //memcpy(&pVerts[i], &m_pVertices[i], sizeof(LMESH_VERTEX)); //If the vertex's bone is -1 it means that it is //not attached to a joint so we don't need to transform it. if(m_pVertexBoneList[i]!=-1) { //Multiply each vertex by it's joints transform. ML_Vec3TransformCoord((ML_VEC3*)&pVerts[i].x, (ML_VEC3*)&m_pVertices[i].x, &m_pAnimMats[m_pVertexBoneList[i]]); //Do the same for each vertex's normal, but we don't transorm by the //x,y,z.. so we call Vec3TransformNormal instead of Coord. ML_Vec3TransformNormal((ML_VEC3*)&pVerts[i].nx, (ML_VEC3*)&m_pVertices[i].nx, &m_pAnimMats[m_pVertexBoneList[i]]); } } //We've written all the vertices so lets unlock the VB. m_lpVB->Unlock(); return; } //TransitionTo should be called after PrepareFrame, it will generate //transforms to transform the current frame to the new animation. lg_bool CLMeshLG::TransitionTo(lg_dword nAnim, float fTime, CLSkel* pSkel) { const LSKEL_ANIM* pAnim=pSkel->GetAnim(nAnim); for(lg_dword i=0; i<m_nNumBones; i++) { ML_MAT matTemp; ML_MAT matTemp2; pSkel->GenerateJointTransform(&matTemp, m_pBoneRef[i], pAnim->m_nFirstFrame, pAnim->m_nFirstFrame, 0.0f); ML_MatMultiply(&matTemp2, pSkel->GetBaseTransform(m_pBoneRef[i]), &matTemp); ML_MatSlerp(&m_pAnimMats[i], &m_pAnimMats[i], &matTemp, fTime); ML_MatSlerp(&m_pAttachMats[i], &m_pAttachMats[i], &matTemp2, fTime); } TransformVerts(); return LG_TRUE; } const ML_MAT* CLMeshLG::GetJointTransform(lg_dword nRef) { if(nRef<m_nNumBones) return &m_pAnimMats[nRef]; else return LG_NULL; } const ML_MAT* CLMeshLG::GetJointAttachTransform(lg_dword nRef) { if(nRef<m_nNumBones) return &m_pAnimMats[nRef+m_nNumBones]; else return LG_NULL; } //This verison of prepare frames takes an animation and //it wants a value from 0.0f to 100.0f. 0.0f would be //the first frame of the animation, and 100.0f would also //be the first frame of the animation. lg_bool CLMeshLG::PrepareFrame(lg_dword nAnim, float fTime, CLSkel* pSkel, lg_bool bSetupVerts) { lg_dword nFrame1, nFrame2; nFrame1=pSkel->GetFrameFromTime(nAnim, fTime, &fTime, &nFrame2); return PrepareFrame(nFrame1, nFrame2, fTime, pSkel, bSetupVerts); } void CLMeshLG::SetCompatibleWithSkel(CLSkel* pSkel) { if(!pSkel || !pSkel->IsLoaded()) return; for(lg_dword i=0; i<m_nNumBones; i++) { for(lg_dword j=0; j<pSkel->m_nNumJoints; j++) { if(L_strnicmp(this->m_pBoneNameList[i], pSkel->m_pBaseSkeleton[j].szName, 0)) { m_pBoneRef[i]=j; j=pSkel->m_nNumJoints+1; } } } } void CLMeshLG::SetRenderTexture(lg_bool b) { m_bRenderTexture=b; } /* Render() Alright this methods is setup to render with a skin. Note however, that this is not optimized at all this is just a basic rendering method, while we work on other parts of the engine. This has quite a few branches, and in general is not optimized. It is set up for pixel and vertex shading. */ lg_bool CLMeshLG::Render(CLSkin* pSkin) { //Test render the model. if(!m_bD3DValid) return LG_FALSE; //PrepareFrame should not be called here, but should be called //by the application prior to the call to Render(). //PrepareFrame(0, 1, 0.0f); s_pDevice->SetFVF(LMESH_VERTEX_FORMAT); s_pDevice->SetStreamSource(0, m_lpVB, 0, sizeof(LMESH_VERTEX)); s_pDevice->SetIndices(m_lpIB); lg_dword i=0; lg_bool bTextured=m_bRenderTexture; //Set the material for the mesh, in the future this might //be controlled by model properties, for now it is //just a default material. D3DMATERIAL9 Material={ {1.0f, 1.0f, 1.0f, 1.0f},//Diffuse {1.0f, 1.0f, 1.0f, 1.0f},//Ambient {1.0f, 1.0f, 1.0f, 1.0f},//Specular {0.0f, 0.0f, 0.0f, 0.0f},//Emissive 0.0f}; //Power s_pDevice->SetMaterial(&Material); if(bTextured) { for(i=0; i<m_nNumMeshes; i++) { if(pSkin && LG_CheckFlag(pSkin->m_nFlags, CLSkin::LMS_LOADED)) { lg_material mtr=pSkin->m_pCmpRefs[i]; ID3DXEffect* pFx=LG_NULL; tm_tex txtr=0; //pFx=CLFxMgr::FXM_GetInterface(1); CLMtrMgr::MTR_GetInterfaces(mtr, &txtr, &pFx); //if(!pFx) // pFx=CLFxMgr::FXM_GetInterface(1); UINT nPasses=0; D3DXMATRIX matWorld, matView, matProj; CLTMgr::TM_SetTexture(txtr, 0); s_pDevice->GetTransform(D3DTS_PROJECTION, &matProj); s_pDevice->GetTransform(D3DTS_VIEW, &matView); s_pDevice->GetTransform(D3DTS_WORLD, &matWorld); matWorld=matWorld*matView*matProj; pFx->SetMatrix("matWVP", &matWorld); //pFx->SetInt("nTime", timeGetTime()); pFx->Begin(&nPasses, 0); for(lg_dword j=0; j<nPasses; j++) { pFx->BeginPass(j); s_pDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, 0, m_nNumVertices, m_pMeshes[i].nFirstIndex, m_pMeshes[i].nNumTriangles); pFx->EndPass(); } pFx->End(); } else { #if 1 if(m_pMeshes[i].nMaterialIndex!=-1) { CLTMgr::TM_SetTexture(m_lppTexs[m_pMeshes[i].nMaterialIndex], 0);//s_pDevice->SetTexture(0, m_lppTexs[m_pMeshes[i].nMaterialIndex]); } else { CLTMgr::TM_SetTexture(0, 0);//s_pDevice->SetTexture(0, LG_NULL); } s_pDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, 0, m_nNumVertices, m_pMeshes[i].nFirstIndex, m_pMeshes[i].nNumTriangles); #endif } } } else { //we can render the whole model at once if there is no texture. s_pDevice->SetTexture(0, LG_NULL); s_pDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, 0, m_nNumVertices, 0, m_nNumTriangles); } return LG_TRUE; } //Slow function for debugging only. lg_bool CLMeshLG::RenderNormals() { if(!m_bD3DValid) return LG_FALSE; s_pDevice->SetTexture(0, LG_NULL); s_pDevice->SetFVF(BONEVERTEX_FVF); BONEVERTEX Normal[2]; lg_dword i=0; LMESH_VERTEX* pVertices; m_lpVB->Lock(0, m_nNumVertices*sizeof(LMESH_VERTEX), (void**)&pVertices, 0); for(i=0; i<this->m_nNumVertices; i++) { Normal[0].x=pVertices[i].x; Normal[0].y=pVertices[i].y; Normal[0].z=pVertices[i].z; Normal[0].color=0xFFFFFFFF; Normal[1].x=pVertices[i].nx; Normal[1].y=pVertices[i].ny; Normal[1].z=pVertices[i].nz; Normal[1].color=0xFFFFFFFF; s_pDevice->DrawPrimitiveUP(D3DPT_LINELIST, 1, &Normal, sizeof(BONEVERTEX)); } m_lpVB->Unlock(); return LG_TRUE; } #include <stdio.h> #ifdef LM_USE_LF2 #include "lf_sys2.h" #endif LM_USE_LF2 #include "lm_sys.h" #include "ML_lib.h" //Alright here is the skeleton class. //Further this needs to support some kind of //mechanism for pointing out different animations //based on a range of animations. //Also need to change the way the model gets rendered. //Either CLegacyMesh needs to have a RenderWithSkel funciton. //Or CLSkel needs to have a RenderModel functions. CLSkel::CLSkel(): m_nID(0), m_nVersion(0), m_nNumJoints(0), m_nNumKeyFrames(0), m_pBaseSkeleton(LG_NULL), m_bLoaded(LG_FALSE), m_pFrames(LG_NULL), m_nNumAnims(0), m_pAnims(LG_NULL) { m_szSkelName[0]=0; } CLSkel::~CLSkel() { Unload(); } lg_dword CLSkel::GetNumAnims() { return m_nNumAnims; } lg_dword CLSkel::GetNumJoints(){return m_nNumJoints;} lg_dword CLSkel::GetNumKeyFrames(){return m_nNumKeyFrames;} lg_bool CLSkel::IsLoaded(){return m_bLoaded;} lg_dword CLSkel::GetParentBoneRef(lg_dword nBone){return m_pBaseSkeleton[nBone].nParentBone;} lg_bool CLSkel::Unload() { this->DeallocateMemory(); m_nID=0; m_nVersion=0; m_nNumJoints=0; m_nNumKeyFrames=0; //m_nTotalSize=0; m_bLoaded=LG_FALSE; m_nNumAnims=0; return LG_TRUE; } #ifdef LM_USE_LF2 //The read and write LF2 functions are used for the legacy mesh //and legacy skel serialize methods when the LF2 file system is in //use. lg_uint CLSkel::ReadLF2(void* buffer, lg_uint size, lg_uint count, void* stream) { return LF_Read((LF_FILE3)stream, buffer, size*count); } lg_bool CLSkel::Load(lf_path szFilename) { Unload(); LF_FILE3 fIn=LF_Open(szFilename, LF_ACCESS_READ, LF_OPEN_EXISTING); if(!fIn) return LG_FALSE; lg_bool bResult=Serialize(fIn, ReadLF2, LG_TRUE); if(!bResult) Unload(); m_bLoaded=bResult; //We will now get all the calculations for the extra data (the local //and final matrices for the base skeleton and keyframes). //this->CalcExData(); if(m_bLoaded) { CalcExData(); } LF_Close(fIn); return m_bLoaded; } #endif lg_bool CLSkel::Load(void* file, LM_RW_FN read) { //Unload in case a skeleton is already loaded. Unload(); lg_bool bResult=Serialize( file, read, LG_TRUE); if(!bResult) Unload(); //pcb->close(file); m_bLoaded=bResult; //We will now get all the calculations for the extra data (the local //and final matrices for the base skeleton and keyframes). //this->CalcExData(); if(m_bLoaded) { CalcExData(); } return m_bLoaded; } lg_bool CLSkel::Save(void* file, LM_RW_FN write) { if(!m_bLoaded) return LG_FALSE; if(!m_pBaseSkeleton || !m_pFrames) return LG_FALSE; if(!file) return LG_FALSE; return Serialize( file, write, LG_FALSE); } lg_bool CLSkel::Serialize( void* file, lg_uint (__cdecl * read_or_write)(void* buffer, lg_uint size, lg_uint count, void* stream), lg_bool bLoading) { lg_dword i=0, j=0; //Read or Write the file header. read_or_write(&m_nID, 4, 1, file); read_or_write(&m_nVersion, 4, 1, file); read_or_write(m_szSkelName, LMESH_MAX_NAME, 1, file); read_or_write(&m_nNumJoints, 4, 1, file); read_or_write(&m_nNumKeyFrames, 4, 1, file); read_or_write(&m_nNumAnims, 4, 1, file); if((m_nID != LSKEL_ID) || (m_nVersion != LSKEL_VERSION)) return LG_FALSE; //Allocate memory if we are loading. if(bLoading) if(!AllocateMemory())return LG_FALSE; //Read or write the base skeleton. for(i=0; i<m_nNumJoints; i++) { read_or_write(&m_pBaseSkeleton[i], sizeof(LSKEL_JOINT), 1, file); } //Read or write the key frames. for(i=0; i<m_nNumKeyFrames; i++) { for(j=0; j<m_nNumJoints; j++) { read_or_write(&m_pFrames[i].LocalPos[j], sizeof(LSKEL_JOINTPOS), 1, file); } //Write the bounding box. read_or_write(&m_pFrames[i].aabbBox, sizeof(ML_AABB), 1, file); } //Read or write the animation information. for(i=0; i<m_nNumAnims; i++) { read_or_write(&m_pAnims[i], sizeof(LSKEL_ANIM), 1, file); } return LG_TRUE; } lg_bool CLSkel::GetMinsAndMaxes( float* fXMin, float* fXMax, float* fYMin, float* fYMax, float* fZMin, float* fZMax) { if(!m_bLoaded) return LG_FALSE; //This only gets the mins and the maxes for the default frame, it //does not get mins and maxes for keyframes. lg_dword i=0; if(fXMin)*fXMin=m_pBaseSkeleton[0].Final._41; if(fXMax)*fXMax=m_pBaseSkeleton[0].Final._41; if(fYMin)*fYMin=m_pBaseSkeleton[0].Final._42; if(fYMax)*fYMax=m_pBaseSkeleton[0].Final._42; if(fZMin)*fZMin=m_pBaseSkeleton[0].Final._43; if(fZMax)*fZMax=m_pBaseSkeleton[0].Final._43; for(i=1; i<m_nNumJoints; i++) { if(fXMin) *fXMin=LG_Min(*fXMin, m_pBaseSkeleton[i].Final._41); if(fXMax) *fXMax=LG_Max(*fXMax, m_pBaseSkeleton[i].Final._41); if(fYMin) *fYMin=LG_Min(*fYMin, m_pBaseSkeleton[i].Final._42); if(fYMax) *fYMax=LG_Max(*fYMax, m_pBaseSkeleton[i].Final._42); if(fZMin) *fZMin=LG_Min(*fZMin, m_pBaseSkeleton[i].Final._43); if(fZMax) *fZMax=LG_Max(*fZMax, m_pBaseSkeleton[i].Final._43); } return LG_TRUE; } const LSKEL_ANIM* CLSkel::GetAnim(lg_dword n) { if(n>=m_nNumAnims) return LG_NULL; return &m_pAnims[n]; } lg_dword CLSkel::GetFrameFromTime(lg_dword nAnim, float fTime, float* pFrameTime, lg_dword* pFrame2) { #define PREP_MAX_RANGE 100.0f if(!m_nNumAnims) return 0; nAnim=LG_Clamp(nAnim, 0, m_nNumAnims-1); fTime=LG_Clamp(fTime, 0.0f, PREP_MAX_RANGE); float fFrame; lg_dword nFrame1, nFrame2; if(L_CHECK_FLAG(m_pAnims[nAnim].m_nFlags, LSKEL_ANIM_LOOPBACK)) { if(fTime>=50.0f) fTime=100.0f-fTime; fFrame=m_pAnims[nAnim].m_nFirstFrame + ((float)m_pAnims[nAnim].m_nNumFrames-1-0.000001f) * fTime/(PREP_MAX_RANGE*0.5f); } else { fFrame=m_pAnims[nAnim].m_nFirstFrame + ((float)m_pAnims[nAnim].m_nNumFrames-0.000001f) * fTime/(PREP_MAX_RANGE); } nFrame1=(lg_dword)fFrame; nFrame2=nFrame1>=(m_pAnims[nAnim].m_nFirstFrame+m_pAnims[nAnim].m_nNumFrames-1)?m_pAnims[nAnim].m_nFirstFrame:nFrame1+1; if(pFrameTime) *pFrameTime=fFrame-nFrame1; if(pFrame2) *pFrame2=nFrame2; return nFrame1; } ML_AABB* CLSkel::GenerateAABB(ML_AABB* pOut, lg_dword nFrame1, lg_dword nFrame2, float t) { if(!pOut) return pOut; nFrame1=LG_Clamp(nFrame1, 1, m_nNumKeyFrames); nFrame2=LG_Clamp(nFrame2, 1, m_nNumKeyFrames); t=LG_Clamp(t, 0.0f, 1.0f); //We should probably have an AABB for frame 0 (the default frame). ML_AABB *a, *b; a=&m_pFrames[nFrame1-1].aabbBox; b=&m_pFrames[nFrame2-1].aabbBox; pOut->v3Min.x=a->v3Min.x+(b->v3Min.x-a->v3Min.x)*t; pOut->v3Min.y=a->v3Min.y+(b->v3Min.y-a->v3Min.y)*t; pOut->v3Min.z=a->v3Min.z+(b->v3Min.z-a->v3Min.z)*t; pOut->v3Max.x=a->v3Max.x+(b->v3Max.x-a->v3Max.x)*t; pOut->v3Max.y=a->v3Max.y+(b->v3Max.y-a->v3Max.y)*t; pOut->v3Max.z=a->v3Max.z+(b->v3Max.z-a->v3Max.z)*t; return pOut; } ML_MAT* CLSkel::GenerateJointTransform(ML_MAT* pOut, lg_dword nJoint, lg_dword nFrame1, lg_dword nFrame2, float t) { if(!pOut) return LG_NULL; nJoint=LG_Clamp(nJoint, 0, m_nNumJoints-1); nFrame1=LG_Clamp(nFrame1, 0, m_nNumKeyFrames); nFrame2=LG_Clamp(nFrame2, 0, m_nNumKeyFrames); t=LG_Clamp(t, 0.0f, 1.0f); const ML_MAT *pM1, *pM2; ML_MAT MI; ML_MatIdentity(&MI); pM1=nFrame1>0?m_pFrames[nFrame1-1].GetFinalMat(nJoint):&MI; pM2=nFrame2>0?m_pFrames[nFrame2-1].GetFinalMat(nJoint):&MI; return ML_MatSlerp( pOut, (ML_MAT*)pM1, (ML_MAT*)pM2, t); } //This second version of GenerateJointTransform uses a second skeleton to generate //the transform. Note that both skeletons should be compatible with each other and //have the same base skeleton, or the transformation may not be pretty. ML_MAT* CLSkel::GenerateJointTransform(ML_MAT* pOut, lg_dword nJoint, lg_dword nFrame1, lg_dword nFrame2, float t, CLSkel* pSkel2) { if(!pOut) return LG_NULL; nJoint=LG_Clamp(nJoint, 0, m_nNumJoints-1); nFrame1=LG_Clamp(nFrame1, 0, m_nNumKeyFrames); nFrame2=LG_Clamp(nFrame2, 0, pSkel2->m_nNumKeyFrames); t=LG_Clamp(t, 0.0f, 1.0f); const ML_MAT *pM1, *pM2; ML_MAT MI; ML_MatIdentity(&MI); pM1=nFrame1>0?m_pFrames[nFrame1-1].GetFinalMat(nJoint):&MI; pM2=nFrame2>0?pSkel2->m_pFrames[nFrame2-1].GetFinalMat(nJoint):&MI; return ML_MatSlerp( pOut, (ML_MAT*)pM1, (ML_MAT*)pM2, t); } const ML_MAT* CLSkel::GetBaseTransform(lg_dword nJoint) { nJoint=LG_Clamp(nJoint, 0, m_nNumJoints-1); return &m_pBaseSkeleton[nJoint].Final; } lg_bool CLSkel::AllocateMemory() { lg_dword i=0, j=0; //Deallocate memory first just in case, //note that because the poitners are set to null in //the constructor it is okay to call this before they //are initialized. DeallocateMemory(); //Allocate memory for the frames and base skeleton. //m_pKeyFrames=new LMESH_KEYFRAME[m_nNumKeyFrames]; m_pFrames=new CLFrame[m_nNumKeyFrames]; if(!m_pFrames) return LG_FALSE; for(i=0; i<m_nNumKeyFrames;i++) { if(!m_pFrames[i].Initialize(m_nNumJoints)) { L_safe_delete_array(m_pFrames); return LG_FALSE; } } m_pBaseSkeleton=new LSKEL_JOINTEX[m_nNumJoints]; if(!m_pBaseSkeleton) { L_safe_delete_array(m_pFrames); return LG_FALSE; } m_pAnims=new LSKEL_ANIM[m_nNumAnims]; if(!m_pAnims) { L_safe_delete_array(m_pFrames); L_safe_delete_array(m_pBaseSkeleton); return LG_FALSE; } return LG_TRUE; } void CLSkel::DeallocateMemory() { L_safe_delete_array(this->m_pBaseSkeleton); L_safe_delete_array(m_pFrames); L_safe_delete_array(m_pAnims); } lg_dword CLSkel::GetNumFrames() { return m_nNumKeyFrames; } lg_bool CLSkel::CalcExData() { lg_dword i=0, j=0; if(!m_bLoaded) return LG_FALSE; //Firstly we must convert Euler angles for the base skeleton and //keyframes to matrices. //Read the base skeleton. for(i=0; i<m_nNumJoints; i++) { //Now create the rotation matrixes (in the final format the rotation //matrices will probably be stored instead of the euler angles. EulerToMatrix((ML_MAT*)&m_pBaseSkeleton[i].Local, (float*)&m_pBaseSkeleton[i].rotation); //Now stick the translation into the matrix. m_pBaseSkeleton[i].Local._41=m_pBaseSkeleton[i].position[0]; m_pBaseSkeleton[i].Local._42=m_pBaseSkeleton[i].position[1]; m_pBaseSkeleton[i].Local._43=m_pBaseSkeleton[i].position[2]; m_pBaseSkeleton[i].nJointRef=i; } //Read the key frames. for(i=0; i<m_nNumKeyFrames; i++) { for(j=0; j<m_nNumJoints; j++) { EulerToMatrix(&m_pFrames[i].Local[j], (float*)&m_pFrames[i].LocalPos[j].rotation); m_pFrames[i].Local[j]._41=m_pFrames[i].LocalPos[j].position[0]; m_pFrames[i].Local[j]._42=m_pFrames[i].LocalPos[j].position[1]; m_pFrames[i].Local[j]._43=m_pFrames[i].LocalPos[j].position[2]; } } //Calculate the final matrices for the base skeleton. //This is simply a matter of multiplying each joint by //all of it's parent's matrices. for(i=0; i<m_nNumJoints; i++) { LSKEL_JOINTEX* pTemp=&m_pBaseSkeleton[i]; m_pBaseSkeleton[i].Final=pTemp->Local; while(pTemp->nParentBone) { pTemp=&m_pBaseSkeleton[pTemp->nParentBone-1]; ML_MatMultiply((ML_MAT*)&m_pBaseSkeleton[i].Final, (ML_MAT*)&m_pBaseSkeleton[i].Final, (ML_MAT*)&m_pBaseSkeleton[pTemp->nJointRef].Local); } } //We calculate the final transformation matrix for each joint for each //frame now, that way we don't have to calculate them on the fly. It //takes more memory this way, but the real time rendering is faster because //it isn't necessary to calculate each frames matrix every frame, it is only //necessary to interploate the joint matrixes for the given frame. //For each joint... for(i=0; i<m_nNumJoints; i++) { //For each frame for each joint... for(j=0; j<m_nNumKeyFrames; j++) { //1. Obtain the base joint for that joint. LSKEL_JOINTEX* pTemp=&m_pBaseSkeleton[i]; //2. Start out by making the final translation for the frame the local frame joint //location multiplyed the by the local base joint. //ML_MatMultiply((ML_MAT*)&m_pKeyFrames[j].pJointPos[i].Final, (ML_MAT*)&m_pKeyFrames[j].pJointPos[i].Local, (ML_MAT*)&pTemp->Local); ML_MatMultiply((ML_MAT*)&m_pFrames[j].Final[i], &m_pFrames[j].Local[i], &pTemp->Local); //3. Then if the joint has a parent... while(pTemp->nParentBone) { //3 (cont'd). It is necessary to multiply the final frame matrix //by the same calculation in step 2 (frame pos for the frame * local pos for the frame). pTemp=&m_pBaseSkeleton[pTemp->nParentBone-1]; ML_MAT MT; ML_MatMultiply( (ML_MAT*)&m_pFrames[j].Final[i], (ML_MAT*)&m_pFrames[j].Final[i], ML_MatMultiply(&MT, (ML_MAT*)&m_pFrames[j].Local[pTemp->nJointRef], (ML_MAT*)&pTemp->Local)); } //4. Fianlly the final position needs to be multiplied by the //final base position's inverse so that the transformation is //relative to the joint's location and not to 0,0,0. ML_MAT MI; ML_MatInverse(&MI, LG_NULL, &m_pBaseSkeleton[i].Final); ML_MatMultiply((ML_MAT*)&m_pFrames[j].Final[i], &MI, (ML_MAT*)&m_pFrames[j].Final[i]); } } return LG_TRUE; } /////////////////////////////// /// CLFrame Member Methods /// /////////////////////////////// CLFrame::CLFrame(): Local(LG_NULL), Final(LG_NULL), m_nNumJoints(0), LocalPos(LG_NULL) { } CLFrame::CLFrame(lg_dword nNumJoints): Local(LG_NULL), Final(LG_NULL), m_nNumJoints(0), LocalPos(LG_NULL) { Initialize(nNumJoints); } CLFrame::~CLFrame() { L_safe_delete_array(Local); L_safe_delete_array(Final); L_safe_delete_array(LocalPos); } lg_bool CLFrame::Initialize(lg_dword nNumJoints) { L_safe_delete_array(Local); L_safe_delete_array(Final); L_safe_delete_array(LocalPos); m_nNumJoints=nNumJoints; Local=new ML_MAT[nNumJoints]; Final=new ML_MAT[nNumJoints]; LocalPos=new LSKEL_JOINTPOS[nNumJoints]; if(!Local || !Final || !LocalPos) return LG_FALSE; float f[3]={0.0f, 0.0f, 0.0f}; for(lg_dword i=0; i<nNumJoints; i++) SetLocalMat(i, f, f); return LG_TRUE; } lg_dword CLFrame::GetNumJoints() { return m_nNumJoints; } const ML_MAT* CLFrame::GetFinalMat(lg_dword nJoint) { nJoint=LG_Clamp(nJoint, 0, m_nNumJoints-1); return &Final[nJoint]; } const ML_MAT* CLFrame::GetLocalMat(lg_dword nJoint) { nJoint=LG_Clamp(nJoint, 0, m_nNumJoints-1); return &Local[nJoint]; } lg_bool CLFrame::SetFinalMat(lg_dword nJoint, ML_MAT* pM) { if(nJoint>=m_nNumJoints) return LG_FALSE; Final[nJoint]=*pM; return LG_TRUE; } lg_bool CLFrame::SetLocalMat(lg_dword nJoint, float* position, float* rotation) { if(nJoint>=m_nNumJoints) return LG_FALSE; LocalPos[nJoint].position[0]=position[0]; LocalPos[nJoint].position[1]=position[1]; LocalPos[nJoint].position[2]=position[2]; LocalPos[nJoint].rotation[0]=rotation[0]; LocalPos[nJoint].rotation[1]=rotation[1]; LocalPos[nJoint].rotation[2]=rotation[2]; CLSkel::EulerToMatrix(&Local[nJoint], rotation); Local[nJoint]._41=position[0]; Local[nJoint]._42=position[1]; Local[nJoint]._43=position[2]; return LG_TRUE; } lg_bool CLFrame::SetLocalMat(lg_dword nJoint, ML_MAT* pM) { if(nJoint>=m_nNumJoints) return LG_FALSE; Local[nJoint]=*pM; return LG_TRUE; } ML_MAT* CLSkel::EulerToMatrix(ML_MAT* pOut, float* pEuler) { ML_MAT MX, MY, MZ; ML_MatRotationX(&MX, -pEuler[0]); ML_MatRotationY(&MY, -pEuler[1]); ML_MatRotationZ(&MZ, -pEuler[2]); return ML_MatMultiply( pOut, &MX, ML_MatMultiply(&MY, &MY, &MZ)); } <file_sep>/games/Legacy-Engine/Source/engine/win_sys.cpp /************************************************************* File: win_sys.c Copyright (c) 2006, <NAME>. Purpose: Entry point for Legacy3D engine. I've tryed to hide as much of the Windows API as possible from the actual Legacy 3D game (possibly to make future portability easier. All the actual Windows API function calls are in this file, and all the linked to librarys are in this file. The actual game is invoked and run with calls to LG_GameLoop in the WindowLoop() function. The console is also controlled from the MainWindowProc() function, but everything else in the game is controlled elswhere. *************************************************************/ /************************************************************************************* Legacy3D Game Engine -------------------- The Legacy3D game engine (will be) a functional 3D graphics and physics engine. It will be engineered for both first person action games, as well as slower paced 3rd person adventure games. The project is in the development stages. *************************************************************************************/ #define WM_USER_ACTIVEAPP (WM_USER+1) /* Including all required libs, I included them here as it makes it easier if I have to re-construct the project. */ #pragma comment(lib, "d3dx9_x86.lib") #pragma comment(lib, "ogg.lib") #pragma comment(lib, "vorbis.lib") #pragma comment(lib, "vorbisfile.lib") #pragma comment(lib, "d3d9.lib") #pragma comment(lib, "dsound.lib") #pragma comment(lib, "dxguid.lib") #pragma comment(lib, "winmm.lib") #pragma comment(lib, "dinput8.lib") #pragma comment(lib, "OpenAl32.lib") #pragma comment(lib, "Newton.lib") #include "common.h" #include "lg_func.h" #include <windows.h> #include <direct.h> #include "lg_sys.h" #include "lg_err_ex.h" #include "resource3.h" /**************************************************************** *** CLGame g_Game-The game class, everything about the game *** *** is controlled from this class, win_sys only needs to call *** *** the GameLoop method and the OnChar methods (for input). *** *** Everything else is called from the game itself. *** ****************************************************************/ CLGame g_Game; #ifdef _DEBUG #include "lg_err.h" extern "C" lg_dword g_nBlocks; #endif _DEBUG /********************************************************** MainWindowProc() The main window proc for Legacy, very little is done from actual windows functions as far as the game is concerned. The input into the console is managed from here. **********************************************************/ LRESULT CALLBACK MainWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch(uMsg) { case WM_ACTIVATEAPP: /* We have the WM_ACTIVEATEAPP keep track whether or not the application is active, this can be useful if the application should pause or something when not being used. */ PostMessage(hwnd, WM_USER_ACTIVEAPP, wParam, 0); break; case WM_KEYDOWN: switch(wParam) { case VK_PRIOR: g_Game.LG_OnChar(LK_PAGEUP); break; case VK_NEXT: g_Game.LG_OnChar(LK_PAGEDOWN); break; case VK_END: g_Game.LG_OnChar(LK_END); break; } break; case WM_CHAR: g_Game.LG_OnChar((char)wParam); break; case WM_CLOSE: //g_Game.LG_SendCommand("quit"); //g_Game.LG_GameLoop(); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hwnd, uMsg, wParam, lParam); } return 0l; } /******************************************************** WindowLoop() The main loop for windows, the actual game loop is called from here when the function LG_GameLoop() is called, the rest of this deals with some windows stuff. ********************************************************/ WPARAM WindowLoop(HWND hwnd) { BOOL bActiveApp=TRUE; BOOL bAlwaysProc=FALSE; MSG msg; memset(&msg, 0, sizeof(msg)); /* ===The window loop=== The idea behind the window loop is that we want to check to see if Windows wants to do something, but other than that we want to do what our game wants to do, so most of the time the GameLoop() function will be called, but if a message comes up, then windows will process it. Most of the game will be managed from the GameLoop function. */ TCHAR StrCwd[1024]; GetCurrentDirectory( 1024 , StrCwd ); //Initialize the game. if(!g_Game.LG_GameInit(".\\", hwnd)) { MessageBox(NULL, "LG_GameInit() failed.", "Legacy", MB_OK); return -1; } //The windows game loop. while(TRUE) { if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { if(msg.message==WM_USER_ACTIVEAPP) bActiveApp=(BOOL)msg.wParam; TranslateMessage(&msg); DispatchMessage(&msg); } else { if(bActiveApp || bAlwaysProc) { if(!g_Game.LG_GameLoop()) { DestroyWindow(msg.hwnd); break; } } else { WaitMessage(); } } } return msg.wParam; } /******************************************************* ChangeDirectory() This insures that the game starts in the directory that the exe file is in. Called from WinMain(). *******************************************************/ void ChangeDirectory(LPTSTR szCommandLine) { TCHAR szNewDir[MAX_PATH+1]; int i=0; int nLen=0; int bFoundQuote=0; /* Get rid of the initial quote. */ szCommandLine++; nLen=L_strlen(szCommandLine); for(i=0; i<nLen; i++) if(szCommandLine[i]=='\"') break; LG_strncpy(szNewDir, szCommandLine, i); /* Now go back until we find a backslash and set that to zero. */ for(i=L_strlen(szNewDir); i--; ) { if(szNewDir[i]=='\\') { szNewDir[i]=0; break; } } _chdir(szNewDir); /* Now if we're debugging then the app is in the legacy_code\debug directory so we need to change that. */ #ifdef _DEBUG _chdir("..\\.."); #endif /*_DEBUG*/ } /************************************************************* WinMain() The entry point for Legacy 3D, not that most of the game stuff is managed in LG_GameLoop(), but that function is from the windows loop. Everything in here is standard windows creation. When MainWindowLoop() is called that is when the game loop starts. *************************************************************/ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { HWND hwnd=NULL; WNDCLASSEX wc; WPARAM nResult=0; TCHAR szAppName[]=TEXT("Legacy Engine"); /* We want the starting directory to be the directory where the EXE file is located. */ #if !defined(_DEBUG) //ChangeDirectory(GetCommandLine()); #endif /* The first thing we need to do is all the standard Window creation calls. */ /* Define and register the Window's Class. */ wc.cbSize=sizeof(wc); wc.style=CS_HREDRAW|CS_VREDRAW|CS_OWNDC; wc.cbClsExtra=0; wc.cbWndExtra=0; wc.lpfnWndProc=MainWindowProc; wc.hInstance=hInstance; wc.hbrBackground=(HBRUSH)GetStockObject(DKGRAY_BRUSH); wc.hIcon=LoadIcon(hInstance, "L3DICO1"); wc.hIconSm=LoadIcon(hInstance, "L3DICO1"); wc.hCursor=LoadCursor(NULL, IDC_ARROW); wc.lpszMenuName=NULL; wc.lpszClassName=szAppName; if(!RegisterClassEx(&wc)) { MessageBox( NULL, TEXT("This program requires Windows NT!"), szAppName, MB_OK|MB_ICONERROR); return 0; } /* Create the Window. */ hwnd=CreateWindowEx( 0, szAppName, szAppName, WS_CAPTION|/*WS_SYSMENU|*/WS_VISIBLE|WS_MINIMIZEBOX, CW_USEDEFAULT, CW_USEDEFAULT, 320, 240, NULL, NULL, hInstance, NULL); if(hwnd==NULL) { MessageBox( NULL, TEXT("Failed to create window! Shutting down."), szAppName, MB_OK|MB_ICONERROR); return 0; } ShowWindow(hwnd, nCmdShow); UpdateWindow(hwnd); try { #ifdef _DEBUG Err_PrintfDebug("There are %u blocks.\n", g_nBlocks); L_BEGIN_D_DUMP nResult=WindowLoop(hwnd); L_END_D_DUMP("legacy.exe") _CrtDumpMemoryLeaks(); Err_PrintfDebug("There are %u blocks.\n", g_nBlocks); return (int)nResult; #else /*_DEBUG*/ return (int)WindowLoop(hwnd); #endif /*_DEBUG*/ } catch(CLError e) { e.Catenate("FATAL ERROR:"); MessageBox(NULL, e.GetMsg(), "Legacy", MB_OK|MB_ICONERROR); return -1; } catch(...) { MessageBox(NULL, "An unknown exception occured!", "Legacy", MB_OK|MB_ICONERROR); } } <file_sep>/games/Legacy-Engine/Source/lm_sys/lm_mesh2.cpp #include <memory.h> #include "lm_mesh.h" CLMesh2::CLMesh2() : CLMBase() , m_nID(0) , m_nVer(0) , m_nNumVerts(0) , m_nNumTris(0) , m_nNumSubMesh(0) , m_nNumMtrs(0) , m_nNumBones(0) , m_pVerts(LG_NULL) , m_pIndexes(LG_NULL) , m_pVertBoneList(LG_NULL) , m_pBoneNameList(LG_NULL) , m_pSubMesh(LG_NULL) , m_pMtrs(LG_NULL) , m_pMem(LG_NULL) { m_szMeshName[0]=0; memset(&m_AABB, 0, sizeof(ML_AABB)); } CLMesh2::~CLMesh2() { Unload(); } lg_bool CLMesh2::AllocateMemory() { DeallocateMemory(); lg_dword nSize=0; lg_dword nVertOffset=nSize; nSize+=sizeof(MeshVertex)*m_nNumVerts; lg_dword nIndexOffset=nSize; nSize+=sizeof(lg_word)*m_nNumTris*3; lg_dword nMtrOffset=nSize; nSize+=sizeof(MeshMtr)*m_nNumMtrs; lg_dword nVertBoneListOffset=nSize; nSize+=sizeof(lg_dword)*m_nNumVerts; lg_dword nBoneNameListOffset=nSize; nSize+=sizeof(LMName)*m_nNumBones; lg_dword nSubMeshOffset=nSize; nSize+=sizeof(SubMesh)*m_nNumSubMesh; m_pMem = new lg_byte[nSize]; if(!m_pMem) { DeallocateMemory(); return LG_FALSE; } memset( m_pMem , 0 , nSize ); m_pVerts= (MeshVertex*)&m_pMem[nVertOffset]; m_pIndexes= (lg_word*) &m_pMem[nIndexOffset]; m_pMtrs= (MeshMtr*) &m_pMem[nMtrOffset]; m_pVertBoneList=(lg_dword*) &m_pMem[nVertBoneListOffset]; m_pBoneNameList=(LMName*) &m_pMem[nBoneNameListOffset]; m_pSubMesh= (SubMesh*) &m_pMem[nSubMeshOffset]; return LG_TRUE; } lg_void CLMesh2::DeallocateMemory() { if(m_pMem) { delete [] m_pMem; } m_pMem=LG_NULL; m_pVerts=LG_NULL; m_pIndexes=LG_NULL; m_pSubMesh=LG_NULL; m_pMtrs=LG_NULL; m_pVertBoneList=LG_NULL; m_pBoneNameList=LG_NULL; } lg_bool CLMesh2::Serialize(lg_void* file, ReadWriteFn read_or_write, RW_MODE mode) { //We'll start by reading or writing the header: read_or_write(file, &m_nID, 4); read_or_write(file, &m_nVer, 4); read_or_write(file, m_szMeshName, 32); read_or_write(file, &m_nNumVerts, 4); read_or_write(file, &m_nNumTris, 4); read_or_write(file, &m_nNumSubMesh, 4); read_or_write(file, &m_nNumMtrs, 4); read_or_write(file, &m_nNumBones, 4); //We have two possible exits from the serialize //method, one if the version or ID wasn't correct //and the other if we couldn't allocate memory on //a read. if(m_nID!=LM_MESH_ID || m_nVer!=LM_MESH_VER) return LG_FALSE; //Now if we are loading we need to allocate memory: if(mode==RW_READ) { if(!AllocateMemory()) return LG_FALSE; } //Now we must read or write the rest of the data: //Vertexes: for(lg_dword i=0; i<m_nNumVerts; i++) { read_or_write(file, &m_pVerts[i], sizeof(MeshVertex)); } //Triangles: for(lg_dword i=0; i<m_nNumTris; i++) { read_or_write(file, &m_pIndexes[i*3], sizeof(lg_word)*3); } //Bone indexes: read_or_write(file, m_pVertBoneList, sizeof(lg_dword)*m_nNumVerts); //Bones: for(lg_dword i=0; i<m_nNumBones; i++) { read_or_write(file, m_pBoneNameList[i], 32); } //Sub Meshes: for(lg_dword i=0; i<m_nNumSubMesh; i++) { read_or_write(file, m_pSubMesh[i].szName, 32); read_or_write(file, &m_pSubMesh[i].nFirstIndex, 3*sizeof(lg_dword)); } //Materials: for(lg_dword i=0; i<m_nNumMtrs; i++) { read_or_write(file, m_pMtrs[i].szName, 32); read_or_write(file, m_pMtrs[i].szFile, 260); } //Bounding box: read_or_write(file, &m_AABB, 24); return LG_TRUE; } lg_void CLMesh2::Unload() { //To unload we'll just deallocate memory, //and set the ID and version to 0 so that //if we load again we won't accidently keep //the information and think that the mesh was //read properly. DeallocateMemory(); m_nID=0; m_nVer=0; //We'll also set the flags to 0 to clear the //LM_FLAG_LOADED setting. m_nFlags=0; }<file_sep>/tools/CornerBin/CornerBin/MainFrm.h // MainFrm.h : interface of the CMainFrame class // #pragma once #include "ChildView.h" class CMainFrame : public CFrameWnd { public: CMainFrame(CCBSettings* pSettings); protected: DECLARE_DYNAMIC(CMainFrame) // Attributes public: static const DWORD UPDATE_TIMER_ID = 1; // Operations public: // Overrides public: virtual BOOL PreCreateWindow(CREATESTRUCT& cs); virtual BOOL OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo); // Implementation public: virtual ~CMainFrame(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif CChildView m_wndView; // Generated message map functions protected: afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnSetFocus(CWnd *pOldWnd); DECLARE_MESSAGE_MAP() virtual BOOL OnWndMsg(UINT message, WPARAM wParam, LPARAM lParam, LRESULT* pResult); public: afx_msg void OnTimer(UINT_PTR nIDEvent); void SetTimerUpdate(DWORD nFreq); private: CCBSettings* m_pSettings; }; <file_sep>/tools/fs_sys2/fs_bdio.win32.h /* NOTE: The bdio functions should be altered according to the operating system that the fs_sys2 library is being compiled for, this file is designed for windows operating systems (in all practicality the fopen, fclose, etc stdc functions could have been used, but the windows methods prove more stable for windows computers. */ #include <windows.h> #include "fs_bdio.h" /* Basic DIO stuff, should only be used internally only. */ BDIO_FILE BDIO_OpenA(fs_cstr8 szFilename, LF_CREATE_MODE nMode, fs_dword nAccess) { HANDLE hFile=INVALID_HANDLE_VALUE; fs_dword dwDesiredAccess=0; fs_dword dwCreateDisposition=0; fs_dword dwFlagsAndAttributes=0; if(sizeof(BDIO_FILE) != sizeof(HANDLE)) { __debugbreak(); return 0; } dwDesiredAccess|=FS_CheckFlag(nAccess, LF_ACCESS_READ)?GENERIC_READ:0; dwDesiredAccess|=FS_CheckFlag(nAccess, LF_ACCESS_WRITE)?GENERIC_WRITE:0; switch(nMode) { case LF_CREATE_ALWAYS: dwCreateDisposition=CREATE_ALWAYS; break; case LF_CREATE_NEW: dwCreateDisposition=CREATE_NEW; break; case LF_OPEN_ALWAYS: dwCreateDisposition=OPEN_ALWAYS; break; case LF_OPEN_EXISTING: dwCreateDisposition=OPEN_EXISTING; break; } dwFlagsAndAttributes=FILE_ATTRIBUTE_NORMAL; if(FS_CheckFlag(nAccess, LF_ACCESS_BDIO_TEMP)) { dwFlagsAndAttributes=FILE_FLAG_DELETE_ON_CLOSE|FILE_ATTRIBUTE_TEMPORARY; } hFile=CreateFileA( szFilename, dwDesiredAccess, FILE_SHARE_READ, NULL, dwCreateDisposition, dwFlagsAndAttributes, NULL); if(hFile==INVALID_HANDLE_VALUE) { hFile = 0; } return (BDIO_FILE)(hFile); } BDIO_FILE BDIO_OpenW(fs_cstr16 szFilename, LF_CREATE_MODE nMode, fs_dword nAccess) { HANDLE hFile=INVALID_HANDLE_VALUE; fs_dword dwDesiredAccess=0; fs_dword dwCreateDisposition=0; fs_dword dwFlagsAndAttributes=0; if(sizeof(BDIO_FILE) != sizeof(HANDLE)) { __debugbreak(); return 0; } dwDesiredAccess|=FS_CheckFlag(nAccess, LF_ACCESS_READ)?GENERIC_READ:0; dwDesiredAccess|=FS_CheckFlag(nAccess, LF_ACCESS_WRITE)?GENERIC_WRITE:0; switch(nMode) { case LF_CREATE_ALWAYS: dwCreateDisposition=CREATE_ALWAYS; break; case LF_CREATE_NEW: dwCreateDisposition=CREATE_NEW; break; case LF_OPEN_ALWAYS: dwCreateDisposition=OPEN_ALWAYS; break; case LF_OPEN_EXISTING: dwCreateDisposition=OPEN_EXISTING; break; } dwFlagsAndAttributes=FILE_ATTRIBUTE_NORMAL; if(FS_CheckFlag(nAccess, LF_ACCESS_BDIO_TEMP)) { dwFlagsAndAttributes=FILE_FLAG_DELETE_ON_CLOSE|FILE_ATTRIBUTE_TEMPORARY; } hFile=CreateFileW( szFilename, dwDesiredAccess, FILE_SHARE_READ, NULL, dwCreateDisposition, dwFlagsAndAttributes, NULL); if(hFile==INVALID_HANDLE_VALUE) { hFile = 0; } return (BDIO_FILE)(hFile); } fs_bool BDIO_Close(BDIO_FILE File) { HANDLE hFile=(HANDLE)(File); fs_bool bResult=CloseHandle(hFile); return bResult; } fs_dword BDIO_Read(BDIO_FILE File, fs_dword nSize, void* pOutBuffer) { HANDLE hFile=(HANDLE)(File); fs_dword dwRead=0; if(ReadFile(hFile, pOutBuffer, nSize, &dwRead, NULL)) return dwRead; else return 0; } fs_dword BDIO_Write(BDIO_FILE File, fs_dword nSize, const void* pInBuffer) { HANDLE hFile=(HANDLE)(File); fs_dword dwWrote=0; if(WriteFile(hFile, pInBuffer, nSize, &dwWrote, NULL)) return dwWrote; else return 0; } fs_dword BDIO_Tell(BDIO_FILE File) { HANDLE hFile=(HANDLE)(File); return SetFilePointer( hFile, 0, NULL, FILE_CURRENT); } fs_dword BDIO_Seek(BDIO_FILE File, fs_long nOffset, LF_SEEK_TYPE nOrigin) { HANDLE hFile=(HANDLE)(File); fs_dword dwMoveMethod=0; switch(nOrigin) { case LF_SEEK_BEGIN: dwMoveMethod=FILE_BEGIN; break; case LF_SEEK_CURRENT: dwMoveMethod=FILE_CURRENT; break; case LF_SEEK_END: dwMoveMethod=FILE_END; break; } return SetFilePointer(hFile,nOffset,NULL,dwMoveMethod); } fs_dword BDIO_GetSize(BDIO_FILE File) { HANDLE hFile=(HANDLE)(File); fs_large_integer nFileSize={0,0}; nFileSize.dwLowPart=GetFileSize(hFile, &nFileSize.dwHighPart); if(nFileSize.dwHighPart) return 0xFFFFFFFF; else return nFileSize.dwLowPart; } BDIO_FILE BDIO_OpenTempFileA(LF_CREATE_MODE nMode, fs_dword nAccess) { fs_pathA szTempPath, szTempFile; GetTempPathA(FS_MAX_PATH, szTempPath); GetTempFileNameA(szTempPath, "BDIO", 0, szTempFile); return BDIO_OpenA(szTempFile, nMode, nAccess|LF_ACCESS_BDIO_TEMP); } BDIO_FILE BDIO_OpenTempFileW(LF_CREATE_MODE nMode, fs_dword nAccess) { fs_pathW szTempPath, szTempFile; GetTempPathW(FS_MAX_PATH, szTempPath); GetTempFileNameW(szTempPath, L"BDIO", 0, szTempFile); return BDIO_OpenW(szTempFile, nMode, nAccess|LF_ACCESS_BDIO_TEMP); } /* Directory manipulation...*/ fs_bool BDIO_ChangeDirA(fs_cstr8 szDir) { return SetCurrentDirectoryA(szDir); } fs_bool BDIO_ChangeDirW(fs_cstr16 szDir) { return SetCurrentDirectoryW(szDir); } fs_dword BDIO_GetCurrentDirA(fs_str8 szDir, fs_dword nSize) { return GetCurrentDirectoryA(nSize, szDir); } fs_dword BDIO_GetCurrentDirW(fs_str16 szDir, fs_dword nSize) { return GetCurrentDirectoryW(nSize, szDir); } /* BDIO_GetFullPathname converts a filename to it's full path according to the current directory */ fs_dword BDIO_GetFullPathNameW(fs_pathW szPath, const fs_pathW szFilename) { return GetFullPathNameW(szFilename, FS_MAX_PATH, szPath, NULL); } fs_dword BDIO_GetFullPathNameA(fs_pathA szPath, const fs_pathA szFilename) { return GetFullPathNameA(szFilename, FS_MAX_PATH, szPath, NULL);; } //Find File functions for finding all files in a directory. BDIO_FIND BDIO_FindFirstFileW(fs_cstr16 szFilename, BDIO_FIND_DATAW* pFindData) { HANDLE hFindFile; WIN32_FIND_DATAW findData; hFindFile=FindFirstFileW(szFilename, &findData); if(INVALID_HANDLE_VALUE==hFindFile) return FS_NULL; pFindData->nFileSize.dwHighPart=findData.nFileSizeHigh; pFindData->nFileSize.dwLowPart=findData.nFileSizeLow; wcsncpy(pFindData->szFilename, findData.cFileName, FS_MAX_PATH); pFindData->bNormal=FS_CheckFlag(findData.dwFileAttributes, FILE_ATTRIBUTE_NORMAL); pFindData->bDirectory=FS_CheckFlag(findData.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY); pFindData->bHidden=FS_CheckFlag(findData.dwFileAttributes, FILE_ATTRIBUTE_HIDDEN); pFindData->bReadOnly=FS_CheckFlag(findData.dwFileAttributes, FILE_ATTRIBUTE_READONLY); return hFindFile; } fs_bool BDIO_FindNextFileW(BDIO_FIND hFindFile, BDIO_FIND_DATAW* pFindData) { WIN32_FIND_DATAW findData; fs_bool bResult=FindNextFileW((HANDLE)hFindFile, &findData); if(!bResult) return bResult; pFindData->nFileSize.dwHighPart=findData.nFileSizeHigh; pFindData->nFileSize.dwLowPart=findData.nFileSizeLow; wcsncpy(pFindData->szFilename, findData.cFileName, FS_MAX_PATH); pFindData->bNormal=FS_CheckFlag(findData.dwFileAttributes, FILE_ATTRIBUTE_NORMAL); pFindData->bDirectory=FS_CheckFlag(findData.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY); pFindData->bHidden=FS_CheckFlag(findData.dwFileAttributes, FILE_ATTRIBUTE_HIDDEN); pFindData->bReadOnly=FS_CheckFlag(findData.dwFileAttributes, FILE_ATTRIBUTE_READONLY); return bResult; } BDIO_FIND BDIO_FindFirstFileA(fs_cstr8 szFilename, BDIO_FIND_DATAA* pFindData) { HANDLE hFindFile; WIN32_FIND_DATAA findData; hFindFile=FindFirstFileA(szFilename, &findData); if(INVALID_HANDLE_VALUE==hFindFile) return FS_NULL; pFindData->nFileSize.dwHighPart=findData.nFileSizeHigh; pFindData->nFileSize.dwLowPart=findData.nFileSizeLow; strncpy(pFindData->szFilename, findData.cFileName, FS_MAX_PATH); pFindData->bNormal=FS_CheckFlag(findData.dwFileAttributes, FILE_ATTRIBUTE_NORMAL); pFindData->bDirectory=FS_CheckFlag(findData.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY); pFindData->bHidden=FS_CheckFlag(findData.dwFileAttributes, FILE_ATTRIBUTE_HIDDEN); pFindData->bReadOnly=FS_CheckFlag(findData.dwFileAttributes, FILE_ATTRIBUTE_READONLY); return hFindFile; } fs_bool BDIO_FindNextFileA(BDIO_FIND hFindFile, BDIO_FIND_DATAA* pFindData) { WIN32_FIND_DATAA findData; fs_bool bResult=FindNextFileA((HANDLE)hFindFile, &findData); if(!bResult) return bResult; pFindData->nFileSize.dwHighPart=findData.nFileSizeHigh; pFindData->nFileSize.dwLowPart=findData.nFileSizeLow; strncpy(pFindData->szFilename, findData.cFileName, FS_MAX_PATH); pFindData->bNormal=FS_CheckFlag(findData.dwFileAttributes, FILE_ATTRIBUTE_NORMAL); pFindData->bDirectory=FS_CheckFlag(findData.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY); pFindData->bHidden=FS_CheckFlag(findData.dwFileAttributes, FILE_ATTRIBUTE_HIDDEN); pFindData->bReadOnly=FS_CheckFlag(findData.dwFileAttributes, FILE_ATTRIBUTE_READONLY); return bResult; } fs_bool BDIO_FindClose(BDIO_FIND hFindFile) { return FindClose((HANDLE)hFindFile); } fs_char8 BDIO_GetOsPathSeparator() { return '\\'; }<file_sep>/games/Legacy-Engine/Source/3rdParty/ML_lib/ML_main.c #define ML_LIB_MAIN #include "ML_lib.h" #include "ML_vec3.h" #include "ML_mat.h" ml_dword FLOAT_SSE_NO_W_MASK[] = {0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000}; ml_dword FLOAT_3DNOW_NO_W_MASK[] = {0xFFFFFFFF, 0x00000000}; const ml_mat ML_matIdentity = {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f}; const ml_vec3 ML_v3Zero = {0.0f, 0.0f, 0.0f}; ml_bool ML_FUNC ML_Init(ML_INSTR nInstr) { //If the instruction set is not supported, or if we //asked for the best support, we get the best support //available... if(nInstr==ML_INSTR_BEST || !ML_InstrSupport(nInstr)) nInstr=ML_GetBestSupport(); //We'll now check to make sure the support we got is supported: if(!ML_InstrSupport(nInstr)) return ML_FALSE; //Our library only really uses FP, SSE, and 3DNOW. //If something like MMX was passed then the library //will default to FP. #define SET_FUNC(fn, fl, se1, se2, se3, now1, now2) { \ if(nInstr==ML_INSTR_F){fn=fn##_##fl;} \ else if(nInstr==ML_INSTR_SSE){fn=fn##_##se1;} \ else if(nInstr==ML_INSTR_SSE2){fn=fn##_##se2;} \ else if(nInstr==ML_INSTR_SSE3){fn=fn##_##se3;} \ else if(nInstr==ML_INSTR_3DNOW){fn=fn##_##now1;} \ else if(nInstr==ML_INSTR_3DNOW2){fn=fn##_##now2;} \ else {fn=fn##_##fl;} \ } //Fuctions declare with ML_DECLARE_FUNC must be initialzed //here, functions that only have one method do not need to //be initialized. SET_FUNC(ML_Vec3Add, F, SSE, SSE, SSE, 3DNOW, 3DNOW); SET_FUNC(ML_Vec3Subtract, F, SSE, SSE, SSE, 3DNOW, 3DNOW); SET_FUNC(ML_Vec3Cross, F, SSE, SSE, SSE, 3DNOW, 3DNOW); SET_FUNC(ML_Vec3Dot, F, SSE, SSE, SSE3, 3DNOW, 3DNOW); SET_FUNC(ML_Vec3Length, F, SSE, SSE, SSE3, 3DNOW, 3DNOW); SET_FUNC(ML_Vec3LengthSq, F, SSE, SSE, SSE3, 3DNOW, 3DNOW); SET_FUNC(ML_Vec3Normalize, F, SSE, SSE, SSE3, 3DNOW, 3DNOW); SET_FUNC(ML_Vec3Scale, F, SSE, SSE, SSE, 3DNOW, 3DNOW); SET_FUNC(ML_Vec3Distance, F, SSE, SSE, SSE3, 3DNOW, 3DNOW); SET_FUNC(ML_Vec3DistanceSq, F, SSE, SSE, SSE3, 3DNOW, 3DNOW); SET_FUNC(ML_Vec3Transform, F, SSE, SSE, SSE, 3DNOW, 3DNOW); SET_FUNC(ML_Vec3TransformCoord, F, SSE, SSE, SSE, 3DNOW, 3DNOW); SET_FUNC(ML_Vec3TransformNormal, F, SSE, SSE, SSE, 3DNOW, 3DNOW); SET_FUNC(ML_MatMultiply, F, SSE, SSE, SSE, 3DNOW, 3DNOW); SET_FUNC(ML_MatInverse, F, F, F, F, F, F); return ML_TRUE; } ml_bool ML_FUNC ML_InstrSupport(ML_INSTR nInstr) { ml_bool bSupport=ML_FALSE; int neax, nebx, necx, nedx; if(nInstr>=ML_INSTR_AMDMMX) neax=0x80000001; else neax=0x00000001; __asm { push ebx mov eax, neax; cpuid mov neax, eax mov nebx, ebx mov necx, ecx mov nedx, edx pop ebx } switch(nInstr) { case ML_INSTR_F: return (nedx>>0)&1; case ML_INSTR_MMX: return (nedx>>23)&1; case ML_INSTR_SSE: return (nedx>>25)&1; case ML_INSTR_SSE2: return (nedx>>26)&1; case ML_INSTR_SSE3: return (necx>>0)&1; case ML_INSTR_AMDMMX: return (nedx>>22)&0x1; case ML_INSTR_3DNOW: return (nedx>>30)&0x1; case ML_INSTR_3DNOW2: return (nedx>>31)&0x1; default: return 0; } return bSupport; } ML_INSTR ML_FUNC ML_GetBestSupport() { #define INSTR_START ML_INSTR nInstr=ML_INSTR_BEST; if(0) {} #define INSTR_END else {nInstr=ML_INSTR_BEST;} return nInstr; #define INSTR_SUPPORT(name) else if(ML_InstrSupport(ML_INSTR_##name)){nInstr=ML_INSTR_##name;} //We put the support in order of //priority, we ignore support that isn't used at all //such as MMX and what not. INSTR_START INSTR_SUPPORT(SSE3) INSTR_SUPPORT(SSE2) INSTR_SUPPORT(SSE) INSTR_SUPPORT(3DNOW2) INSTR_SUPPORT(3DNOW) INSTR_SUPPORT(F) INSTR_END } <file_sep>/games/Legacy-Engine/Source/3rdParty/ML_lib/ML_vec3.h #ifndef __ml_vec3_H__ #define __ml_vec3_H__ #include "ML_types.h" #ifdef __cplusplus extern "C"{ #endif __cplusplus /************************************* ml_vec3 function implimentations: *************************************/ /**** AVAILABLE FUNCTIONS **** *** ML_Vec3Add *** *** ML_Vec3Subtract *** *** ML_Vec3Cross *** *** ML_Vec3Dot *** *** ML_Vec3Length *** *** ML_Vec3LengthSq *** *** ML_Vec3Normalize *** *** ML_Vec3Scale *** *** ML_Vec3Distance *** *** ML_Vec3DistanceSq *** *** ML_Vec3Transform *** *** ML_Vec3TransformCoord *** *** ML_Vec3TransformNormal *** *****************************/ ml_vec3* ML_FUNC ML_Vec3Add_F(ml_vec3* pOut, const ml_vec3* pV1, const ml_vec3* pV2); ml_vec3* ML_FUNC ML_Vec3Add_SSE(ml_vec3* pOut, const ml_vec3* pV1, const ml_vec3* pV2); ml_vec3* ML_FUNC ML_Vec3Add_3DNOW(ml_vec3* pOut, const ml_vec3* pV1, const ml_vec3* pV2); ml_vec3* ML_FUNC ML_Vec3Cross_F(ml_vec3* pOut, const ml_vec3* pV1, const ml_vec3* pV2); ml_vec3* ML_FUNC ML_Vec3Cross_SSE(ml_vec3* pOut, const ml_vec3* pV1, const ml_vec3* pV2); ml_vec3* ML_FUNC ML_Vec3Cross_3DNOW(ml_vec3* pOut, const ml_vec3* pV1, const ml_vec3* pV2); ml_float ML_FUNC ML_Vec3Dot_F(const ml_vec3* pV1, const ml_vec3* pV2); ml_float ML_FUNC ML_Vec3Dot_SSE3(const ml_vec3* pV1, const ml_vec3* pV2); ml_float ML_FUNC ML_Vec3Dot_SSE(const ml_vec3* pV1, const ml_vec3* pV2); ml_float ML_FUNC ML_Vec3Dot_3DNOW(const ml_vec3* pV1, const ml_vec3* pV2); ml_float ML_FUNC ML_Vec3Length_F(const ml_vec3* pV); ml_float ML_FUNC ML_Vec3Length_SSE3(const ml_vec3* pV); ml_float ML_FUNC ML_Vec3Length_SSE(const ml_vec3* pV); ml_float ML_FUNC ML_Vec3Length_3DNOW(const ml_vec3* pV); ml_float ML_FUNC ML_Vec3LengthSq_F(const ml_vec3* pV); ml_float ML_FUNC ML_Vec3LengthSq_SSE3(const ml_vec3* pV); ml_float ML_FUNC ML_Vec3LengthSq_SSE(const ml_vec3* pV); ml_float ML_FUNC ML_Vec3LengthSq_3DNOW(const ml_vec3* pV); ml_vec3* ML_FUNC ML_Vec3Normalize_F(ml_vec3* pOut, const ml_vec3* pV); ml_vec3* ML_FUNC ML_Vec3Normalize_SSE3(ml_vec3* pOut, const ml_vec3* pV); ml_vec3* ML_FUNC ML_Vec3Normalize_SSE(ml_vec3* pOut, const ml_vec3* pV); ml_vec3* ML_FUNC ML_Vec3Normalize_3DNOW(ml_vec3* pOut, const ml_vec3* pV); ml_vec3* ML_FUNC ML_Vec3Scale_F(ml_vec3* pOut, const ml_vec3* pV, ml_float s); ml_vec3* ML_FUNC ML_Vec3Scale_SSE(ml_vec3* pOut, const ml_vec3* pV, ml_float s); ml_vec3* ML_FUNC ML_Vec3Scale_3DNOW(ml_vec3* pOut, const ml_vec3* pV, ml_float s); ml_vec3* ML_FUNC ML_Vec3Subtract_F(ml_vec3* pOut, const ml_vec3* pV1, const ml_vec3* pV2); ml_vec3* ML_FUNC ML_Vec3Subtract_SSE(ml_vec3* pOut, const ml_vec3* pV1, const ml_vec3* pV2); ml_vec3* ML_FUNC ML_Vec3Subtract_3DNOW(ml_vec3* pOut, const ml_vec3* pV1, const ml_vec3* pV2); ml_float ML_FUNC ML_Vec3Distance_F(const ml_vec3* pV1, const ml_vec3* pV2); ml_float ML_FUNC ML_Vec3Distance_SSE3(const ml_vec3* pV1, const ml_vec3* pV2); ml_float ML_FUNC ML_Vec3Distance_SSE(const ml_vec3* pV1, const ml_vec3* pV2); ml_float ML_FUNC ML_Vec3Distance_3DNOW(const ml_vec3* pV1, const ml_vec3* pV2); ml_float ML_FUNC ML_Vec3DistanceSq_F(const ml_vec3* pV1, const ml_vec3* pV2); ml_float ML_FUNC ML_Vec3DistanceSq_SSE3(const ml_vec3* pV1, const ml_vec3* pV2); ml_float ML_FUNC ML_Vec3DistanceSq_SSE(const ml_vec3* pV1, const ml_vec3* pV2); ml_float ML_FUNC ML_Vec3DistanceSq_3DNOW(const ml_vec3* pV1, const ml_vec3* pV2); ml_vec4* ML_FUNC ML_Vec3Transform_F(ml_vec4* pOut, const ml_vec3* pV, const ml_mat* pM); ml_vec4* ML_FUNC ML_Vec3Transform_SSE(ml_vec4* pOut, const ml_vec3* pV, const ml_mat* pM); ml_vec4* ML_FUNC ML_Vec3Transform_3DNOW(ml_vec4* pOut, const ml_vec3* pV, const ml_mat* pM); ml_vec3* ML_FUNC ML_Vec3TransformCoord_F(ml_vec3* pOut, const ml_vec3* pV, const ml_mat* pM); ml_vec3* ML_FUNC ML_Vec3TransformCoord_SSE(ml_vec3* pOut, const ml_vec3* pV, const ml_mat* pM); ml_vec3* ML_FUNC ML_Vec3TransformCoord_3DNOW(ml_vec3* pOut, const ml_vec3* pV, const ml_mat* pM); ml_vec3* ML_FUNC ML_Vec3TransformNormal_F(ml_vec3* pOut, const ml_vec3* pV, const ml_mat* pM); ml_vec3* ML_FUNC ML_Vec3TransformNormal_SSE(ml_vec3* pOut, const ml_vec3* pV, const ml_mat* pM); ml_vec3* ML_FUNC ML_Vec3TransformNormal_3DNOW(ml_vec3* pOut, const ml_vec3* pV, const ml_mat* pM); #ifdef __cplusplus } /* extern "C" */ #endif __cplusplus #endif __ml_vec3_H__<file_sep>/games/Legacy-Engine/Scrapped/old/le_3dbase.cpp #include "le_3dbase.h" #include "le_test.h" #include "lg_err.h" #include "lg_sys.h" #include "ld_sys.h" #include "lg_err_ex.h" CLBase3DEntity::CLBase3DEntity(): PHYSICS_ENGINE(), m_pMeshNodes(LG_NULL), m_nMeshCount(0), m_fScale(1.0f) { m_v3Pos.x=m_v3Pos.y=m_v3Pos.z=0.0f; m_v3PhysVel.x=m_v3PhysVel.x=m_v3PhysVel.z=0.0f; //The LENTITY_RENDER180 flag tells the rasterizer //to rotate whatever gets rendered an addition 180 //degrees. Most LMeshes (especially humaniods) need //this flag because the meshes are typically saved with //the front facing the negative z direction, and for //the legacy engine positive z is considered forward. m_nFlags|=LENTITY_RENDER180|LENTITY_TRANSYAWONLY; CLEntity::Update(); } CLBase3DEntity::~CLBase3DEntity() { LM_DeleteMeshNodes(m_pMeshNodes); } void CLBase3DEntity::Initialize(ML_VEC3* v3Pos) { if(!s_pWorldMap) { throw CLError(LG_ERR_DEFAULT, __FILE__, __LINE__, "Attempted to create an entity without establishing the world."); } if(v3Pos) m_v3Pos=*v3Pos; m_v3PhysVel.x=m_v3PhysVel.y=m_v3PhysVel.z=0.0f; //m_v3ExtForces.x=m_v3ExtForces.y=m_v3ExtForces.z=0.0f; } void CLBase3DEntity::Render() { if(!m_pMeshNodes) return; //Should do some checking to make sure the entity should //actually be rendered. s_matTemp=m_matOrient; //To render the entity simply call Render on the base node //passing the orientation matrix. All child nodes will //be rendered from by rendering the parent node (which should //be node 0). if(m_fScale!=1.0f) { ML_MatScaling(&s_matTemp2, m_fScale, m_fScale, m_fScale); ML_MatMultiply(&s_matTemp, &s_matTemp2, &m_matOrient); } if(L_CHECK_FLAG(m_nFlags, LENTITY_RENDER180)) { ML_MatRotationY(&s_matTemp2, ML_PI); ML_MatMultiply(&s_matTemp, &s_matTemp2, &s_matTemp); } m_pMeshNodes[0].Render(&s_matTemp); } void CLBase3DEntity::LoadMesh(lf_path szXMLScriptFile, lg_float fScale, lg_dword Flags) { m_fScale=fScale; LM_DeleteMeshNodes(m_pMeshNodes); m_pMeshNodes=LM_LoadMeshNodes(szXMLScriptFile, &m_nMeshCount); if(!m_pMeshNodes) return; //If we acquired a skeleton for the base mesh (m_pMeshNodes[0]), //then we will set a bounding box based of the first frame of //animation. if(m_pMeshNodes[0].m_pDefSkel) { m_pMeshNodes[0].m_pDefSkel->GenerateAABB(&m_aabbBase, 1, 1, 0.0f); } else if(m_pMeshNodes[0].m_pMesh) { m_aabbBase=*m_pMeshNodes[0].m_pMesh->GetBoundingBox(); } ML_MAT matTrans; ML_MatScaling(&matTrans, m_fScale, m_fScale, m_fScale); ML_Vec3TransformCoordArray((ML_VEC3*)&m_aabbBase, sizeof(ML_VEC3), (ML_VEC3*)&m_aabbBase, sizeof(ML_VEC3), (ML_MAT*)&matTrans, 2); if(L_CHECK_FLAG(Flags, LOADMESH_BB45)) { ML_MatRotationY(&matTrans, ML_PI*0.25f); ML_AABBTransform(&m_aabbBase, &m_aabbBase, &matTrans); } else if(L_CHECK_FLAG(Flags, LOADMESH_BB90)) { ML_MatRotationY(&matTrans, ML_PI*0.5); ML_AABBTransform(&m_aabbBase, &m_aabbBase, &matTrans); } } <file_sep>/games/Legacy-Engine/Scrapped/libs/ML_lib2008April/ML_lib_cover.h /* ML_lib.h - Header LM_lib math library. Copyright (c) 2006, <NAME>. With code by: <NAME>, 2005 (<EMAIL>) Under LGPL License */ #ifndef __ML_LIB_H__ #define __ML_LIB_H__ #include <d3dx9.h> #ifdef __cplusplus extern "C"{ #endif __cplusplus /* Some types that we will use.*/ typedef unsigned char ml_byte; typedef signed char ml_sbyte; typedef unsigned short ml_word; typedef signed short ml_short; typedef unsigned long ml_dword; typedef signed long ml_long; typedef int ml_bool; typedef unsigned int ml_uint; typedef signed int ml_int; typedef void ml_void; /* A few definitions. */ #define ML_TRUE (1) #define ML_FALSE (0) #define ML_FUNC __cdecl /**************************************** Some constants for the math library. ****************************************/ #define ML_PI ((float)3.141592654f) /************************************* Structures for the math functions. *************************************/ typedef D3DXMATRIX ML_MAT; typedef D3DXQUATERNION ML_QUAT; typedef D3DXVECTOR2 ML_VEC2; typedef D3DXVECTOR3 ML_VEC3; typedef D3DXVECTOR4 ML_VEC4; /*********************** ML_vector2 functions. ***********************/ /*********************** ML_VEC3 functions. ***********************/ #define ML_Vec3Add(pOut, pV1, pV2) (ML_VEC3*)D3DXVec3Add((D3DXVECTOR3*)pOut, (D3DXVECTOR3*)pV1, (D3DXVECTOR3*)pV2) #define ML_Vec3Dot(pV1, pV2) D3DXVec3Dot((D3DXVECTOR3*)pV1, (D3DXVECTOR3*)pV2) #define ML_Vec3Length(pV) D3DXVec3Length((D3DXVECTOR3*)pV) #define ML_Vec3Magnitude ML_Vec3Length #define ML_Vec3Normalize(pOut, pV) D3DXVec3Normalize((D3DXVECTOR3*)pOut, (D3DXVECTOR3*)pV) #define ML_Vec3Scale(pOut, pV, s) D3DXVec3Scale((D3DXVECTOR3*)pOut, (D3DXVECTOR3*)pV, s) #define ML_Vec3Subtract(ML_VEC3* pOut, const ML_VEC3* pV1, const ML_VEC3* pV2) #define ML_Vec3Transform(pOut, pV, pM) D3DXVec3Transform(pOut, pV, pM) #define ML_Vec3TransformCoord(pOut, pV, pM) D3DXVec3TransformCoord(pOut, pV, pM) #define ML_Vec3TransformNormal(pOut, pV, pM) D3DXVec3TransformNormal(pOut, pV, pM) #define ML_Vec3Distance(pV1, pV2) D3DXVec3Distance(pV1, pV2) /*********************** ML_vector4 functions. ***********************/ /******************** Matrix functions. ********************/ #define ML_MatIdentity D3DXMatrixIdentity #define ML_MatMultiply D3DXMatrixMultiply #define ML_MatRotationX D3DXMatrixRotationX #define ML_MatRotationY D3DXMatrixRotationY #define ML_MatRotationZ D3DXMatrixRotationZ #define ML_MatPerspectiveFovLH D3DXMatrixPerspectiveFovLH #define ML_MatRotationQuat D3DXMatrixRotationQuat ML_MAT* ML_MatSlerp(ML_MAT* pOut, ML_MAT* pM1, ML_MAT* pM2, float t); #define ML_MatDeterminant D3DXMatrixDeterminant #define ML_MatInverse D3DXMatrixInverse /************************* Quaternion functions. *************************/ #define ML_QuatRotationMat D3DXQuaternionRotationMatrix #define ML_QuatSlerp D3DXQauternionSlerp /******************************** Instruction Set Determination ********************************/ /****************** Misc functions. ******************/ ml_dword ML_FUNC ML_NextPow2(const ml_dword n); // Find the next highest power of 2. ml_dword ML_FUNC ML_Pow2(const ml_byte n); // Find (2^n). float ML_FUNC ML_sqrtf(const float f); float ML_FUNC ML_cosf(const float f); float ML_FUNC ML_sinf(const float f); float ML_FUNC ML_tanf(const float f); float ML_FUNC ML_acosf(const float f); float ML_FUNC ML_asinf(const float f); /****************************** Instruction set functions. ******************************/ typedef enum _ML_INSTR{ ML_INSTR_F= 0x00000000, ML_INSTR_MMX= 0x00000001, ML_INSTR_SSE= 0x00000002, ML_INSTR_SSE2= 0x00000003, ML_INSTR_SSE3= 0x00000004, ML_INSTR_AMDMMX=0x00000005, ML_INSTR_3DNOW= 0x00000006, ML_INSTR_3DNOW2=0x00000007 }ML_INSTR; ml_bool ML_SetSIMDSupport(ML_INSTR nInstr); ML_INSTR ML_FUNC ML_SetBestSIMDSupport(); #ifdef __cplusplus } #endif __cplusplus #endif /*__ML_LIB_H__*/<file_sep>/games/Explor2002/Source/Game/Player.cpp #include "player.h" CPlayerObject::CPlayerObject(int x, int y, Direction face){ m_nFace=face; m_nXLoc=x; m_nYLoc=y; } CPlayerObject::~CPlayerObject(){ } BOOL CPlayerObject::Move(MoveType Move, int movedst){ switch(Move){ case FORWARD:{ switch(m_nFace){ case NORTH:m_nYLoc-=movedst;break; case SOUTH:m_nYLoc+=movedst;break; case EAST:m_nXLoc+=movedst;break; case WEST:m_nXLoc-=movedst;break; default:return FALSE; } }break; case BACKWARD:{ switch(m_nFace){ case NORTH:m_nYLoc+=movedst;break; case SOUTH:m_nYLoc-=movedst;break; case EAST:m_nXLoc-=movedst;break; case WEST:m_nXLoc+=movedst;break; default:return FALSE; } }break; case STRAFE_LEFT:{ switch(m_nFace){ case NORTH:m_nXLoc-=movedst;break; case SOUTH:m_nXLoc+=movedst;break; case EAST:m_nYLoc-=movedst;break; case WEST:m_nYLoc+=movedst;break; default:return FALSE; } }break; case STRAFE_RIGHT:{ switch(m_nFace){ case NORTH:m_nXLoc+=movedst;break; case SOUTH:m_nXLoc-=movedst;break; case EAST:m_nYLoc+=movedst;break; case WEST:m_nYLoc-=movedst;break; default:return FALSE; } }break; default:return FALSE; } return TRUE; } void CPlayerObject::SetFace(Direction NewFace){ m_nFace=NewFace; } void CPlayerObject::SetLocation(int x, int y){ m_nXLoc=x; m_nYLoc=y; } BOOL CPlayerObject::CopyTFront(USHORT src[TFRONT_SIZE]){ for(int i=0;i<TFRONT_SIZE;i++) m_aTFront[i]=src[i]; return TRUE; } BOOL CPlayerObject::Turn(TurnType Turn){ switch(Turn){ case LEFT:{ switch(m_nFace){ case NORTH:m_nFace=WEST;break; case EAST:m_nFace=NORTH;break; case SOUTH:m_nFace=EAST;break; case WEST:m_nFace=SOUTH;break; default:return FALSE; } }break; case RIGHT:{ switch(m_nFace){ case NORTH:m_nFace=EAST;break; case EAST:m_nFace=SOUTH;break; case SOUTH:m_nFace=WEST;break; case WEST:m_nFace=NORTH;break; default:return FALSE; } }break; default:return FALSE; } return TRUE; } int CPlayerObject::GetXLoc(){ return m_nXLoc; } int CPlayerObject::GetYLoc(){ return m_nYLoc; } Direction CPlayerObject::GetFace(){ return m_nFace; }<file_sep>/games/Legacy-Engine/Source/engine/lg_mgr.cpp #include "lg_mgr.h" #include "lg_err.h" #include "lg_cvars.h" CLMgrs::CLMgrs() : m_pMMgr(LG_NULL) , m_pFxMgr(LG_NULL) , m_pTexMgr(LG_NULL) , m_pMtrMgr(LG_NULL) , m_pSkinMgr(LG_NULL) { } CLMgrs::~CLMgrs() { } lg_void CLMgrs::InitMgrs(IDirect3DDevice9* pDevice) { //We'll initalize all managers here, note that they have //to be initialized in a certain order (i.e. the mesh & //skeleton manager use the texture, fx, and material managers //so it must be initialized last.) Err_Printf("=== Initializing Resource Managers ==="); Err_IncTab(); //Should get maximum textures from a cvar. Err_Printf("Texture manager..."); m_pTexMgr=new CLTMgr(pDevice, CV_Get(CVAR_lg_MaxTex)->nValue); Err_Printf("FX manager..."); m_pFxMgr=new CLFxMgr(pDevice, CV_Get(CVAR_lg_MaxFx)->nValue); Err_Printf("Material manager..."); m_pMtrMgr=new CLMtrMgr(CV_Get(CVAR_lg_MaxMtr)->nValue); Err_Printf("Skin manager..."); m_pSkinMgr=new CLSkinMgr(CV_Get(CVAR_lg_MaxSkin)->nValue); Err_Printf("Mesh & skeleton manager..."); m_pMMgr=new CLMMgr(pDevice, CV_Get(CVAR_lg_MaxMeshes)->nValue, CV_Get(CVAR_lg_MaxSkels)->nValue); Err_DecTab(); Err_Printf("======================================"); } lg_void CLMgrs::ShutdownMgrs() { Err_Printf("=== Destroying Resource Managers ==="); Err_IncTab(); //We'll juse destroy these in the opposite order //that we initialized them. Err_Printf("Mesh & skeleton manager..."); LG_SafeDelete(m_pMMgr); Err_Printf("Skin manager..."); LG_SafeDelete(m_pSkinMgr); Err_Printf("Material manager..."); LG_SafeDelete(m_pMtrMgr); Err_Printf("FX manager..."); LG_SafeDelete(m_pFxMgr); Err_Printf("Texture manager..."); LG_SafeDelete(m_pTexMgr); Err_DecTab(); Err_Printf("===================================="); } lg_void CLMgrs::ValidateMgrs() { m_pTexMgr->Validate(); m_pFxMgr->Validate(); m_pMMgr->ValidateMeshes(); } lg_void CLMgrs::InvalidateMgrs() { m_pTexMgr->Validate(); m_pFxMgr->Validate(); m_pMMgr->InvalidateMeshes(); } <file_sep>/samples/Project3/src/project3/SceneLight.java /* SceneLight.java - Light Management code. <NAME> Project 3 CS 1400-002 Copyright (c) 2006, <NAME> */ package project3; import java.awt.*; import javax.swing.*; public class SceneLight extends JComponent { private int m_nR, m_nG, m_nB; public SceneLight(int nRGBColor, int x, int y) { super(); setBounds(0, 0, 10, 10); setLocation(x, y); m_nR=((nRGBColor&0x00FF0000)>>16); m_nG=((nRGBColor&0x0000FF00)>>8); m_nB=((nRGBColor&0x000000FF)); setIntensity(1.0f); } public void paint(Graphics g) { g.setColor(getBackground()); g.fillOval(0, 0, getWidth()-1, getHeight()-1); paintChildren(g); } public void setIntensity(float fIntensity) { //Clamp to between 0.0f and 1.0f. fIntensity=fIntensity<0.0f?0.0f:fIntensity>1.0f?1.0f:fIntensity; int r, g, b; r=(int)((float)m_nR*fIntensity); g=(int)((float)m_nG*fIntensity); b=(int)((float)m_nB*fIntensity); setBackground(new Color(r, g, b)); } } <file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/win_sys.c /************************************************************* File: win_sys.c Copyright (c) 2006, <NAME>. Purpose: Entry point for Legacy3D engine. I've tryed to hide as much of the Windows API as possible from the actual Legacy 3D game (possibly to make future portability easier. All the actual Windows API function calls are in this file, and all the linked to librarys are in this file. The actual game is invoked and run with calls to LG_GameLoop in the WindowLoop() function. The console is also controlled from the MainWindowProc() function, but everything else in teh game is controlled elswhere. *************************************************************/ /************************************************************************************* Legacy3D Game Engine -------------------- The Legacy3D game engine (will be) a functional 3D graphics and physics engine. It will be engineered for both first person action games, as well as slower paced 3rd person adventure games. The project is in the development stages. *************************************************************************************/ #define WM_USER_ACTIVEAPP (WM_USER+1) /* Including all required libs, I included them here as it makes it easier if I have to re-construct the project. */ #ifdef _DEBUG #pragma comment(lib, "d3dx9d.lib") #pragma comment(lib, "ogg_d.lib") #pragma comment(lib, "vorbis_d.lib") #pragma comment(lib, "vorbisfile_d.lib") #pragma comment(lib, "..\\common\\lc_sys_d.lib") #pragma comment(lib, "..\\common\\lf_sys_d.lib") #pragma comment(lib, "..\\common\\img_lib_mt_d.lib") #else /*_DEBUG*/ #pragma comment(lib, "d3dx9.lib") #pragma comment(lib, "ogg.lib") #pragma comment(lib, "vorbis.lib") #pragma comment(lib, "vorbisfile.lib") #pragma comment(lib, "..\\common\\lc_sys.lib") #pragma comment(lib, "..\\common\\lf_sys.lib") #pragma comment(lib, "..\\common\\img_lib_mt.lib") #endif /*_DEBUG*/ #pragma comment(lib, "d3d9.lib") #pragma comment(lib, "dsound.lib") #pragma comment(lib, "dxguid.lib") #pragma comment(lib, "dxerr9.lib") #pragma comment(lib, "winmm.lib") #include "common.h" #include <windows.h> #include <direct.h> #include "lg_sys.h" #include "resource.h" /********************************************************** MainWindowProc() The main window proc for Legacy 3D, very little is done from actual windows functions as far as the game is concerned. The input into the console is managed from here, as well as someshutdown, and activation and deactivation of the app stuf **********************************************************/ LRESULT CALLBACK MainWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch(uMsg) { case WM_ACTIVATEAPP: /* We have the WM_ACTIVEATEAPP keep track whether or not the application is active, this can be useful if the application should pause or something when not being used. */ PostMessage(hwnd, WM_USER_ACTIVEAPP, wParam, 0); break; case WM_COMMAND: { if(LOWORD(wParam)==ID_FILE_EXIT) { SendMessage(hwnd, WM_CLOSE, 0, 0); } break; } case WM_KEYDOWN: switch(wParam) { case VK_PRIOR: LG_OnChar(LK_PAGEUP); break; case VK_NEXT: LG_OnChar(LK_PAGEDOWN); break; case VK_END: LG_OnChar(LK_END); break; } break; /* case WM_MOUSEMOVE: { static D3DXMATRIX RotX; static D3DXMATRIX RotY; static L_bool bFirstTime=1; if(bFirstTime) { D3DXMatrixIdentity(&RotX); D3DXMatrixIdentity(&RotY); bFirstTime=0; } if(L_CHECK_FLAG(wParam, MK_LBUTTON)) { D3DXMATRIX Temp; D3DXMatrixRotationX(&Temp, (float)LOWORD(lParam)/1000.0f); D3DXMatrixMultiply(&RotX, &Temp, &RotX); D3DXMatrixRotationY(&Temp, (float)HIWORD(lParam)/1000.0f); D3DXMatrixMultiply(&RotY, &Temp, &RotY); D3DXMatrixMultiply(&Temp, &RotX, &RotY); IDirect3DDevice9_SetTransform(LG_GetGame()->v.m_lpDevice, D3DTS_WORLD,&Temp); } break; } */ case WM_CHAR: /* if(wParam==VK_ESCAPE) SendMessage(hwnd, WM_CLOSE, 0, 0); */ LG_OnChar((char)wParam); break; case WM_CLOSE: /* Of course we need to be able to shutdown our application, this will probably be done through an ingame menu later on, but in this stage of development we need a way to shutdown our application. */ DestroyWindow(hwnd); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hwnd, uMsg, wParam, lParam); } return 0l; } /******************************************************** WindowLoop() The main loop for windows, the actual game loop is called from here when the function LG_GameLoop() is called, the rest of this deals with some windows stuff. ********************************************************/ int WindowLoop(HWND hwnd) { BOOL bActiveApp=TRUE; BOOL bAlwaysProc=FALSE; MSG msg; memset(&msg, 0, sizeof(msg)); /* ===The window loop=== The idea behind the window loop is that we want to check to see if Windows wants to do something, but other than that we want to do what our game wants to do, so most of the time the GameLoop() function will be called, but if a message comes up, then windows will process it. Most of the game will be managed from the GameLoop function. */ /* This game loop should be used if the game should stop running when the window is not active. */ while(TRUE) { if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { if(msg.message==WM_QUIT) { LG_GameLoop(hwnd, TRUE, bActiveApp); break; } else if(msg.message==WM_USER_ACTIVEAPP) bActiveApp=msg.wParam; TranslateMessage(&msg); DispatchMessage(&msg); } else { if(bAlwaysProc || bActiveApp) { if(!LG_GameLoop(hwnd, FALSE, bActiveApp)) SendMessage(msg.hwnd, WM_CLOSE, 0, 0); } else { WaitMessage(); } } } return msg.wParam; } /******************************************************* ChangeDirectory() This insures that the game starts in the directory that the exe file is in. Called from WinMain(). *******************************************************/ void ChangeDirectory(char* szCommandLine) { char szNewDir[MAX_PATH]; int i=0; int nLen=0; int bFoundQuote=0; /* Get rid of the initial quote. */ szCommandLine++; nLen=L_strlen(szCommandLine); for(i=0; i<nLen; i++) if(szCommandLine[i]=='\"') break; L_strncpy(szNewDir, szCommandLine, i); /* Now go back until we find a backslash and set that to zero. */ for(i=L_strlen(szNewDir); i--; ) { if(szNewDir[i]=='\\') { szNewDir[i]=0; break; } } _chdir(szNewDir); /* Now if we're debugging then the app is in the legacy3d\debug directory so we need to change that. */ #ifdef _DEBUG _chdir("..\\.."); #endif /*_DEBUG*/ } /************************************************************* WinMain() The entry point for Legacy 3D, not that most of the game stuff is managed in LG_GameLoop(), but that function is from the windows loop. Everything in here is standard windows creation. When MainWindowLoop() is called that is when the game loop starts. *************************************************************/ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { HWND hwnd=NULL; WNDCLASSEX wc; int nResult=0; static TCHAR szAppName[]=TEXT("Legacy3D Engine"); /* We want the starting directory to be the directory where the EXE file is located. */ ChangeDirectory(GetCommandLine()); /* The first thing we need to do is all the standard Window creation calls. */ /* Define and register the Window's Class. */ wc.cbSize=sizeof(wc); wc.style=CS_HREDRAW|CS_VREDRAW|CS_OWNDC; wc.cbClsExtra=0; wc.cbWndExtra=0; wc.lpfnWndProc=MainWindowProc; wc.hInstance=hInstance; wc.hbrBackground=(HBRUSH)GetStockObject(DKGRAY_BRUSH); wc.hIcon=LoadIcon(hInstance, "L3DICO"); wc.hIconSm=LoadIcon(hInstance, "L3DICO"); wc.hCursor=LoadCursor(NULL, IDC_ARROW); wc.lpszMenuName="LEGACY3DMENU"; wc.lpszClassName=szAppName; if(!RegisterClassEx(&wc)) { MessageBox( NULL, TEXT("This program requires Windows NT!"), szAppName, MB_OK|MB_ICONERROR); return 0; } /* Create the Window. */ hwnd=CreateWindowEx( 0, szAppName, szAppName, WS_CAPTION|WS_SYSMENU|WS_VISIBLE|WS_MINIMIZEBOX, CW_USEDEFAULT, CW_USEDEFAULT, 320, 240, NULL, NULL, hInstance, NULL); if(hwnd==NULL) { MessageBox( NULL, TEXT("Failed to create window! Shutting down."), szAppName, MB_OK|MB_ICONERROR); return 0; } ShowWindow(hwnd, nCmdShow); UpdateWindow(hwnd); #ifdef _DEBUG L_BEGIN_D_DUMP nResult=WindowLoop(hwnd); L_END_D_DUMP("legacy3d.exe") _CrtDumpMemoryLeaks(); return nResult; #else /*_DEBUG*/ return WindowLoop(hwnd); #endif /*_DEBUG*/ } <file_sep>/games/Legacy-Engine/Source/engine/lv_font.cpp #include <d3dx9.h> #include "lf_sys2.h" #include "lg_err.h" #include "lv_font.h" #include "lg_func.h" #include "lg_tmgr.h" #define FONTRENDER_WIDTH 640.0f #define FONTRENDER_HEIGHT 480.0f class CLFontL: public CLFont { private: typedef struct _LVFONTVERTEX{ float x, y, z; float tu, tv; }LVFONTVERTEX, *PLVFONTVERTEX; static const lg_dword LVFONTVERTEX_TYPE=D3DFVF_XYZ|D3DFVF_TEX1; static lg_bool SetResetStates(IDirect3DDevice9* lpDevice, lg_bool bStart); private: tm_tex m_lpFontTexture; IDirect3DVertexBuffer9* m_lpFontVB; lg_byte m_nCharWidthInFile; lg_byte m_nCharHeightInFile; LVFONTVERTEX m_lpVertices[96*4]; public: CLFontL(); ~CLFontL(); lg_bool Create( IDirect3DDevice9* lpDevice, char* szFont, lg_byte nCharWidth, lg_byte nCharHeight, lg_byte nCharWidthInFile, lg_byte nCharHeightInFile); void Delete(); lg_bool Validate(); void Invalidate(); void Begin(); void End(); void DrawString(char* szString, lg_long x, lg_long y); void GetDims(lg_byte* nWidth, lg_byte* nHeight, lg_void* pExtra); private: void DrawChar(char c, lg_long x, lg_long y); }; class CLFontD3D: public CLFont { private: ID3DXFont* m_lpD3DXFont; ID3DXSprite* m_lpD3DXSurface; lg_dword m_dwD3DColor; public: CLFontD3D(); ~CLFontD3D(); lg_bool Create( IDirect3DDevice9* lpDevice, char* szFont, lg_byte nCharWidth, lg_byte nCharHeight, lg_dword dwD3DColor); void Delete(); lg_bool Validate(); void Invalidate(); void Begin(); void End(); void DrawString(char* szString, lg_long x, lg_long y); void GetDims(lg_byte* nWidth, lg_byte* nHeight, lg_void* pExtra); }; /************************ *** CLFont Base Class *** ************************/ CLFont::CLFont(): m_pDevice(0), m_nCharWidth(0), m_nCharHeight(0), m_bIsDrawing(0) { memset(m_szFont, 0, sizeof(m_szFont)); } CLFont::~CLFont() { Delete(); } CLFont* CLFont::Create( IDirect3DDevice9* lpDevice, char* szFont, lg_byte nCharWidth, lg_byte nCharHeight, lg_bool bD3DXFont, lg_byte nCharWidthInFile, lg_byte nCharHeightInFile, lg_dword dwD3DColor) { if(bD3DXFont) { CLFontD3D* pFont=new CLFontD3D(); if(!pFont->Create( lpDevice, szFont, nCharWidth, nCharHeight, dwD3DColor)) { delete pFont; return LG_NULL; } return pFont; } else { CLFontL* pFont=new CLFontL(); if(!pFont->Create( lpDevice, szFont, nCharWidth, nCharHeight, nCharWidthInFile, nCharHeightInFile)) { delete pFont; return LG_NULL; } return pFont; } } /****************************** *** CLFontL The Legacy Font *** ******************************/ CLFontL::CLFontL(): CLFont(), m_lpFontTexture(0), m_lpFontVB(0), m_nCharWidthInFile(0), m_nCharHeightInFile(0) { memset(m_lpVertices, 0, sizeof(m_lpVertices)); } CLFontL::~CLFontL() { Delete(); } lg_bool CLFontL::Create( IDirect3DDevice9* lpDevice, char* szFont, lg_byte nCharWidth, lg_byte nCharHeight, lg_byte nCharWidthInFile, lg_byte nCharHeightInFile) { Delete(); lg_result nResult=0; /* Nullify everything in the font.*/ m_pDevice=lpDevice; lpDevice->AddRef(); m_nCharWidth=nCharWidth; m_nCharHeight=nCharHeight; m_nCharWidthInFile=nCharWidthInFile; m_nCharHeightInFile=nCharHeightInFile; LG_strncpy(m_szFont, szFont, LF_MAX_PATH); if(!Validate()) { L_safe_release(m_pDevice); return LG_FALSE; } return LG_TRUE; } void CLFontL::GetDims(lg_byte* nWidth, lg_byte* nHeight, lg_void* pExtra) { if(nWidth) *nWidth=m_nCharWidth; if(nHeight) *nHeight=m_nCharHeight; if(pExtra) *((lg_bool*)pExtra)=LG_FALSE; } void CLFontL::Delete() { m_lpFontTexture=0;//L_safe_release(m_lpFontTexture); L_safe_release(m_lpFontVB); L_safe_release(m_pDevice); } lg_bool CLFontL::Validate() { lg_result nResult=0; if(m_lpFontTexture || m_lpFontVB) return LG_TRUE; D3DSURFACE_DESC desc; int i=0, j=0, c=0, a=0, nCharsPerLine=0; LVFONTVERTEX* v; /* We need a texture for the font.*/ m_lpFontTexture=CLTMgr::TM_LoadTex(m_szFont, CLTMgr::TM_FORCENOMIP); if(!m_lpFontTexture) { Err_Printf("Font_Create2 Error: Could not create texture from \"%s\".", m_szFont); return LG_FALSE; } /* Create the vertex buffer.*/ nResult=IDirect3DDevice9_CreateVertexBuffer( m_pDevice, sizeof(LVFONTVERTEX)*96*4, D3DUSAGE_WRITEONLY, LVFONTVERTEX_TYPE, D3DPOOL_DEFAULT, &m_lpFontVB, LG_NULL); if(LG_FAILED(nResult)) { Err_Printf("Font_Create2 Error: Could not create vertex buffer."); Err_PrintDX(" IDirect3DDevice9::CreateVertexBuffer", nResult); m_lpFontTexture=0;//L_safe_release(m_lpFontTexture); return LG_FALSE; } //m_lpFontTexture->GetLevelDesc(0, &desc); desc.Width=128; /* Now find each individual letter in the texture.*/ nCharsPerLine=desc.Width/m_nCharWidthInFile; if((desc.Width%m_nCharWidthInFile)>0) nCharsPerLine++;//+((desc.Width%m_nCharWidthInFile)>0)?1:0; IDirect3DVertexBuffer9_Lock(m_lpFontVB, 0, sizeof(LVFONTVERTEX)*96*4, (void**)&v, 0); i=0;j=0; for(c=0, a=0; c<96; c++, a+=4) { if(j>nCharsPerLine){j=0; i++;} v[a].x=0.0f; v[a].y=0.0f; v[a+1].x=(float)m_nCharWidth; v[a+1].y=0.0f; v[a+2].x=(float)m_nCharWidth; v[a+2].y=-(float)m_nCharHeight; v[a+3].x=0.0f; v[a+3].y=-(float)m_nCharHeight; v[a].z=v[a+1].z=v[a+2].z=v[a+3].z=0.0f; /* v[a].Diffuse= v[a+1].Diffuse= v[a+2].Diffuse= v[a+3].Diffuse=0xFFFFFFFF; */ } for(i=0, a=0; a<(96*4); i++) { for(j=0; j<nCharsPerLine && a<(96*4); j++, a+=4) { v[a].x=0.0f; v[a].y=0.0f; v[a+1].x=(float)m_nCharWidth; v[a+1].y=0.0f; v[a+2].x=(float)m_nCharWidth; v[a+2].y=-(float)m_nCharHeight; v[a+3].x=0.0f; v[a+3].y=-(float)m_nCharHeight; v[a].z=v[a+1].z=v[a+2].z=v[a+3].z=0.0f; /* v[a].Diffuse= v[a+1].Diffuse= v[a+2].Diffuse= v[a+3].Diffuse=0xFFFFFFFF; */ v[a].tu= v[a+3].tu=(float)j*(float)m_nCharWidthInFile/(float)desc.Width; v[a+1].tu= v[a+2].tu=(float)(j+1)*(float)m_nCharWidthInFile/(float)desc.Width; v[a+2].tv= v[a+3].tv=(float)(i+1)*(float)m_nCharHeightInFile/(float)desc.Height; v[a].tv= v[a+1].tv=(float)i*(float)m_nCharHeightInFile/(float)desc.Height; } } IDirect3DVertexBuffer9_Unlock(m_lpFontVB); return LG_TRUE; } void CLFontL::Invalidate() { L_safe_release(m_lpFontVB); //L_safe_release(m_lpFontTexture); m_lpFontTexture=0; } void CLFontL::Begin() { if(m_bIsDrawing || !m_lpFontVB) return; D3DXMATRIX TempMatrix; //Set some render states. D3DXMatrixOrthoLH(&TempMatrix, FONTRENDER_WIDTH, FONTRENDER_HEIGHT, 0.0f, 1.0f); IDirect3DDevice9_SetTransform(m_pDevice, D3DTS_PROJECTION, &TempMatrix); IDirect3DDevice9_SetTransform(m_pDevice, D3DTS_VIEW, D3DXMatrixIdentity(&TempMatrix)); SetResetStates(m_pDevice, LG_TRUE); // Set the texture and vertex buffer. //IDirect3DDevice9_SetTexture(m_pDevice, 0, (LPDIRECT3DBASETEXTURE9)m_lpFontTexture); CLTMgr::TM_SetTexture(m_lpFontTexture, 0); IDirect3DDevice9_SetStreamSource(m_pDevice, 0, m_lpFontVB, 0, sizeof(LVFONTVERTEX)); m_bIsDrawing=LG_TRUE; } void CLFontL::End() { if(!m_bIsDrawing) return; SetResetStates(m_pDevice, LG_FALSE); m_bIsDrawing=LG_FALSE; } void CLFontL::DrawString(char* szString, lg_long x, lg_long y) { if(!szString) return; lg_dword dwLen=L_strlen(szString), i=0; for(i=0; i<dwLen; i++) { DrawChar(szString[i], x+(i*m_nCharWidth), y); } } void CLFontL::DrawChar(char c, lg_long x, lg_long y) { D3DXMATRIX TempMatrix; if(c<' ' || c>'~') c=' '; D3DXMatrixIdentity(&TempMatrix); D3DXMatrixTranslation(&TempMatrix, x-FONTRENDER_WIDTH/2.0f, FONTRENDER_HEIGHT/2.0f-y, 0.0f); IDirect3DDevice9_SetTransform(m_pDevice, D3DTS_WORLD, &TempMatrix); /* Set the texture.*/ IDirect3DDevice9_DrawPrimitive(m_pDevice, D3DPT_TRIANGLEFAN, (c-' ')*4, 2); } lg_bool CLFontL::SetResetStates(IDirect3DDevice9* lpDevice, lg_bool bStart) { static lg_dword dwPrevFVF=0; static lg_dword dwOldCullMode=0; static lg_dword dwOldAA=0; //static LPDIRECT3DVERTEXSHADER9 lpOldVS=NULL; static lg_dword dwOldAlphaEnable=0, dwOldSrcBlend=0, dwOldDestBlend=0, dwOldAlphaA=0; static lg_dword dwOldZEnable=0; static lg_dword dwOldLighting=0; static lg_dword dwOldMipFilter=0; static lg_dword dwOldMinFilter=0; static lg_dword dwOldMagFilter=0; static lg_dword dwOldFill=0; if(bStart) { // Save the old filter modes. IDirect3DDevice9_GetSamplerState(lpDevice, 0, D3DSAMP_MAGFILTER, &dwOldMagFilter); IDirect3DDevice9_GetSamplerState(lpDevice, 0, D3DSAMP_MINFILTER, &dwOldMinFilter); IDirect3DDevice9_GetSamplerState(lpDevice, 0, D3DSAMP_MIPFILTER, &dwOldMipFilter); IDirect3DDevice9_SetSamplerState(lpDevice, 0, D3DSAMP_MAGFILTER, D3DTEXF_POINT); IDirect3DDevice9_SetSamplerState(lpDevice, 0, D3DSAMP_MINFILTER, D3DTEXF_NONE); IDirect3DDevice9_SetSamplerState(lpDevice, 0, D3DSAMP_MIPFILTER, D3DTEXF_NONE); // Save some rendering state values, they will be restored when this function // is called with bStart set to FALSE. lpDevice->GetRenderState(D3DRS_LIGHTING, &dwOldLighting); lpDevice->SetRenderState(D3DRS_LIGHTING, FALSE); //* Get and set FVF. lpDevice->GetFVF(&dwPrevFVF); lpDevice->SetFVF(LVFONTVERTEX_TYPE); //* Get and set vertex shader. //lpDevice->GetVertexShader(&lpOldVS); //lpDevice->SetVertexShader(NULL); //* Get and set cull mode. lpDevice->GetRenderState(D3DRS_CULLMODE, &dwOldCullMode); lpDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW); //* Set alpha blending. lpDevice->GetRenderState(D3DRS_ALPHABLENDENABLE, &dwOldAlphaEnable); lpDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); lpDevice->GetRenderState(D3DRS_SRCBLEND, &dwOldSrcBlend); lpDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); lpDevice->GetRenderState(D3DRS_DESTBLEND, &dwOldDestBlend); lpDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); lpDevice->GetTextureStageState(0, D3DTSS_ALPHAARG1, &dwOldAlphaA); lpDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); // Get and set z-buffer status. lpDevice->GetRenderState(D3DRS_ZENABLE, &dwOldZEnable); lpDevice->SetRenderState(D3DRS_ZENABLE, FALSE); lpDevice->GetRenderState(D3DRS_MULTISAMPLEANTIALIAS, &dwOldAA); lpDevice->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, FALSE); lpDevice->GetRenderState(D3DRS_FILLMODE, &dwOldFill); IDirect3DDevice9_SetRenderState(lpDevice, D3DRS_FILLMODE, D3DFILL_SOLID); } else { // Restore all saved values. lpDevice->SetFVF(dwPrevFVF); //lpDevice->SetVertexShader(lpOldVS); lpDevice->SetRenderState(D3DRS_CULLMODE, dwOldCullMode); // Restore alpha blending state. lpDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, dwOldAlphaEnable); lpDevice->SetRenderState(D3DRS_SRCBLEND, dwOldSrcBlend); lpDevice->SetRenderState(D3DRS_DESTBLEND, dwOldDestBlend); lpDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, dwOldAlphaA); // Restore Z-Buffering status. lpDevice->SetRenderState(D3DRS_ZENABLE, dwOldZEnable); lpDevice->SetRenderState(D3DRS_LIGHTING, dwOldLighting); lpDevice->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, dwOldAA); IDirect3DDevice9_SetSamplerState(lpDevice, 0, D3DSAMP_MAGFILTER, dwOldMagFilter); IDirect3DDevice9_SetSamplerState(lpDevice, 0, D3DSAMP_MINFILTER, dwOldMinFilter); IDirect3DDevice9_SetSamplerState(lpDevice, 0, D3DSAMP_MIPFILTER, dwOldMipFilter); IDirect3DDevice9_SetRenderState(lpDevice, D3DRS_FILLMODE, dwOldFill); //lpDevice->lpVtbl->SetVertexShader(lpDevice, lpOldVS); //L_safe_release(lpOldVS); } return LG_TRUE; } /************************************************** *** CLFontD3D The Legacy Font Based on D3DXFont *** **************************************************/ CLFontD3D::CLFontD3D(): CLFont(), m_lpD3DXFont(0), m_lpD3DXSurface(0), m_dwD3DColor(0) { } CLFontD3D::~CLFontD3D() { Delete(); } lg_bool CLFontD3D::Create( IDirect3DDevice9* lpDevice, char* szFont, lg_byte nCharWidth, lg_byte nCharHeight, lg_dword dwD3DColor) { Delete(); lg_result nResult=0; /* Nullify everything in the font.*/ m_pDevice=lpDevice; lpDevice->AddRef(); m_nCharWidth=nCharWidth; m_nCharHeight=nCharHeight; m_dwD3DColor=dwD3DColor; LG_strncpy(m_szFont, szFont, LG_MAX_PATH); D3DXFONT_DESC fdesc; nResult=D3DXCreateFont( lpDevice, nCharHeight, nCharWidth, FW_DONTCARE, 1, LG_FALSE, ANSI_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH, szFont, &m_lpD3DXFont); if(LG_FAILED(nResult)) { Err_Printf("Could not create \"%s\" font.", szFont); Err_PrintDX(" D3DXCreateFont", nResult); m_pDevice->Release(); return LG_NULL; } nResult=D3DXCreateSprite(lpDevice, &m_lpD3DXSurface); if(LG_FAILED(nResult)) { Err_Printf("Failed to create font surface for writing, expect slower font drawing."); m_lpD3DXSurface=LG_NULL; } memset(&fdesc, 0, sizeof(fdesc)); m_lpD3DXFont->GetDescA(&fdesc); m_nCharHeight=fdesc.Height; m_nCharWidth=fdesc.Width; m_bIsDrawing=LG_FALSE; return LG_TRUE; } void CLFontD3D::Delete() { L_safe_release(m_lpD3DXFont); L_safe_release(m_lpD3DXSurface); L_safe_release(m_pDevice); } lg_bool CLFontD3D::Validate() { lg_result nResult=0; nResult=m_lpD3DXFont->OnResetDevice(); if(LG_FAILED(D3DXCreateSprite(m_pDevice, &m_lpD3DXSurface))) { Err_Printf("Failed to create font surface for writing, expect slower font drawing."); m_lpD3DXSurface=LG_NULL; } return LG_SUCCEEDED(nResult); } void CLFontD3D::Invalidate() { lg_result nResult=0; nResult=m_lpD3DXFont->OnLostDevice(); L_safe_release(m_lpD3DXSurface); } void CLFontD3D::Begin() { if(m_bIsDrawing) return; if(m_lpD3DXSurface) m_lpD3DXSurface->Begin(D3DXSPRITE_ALPHABLEND); m_bIsDrawing=LG_TRUE; } void CLFontD3D::End() { if(!m_bIsDrawing) return; if(m_lpD3DXSurface) m_lpD3DXSurface->End(); m_bIsDrawing=LG_FALSE; } void CLFontD3D::DrawString(char* szString, lg_long x, lg_long y) { if(!szString) return; lg_result nResult=0; lg_long nWidth = 1024; lg_rect rcDest={x, y, x+nWidth, y+m_nCharHeight}; /* Note in parameter 2 we test to see if drawing has started, if it hasn't we pass null for the surface, so the text will be drawn anyway, but this will be slower.*/ m_lpD3DXFont->DrawText( m_bIsDrawing?m_lpD3DXSurface:LG_NULL, szString, -1, (LPRECT)&rcDest, DT_LEFT, m_dwD3DColor); } void CLFontD3D::GetDims(lg_byte* nWidth, lg_byte* nHeight, lg_void* pExtra) { if(nWidth) *nWidth=m_nCharWidth; if(nHeight) *nHeight=m_nCharHeight; if(pExtra) *((lg_bool*)pExtra)=LG_TRUE; }<file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/lg_math/lg_math_c.c #include <math.h> #include "lg_math.h" L_dword __cdecl L_nextpow2_C(const L_dword n) { L_dword result = 1; if(n>=0x80000000) return 0x80000000; while(result<n) { result <<= 1; } return result; } L_vector3* __cdecl L_vec3add_C(L_vector3* pOut, const L_vector3* pV1, const L_vector3* pV2) { pOut->x=pV1->x+pV2->x; pOut->y=pV1->y+pV2->y; pOut->z=pV1->z+pV2->z; return pOut; } float __cdecl L_vec3distance_C(const L_vector3* pV1, const L_vector3* pV2) { return (float)sqrt(((pV1->x-pV2->x)*(pV1->x-pV2->x)+(pV1->y-pV2->y)*(pV1->y-pV2->y)+(pV1->z-pV2->z)*(pV1->z-pV2->z))); } L_matrix* __cdecl L_matmultiply_C(L_matrix* pOut, const L_matrix* pM1, const L_matrix* pM2) { L_matrix out; out._11 = (pM1->_11 * pM2->_11) + (pM1->_12 * pM2->_21) + (pM1->_13 * pM2->_31) + (pM1->_14 * pM2->_41); out._12 = (pM1->_11 * pM2->_12) + (pM1->_12 * pM2->_22) + (pM1->_13 * pM2->_32) + (pM1->_14 * pM2->_42); out._13 = (pM1->_11 * pM2->_13) + (pM1->_12 * pM2->_23) + (pM1->_13 * pM2->_33) + (pM1->_14 * pM2->_43); out._14 = (pM1->_11 * pM2->_14) + (pM1->_12 * pM2->_24) + (pM1->_13 * pM2->_34) + (pM1->_14 * pM2->_44); out._21 = (pM1->_21 * pM2->_11) + (pM1->_22 * pM2->_21) + (pM1->_23 * pM2->_31) + (pM1->_24 * pM2->_41); out._22 = (pM1->_21 * pM2->_12) + (pM1->_22 * pM2->_22) + (pM1->_23 * pM2->_32) + (pM1->_24 * pM2->_42); out._23 = (pM1->_21 * pM2->_13) + (pM1->_22 * pM2->_23) + (pM1->_23 * pM2->_33) + (pM1->_24 * pM2->_43); out._24 = (pM1->_21 * pM2->_14) + (pM1->_22 * pM2->_24) + (pM1->_23 * pM2->_34) + (pM1->_24 * pM2->_44); out._31 = (pM1->_31 * pM2->_11) + (pM1->_32 * pM2->_21) + (pM1->_33 * pM2->_31) + (pM1->_34 * pM2->_41); out._32 = (pM1->_31 * pM2->_12) + (pM1->_32 * pM2->_22) + (pM1->_33 * pM2->_32) + (pM1->_34 * pM2->_42); out._33 = (pM1->_31 * pM2->_13) + (pM1->_32 * pM2->_23) + (pM1->_33 * pM2->_33) + (pM1->_34 * pM2->_43); out._34 = (pM1->_31 * pM2->_14) + (pM1->_32 * pM2->_24) + (pM1->_33 * pM2->_34) + (pM1->_34 * pM2->_44); out._41 = (pM1->_41 * pM2->_11) + (pM1->_42 * pM2->_21) + (pM1->_43 * pM2->_31) + (pM1->_44 * pM2->_41); out._42 = (pM1->_41 * pM2->_12) + (pM1->_42 * pM2->_22) + (pM1->_43 * pM2->_32) + (pM1->_44 * pM2->_42); out._43 = (pM1->_41 * pM2->_13) + (pM1->_42 * pM2->_23) + (pM1->_43 * pM2->_33) + (pM1->_44 * pM2->_43); out._44 = (pM1->_41 * pM2->_14) + (pM1->_42 * pM2->_24) + (pM1->_43 * pM2->_34) + (pM1->_44 * pM2->_44); *pOut = out; return pOut; } L_matrix* __cdecl L_matmultiply3DNow(L_matrix* pOut, const L_matrix* pM1, const L_matrix* pM2) { return L_null; #ifdef GPP asm( "movl $4, %%ecx\n" "MatrixMultiplyOf_3DNow_Loop%=:\n" "movd (%0), %%mm0\n" /* mm0 = ? | x */ "movd 4(%0), %%mm2\n" /* mm2 = ? | y */ "movd 8(%0), %%mm4\n" /* mm4 = ? | z */ "movd 12(%0), %%mm6\n" /* mm6 = ? | w */ "prefetch 16(%0)\n" /* prefetch_for_reading(in+4); */ "prefetchw 16(%2)\n" /* prefetch_for_writing(out+4); */ "punpckldq %%mm0, %%mm0\n" /* mm0 = x | x */ "punpckldq %%mm2, %%mm2\n" /* mm2 = y | y */ "punpckldq %%mm4, %%mm4\n" /* mm4 = z | z */ "punpckldq %%mm6, %%mm6\n" /* mm6 = w | w */ "movq %%mm0, %%mm1\n" /* mm1 = x | x */ "movq %%mm2, %%mm3\n" /* mm3 = y | y */ "movq %%mm4, %%mm5\n" /* mm5 = z | z */ "movq %%mm6, %%mm7\n" /* mm7 = w | w */ "pfmul (%1), %%mm0\n" /* mm0 = x*m[1] | x*m[0] */ "pfmul 8(%1), %%mm1\n" /* mm1 = x*m[3] | x*m[2] */ "pfmul 16(%1), %%mm2\n" /* mm2 = y*m[5] | y*m[4] */ "pfmul 24(%1), %%mm3\n" /* mm3 = y*m[7] | y*m[6] */ "pfmul 32(%1), %%mm4\n" /* mm4 = z*m[9] | z*m[8] */ "pfmul 40(%1), %%mm5\n" /* mm5 = z*m[11] | z*m[10] */ "pfmul 48(%1), %%mm6\n" /* mm6 = w*m[13] | w*m[12] */ "pfmul 56(%1), %%mm7\n" /* mm7 = w*m[15] | w*m[14] */ "pfadd %%mm0, %%mm2\n" "pfadd %%mm1, %%mm3\n" "pfadd %%mm4, %%mm6\n" "pfadd %%mm5, %%mm7\n" "pfadd %%mm2, %%mm6\n" "pfadd %%mm3, %%mm7\n" "movq %%mm6, (%2)\n" "movq %%mm7, 8(%2)\n" "addl $16, %0\n" "addl $16, %2\n" "loop MatrixMultiplyOf_3DNow_Loop%=\n" : : "r" (pLeft), "r" (pRight), "r" (pOut) : "%ecx" ); #endif }<file_sep>/games/Legacy-Engine/Source/engine/lw_map.cpp //lw_sys.cpp - The Legacy World (Map) system. //Copyright (c) 2007 <NAME> #include "lw_map.h" #include "lg_err.h" #include "lg_err_ex.h" #include "ML_lib.h" #include "ld_sys.h" #include "lg_tmgr.h" #include "lg_func.h" #include <stdio.h> CLMap::CLMap(): m_bLoaded(LG_FALSE), m_nID(0), m_nVersion(0), m_nVertexCount(0), m_nVertexOffset(0), m_nMaterialCount(0), m_nMaterialOffset(0), m_nLMCount(0), m_nLMOffset(0), m_nLMTotalSize(0), m_nSegmentCount(0), m_nSegmentOffset(0), m_nRegionCount(0), m_nRegionOffset(0), m_nGeoBlockCount(0), m_nGeoBlockOffset(0), m_nGeoFaceCount(0), m_nGeoFaceOffset(0), m_nLightCount(0), m_nLightOffset(0), m_nGeoVertOffset(0), m_nGeoVertCount(0), m_nGeoTriCount(0), m_nGeoTriOffset(0), m_pVertexes(LG_NULL), m_pLMData(LG_NULL), m_pLMs(LG_NULL), m_pSegments(LG_NULL), m_pRegions(LG_NULL), m_pGeoBlocks(LG_NULL), m_pGeoFaces(LG_NULL), m_pLights(LG_NULL), m_pGeoVerts(LG_NULL), m_pGeoTris(LG_NULL), m_pMem(LG_NULL) { m_szMapPath[0]=0; } CLMap::~CLMap() { Unload(); } const lg_str CLMap::GetMapPath() { return m_szMapPath; } lg_bool CLMap::IsLoaded() { return m_bLoaded; } void CLMap::Unload() { DeallocateMemory(); m_nID=0; m_nVersion=0; m_nVertexCount=0; m_nVertexOffset=0; m_nMaterialCount=0; m_nMaterialOffset=0; m_nLMCount=0; m_nLMOffset=0; m_nLMTotalSize=0; m_nSegmentCount=0; m_nSegmentOffset=0; m_nRegionCount=0; m_nRegionOffset=0; m_nGeoBlockCount=0; m_nGeoBlockOffset=0; m_nGeoFaceCount=0; m_nGeoFaceOffset=0; m_nLightCount=0; m_nLightOffset=0; m_nGeoVertCount=0; m_nGeoVertOffset=0; m_nGeoTriCount=0; m_nGeoTriOffset=0; m_szMapPath[0]=0; m_bLoaded=LG_FALSE; } lg_bool CLMap::AllocateMemory() { DeallocateMemory(); lg_dword nOffset=0; lg_dword nVertexOffset=nOffset; nOffset+=m_nVertexCount*sizeof(LW_VERTEX); lg_dword nMaterialOffset=nOffset; nOffset+=m_nMaterialCount*sizeof(LW_MATERIAL); lg_dword nLMOffset=nOffset; nOffset+=m_nLMTotalSize; lg_dword nLMPointerOffset=nOffset; nOffset+=m_nLMCount*sizeof(lg_byte*); lg_dword nFaceOffset=nOffset; nOffset+=m_nSegmentCount*sizeof(LW_RASTER_SEGMENT); lg_dword nRegionOffset=nOffset; nOffset+=m_nRegionCount*sizeof(LW_REGION_EX); lg_dword nGeoBlockOffset=nOffset; nOffset+=m_nGeoBlockCount*sizeof(LW_GEO_BLOCK_EX); lg_dword nGeoFaceOffset=nOffset; nOffset+=m_nGeoFaceCount*sizeof(LW_GEO_FACE); lg_dword nLightOffset=nOffset; nOffset+=m_nLightCount*sizeof(LW_LIGHT); lg_dword nGeoVertOffset=nOffset; nOffset+=m_nGeoVertCount*sizeof(LW_GEO_VERTEX); lg_dword nGeoTriOffset=nOffset; nOffset+=m_nGeoTriCount*sizeof(LW_GEO_TRI); lg_dword nSize=nOffset; //For more efficient memory usage, we'll allocate one big //lump of memory and simply point to the data within that //memory, for most of the items. m_pMem=new lg_byte[nSize]; if(!m_pMem) { DeallocateMemory(); return LG_FALSE; } m_pVertexes=(LW_VERTEX*)(m_pMem+nVertexOffset); m_pMaterials=(LW_MATERIAL*)(m_pMem+nMaterialOffset); m_pLMData=(lg_byte*)(m_pMem+nLMOffset); m_pLMs=(lg_byte**)(m_pMem+nLMPointerOffset); m_pSegments=(LW_RASTER_SEGMENT*)(m_pMem+nFaceOffset); m_pRegions=(LW_REGION_EX*)(m_pMem+nRegionOffset); m_pGeoBlocks=(LW_GEO_BLOCK_EX*)(m_pMem+nGeoBlockOffset); m_pGeoFaces=(LW_GEO_FACE*)(m_pMem+nGeoFaceOffset); m_pLights=(LW_LIGHT*)(m_pMem+nLightOffset); m_pGeoVerts=(LW_GEO_VERTEX*)(m_pMem+nGeoVertOffset); m_pGeoTris=(LW_GEO_TRI*)(m_pMem+nGeoTriOffset); Err_Printf(" %u bytes allocated.", nSize); return LG_TRUE; } void CLMap::DeallocateMemory() { //We only have to delete the lump of data, //then set everything else to null. LG_SafeDeleteArray(m_pMem); m_pVertexes=LG_NULL; m_pMaterials=LG_NULL; m_pLMData=LG_NULL; m_pLMs=LG_NULL; m_pSegments=LG_NULL; m_pRegions=LG_NULL; m_pGeoBlocks=LG_NULL; m_pGeoFaces=LG_NULL; m_pLights=LG_NULL; m_pGeoVerts=LG_NULL; m_pGeoTris=LG_NULL; } lg_bool CLMap::LoadReal(lf_path szFilename) { Unload(); Err_Printf("Loading \"%s\"...", szFilename); LF_FILE3 fin=LF_Open(szFilename, LF_ACCESS_READ, LF_OPEN_EXISTING); if(!fin) { Err_Printf(" CLMap::Load ERROR: Could not open \"%s\".", szFilename); return LG_FALSE; } //Read the header, and make sure the map is actually a legacy world. LF_Read(fin, &m_nID, 2); LF_Read(fin, &m_nVersion, 4); if((m_nID!=LW_ID) || (m_nVersion!=LW_VERSION)) { Err_Printf(" CLMap::Load ERROR: \"%s\" is not a valid Legacy World.", szFilename); LF_Close(fin); return LG_FALSE; } //Read the rest of the header... LF_Read(fin, &m_nVertexCount, 4); LF_Read(fin, &m_nVertexOffset, 4); LF_Read(fin, &m_nMaterialCount, 4); LF_Read(fin, &m_nMaterialOffset, 4); LF_Read(fin, &m_nLMCount, 4); LF_Read(fin, &m_nLMOffset, 4); LF_Read(fin, &m_nLMTotalSize, 4); LF_Read(fin, &m_nSegmentCount, 4); LF_Read(fin, &m_nSegmentOffset, 4); LF_Read(fin, &m_nRegionCount, 4); LF_Read(fin, &m_nRegionOffset, 4); LF_Read(fin, &m_nGeoBlockCount, 4); LF_Read(fin, &m_nGeoBlockOffset, 4); LF_Read(fin, &m_nGeoFaceCount, 4); LF_Read(fin, &m_nGeoFaceOffset, 4); LF_Read(fin, &m_nLightCount, 4); LF_Read(fin, &m_nLightOffset, 4); LF_Read(fin, &m_nGeoVertCount, 4); LF_Read(fin, &m_nGeoVertOffset, 4); LF_Read(fin, &m_nGeoTriCount, 4); LF_Read(fin, &m_nGeoTriOffset, 4); LF_Read(fin, &m_aabbMapBounds, 24); Err_Printf(" %u vertexes (%u bytes).", m_nVertexCount, m_nVertexCount*sizeof(LW_VERTEX)); Err_Printf(" %u materials.", m_nMaterialCount); Err_Printf(" %u lightmaps (%u bytes).", m_nLMCount, m_nLMTotalSize); Err_Printf(" %u segments.", m_nSegmentCount); Err_Printf(" %u regions.", m_nRegionCount); Err_Printf(" %u geo blocks.", m_nGeoBlockCount); Err_Printf(" %u geo faces.", m_nGeoFaceCount); Err_Printf(" %u geo vertexes.", m_nGeoVertCount); Err_Printf(" %u lights.", m_nLightCount); //Now to begin reading the file... //We need some memory... Err_Printf(" Allocating memory..."); if(!AllocateMemory()) { Err_Printf(" CLMap::Load ERROR: Cannot load \"%s\". Out of memory.", szFilename); LF_Close(fin); return LG_FALSE; } Err_Printf(" Reading world data..."); //Read the vertexes LF_Seek(fin, LF_SEEK_BEGIN, m_nVertexOffset); for(lg_dword i=0; i<m_nVertexCount; i++) { LF_Read(fin, &m_pVertexes[i], 28); } //Read the materials LF_Seek(fin, LF_SEEK_BEGIN, m_nMaterialOffset); for(lg_dword i=0; i<m_nMaterialCount; i++) { LF_Read(fin, &m_pMaterials[i], 256); } //Read the lightmaps and setup the data LF_Seek(fin, LF_SEEK_BEGIN, m_nLMOffset); LF_Read(fin, m_pLMData, m_nLMTotalSize); lg_byte* pTemp=m_pLMData; for(lg_dword i=0; i<m_nLMCount; i++) { //The first dword at the beginning of //a light map entry is the size of the lightmap //then the data is that size. //First get the size of the lm (so we can jump to the next lm). lg_dword nSize=0; memcpy(&nSize, pTemp, 4); m_pLMs[i]=pTemp; //jump to the next lightmap which is the size of the //current lightmap + 4 (the size position); pTemp+=nSize+4; } //Read the segments... LF_Seek(fin, LF_SEEK_BEGIN, m_nSegmentOffset); for(lg_dword i=0; i<m_nSegmentCount; i++) { LF_Read(fin, &m_pSegments[i], 16); } //Read the regions LF_Seek(fin, LF_SEEK_BEGIN, m_nRegionOffset); for(lg_dword i=0; i<m_nRegionCount; i++) { LF_Read(fin, &m_pRegions[i], LW_MAX_NAME+56); m_pRegions[i].pGeoBlocks=&m_pGeoBlocks[m_pRegions[i].nFirstGeoBlock]; m_pRegions[i].pRasterSegs=&m_pSegments[m_pRegions[i].nFirstRasterSeg]; m_pRegions[i].pLights=&m_pLights[m_pRegions[i].nFirstLight]; //Err_Printf("=== Region %u: %s ===", i, m_pRegions[i].szName); //Err_Printf("Light Count: %u. First Light: %u.", m_pRegions[i].nLightcount, m_pRegions[i].nFirstLight); } //Read the geo blocks LF_Seek(fin, LF_SEEK_BEGIN, m_nGeoBlockOffset); for(lg_dword i=0; i<m_nGeoBlockCount; i++) { LF_Read(fin, &m_pGeoBlocks[i], 24+24); m_pGeoBlocks[i].pFaces=&m_pGeoFaces[m_pGeoBlocks[i].nFirstFace]; m_pGeoBlocks[i].pVerts=&m_pGeoVerts[m_pGeoBlocks[i].nFirstVertex]; m_pGeoBlocks[i].pTris=&m_pGeoTris[m_pGeoBlocks[i].nFirstTri]; } //Read the geo faces... LF_Seek(fin, LF_SEEK_BEGIN, m_nGeoFaceOffset); for(lg_dword i=0; i<m_nGeoFaceCount; i++) { LF_Read(fin, &m_pGeoFaces[i], 16); } //Read the geo vertexes... LF_Seek(fin, LF_SEEK_BEGIN, m_nGeoVertOffset); for(lg_dword i=0; i<m_nGeoVertCount; i++) { LF_Read(fin, &m_pGeoVerts[i], 12); } //Read the lights... LF_Seek(fin, LF_SEEK_BEGIN, m_nLightOffset); for(lg_dword i=0; i<m_nLightCount; i++) { LF_Read(fin, &m_pLights[i], 28); /* Err_Printf("Light: (%f, %f, %f) Color: (%f, %f, %f)", m_pLights[i].v3Pos.x, m_pLights[i].v3Pos.y, m_pLights[i].v3Pos.z, m_pLights[i].Color.r, m_pLights[i].Color.g, m_pLights[i].Color.b); */ } LF_Seek(fin, LF_SEEK_BEGIN, m_nGeoTriOffset); for(lg_dword i=0; i<m_nGeoTriCount; i++) { LF_Read(fin, &m_pGeoTris[i], 12*3); } LF_Close(fin); strcpy(m_szMapPath, szFilename); m_bLoaded=LG_TRUE; Err_Printf(" Legacy World successfully loaded."); return LG_TRUE; } //Load is only temporary till the final map format //is established, but for now it will load a //3dws map. lg_bool CLMap::Load(lf_path szFilename) { Unload(); return LoadFromWS(szFilename); } #include "../ws_sys/ws_file.h" lg_bool CLMap::LoadFromWS(lf_path szFilename) { LF_FILE3 fin=LF_Open(szFilename, LF_ACCESS_MEMORY|LF_ACCESS_READ, LF_OPEN_EXISTING); if(!fin) { Err_Printf("CLWorld::Load ERROR: Could not open \"%s\".", szFilename); return LG_FALSE; } CWSFile wsFile; if(!wsFile.Load((lf_byte*)LF_GetMemPointer(fin), LF_GetSize(fin))) { LF_Close(fin); Err_Printf("CLWorld::Load ERROR could not convert 3DW file."); return LG_FALSE; } wsFile.ScaleMap(0.01f); wsFile.SaveAsLW("/dbase/maps/temp.lw"); LF_Close(fin); return LoadReal("/dbase/maps/temp.lw"); } lg_dword CLMap::CheckRegions(const ML_AABB* pAABB, lg_dword* pRegions, lg_dword nMaxRegions) { //CheckRegions checks to see which regions the entity is currently occupying. //it checks the catenated aabb against each regions aabb, so this method is meant //to be called after ProcessAI, but before world and entity collision testing. lg_dword nNumRegions=0; //If no map is set then we aren't occupying any rooms. if(!m_bLoaded) return 0; //TODO: First should check the regions that the object was previously //occupying, then check adjacent regions, in that way we don't have to //check every region every time. for(lg_dword i=0; (i<m_nRegionCount) && (nNumRegions<nMaxRegions); i++) { if(ML_AABBIntersect(pAABB, &m_pRegions[i].aabbAreaBounds, LG_NULL)) { pRegions[nNumRegions++]=i; } } return nNumRegions; } /*************************************** CLMapD3D - 3D Renderable Map Stuff ***************************************/ #if 0 class CLMapD3D { public: CLMapD3D(); ~CLMapD3D(); void Render(); void Validate(); void Invalidate(); void Init(CLMap* pMap); void UnInit(); }; #endif CLMapD3D::CLMapD3D(): m_pMap(LG_NULL), m_pDevice(LG_NULL), m_pTextures(LG_NULL), m_pLMTextures(LG_NULL), m_pVB(LG_NULL), m_pMem(LG_NULL), m_bIsValid(LG_NULL) { } CLMapD3D::~CLMapD3D() { UnInit(); } void CLMapD3D::Init(IDirect3DDevice9 *pDevice, CLMap *pMap) { UnInit(); m_pDevice=pDevice; if(m_pDevice) m_pDevice->AddRef(); m_pMap=pMap; //Calculate the total size of memory needed. lg_dword nOffset=0; lg_dword nTexOffset=nOffset; nOffset += m_pMap->m_nMaterialCount * sizeof(tm_tex); lg_dword nLMOffset=nOffset; nOffset += m_pMap->m_nLMCount * sizeof(tm_tex); lg_dword nSize=nOffset; m_pMem = new lg_byte[nSize]; m_pTextures = (tm_tex*)(m_pMem+nTexOffset); m_pLMTextures = (tm_tex*)(m_pMem+nLMOffset); //If there is no map we are done. if(!m_pMap || !m_pDevice || !m_pMap->IsLoaded()) return; //Load the materials and light maps. for(lg_dword i=0; i<m_pMap->m_nMaterialCount; i++) { //Technically the entire pathname should be saved //in the map file (/dbase/... or /gbase/...) but //as of now the map format is incomplete so we'll //make a substitution. lf_path szFullPath; sprintf(szFullPath, "/dbase/%s", m_pMap->m_pMaterials[i]); m_pTextures[i]=CLTMgr::TM_LoadTex(szFullPath, 0); //If we couldn't load the texture then the default //texture is returned, so we can still use the texture. } for(lg_dword i=0; i<m_pMap->m_nLMCount; i++) { lg_dword nSize; memcpy(&nSize, m_pMap->m_pLMs[i], 4); m_pLMTextures[i]=CLTMgr::TM_LoadTexMem(m_pMap->m_pLMs[i]+4, nSize, 0); } Validate(); } void CLMapD3D::UnInit() { Invalidate(); LG_SafeDeleteArray(m_pMem); LG_SafeRelease(m_pDevice); m_pMap=LG_NULL; } void CLMapD3D::Validate() { //If we're already valid we're done, note that when the client //updates the map '''the client''' needs to call invalidate //first. if(m_bIsValid) return; //Create the vertex buffer... lg_result nResult=m_pDevice->CreateVertexBuffer( sizeof(LW_VERTEX)*m_pMap->m_nVertexCount, 0, LW_VERTEX_TYPE, D3DPOOL_DEFAULT, &m_pVB, LG_NULL); if(LG_FAILED(nResult)) { Err_Printf("CLMapD3D ERROR: Could not create vertex buffer."); Err_PrintDX("IDirect3DDevice9::CreateVertexBuffer", nResult); m_pVB=LG_NULL; Invalidate(); return; } LW_VERTEX* pLockedVerts=LG_NULL; nResult=m_pVB->Lock(0, sizeof(LW_VERTEX)*m_pMap->m_nVertexCount, (void**)&pLockedVerts, 0); if(LG_FAILED(nResult)) { Err_Printf("CLWorldMap ERROR: Could not lock vertex buffer."); Err_PrintDX("IDirect3DVertexBuffer9::Lock", nResult); Invalidate(); return; } memcpy(pLockedVerts, m_pMap->m_pVertexes, sizeof(LW_VERTEX)*m_pMap->m_nVertexCount); m_pVB->Unlock(); m_bIsValid=LG_TRUE; } void CLMapD3D::Invalidate() { //If we are already invalid, or the map is //not set, then we won't do anything. if(!m_bIsValid || !m_pMap) return; LG_SafeRelease(m_pVB); m_bIsValid=LG_FALSE; } void CLMapD3D::RenderAABBs(lg_dword nFlags) { if(!m_bIsValid) return; /* static const lg_dword MAPDEBUG_HULLAABB=0x00000001; static const lg_dword MAPDEBUG_HULLTRI=0x00000002; static const lg_dword MAPDEBUG_WORLDAABB=0x00000004; */ if(LG_CheckFlag(nFlags, MAPDEBUG_HULLAABB)) { for(lg_dword i=0; i<m_pMap->m_nGeoBlockCount; i++) { LD_DrawAABB(m_pDevice, &m_pMap->m_pGeoBlocks[i].aabbBlock, 0xFFFF0000); } } if(LG_CheckFlag(nFlags, MAPDEBUG_WORLDAABB)) LD_DrawAABB(m_pDevice, &m_pMap->m_aabbMapBounds, 0xFF0000FF); if(LG_CheckFlag(nFlags, MAPDEBUG_HULLTRI)) { for(lg_dword i=0; i<m_pMap->m_nGeoBlockCount; i++) { LD_DrawTris( m_pDevice, (ml_vec3*)&m_pMap->m_pGeoBlocks[i].pTris[0], m_pMap->m_pGeoBlocks[i].nTriCount); } } } void CLMapD3D::Render() { if(!m_bIsValid) return; m_pDevice->SetFVF(LW_VERTEX_TYPE); m_pDevice->SetStreamSource(0, m_pVB, 0, sizeof(LW_VERTEX)); m_pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW); m_pDevice->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP); m_pDevice->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP); m_pDevice->SetRenderState(D3DRS_ZENABLE, TRUE); m_pDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE); m_pDevice->SetRenderState(D3DRS_LIGHTING, FALSE); //First pass (texture) m_pDevice->SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, 0); m_pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE); for(lg_dword nRegion=0; nRegion<m_pMap->m_nRegionCount; nRegion++) { for(lg_dword j=0; j<m_pMap->m_pRegions[nRegion].nRasterSegCount; j++) { lg_dword nFace=m_pMap->m_pRegions[nRegion].nFirstRasterSeg+j; //m_pDevice->SetTexture(0, m_pTextures[m_pMap->m_pSegments[nFace].nMaterialRef]); CLTMgr::TM_SetTexture(m_pTextures[m_pMap->m_pSegments[nFace].nMaterialRef], 0); m_pDevice->DrawPrimitive( D3DPT_TRIANGLELIST, m_pMap->m_pSegments[nFace].nFirst, m_pMap->m_pSegments[nFace].nTriCount); } } //Second pass (lightmap) m_pDevice->SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, 1); m_pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); m_pDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ZERO); m_pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_SRCCOLOR); m_pDevice->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP); m_pDevice->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP); for(lg_dword nRegion=0; nRegion<m_pMap->m_nRegionCount; nRegion++) { for(lg_dword j=0; j<m_pMap->m_pRegions[nRegion].nRasterSegCount; j++) { lg_dword nFace=m_pMap->m_pRegions[nRegion].nFirstRasterSeg+j; if(m_pMap->m_pSegments[nFace].nLMRef==0xFFFFFFFF) continue; //m_pDevice->SetTexture(0, m_pLMTextures[m_pMap->m_pSegments[nFace].nLMRef]); CLTMgr::TM_SetTexture(m_pLMTextures[m_pMap->m_pSegments[nFace].nLMRef], 0); m_pDevice->DrawPrimitive( D3DPT_TRIANGLELIST, m_pMap->m_pSegments[nFace].nFirst, m_pMap->m_pSegments[nFace].nTriCount); } } m_pDevice->SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, 0); } /*****************************************/ #if 0 CLWorldMap::CLWorldMap(): CLMap(), m_pVB(LG_NULL), m_pTextures(LG_NULL), m_pLMTextures(LG_NULL), m_bD3DValid(LG_FALSE), m_pDevice(LG_NULL) { } CLWorldMap::~CLWorldMap() { Unload(); } #if 0 void CLWorldMap::Render() { if(!m_bD3DValid) return; m_pDevice->SetFVF(LW_VERTEX_TYPE); m_pDevice->SetStreamSource(0, m_pVB, 0, sizeof(LW_VERTEX)); m_pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW); m_pDevice->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP); m_pDevice->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP); //First pass (texture) m_pDevice->SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, 0); m_pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE); for(lg_dword nRegion=0; nRegion<m_nRegionCount; nRegion++) { for(lg_dword j=0; j<m_pRegions[nRegion].nRasterSegCount; j++) { lg_dword nFace=m_pRegions[nRegion].nFirstRasterSeg+j; //m_pDevice->SetTexture(0, m_pTextures[m_pSegments[nFace].nMaterialRef]); CLTMgr::TM_SetTexture(m_pTextures[m_pSegments[nFace].nMaterialRef], 0); m_pDevice->DrawPrimitive( D3DPT_TRIANGLELIST, m_pSegments[nFace].nFirst, m_pSegments[nFace].nTriCount); } } //Second pass (lightmap) m_pDevice->SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, 1); m_pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); m_pDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ZERO); m_pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_SRCCOLOR); m_pDevice->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP); m_pDevice->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP); for(lg_dword nRegion=0; nRegion<m_nRegionCount; nRegion++) { for(lg_dword j=0; j<m_pRegions[nRegion].nRasterSegCount; j++) { lg_dword nFace=m_pRegions[nRegion].nFirstRasterSeg+j; if(m_pSegments[nFace].nLMRef==0xFFFFFFFF) continue; //m_pDevice->SetTexture(0, m_pLMTextures[m_pSegments[nFace].nLMRef]); CLTMgr::TM_SetTexture(m_pLMTextures[m_pSegments[nFace].nLMRef], 0); m_pDevice->DrawPrimitive( D3DPT_TRIANGLELIST, m_pSegments[nFace].nFirst, m_pSegments[nFace].nTriCount); } } m_pDevice->SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, 0); } #endif void CLWorldMap::Unload() { Invalidate(); L_safe_release(m_pDevice); CLMap::Unload(); } #if 0 lg_bool CLWorldMap::Validate() { if(m_bD3DValid) return LG_TRUE; if(!m_bLoaded) return LG_FALSE; //m_pTextures=new tm_tex[m_nMaterialCount]; //m_pLMTextures=new tm_tex[m_nLMCount]; //Load up the materials and lightmaps... for(lg_dword i=0; i<m_nMaterialCount; i++) { lf_path szFullMatName; sprintf(szFullMatName, "/dbase/%s", m_pMaterials[i]); m_pTextures[i]=CLTMgr::TM_LoadTex(szFullMatName, 0);//Tex_Load2(szFullMatName, LG_FALSE); } for(lg_dword i=0; i<m_nLMCount; i++) { lg_dword nSize; memcpy(&nSize, m_pLMs[i], 4); m_pLMTextures[i]=CLTMgr::TM_LoadTexMem(m_pLMs[i]+4, nSize, 0); } //Create the vertex buffer... lg_result nResult=m_pDevice->CreateVertexBuffer( sizeof(LW_VERTEX)*m_nVertexCount, 0, LW_VERTEX_TYPE, D3DPOOL_DEFAULT, &m_pVB, LG_NULL); if(LG_FAILED(nResult)) { Err_Printf("CLWorldMap ERROR: Could not create vertex buffer."); Err_PrintDX("IDirect3DDevice9::CreateVertexBuffer", nResult); m_pVB=LG_NULL; Invalidate(); return LG_FALSE; } LW_VERTEX* pLockedVerts=LG_NULL; nResult=m_pVB->Lock(0, sizeof(LW_VERTEX)*m_nVertexCount, (void**)&pLockedVerts, 0); if(LG_FAILED(nResult)) { Err_Printf("CLWorldMap ERROR: Could not lock vertex buffer."); Err_PrintDX("IDirect3DVertexBuffer9::Lock", nResult); Invalidate(); return LG_FALSE; } memcpy(pLockedVerts, m_pVertexes, sizeof(LW_VERTEX)*m_nVertexCount); m_pVB->Unlock(); m_bD3DValid=LG_TRUE; return LG_TRUE; } void CLWorldMap::Invalidate() { #if 0 for(lg_dword i=0; i<m_nMaterialCount; i++) { L_safe_release(m_pTextures[i]); } for(lg_dword i=0; i<m_nLMCount; i++) { m_pLMTextures[i]=0;//L_safe_release(m_pLMTextures[i]); } #endif L_safe_release(m_pVB); L_safe_delete_array(m_pTextures); L_safe_delete_array(m_pLMTextures); m_bD3DValid=LG_FALSE; } #endif lg_bool CLWorldMap::Load(lf_path szFilename, IDirect3DDevice9* pDevice) { Unload(); CLMap::Load(szFilename); Err_Printf(" Creating Direct3D resources..."); m_pDevice=pDevice; m_pDevice->AddRef(); if(Validate()) Err_Printf(" Legacy World successfully loaded."); else Err_Printf(" CLWorldMap::Load ERROR: Could not create Direct3D resources."); return LG_TRUE; } #include "../ws_sys/ws_file.h" lg_bool CLWorldMap::LoadFromWS(lf_path szFilename, IDirect3DDevice9* pDevice) { LF_FILE3 fin=LF_Open(szFilename, LF_ACCESS_MEMORY|LF_ACCESS_READ, LF_OPEN_EXISTING); if(!fin) { Err_Printf("CLWorld::Load ERROR: Could not open \"%s\".", szFilename); return LG_FALSE; } CWSFile wsFile; if(!wsFile.Load((lf_byte*)LF_GetMemPointer(fin), LF_GetSize(fin))) { LF_Close(fin); Err_Printf("CLWorld::Load ERROR could not convert 3DW file."); return LG_FALSE; } wsFile.ScaleMap(0.01f); wsFile.SaveAsLW("/dbase/maps/temp.lw"); LF_Close(fin); Err_Printf("HERE"); return Load("/dbase/maps/temp.lw", pDevice); } #endif<file_sep>/games/Legacy-Engine/Scrapped/tools/larchiver/larchiver.c #include <stdio.h> #include <string.h> #include <direct.h> #include <io.h> #include <windows.h> #include "la_sys.h" #pragma comment(lib, "larchive.lib") int main(int argc, char* argv[]) { char szDir[MAX_A_PATH]; char* szPath; unsigned long nCount=0; szPath=argv[1]; printf("Legacy Archiver v1.0 Copyright (c) 2006, <NAME>\n"); if(argc<3) { printf("Usage: larchiver <pathtree> <archivefile>\n"); return 0; } if(szPath[0]=='\\') szPath++; _snprintf(szDir, MAX_A_PATH-1, "%s\\%s", _getdcwd(_getdrive(), szDir, MAX_A_PATH-1), szPath); printf("Packaging everything in \"%s\"\n", szDir); _chdir(szDir); sprintf(szDir, "..\\%s", argv[2]); Arc_Archive(szDir, ".", NULL); return 0; }<file_sep>/Misc/GamepadToKey/GamepadToKeyTestReceiver/GamepadToKeyTestReceiver.cpp // GamepadToKey.cpp : Defines the entry point for the application. // #include <windows.h> #include <vector> #include <string> #include <stdio.h> static HINSTANCE g_Inst = nullptr; std::vector<std::wstring> g_InputHistory; // Forward declarations of functions included in this code module: LRESULT CALLBACK GamepadToKeyReceiver_WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK GamepadToKeyReceiver_About(HWND, UINT, WPARAM, LPARAM); int APIENTRY wWinMain( _In_ HINSTANCE hInstance , _In_opt_ HINSTANCE hPrevInstance ,_In_ LPWSTR lpCmdLine , _In_ int nCmdShow ) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); static const WCHAR szTitle[] = L"Test Receiver"; // The title bar text static const WCHAR szWindowClass[] = L"Test Receiver Class"; // the main window class name auto DoRegisterClass = [](HINSTANCE hInstance) -> ATOM { WNDCLASSEXW wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = GamepadToKeyReceiver_WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = nullptr; wcex.hCursor = LoadCursor(nullptr, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = nullptr; wcex.lpszClassName = szWindowClass; wcex.hIconSm = nullptr; return RegisterClassExW(&wcex); }; auto InitInstance =[](HINSTANCE hInstance, int nCmdShow) -> BOOL { g_Inst = hInstance; HWND hWnd = CreateWindowExW( WS_EX_TOPMOST , szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 400 , 600, nullptr, nullptr, hInstance, nullptr); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; }; // Initialize global strings DoRegisterClass( hInstance ); // Perform application initialization: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } MSG msg; // Main message loop: while (GetMessage(&msg, nullptr, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return (int) msg.wParam; } LRESULT CALLBACK GamepadToKeyReceiver_WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hWnd, &ps); RECT DisplayRect; GetClientRect( hWnd , &DisplayRect ); TEXTMETRICW TextMetrics; GetTextMetricsW( hdc , &TextMetrics ); INT Offset = 0; for( const std::wstring& Line : g_InputHistory ) { RECT DrawRect = DisplayRect; DrawRect.top += Offset; DrawTextW( hdc , Line.c_str() , -1 , &DrawRect , 0 ); Offset += TextMetrics.tmHeight; } EndPaint(hWnd, &ps); } break; case WM_DESTROY: PostQuitMessage(0); break; case WM_KEYDOWN: case WM_KEYUP: { struct gptkKeyLParam { int Repeat:16; int ScanCode:8; int IsExtended:1; int Reserved:4; int ContextCode:1; int PreviousState:1; int TransitionState:1; }; gptkKeyLParam Info; union gptkKeyLParamConverter { LPARAM lParam; gptkKeyLParam AsStruct; }; gptkKeyLParamConverter lParam2; lParam2.lParam = lParam; WCHAR KeyName[256]; GetKeyNameTextW( lParam , KeyName , sizeof(KeyName)/sizeof(KeyName[0]) ); WCHAR Desc[256]; _swprintf( Desc , L"%s (%u,0x%X,%u) %s" , KeyName , wParam , wParam , lParam2.AsStruct.ScanCode, (WM_KEYDOWN == message ? L"DOWN" : L"UP") ); std::wstring CmdText = Desc; g_InputHistory.push_back( CmdText ); if( g_InputHistory.size() > 30 ) { g_InputHistory.erase( g_InputHistory.begin() ); } InvalidateRect( hWnd , nullptr , true ); UpdateWindow( hWnd ); //RedrawWindow( hWnd , nullptr , nullptr , RDW_ERASE|RDW_UPDATENOW ); } break; default: return DefWindowProcW(hWnd, message, wParam, lParam); } return 0; } <file_sep>/games/Legacy-Engine/Scrapped/tools/Texview2/src/MainFrm.h // MainFrm.h : interface of the CMainFrame class // ///////////////////////////////////////////////////////////////////////////// #if !defined(AFX_MAINFRM_H__6A16EED8_305C_4188_92AC_72577D431120__INCLUDED_) #define AFX_MAINFRM_H__6A16EED8_305C_4188_92AC_72577D431120__INCLUDED_ #define NUM_TEX_SIZES (16) #define ID_TEXTURESIZE (ID_VIEW_SIZE) #define ID_TEXTURESIZEMAX (ID_TEXTURESIZE+NUM_TEX_SIZES) #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "ChildView.h" class CMainFrame : public CFrameWnd { public: CMainFrame(); protected: DECLARE_DYNAMIC(CMainFrame) // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CMainFrame) virtual BOOL PreCreateWindow(CREATESTRUCT& cs); virtual BOOL OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo); //}}AFX_VIRTUAL // Implementation public: void UpdateMenuTexSizes(int cx, int cy); BOOL LoadTexture(LPTSTR szFilename); virtual ~CMainFrame(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // control bar embedded members CStatusBar m_wndStatusBar; CChildView m_wndView; // Generated message map functions protected: //{{AFX_MSG(CMainFrame) afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnSetFocus(CWnd *pOldWnd); afx_msg void OnFileOpen(); //}}AFX_MSG afx_msg void OnViewSize(UINT nID); afx_msg void OnFilterType(UINT nID); DECLARE_MESSAGE_MAP() private: afx_msg void OnToolsRegisterfiletypes(); protected: int RegisterFileType(char* szExt, char* szDesc, char* szText, int nIcon); }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_MAINFRM_H__6A16EED8_305C_4188_92AC_72577D431120__INCLUDED_) <file_sep>/games/Legacy-Engine/Source/lf_sys2/lf_lpk.cpp #include <string.h> #include <stdlib.h> #include "lf_lpk.h" #include "stdio.h" //#include <windows.h> CLArchive::CLArchive(): m_bOpen(LF_FALSE), m_pFileList(LF_NULL), m_nType(0), m_nVersion(0), m_nCount(0), m_nInfoOffset(0), m_File(LF_NULL), m_TempFile(LF_NULL), m_nMainFileWritePos(0), m_bHasChanged(LF_FALSE), m_nCmpThreshold(20) { } CLArchive::~CLArchive() { Close(); } lf_dword CLArchive::GetNumFiles() { return m_nCount; } lf_bool CLArchive::IsOpen() { return m_bOpen; } const LPK_FILE_INFO* CLArchive::GetFileInfo(lf_dword n) { if(n>=m_nCount) return LF_NULL; return &m_pFileList[n]; } lf_bool CLArchive::GetFileInfo(lf_dword nRef, LPK_FILE_INFO* pInfo) { if(nRef>=m_nCount) return LF_FALSE; *pInfo=m_pFileList[nRef]; return LF_TRUE; } lf_bool CLArchive::CreateNewW(lf_cwstr szFilename) { Close(); m_File=BDIO_OpenW(szFilename, BDIO_CREATE_ALWAYS, BDIO_ACCESS_READ|BDIO_ACCESS_WRITE); if(!m_File) return LF_FALSE; m_bWriteable=LF_TRUE; m_TempFile=BDIO_OpenTempFileW(BDIO_CREATE_ALWAYS, BDIO_ACCESS_READ|BDIO_ACCESS_WRITE|BDIO_ACCESS_TEMP); if(!m_TempFile) { BDIO_Close(m_File); m_File=NULL; m_TempFile=NULL; return LF_FALSE; } m_nType=LPK_TYPE; m_nVersion=LPK_VERSION; m_nCount=0; m_nInfoOffset=0; m_pFileList=LF_NULL; m_bOpen=LF_TRUE; m_bHasChanged=LF_TRUE; return m_bOpen; } lf_bool CLArchive::CreateNewA(lf_cstr szFilename) { Close(); m_File=BDIO_OpenA(szFilename, BDIO_CREATE_ALWAYS, BDIO_ACCESS_READ|BDIO_ACCESS_WRITE); if(!m_File) return LF_FALSE; m_bWriteable=LF_TRUE; m_TempFile=BDIO_OpenTempFileA(BDIO_CREATE_ALWAYS, BDIO_ACCESS_READ|BDIO_ACCESS_WRITE|BDIO_ACCESS_TEMP); if(!m_TempFile) { BDIO_Close(m_File); m_File=NULL; m_TempFile=NULL; return LF_FALSE; } m_nType=LPK_TYPE; m_nVersion=LPK_VERSION; m_nCount=0; m_nInfoOffset=0; m_pFileList=LF_NULL; m_bOpen=LF_TRUE; m_bHasChanged=LF_TRUE; return m_bOpen; } lf_bool CLArchive::OpenW(lf_cwstr szFilename, lf_dword Flags) { Close(); lf_dword dwAccess=BDIO_ACCESS_READ; if(LF_CHECK_FLAG(Flags, LPK_OPEN_ENABLEWRITE)) { m_bWriteable=LF_TRUE; dwAccess|=BDIO_ACCESS_WRITE; } m_File=BDIO_OpenW(szFilename, BDIO_OPEN_ALWAYS, dwAccess); if(!m_File) { Close(); return LF_FALSE; } //If the archive is going to be writable then we open a temp file. //if a temp file can't be openened then the archive is set to read //only. if(m_bWriteable) { m_TempFile=BDIO_OpenTempFileW(BDIO_CREATE_ALWAYS, BDIO_ACCESS_READ|BDIO_ACCESS_WRITE|BDIO_ACCESS_TEMP); if(!m_TempFile) m_bWriteable=LF_FALSE; } else m_TempFile=LF_NULL; if(!ReadArcInfo()) { if(!OpenOld()) { Close(); return LF_FALSE; } } m_bHasChanged=LF_FALSE; m_bOpen=LF_TRUE; return LF_TRUE; } lf_bool CLArchive::OpenA(lf_cstr szFilename, lf_dword Flags) { Close(); lf_dword dwAccess=BDIO_ACCESS_READ; if(LF_CHECK_FLAG(Flags, LPK_OPEN_ENABLEWRITE)) { m_bWriteable=LF_TRUE; dwAccess|=BDIO_ACCESS_WRITE; } m_File=BDIO_OpenA(szFilename, BDIO_OPEN_ALWAYS, dwAccess); if(!m_File) { Close(); return LF_FALSE; } //If the archive is going to be writable then we open a temp file. //if a temp file can't be openened then the archive is set to read //only. if(m_bWriteable) { m_TempFile=BDIO_OpenTempFileA(BDIO_CREATE_ALWAYS, BDIO_ACCESS_READ|BDIO_ACCESS_WRITE|BDIO_ACCESS_TEMP); if(!m_TempFile) m_bWriteable=LF_FALSE; } else m_TempFile=LF_NULL; if(!ReadArcInfo()) { if(!OpenOld()) { Close(); return LF_FALSE; } } m_bHasChanged=LF_FALSE; m_bOpen=LF_TRUE; return LF_TRUE; } lf_bool CLArchive::OpenOld() { BDIO_Seek(m_File, 0, BDIO_SEEK_BEGIN); BDIO_Read(m_File, 4, &m_nType); BDIO_Read(m_File, 4, &m_nVersion); BDIO_Read(m_File, 4, &m_nCount); m_bWriteable=LF_FALSE; if(m_nType!=LPK_TYPE || m_nVersion!=101) { m_bOpen=LF_FALSE; return LF_FALSE; } m_pFileList=new LPK_FILE_INFO_EX[m_nCount]; for(lf_dword i=0; i<m_nCount; i++) { lf_char szFilename[260]; lf_dword nType=0; lf_dword nInfoOffset=0; BDIO_Read(m_File, 260, szFilename); BDIO_Read(m_File, 4, &nType); BDIO_Read(m_File, 4, &m_pFileList[i].nOffset); BDIO_Read(m_File, 4, &nInfoOffset); BDIO_Read(m_File, 4, &m_pFileList[i].nCmpSize); BDIO_Read(m_File, 4, &m_pFileList[i].nSize); if(nType==1) m_pFileList[i].nType=LPK_FILE_TYPE_ZLIBCMP; else m_pFileList[i].nType=LPK_FILE_TYPE_NORMAL; m_pFileList[i].nInternalPosition=LPK_FILE_POS_MAIN; mbstowcs(m_pFileList[i].szFilename, &szFilename[2], LF_MAX_PATH); for(lf_dword j=0; j<wcslen(m_pFileList[i].szFilename); j++) if(m_pFileList[i].szFilename[j]=='\\')m_pFileList[i].szFilename[j]='/'; } m_bOpen=LF_TRUE; return LF_TRUE; } lf_dword CLArchive::DoAddFile(BDIO_FILE fin, lf_cwstr szNameInArc, lf_dword Flags) { LPK_FILE_INFO_EX Entry; Entry.nSize=BDIO_GetSize(fin); Entry.nCmpSize=Entry.nSize; //Entry.nOffset=BDIO_Tell(m_File); Entry.nType=LF_CHECK_FLAG(Flags, LPK_ADD_ZLIBCMP)?LPK_FILE_TYPE_ZLIBCMP:LPK_FILE_TYPE_NORMAL; Entry.nInternalPosition=LPK_FILE_POS_MAIN; //Just in case a file with the same name already exists, go ahead //and add something onto the end of it (we'll add an X). wcsncpy(Entry.szFilename, szNameInArc, LF_MAX_PATH); while(GetFileRef(Entry.szFilename)!=0xFFFFFFFF) { wcscat(Entry.szFilename, L"X"); } lf_byte* pTemp=new lf_byte[Entry.nSize]; if(!pTemp) { return 0; } if(BDIO_Read(fin, Entry.nSize, pTemp)!=Entry.nSize) { delete[]pTemp; return 0; } //Write the file to the end of the main file. BDIO_Seek(m_File, m_nMainFileWritePos, BDIO_SEEK_BEGIN); Entry.nOffset=BDIO_Tell(m_File); if(Entry.nType==LPK_FILE_TYPE_ZLIBCMP) { Entry.nCmpSize=BDIO_WriteCompressed(m_File, Entry.nSize, pTemp); lf_dword nCmp=(lf_dword)(100.0f-(float)Entry.nCmpSize/(float)Entry.nSize*100.0f); //If the compression did not occur, or if the compression //percentage was too low, we'll just write the file data. //By default the compression threshold is 20. if( (Entry.nCmpSize==0) || (nCmp<m_nCmpThreshold) ) { BDIO_Seek(m_File, Entry.nOffset, BDIO_SEEK_BEGIN); Entry.nCmpSize=BDIO_Write(m_File, Entry.nSize, pTemp); Entry.nType=LPK_FILE_TYPE_NORMAL; } } else { Entry.nCmpSize=BDIO_Write(m_File, Entry.nSize, pTemp); } m_nMainFileWritePos=BDIO_Tell(m_File); delete[]pTemp; LPK_FILE_INFO_EX* pNew=new LPK_FILE_INFO_EX[m_nCount+1]; for(lf_dword i=0; i<m_nCount; i++) { pNew[i]=m_pFileList[i]; } pNew[m_nCount]=Entry; m_nCount++; if(m_pFileList){delete[]m_pFileList;} m_pFileList=pNew; m_bHasChanged=LF_TRUE; return Entry.nCmpSize; } lf_dword CLArchive::AddFileW(lf_cwstr szFilename, lf_cwstr szNameInArc, lf_dword Flags) { if(!m_bOpen || !m_bWriteable) return 0; BDIO_FILE fin=BDIO_OpenW(szFilename, BDIO_OPEN_EXISTING, BDIO_ACCESS_READ); if(!fin) return 0; lf_dword nSize=DoAddFile(fin, szNameInArc, Flags); BDIO_Close(fin); return nSize; } lf_dword CLArchive::AddFileA(lf_cstr szFilename, lf_cstr szNameInArc, lf_dword Flags) { if(!m_bOpen || !m_bWriteable) return 0; BDIO_FILE fin=BDIO_OpenA(szFilename, BDIO_OPEN_EXISTING, BDIO_ACCESS_READ); if(!fin) return 0; lf_pathW szWideName; mbstowcs(szWideName, szNameInArc, LF_MAX_PATH); lf_dword nSize=DoAddFile(fin, szWideName, Flags); BDIO_Close(fin); return nSize; } lf_bool CLArchive::ReadArcInfo() { //Read the header info. It should be the last 16 bytes of //the file. BDIO_Seek(m_File, -16, BDIO_SEEK_END); BDIO_Read(m_File, 4, &m_nType); BDIO_Read(m_File, 4, &m_nVersion); BDIO_Read(m_File, 4, &m_nCount); BDIO_Read(m_File, 4, &m_nInfoOffset); if((m_nType!=LPK_TYPE) || (m_nVersion!=LPK_VERSION)) return LF_FALSE; //Seek to the beginning of the file data. BDIO_Seek(m_File, m_nInfoOffset, BDIO_SEEK_BEGIN); if(BDIO_Tell(m_File)!=m_nInfoOffset) return LF_FALSE; //Save the info offset as the main file write position, //as this will be where new files are written to. m_nMainFileWritePos=m_nInfoOffset; //Allocate memory for file data. m_pFileList=new LPK_FILE_INFO_EX[m_nCount]; if(!m_pFileList) return LF_FALSE; //Now read the data. for(lf_dword i=0; i<m_nCount; i++) { BDIO_Read(m_File, 256, &m_pFileList[i].szFilename); BDIO_Read(m_File, 4, &m_pFileList[i].nType); BDIO_Read(m_File, 4, &m_pFileList[i].nOffset); BDIO_Read(m_File, 4, &m_pFileList[i].nSize); BDIO_Read(m_File, 4, &m_pFileList[i].nCmpSize); m_pFileList[i].nInternalPosition=LPK_FILE_POS_MAIN; } return LF_TRUE; } lf_bool CLArchive::Save() { if(!m_bWriteable || !m_bOpen || !m_bHasChanged) return LF_FALSE; BDIO_Seek(m_File, m_nMainFileWritePos, BDIO_SEEK_BEGIN); BDIO_Seek(m_TempFile, 0, BDIO_SEEK_BEGIN); for(lf_dword i=0; i<m_nCount; i++) { if(m_pFileList[i].nInternalPosition==LPK_FILE_POS_TEMP) { BDIO_Seek(m_TempFile, m_pFileList[i].nOffset, BDIO_SEEK_BEGIN); m_pFileList[i].nOffset=BDIO_Tell(m_File); BDIO_CopyData(m_File, m_TempFile, m_pFileList[i].nCmpSize); m_pFileList[i].nInternalPosition=LPK_FILE_POS_MAIN; } else { //We don't need to do anything. } } m_nInfoOffset=BDIO_Tell(m_File); //Write the file info data. for(lf_dword i=0; i<m_nCount; i++) { BDIO_Write(m_File, 256, &m_pFileList[i].szFilename); BDIO_Write(m_File, 4, &m_pFileList[i].nType); BDIO_Write(m_File, 4, &m_pFileList[i].nOffset); BDIO_Write(m_File, 4, &m_pFileList[i].nSize); BDIO_Write(m_File, 4, &m_pFileList[i].nCmpSize); } BDIO_Seek(m_File, 0, BDIO_SEEK_END); //Write the header... BDIO_Write(m_File, 4, &m_nType); BDIO_Write(m_File, 4, &m_nVersion); BDIO_Write(m_File, 4, &m_nCount); BDIO_Write(m_File, 4, &m_nInfoOffset); BDIO_Seek(m_TempFile, 0, BDIO_SEEK_BEGIN); m_bHasChanged=LF_FALSE; return LF_TRUE; } void CLArchive::Close() { //If the file was writeable then everything will be written from the temp file. if(m_bWriteable && m_bOpen) { Save(); } if(m_File) BDIO_Close(m_File); if(m_TempFile) BDIO_Close(m_TempFile); if(m_pFileList) delete[]m_pFileList; m_File=m_TempFile=m_pFileList=LF_NULL; m_bOpen=LF_FALSE; m_nType=0; m_nVersion=0; m_nCount=0; m_nInfoOffset=0; m_bHasChanged=LF_FALSE; } lf_dword CLArchive::GetFileRef(const lf_pathW szName) { for(lf_dword i=0; i<this->m_nCount; i++) { if(wcscmp(szName, m_pFileList[i].szFilename)==0) return i; } return 0xFFFFFFFF; } lf_byte* CLArchive::ExtractFile(lf_byte* pOut, lf_dword nRef) { if(nRef>=m_nCount) return LF_NULL; BDIO_FILE fin=LF_NULL; if(m_pFileList[nRef].nInternalPosition==LPK_FILE_POS_TEMP) fin=m_TempFile; else fin=m_File; BDIO_Seek(fin, m_pFileList[nRef].nOffset, BDIO_SEEK_BEGIN); lf_dword nRead=0; if(m_pFileList[nRef].nType==LPK_FILE_TYPE_ZLIBCMP) { nRead=BDIO_ReadCompressed(fin, m_pFileList[nRef].nSize, pOut); } else { nRead=BDIO_Read(fin, m_pFileList[nRef].nSize, pOut); } if(nRead!=m_pFileList[nRef].nSize) { //An error occured while reading. } return pOut; } <file_sep>/games/Legacy-Engine/Source/lf_sys2/lf_sys2.h #ifndef __LF_SYS2_H__ #define __LF_SYS2_H__ /* lf_sys2 - The Legacy File System version 2.0 */ /******************************** Definitions for the file system ********************************/ //#define ARC_VERSION 102 //#define ARC_TYPE 0x314B504C //(*(lf_dword*)"LPK1") #define MOUNT_MOUNT_SUBDIRS 0x00000002 #define MOUNT_FILE_OVERWRITE 0x00000004 #define MOUNT_FILE_OVERWRITELPKONLY 0x00000008 /********************************* Definitions for file access *********************************/ typedef enum _LF_SEEK_TYPE{ LF_SEEK_BEGIN=0, LF_SEEK_CURRENT=1, LF_SEEK_END=2 }LF_SEEK_TYPE; typedef enum _LF_CREATE_MODE{ LF_CREATE_ALWAYS=1, LF_CREATE_NEW=2, LF_OPEN_ALWAYS=3, LF_OPEN_EXISTING=4 }LF_CREATE_MODE; #define LF_ACCESS_READ 0x00000002 //Open file for reading. #define LF_ACCESS_WRITE 0x00000004 //Open file for writing. #define LF_ACCESS_MEMORY 0x00000008 //Open file and access it from memory, file must be read only. /******************************** Disable some of VCs warnings *********************************/ #pragma warning(disable: 4267) #pragma warning(disable: 4996) #define LF_SYS2_EXPORTS #ifdef __cplusplus extern "C"{ #endif __cplusplus /* File System Types */ typedef signed int lf_int, *lf_pint; typedef unsigned int lf_uint, *lf_puint; typedef char lf_char, *lf_pchar; typedef unsigned char lf_byte, *lf_pbyte; typedef signed char lf_sbyte, *lf_psbyte; typedef signed char lf_schar, *lf_pschar; typedef char *lf_str, *lf_pstr, *lf_lpstr; typedef const char *lf_cstr, *lf_pcstr, *lf_lpcstr; typedef unsigned short lf_word, *lf_pword, lf_ushort, *lf_pushort; typedef signed short lf_short, *lf_pshort; typedef unsigned long lf_dword, *lf_pdword, lf_ulong, *lf_pulong; typedef signed long lf_long, *lf_plong; typedef float lf_float, *lf_pfloat; typedef double lf_double, *lf_pdouble; typedef long double lf_ldouble, *lf_lpdouble; typedef void lf_void, *lf_pvoid; typedef const void lf_cvoid, *lf_pcvoid; typedef unsigned int lf_size_t; #ifdef __cplusplus typedef wchar_t wchar_t_d; #else typedef unsigned short wchar_t_d; #endif typedef wchar_t_d lf_wchar, lf_wchar_t; typedef lf_wchar_t *lf_wstr, *lf_pwstr, *lf_lpwstr; typedef const lf_wchar_t *lf_cwstr, *lf_pcwstr, *lf_lpcwstr; typedef struct _lf_large_integer{ lf_dword dwLowPart; lf_long dwHighPart; }lf_large_integer, *lf_plarge_integer, *lf_lplarge_integer; typedef int lf_bool; #define LF_TRUE (1) #define LF_FALSE (0) #ifdef __cplusplus #define LF_NULL (0) #else __cplusplus #define LF_NULL ((void*)0) #endif __cplusplus #define LF_CHECK_FLAG(flag, var) ((flag&var)) #define LF_MAX_PATH 255 typedef lf_char lf_pathA[LF_MAX_PATH+1]; typedef lf_wchar lf_pathW[LF_MAX_PATH+1]; #ifdef UNICODE #define lf_path lf_pathW #else !UNICODE #define lf_path lf_pathA #endif UNICODE #define LF_max(v1, v2) ((v1)>(v2))?(v1):(v2) #define LF_min(v1, v2) ((v1)<(v2))?(v1):(v2) #define LF_clamp(v1, min, max) ( (v1)>(max)?(max):(v1)<(min)?(min):(v1) ) #define LF_SAFE_DELETE_ARRAY(p) if(p){delete [] p; p=LF_NULL;} #define LF_SAFE_DELETE(p) if(p){delete p; p=LF_NULL;} #define LF_SAFE_FREE(p) if(p){LF_Free(p);p=LF_NULL;} //Path name parsing functions... lf_str LF_SYS2_EXPORTS LF_GetFileNameFromPathA(lf_str szFileName, lf_cstr szFullPath); lf_wstr LF_SYS2_EXPORTS LF_GetFileNameFromPathW(lf_wstr szFileName, lf_cwstr szFullPath); lf_str LF_SYS2_EXPORTS LF_GetShortNameFromPathA(lf_str szName, lf_cstr szFullPath); lf_wstr LF_SYS2_EXPORTS LF_GetShortNameFromPathW(lf_wstr szName, lf_cwstr szFullPath); lf_str LF_SYS2_EXPORTS LF_GetDirFromPathA(lf_str szDir, lf_cstr szFullPath); lf_wstr LF_SYS2_EXPORTS LF_GetDirFromPathW(lf_wstr szDir, lf_cwstr szFullPath); /* Memory Functions */ typedef lf_void* ( * LF_ALLOC_FUNC)(lf_size_t size); typedef lf_void ( * LF_FREE_FUNC)(lf_void* p); lf_void* LF_Malloc(lf_size_t size); lf_void LF_Free(lf_void* p); lf_void LF_SetMemFuncs(LF_ALLOC_FUNC pAlloc, LF_FREE_FUNC pFree); #ifdef UNICODE #define LF_GetFileNameFromPath LF_GetFileNameFromPathW #define LF_GetShortNameFromPath LF_GetShortNameFromPathW #define LF_GetDirFromPath LF_GetDirFromPathW #else UNICODE #define LF_GetFileNameFromPath LF_GetFileNameFromPathA #define LF_GetShortNameFromPath LF_GetShortNameFromPathA #define LF_GetDirFromPath LF_GetDirFromPathA #endif UNICODE /************************* Error Handling Stuff *************************/ typedef enum _LF_ERR_LEVEL{ ERR_LEVEL_UNKNOWN=0, //Messages are always printed. ERR_LEVEL_SUPERDETAIL=1, ERR_LEVEL_DETAIL, ERR_LEVEL_NOTICE, ERR_LEVEL_WARNING, ERR_LEVEL_ERROR, ERR_LEVEL_ALWAYS //Message is is printed. }LF_ERR_LEVEL; void LF_SYS2_EXPORTS LF_SetErrLevel(LF_ERR_LEVEL nLevel); void LF_SYS2_EXPORTS LF_ErrPrintW(lf_cwstr szFormat, LF_ERR_LEVEL nErrLevel, ...); void LF_SYS2_EXPORTS LF_ErrPrintA(lf_cstr szFormat, LF_ERR_LEVEL nErrLevel, ...); void LF_SYS2_EXPORTS __cdecl LF_DefaultErrPrint(lf_cwstr szFormat); void LF_SYS2_EXPORTS LF_SetErrPrintFn(void (__cdecl*pfn)(lf_cwstr szFormat)); typedef void (__cdecl * LF_ERR_CALLBACK)(lf_cwstr); #ifdef UNICODE #define LF_ErrPrint LF_ErrPrintW #else !UNICODE #define LF_ErrPrint LF_ErrPrintA #endif UNICODE /************************** File System Functions Mounting, etc. **************************/ lf_bool LF_SYS2_EXPORTS FS_Initialize(lf_dword nMaxFiles, LF_ALLOC_FUNC pAlloc, LF_FREE_FUNC pFree); lf_dword LF_SYS2_EXPORTS FS_MountBaseA(lf_cstr szOSPath); lf_dword LF_SYS2_EXPORTS FS_MountBaseW(lf_cwstr szOSPath); lf_dword LF_SYS2_EXPORTS FS_MountA(lf_cstr szOSPath, lf_cstr szMountPath, lf_dword Flags); lf_dword LF_SYS2_EXPORTS FS_MountW(lf_cwstr szOSPath, lf_cwstr szMountPath, lf_dword Flags); lf_dword LF_SYS2_EXPORTS FS_MountLPKA(lf_cstr szMountedFile, lf_dword Flags); lf_dword LF_SYS2_EXPORTS FS_MountLPKW(lf_cwstr szMountedFile, lf_dword Flags); lf_bool LF_SYS2_EXPORTS FS_UnMountAll(); lf_bool LF_SYS2_EXPORTS FS_Shutdown(); void LF_SYS2_EXPORTS FS_PrintMountInfo(); #ifdef UNICODE #define FS_MountBase FS_MountBaseW #define FS_Mount FS_MountW #define FS_MountLPK FS_MountLPKW #else !UNICODE #define FS_MountBase FS_MountBaseA #define FS_Mount FS_MountA #define FS_MountLPK FS_MountLPKA #endif UNICODE /******************************************** File Access Functions Opening, Closing, Reading, Writing, etc. ********************************************/ typedef lf_pvoid LF_FILE3; LF_FILE3 LF_SYS2_EXPORTS LF_OpenA(lf_cstr szFilename, lf_dword Access, lf_dword CreateMode); LF_FILE3 LF_SYS2_EXPORTS LF_OpenW(lf_cwstr szFilename, lf_dword Access, lf_dword CreateMode); lf_bool LF_SYS2_EXPORTS LF_Close(LF_FILE3 File); lf_dword LF_SYS2_EXPORTS LF_Read(LF_FILE3 File, lf_void* pOutBuffer, lf_dword nSize); lf_dword LF_SYS2_EXPORTS LF_Write(LF_FILE3 File, lf_void* pInBuffer, lf_dword nSize); lf_dword LF_SYS2_EXPORTS LF_Tell(LF_FILE3 File); lf_dword LF_SYS2_EXPORTS LF_Seek(LF_FILE3 File, LF_SEEK_TYPE nMode, lf_long nOffset); lf_dword LF_SYS2_EXPORTS LF_GetSize(LF_FILE3 File); lf_pcvoid LF_SYS2_EXPORTS LF_GetMemPointer(LF_FILE3 File); lf_bool LF_SYS2_EXPORTS LF_IsEOF(LF_FILE3 File); #ifdef UNICODE #define LF_Open LF_OpenW #else !UNICODE #define LF_Open LF_OpenA #endif UNICODE #ifdef __cplusplus } //extern "C" #endif __cplusplus #endif __LF_SYS2_H__ <file_sep>/samples/D3DDemo/code/GFX3D9/D3DFont.c /* D3DFont.c - Functionality for font objects. Copyright (c) 2003 <NAME> */ #include <d3dx9.h> #include "GFX3D9.h" #include "resource.h" typedef struct tagD3DFONT{ HD3DIMAGE FontImage; WORD wCharsPerLine; WORD wNumLines; float fCharWidth; float fCharHeight; WORD wFontHeight; WORD wFontWidth; BOOL bUseD3DFont; LPD3DXFONT lpD3DXFont; HFONT hD3DFont; DWORD dwD3DColor; LPDIRECT3DDEVICE9 lpDevice; }D3DFONT, *LPD3DFONT; HD3DFONT CopyD3DFont( LPDIRECT3DDEVICE9 lpDevice, HD3DFONT lpFontSrc) { HD3DFONT tempDest=NULL; if(!lpFontSrc) return NULL; if(!((LPD3DFONT)lpFontSrc)->bUseD3DFont){ tempDest=CreateD3DFontFromD3DImage(lpDevice, ((LPD3DFONT)lpFontSrc)->FontImage, ((LPD3DFONT)lpFontSrc)->wCharsPerLine, ((LPD3DFONT)lpFontSrc)->wNumLines); ((LPD3DFONT)tempDest)->wFontHeight=((LPD3DFONT)lpFontSrc)->wFontHeight; ((LPD3DFONT)tempDest)->wFontWidth=((LPD3DFONT)lpFontSrc)->wFontWidth; return tempDest; }else{ return CreateD3DFontFromFont(lpDevice, ((LPD3DFONT)lpFontSrc)->hD3DFont, ((LPD3DFONT)lpFontSrc)->dwD3DColor); } return (HD3DFONT)tempDest; } HD3DFONT GetD3DFontDefault( LPDIRECT3DDEVICE9 lpDevice) { HANDLE hFontRes=NULL; HRSRC hRsrc=NULL; LPBYTE lpData=NULL; HD3DFONT hD3DFont=NULL; LPDIRECT3DTEXTURE9 lpFontTex=NULL; HINSTANCE hInst=NULL; hInst=GetModuleHandleA("GFX3D9.DLL"); hRsrc=FindResourceA(hInst, MAKEINTRESOURCE(IDB_DEFFONT), RT_BITMAP); if(hRsrc==NULL) return NULL; hFontRes=LoadResource(hInst, hRsrc); if(hFontRes==NULL) return NULL; lpData=LockResource(hFontRes); if(lpData==NULL){ DeleteObject(hFontRes); return NULL; } if(FAILED(D3DXCreateTextureFromFileInMemoryEx( lpDevice, lpData, SizeofResource(hInst, hRsrc), 0, 0, 0, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_FILTER_POINT, D3DX_FILTER_POINT, 0xFFFF00FF, NULL, NULL, &lpFontTex))) { DeleteObject(hFontRes); return FALSE; } DeleteObject(hFontRes); hD3DFont=CreateD3DFontFromTexture( lpDevice, lpFontTex, 8, 16); SetD3DFontSize(hD3DFont, 16, 16); lpFontTex->lpVtbl->Release(lpFontTex); return hD3DFont; } HD3DFONT CreateD3DFontFromFont( LPDIRECT3DDEVICE9 lpDevice, HFONT hFont, DWORD dwColor) { LPD3DFONT lpFont=NULL; LOGFONT TempData; if(!hFont) return NULL; lpFont=malloc(sizeof(D3DFONT)); if(lpFont==NULL) return NULL; ZeroMemory(&TempData, sizeof(LOGFONT)); lpFont->FontImage=NULL; lpFont->wCharsPerLine=0; lpFont->wNumLines=0; lpFont->fCharHeight=0.0f; lpFont->fCharWidth=0.0f; lpFont->bUseD3DFont=TRUE; lpFont->dwD3DColor=dwColor; lpFont->hD3DFont=hFont; lpFont->lpD3DXFont=NULL; GetObject(hFont, sizeof(LOGFONT), &TempData); lpFont->wFontHeight=(WORD)TempData.lfHeight; lpFont->wFontWidth=(WORD)TempData.lfWidth; lpFont->lpDevice=lpDevice; lpFont->lpDevice->lpVtbl->AddRef(lpFont->lpDevice); /* Create the font. */ if(!ValidateD3DFont((HD3DFONT)lpFont)){ SAFE_FREE(lpFont); lpFont->lpDevice->lpVtbl->Release(lpFont->lpDevice); return NULL; } return (HD3DFONT)lpFont; } HD3DFONT CreateD3DFontFromD3DImage( LPDIRECT3DDEVICE9 lpDevice, HD3DIMAGE hImage, WORD wCharsPerLine, WORD wNumLines) { LPD3DFONT lpFont=NULL; lpFont=malloc(sizeof(D3DFONT)); if(lpFont==NULL) return NULL; lpFont->FontImage=CopyD3DImage(hImage); lpFont->wCharsPerLine=wCharsPerLine; lpFont->wNumLines=wNumLines; lpFont->fCharWidth=(float)GetD3DImageWidth(lpFont->FontImage)/(float)wCharsPerLine; lpFont->fCharHeight=(float)GetD3DImageHeight(lpFont->FontImage)/(float)wNumLines; lpFont->wFontWidth=16; lpFont->wFontHeight=32; lpFont->bUseD3DFont=FALSE; lpFont->hD3DFont=NULL; lpFont->lpD3DXFont=NULL; lpFont->dwD3DColor=0; lpFont->lpDevice=lpDevice; lpFont->lpDevice->lpVtbl->AddRef(lpFont->lpDevice); return (HD3DFONT)lpFont; } HD3DFONT CreateD3DFontFromImageA( LPDIRECT3DDEVICE9 lpDevice, char szFilename[MAX_PATH], WORD wCharsPerLine, WORD wNumLines) { LPD3DFONT lpFont=NULL; lpFont=malloc(sizeof(D3DFONT)); if(lpFont==NULL) return NULL; /* Attempt to load the font's image. */ lpFont->FontImage=CreateD3DImageFromFileA( lpDevice, szFilename, -1, -1, 0xFFFF00FF); if(lpFont->FontImage==NULL) { SAFE_FREE(lpFont); return NULL; } lpFont->wCharsPerLine=wCharsPerLine; lpFont->wNumLines=wNumLines; lpFont->fCharWidth=(float)GetD3DImageWidth(lpFont->FontImage)/(float)wCharsPerLine; lpFont->fCharHeight=(float)GetD3DImageHeight(lpFont->FontImage)/(float)wNumLines; lpFont->wFontWidth=16; lpFont->wFontHeight=32; lpFont->bUseD3DFont=FALSE; lpFont->hD3DFont=NULL; lpFont->lpD3DXFont=NULL; lpFont->dwD3DColor=0; lpFont->lpDevice=lpDevice; lpFont->lpDevice->lpVtbl->AddRef(lpFont->lpDevice); return (HD3DFONT)lpFont; } HD3DFONT CreateD3DFontFromImageW( LPDIRECT3DDEVICE9 lpDevice, WCHAR szFilename[MAX_PATH], WORD wCharsPerLine, WORD wNumLines) { LPD3DFONT lpFont=NULL; lpFont=malloc(sizeof(D3DFONT)); if(lpFont==NULL) return NULL; /* Attempt to load the font's image. */ lpFont->FontImage=CreateD3DImageFromFileW( lpDevice, szFilename, -1, -1, 0xFFFF00FF); if(lpFont->FontImage==NULL) { SAFE_FREE(lpFont); return NULL; } lpFont->wCharsPerLine=wCharsPerLine; lpFont->wNumLines=wNumLines; lpFont->fCharWidth=(float)GetD3DImageWidth(lpFont->FontImage)/(float)wCharsPerLine; lpFont->fCharHeight=(float)GetD3DImageHeight(lpFont->FontImage)/(float)wNumLines; lpFont->wFontWidth=16; lpFont->wFontHeight=32; lpFont->bUseD3DFont=FALSE; lpFont->hD3DFont=NULL; lpFont->lpD3DXFont=NULL; lpFont->dwD3DColor=0; lpFont->lpDevice=lpDevice; lpFont->lpDevice->lpVtbl->AddRef(lpFont->lpDevice); return (HD3DFONT)lpFont; } HD3DFONT CreateD3DFontFromTexture( LPDIRECT3DDEVICE9 lpDevice, LPDIRECT3DTEXTURE9 lpTexture, WORD wCharsPerLine, WORD wNumLines) { LPD3DFONT lpFont=NULL; lpFont=malloc(sizeof(D3DFONT)); if(lpFont==NULL) return NULL; /* Attempt to load the font's image. */ lpFont->FontImage=CreateD3DImageFromTexture( lpDevice, -1, -1, lpTexture); if(lpFont->FontImage==NULL) { SAFE_FREE(lpFont); return NULL; } lpFont->wCharsPerLine=wCharsPerLine; lpFont->wNumLines=wNumLines; lpFont->fCharWidth=(float)GetD3DImageWidth(lpFont->FontImage)/(float)wCharsPerLine; lpFont->fCharHeight=(float)GetD3DImageHeight(lpFont->FontImage)/(float)wNumLines; lpFont->wFontWidth=16; lpFont->wFontHeight=32; lpFont->bUseD3DFont=FALSE; lpFont->hD3DFont=NULL; lpFont->lpD3DXFont=NULL; lpFont->dwD3DColor=0; lpFont->lpDevice=lpDevice; lpFont->lpDevice->lpVtbl->AddRef(lpFont->lpDevice); return (HD3DFONT)lpFont; } BOOL InvalidateD3DFont( HD3DFONT lpFont) { if(!lpFont) return FALSE; if(!((LPD3DFONT)lpFont)->bUseD3DFont) return InvalidateD3DImage(((LPD3DFONT)lpFont)->FontImage); else{ /* Release D3DXFont. */ SAFE_RELEASE((((LPD3DFONT)lpFont)->lpD3DXFont)); return TRUE; } } BOOL ValidateD3DFont( HD3DFONT hFont) { LPD3DFONT lpFont=hFont; if(!lpFont) return FALSE; /* If we're not using a D3DXFONT we validate the image. Otherwize we create the font. */ if(!((LPD3DFONT)lpFont)->bUseD3DFont) return ValidateD3DImage(((LPD3DFONT)lpFont)->FontImage); else{ /* Create D3D font here. */ if(((LPD3DFONT)lpFont)->lpD3DXFont) return TRUE; if(FAILED(D3DXCreateFont( ((LPD3DFONT)lpFont)->lpDevice, lpFont->fCharHeight, lpFont->fCharWidth, 1, 1, FALSE, "Courier New", 0, 0, 0, "Courier New", //((LPD3DFONT)lpFont)->hD3DFont, &((LPD3DFONT)lpFont)->lpD3DXFont))) return FALSE; return TRUE; } } BOOL DeleteD3DFont( HD3DFONT lpFont) { if(!lpFont) return FALSE; if(!((LPD3DFONT)lpFont)->bUseD3DFont){ DeleteD3DImage(((LPD3DFONT)lpFont)->FontImage); }else{ /* Release D3DX Font. */ SAFE_RELEASE((((LPD3DFONT)lpFont)->lpD3DXFont)); } SAFE_RELEASE( (((LPD3DFONT)lpFont)->lpDevice) ); SAFE_FREE(lpFont); return TRUE; } BOOL GetD3DFontDims(HD3DFONT lpFont, WORD * lpWidth, WORD * lpHeight) { if(!lpFont) return FALSE; if(lpWidth) *lpWidth=((LPD3DFONT)lpFont)->wFontWidth; if(lpHeight) *lpHeight=((LPD3DFONT)lpFont)->wFontHeight; return TRUE; } BOOL RenderD3DFontChar( HD3DFONT lpFont, LONG nXDest, LONG nYDest, char cChar) { WORD nColumn=0, nRow=0; RECT rcDest; DWORD dwSavedMin=0, dwSavedMag=0, dwSavedMip=0; BOOL bResult=TRUE; if(!lpFont) return FALSE; if(!((LPD3DFONT)lpFont)->bUseD3DFont){ if(cChar<0x0020 || cChar>0x007E){ /* Change to space for nonexistant characters. */ cChar=0; }else{ cChar-=32; } if(cChar==0){ nRow=0; nColumn=0; }else{ nRow=cChar/((LPD3DFONT)lpFont)->wCharsPerLine; nColumn=cChar%((LPD3DFONT)lpFont)->wCharsPerLine; } /* Set the texture filter to point filtering. */ ((LPD3DFONT)lpFont)->lpDevice->lpVtbl->GetSamplerState(((LPD3DFONT)lpFont)->lpDevice, 0, D3DSAMP_MAGFILTER, &dwSavedMag); ((LPD3DFONT)lpFont)->lpDevice->lpVtbl->GetSamplerState(((LPD3DFONT)lpFont)->lpDevice, 0, D3DSAMP_MINFILTER, &dwSavedMin); ((LPD3DFONT)lpFont)->lpDevice->lpVtbl->GetSamplerState(((LPD3DFONT)lpFont)->lpDevice, 0, D3DSAMP_MIPFILTER, &dwSavedMip); ((LPD3DFONT)lpFont)->lpDevice->lpVtbl->SetSamplerState(((LPD3DFONT)lpFont)->lpDevice, 0, D3DSAMP_MAGFILTER, D3DTEXF_POINT); ((LPD3DFONT)lpFont)->lpDevice->lpVtbl->SetSamplerState(((LPD3DFONT)lpFont)->lpDevice, 0, D3DSAMP_MINFILTER, D3DTEXF_POINT); ((LPD3DFONT)lpFont)->lpDevice->lpVtbl->SetSamplerState(((LPD3DFONT)lpFont)->lpDevice, 0, D3DSAMP_MIPFILTER, D3DTEXF_NONE); bResult=RenderD3DImageEx( ((LPD3DFONT)lpFont)->FontImage, nXDest, nYDest, ((LPD3DFONT)lpFont)->wFontWidth, ((LPD3DFONT)lpFont)->wFontHeight, (LONG)(nColumn*((LPD3DFONT)lpFont)->fCharWidth), (LONG)(nRow*((LPD3DFONT)lpFont)->fCharHeight), (LONG)((LPD3DFONT)lpFont)->fCharWidth, (LONG)((LPD3DFONT)lpFont)->fCharHeight); /* Restore old filter format. */ ((LPD3DFONT)lpFont)->lpDevice->lpVtbl->SetSamplerState(((LPD3DFONT)lpFont)->lpDevice, 0, D3DSAMP_MAGFILTER, dwSavedMag); ((LPD3DFONT)lpFont)->lpDevice->lpVtbl->SetSamplerState(((LPD3DFONT)lpFont)->lpDevice, 0, D3DSAMP_MINFILTER, dwSavedMin); ((LPD3DFONT)lpFont)->lpDevice->lpVtbl->SetSamplerState(((LPD3DFONT)lpFont)->lpDevice, 0, D3DSAMP_MIPFILTER, dwSavedMip); return bResult; }else{ /* Render D3DX Font string. */ if(((LPD3DFONT)lpFont)->lpD3DXFont==NULL) return FALSE; nXDest++; nYDest++; // ((LPD3DFONT)lpFont)->lpD3DXFont->lpVtbl->Begin(((LPD3DFONT)lpFont)->lpD3DXFont); SetRect(&rcDest, nXDest, nYDest, 0, 0); ((LPD3DFONT)lpFont)->lpD3DXFont->lpVtbl->DrawTextA(((LPD3DFONT)lpFont)->lpD3DXFont, NULL, (char *)&cChar, 1, &rcDest, 0, ((LPD3DFONT)lpFont)->dwD3DColor); // ((LPD3DFONT)lpFont)->lpD3DXFont->lpVtbl->End(((LPD3DFONT)lpFont)->lpD3DXFont); return TRUE; } } BOOL SetD3DFontSize( HD3DFONT lpFont, WORD wWidth, WORD wHeight) { if(!lpFont) return FALSE; ((LPD3DFONT)lpFont)->wFontHeight=wHeight; ((LPD3DFONT)lpFont)->wFontWidth=wWidth; return TRUE; } BOOL RenderD3DFontString( HD3DFONT lpFont, LONG nXDest, LONG nYDest, char szString[]) { DWORD i=0, dwXOffset=0; LONG y=nYDest; RECT rcDest; if(!lpFont) return FALSE; if(((LPD3DFONT)lpFont)->bUseD3DFont){ SetRect(&rcDest, nXDest, nYDest, 0, 0); nXDest++; nYDest++; // ((LPD3DFONT)lpFont)->lpD3DXFont->lpVtbl->Begin(((LPD3DFONT)lpFont)->lpD3DXFont); ((LPD3DFONT)lpFont)->lpD3DXFont->lpVtbl->DrawTextA(((LPD3DFONT)lpFont)->lpD3DXFont, NULL, szString, -1, &rcDest, DT_NOPREFIX, 0xFFFFFF00); // ((LPD3DFONT)lpFont)->lpD3DXFont->lpVtbl->End(((LPD3DFONT)lpFont)->lpD3DXFont); }else{ while(szString[i]!=0){ if(szString[i]=='\n'){ dwXOffset=0; y+=((LPD3DFONT)lpFont)->wFontHeight; i++; continue; } RenderD3DFontChar( lpFont, nXDest+dwXOffset*((LPD3DFONT)lpFont)->wFontWidth, y, szString[i]); i++; dwXOffset++; } } return TRUE; }<file_sep>/games/Explor2002/Source_Old/ExplorED DOS/dosexplored/OPENMAP.H /* OpenMap.h: Process for opening a Map. This version was designed for ExplorED. The program will return the name of the chosen map. */ #include <stdio.h> #include <dos.h> #include <string.h> #include <stdlib.h> #define UP 0 + 'H' #define DOWN 0 + 'P' #define MAXFLIST 255 //How many file names can be displayed #define MAXTODISP 23 int GenList(char templist[MAXFLIST][13]); int LoadMap(char templist[13]); int printList(char listtoprint[MAXFLIST][13], int startposition, int maximum); <file_sep>/games/Legacy-Engine/Scrapped/libs/tga_lib/tga_lib.c #include <stdio.h> #include <string.h> #include <malloc.h> #include "tga_lib.h" #include <math.h> #define TGA_IMAGE_ORIGIN(p) (((p)&0x30) >> 4) #define TGA_ALPHABITS(p) ((p)&0x0F) typedef struct tagTGAHEADER { unsigned char nIDSize; unsigned char nColorMapType; unsigned char nImageType; /* Color Map Info. */ unsigned short nFirstCMIndex; unsigned short nNumCMEntries; unsigned char nCMEntrySize; /* Image Specifications. */ unsigned short nXOrigin; unsigned short nYOrigin; unsigned short nWidth; unsigned short nHeight; unsigned char nBitsPerPixel; unsigned char nImageDesc; }TGAHEADER, *LPTGAHEADER; typedef struct tagTGAFOOTER { unsigned long nExtensionOffset; unsigned long nDeveloperOffset; char szSignature[18]; }TGAFOOTER, *LPTGAFOOTER; typedef struct tagTGAIMAGE { TGAHEADER Header; char szImageID[255]; void* ColorMap; void* ImageData; TGAFOOTER Footer; TGAFMT DataFmt; TGAFMT ColorMapFmt; }TGAIMAGE, *LPTGAIMAGE; /************************* *** Private Functions. *** *************************/ int TGA_ReadHeader(void* stream, TGA_CALLBACKS* lpCB, LPTGAHEADER lpHeader) { lpCB->seek(stream, 0, SEEK_SET); /* Read the Header info. */ lpCB->read(&lpHeader->nIDSize, 1, 1, stream); lpCB->read(&lpHeader->nColorMapType, 1, 1, stream); lpCB->read(&lpHeader->nImageType, 1, 1, stream); /* Read the Color map info. */ lpCB->read(&lpHeader->nFirstCMIndex, 2, 1, stream); lpCB->read(&lpHeader->nNumCMEntries, 2, 1, stream); lpCB->read(&lpHeader->nCMEntrySize, 1, 1, stream); /* Read the image specifications. */ lpCB->read(&lpHeader->nXOrigin, 2, 1, stream); lpCB->read(&lpHeader->nYOrigin, 2, 1, stream); lpCB->read(&lpHeader->nWidth, 2, 1, stream); lpCB->read(&lpHeader->nHeight, 2, 1, stream); lpCB->read(&lpHeader->nBitsPerPixel, 1, 1, stream); lpCB->read(&lpHeader->nImageDesc, 1, 1, stream); return 1; } int TGA_ReadFooter(void* stream, TGA_CALLBACKS* lpCB, LPTGAFOOTER lpFooter) { lpCB->seek(stream, -26, SEEK_END); lpCB->read(&lpFooter->nExtensionOffset, 4, 1, stream); lpCB->read(&lpFooter->nDeveloperOffset, 4, 1, stream); lpCB->read(&lpFooter->szSignature, 1, 18, stream); if(_strnicmp("TRUEVISION-XFILE.", lpFooter->szSignature, 17)==0) { return 1; } else { lpFooter->szSignature[0]=0; return 0; } return 0; } /* The idea behind TGAReadRLEData is that it reads RLE data out of the file decompressing it as it goes along. */ TGA_ReadRLEData(void* stream, TGA_CALLBACKS* lpCB, LPTGAIMAGE lpImage) { unsigned char nBPP=0; int bCompressed=0; unsigned char nLen=0; unsigned char nCompress=0; unsigned long nDecodePos=0; unsigned long j=0; void * lpData=NULL; nBPP=lpImage->Header.nBitsPerPixel/8; /* Allocate some memory for the input data. */ lpData=malloc(nBPP); nDecodePos=0; for(nDecodePos=0; nDecodePos<(unsigned long)(nBPP*lpImage->Header.nWidth*lpImage->Header.nHeight); ) { /* Read the encodeing byte. */ lpCB->read(&nCompress, 1, 1, stream); /* The compression mode is the last bit. */ bCompressed=(nCompress&0x80)>>7; /* The length of the data is the first 7 bits plus 1. */ nLen=(nCompress&0x7F)+1; if(bCompressed) { /* If compressed we decompress the data. */ /* Read the compressed data. */ lpCB->read(lpData, 1, nBPP, stream); for(j=0; j<nLen; j++) { /* Copy the data into the appropriate length of image. */ memcpy((void*)((unsigned int)lpImage->ImageData+nDecodePos), lpData, nBPP); nDecodePos+=nBPP; } } else { /* Otherwize we simply read the data. */ for(j=0; j<nLen; j++) { lpCB->read(lpData, 1, nBPP, stream); memcpy((void*)((unsigned int)lpImage->ImageData+nDecodePos), lpData, nBPP); nDecodePos+=nBPP; } } } /* Make the image type represent that which it now is. */ switch(lpImage->Header.nImageType) { case 9: lpImage->Header.nImageType=1; break; case 10: lpImage->Header.nImageType=2; break; case 11: lpImage->Header.nImageType=3; break; } /* Free the memory from the input. */ free(lpData); return 1; } /************************ *** Public Functions. *** ************************/ HTGAIMAGE TGA_OpenCallbacks(void* stream, TGA_CALLBACKS* lpCB) { LPTGAIMAGE lpImage=NULL; int bValid=0; int bFooter=0; if(!stream || !lpCB) return NULL; lpImage=malloc(sizeof(TGAIMAGE)); if(!lpImage) return NULL; lpImage->ColorMap=NULL; lpImage->ImageData=NULL; lpImage->szImageID[0]=0; TGA_ReadHeader(stream, lpCB, &lpImage->Header); bFooter=bValid=TGA_ReadFooter(stream, lpCB, &lpImage->Footer); //#define DEBUG_MSG #ifdef DEBUG_MSG { char szTemp[1000]; sprintf( szTemp, "ID Len: %i\nCM Type: %i\nImage Type: %i\nFirst CM Indes: %i\nNum CM Entires: %i\nCM Entry Size: %i\n(%i, %i)\n%ix%ix%i\n%i", lpImage->Header.nIDSize, lpImage->Header.nColorMapType, lpImage->Header.nImageType, lpImage->Header.nFirstCMIndex, lpImage->Header.nNumCMEntries, lpImage->Header.nCMEntrySize, lpImage->Header.nXOrigin, lpImage->Header.nYOrigin, lpImage->Header.nWidth, lpImage->Header.nHeight, lpImage->Header.nBitsPerPixel, lpImage->Header.nImageDesc); MessageBox(0, szTemp, 0, 0); if(bFooter) { sprintf( szTemp, "Extension Offset: %i\nDev Offset: %i\nSignature: %s\n", lpImage->Footer.nExtensionOffset, lpImage->Footer.nDeveloperOffset, lpImage->Footer.szSignature); MessageBox(0, szTemp, 0, 0); } } #endif // DEBUG_MSG // Make sure we have a valid file. if(!bValid) { if(lpImage->Header.nColorMapType==1) { if( (lpImage->Header.nImageType==1) || (lpImage->Header.nImageType==9)) bValid=1; else bValid=0; } else if(lpImage->Header.nColorMapType==0) { if( (lpImage->Header.nImageType==0) || (lpImage->Header.nImageType==2) || (lpImage->Header.nImageType==3) || (lpImage->Header.nImageType==10) || (lpImage->Header.nImageType==11)) bValid=1; else bValid=0; } else { bValid=0; } } //If the bits per pixel is not evenly divided by //8 we can't read the file. In theory 15 bit tga //images exist, but I haven't found one, and they //aren't supported by this library. if(lpImage->Header.nBitsPerPixel%8) bValid=0; if(!bValid) { lpCB->close(stream); free(lpImage); return NULL; } // We assume a valid file now and read the id. lpCB->seek(stream, 18, SEEK_SET); lpCB->read( &lpImage->szImageID, 1, lpImage->Header.nIDSize, stream); // Now read the color map data if it exists. if(lpImage->Header.nColorMapType) { lpImage->ColorMap=malloc(lpImage->Header.nNumCMEntries * (lpImage->Header.nCMEntrySize/8)); if(lpImage->ColorMap==(void*)0) { lpCB->close(stream); free(lpImage); return NULL; } lpCB->read( lpImage->ColorMap, 1, (lpImage->Header.nCMEntrySize/8)*lpImage->Header.nNumCMEntries, stream); } // Read the image data. lpImage->ImageData=malloc(lpImage->Header.nHeight*lpImage->Header.nWidth*lpImage->Header.nBitsPerPixel/8); if(!lpImage->ImageData) { if(lpImage->ColorMap)free(lpImage->ColorMap); lpCB->close(stream); if(lpImage)free(lpImage); return NULL; } // Read the data. If the data is compressed we need to decode. if((lpImage->Header.nImageType >= 9) && (lpImage->Header.nImageType <=11)) { TGA_ReadRLEData(stream, lpCB, lpImage); } else { lpCB->read( lpImage->ImageData, 1, (lpImage->Header.nBitsPerPixel/8)*(lpImage->Header.nHeight*lpImage->Header.nWidth), stream); } lpCB->close(stream); switch(lpImage->Header.nBitsPerPixel) { case 8: { lpImage->DataFmt=TGAFMT_PALETTE; switch(lpImage->Header.nCMEntrySize) { case 16: lpImage->ColorMapFmt=TGAFMT_X1R5G5B5; break; case 24: lpImage->ColorMapFmt=TGAFMT_R8G8B8; break; case 32: lpImage->ColorMapFmt=TGAFMT_A8R8G8B8; break; default: lpImage->ColorMapFmt=TGAFMT_UNKNOWN; } break; } case 16: lpImage->DataFmt=TGAFMT_X1R5G5B5; lpImage->ColorMapFmt=TGAFMT_NONE; break; case 24: lpImage->DataFmt=TGAFMT_R8G8B8; lpImage->ColorMapFmt=TGAFMT_NONE; break; case 32: lpImage->DataFmt=TGAFMT_A8R8G8B8; lpImage->ColorMapFmt=TGAFMT_NONE; break; default: lpImage->DataFmt=TGAFMT_UNKNOWN; lpImage->ColorMapFmt=TGAFMT_UNKNOWN; break; } return (HTGAIMAGE)lpImage; } HTGAIMAGE TGA_Open(char* szFilename) { TGA_CALLBACKS cb; FILE* fin=NULL; cb.close=fclose; cb.read=fread; cb.seek=fseek; cb.tell=ftell; fin=fopen(szFilename, "rb"); if(!fin) return NULL; return TGA_OpenCallbacks(fin, &cb); } int TGA_Delete(HTGAIMAGE hImage) { if(!hImage) return 0; /* Delete the color map data. */ if( ((LPTGAIMAGE)hImage)->ColorMap ) free( ((LPTGAIMAGE)hImage)->ColorMap); /* Delete the image data. */ if( ((LPTGAIMAGE)hImage)->ImageData ) free( ((LPTGAIMAGE)hImage)->ImageData); /* Free the structure. */ free(hImage); return 1; } int TGA_GetPalette( HTGAIMAGE hImage, void* lpDataOut) { if( (!lpDataOut) || (!((LPTGAIMAGE)hImage)->ColorMap) ) return 0; memcpy( lpDataOut, ((LPTGAIMAGE)hImage)->ColorMap, (((LPTGAIMAGE)hImage)->Header.nCMEntrySize/8)*((LPTGAIMAGE)hImage)->Header.nNumCMEntries); return 1; } #define TGA_scale_float(value, scale) (long)(((float)value)*(scale)) #define TGA_scale_int(value, scale) (long)((((long)value)*(scale)) int TGA_ChangeBitDepth( unsigned long* color, TGAFMT prevdepth, TGAFMT newdepth, unsigned char extra) { unsigned long r=0, g=0, b=0, a=0; unsigned long newcolor=0x00000000l; if(!color) return 0; if(prevdepth==newdepth) return 1; if(newdepth==TGAFMT_PALETTE) return 0; switch(prevdepth) { case TGAFMT_X1R5G5B5: /* Using floating point, for the conversion proccess, is more accurate, but slower. */ a=((*color)&0x8000)>>15; r=((*color)&0x7C00)>>10; g=((*color)&0x03E0)>>5; b=((*color)&0x001F)>>0; //a*=255; a=extra; r=TGA_scale_float(r, 255.0f/31.0f); g=TGA_scale_float(g, 255.0f/31.0f); b=TGA_scale_float(b, 255.0f/31.0f); break; case TGAFMT_R5G6B5: a = extra; r = ((*color)&0xF800)>>10; g = ((*color)&0x07E0)>>5; b = ((*color)&0x001F)>>0; a = extra; r=TGA_scale_float(r, 255.0f/31.0f); g=TGA_scale_float(g, 255.0f/63.0f); b=TGA_scale_float(b, 255.0f/31.0f); case TGAFMT_A8R8G8B8: //Not 100% sure this is getting the right value. a=(char)(((*color)&0xFF000000)>>24); extra=(char)a; case TGAFMT_R8G8B8: a=extra; r=((*color)&0x00FF0000)>>16; g=((*color)&0x0000FF00)>>8; b=((*color)&0x000000FF)>>0; break; case TGAFMT_PALETTE: return 0; break; } switch(newdepth) { case TGAFMT_X1R5G5B5: r=TGA_scale_float(r, 31.0f/255.0f); g=TGA_scale_float(g, 31.0f/255.0f); b=TGA_scale_float(b, 31.0f/255.0f); *color=0; *color=((a>0?1:0)<<15)|(r<<10)|(g<<5)|(b<<0); break; case TGAFMT_R5G6B5: r=TGA_scale_float(r, 31.0f/255.0f); g=TGA_scale_float(g, 63.0f/255.0f); b=TGA_scale_float(b, 31.0f/255.0f); *color=0; *color=(r<<11)|(g<<5)|(b<<0); break; case TGAFMT_R8G8B8: case TGAFMT_A8R8G8B8: *color=(a<<24)|(r<<16)|(g<<8)|(b<<0); break; } return 1; } int TGA_GetPixel( HTGAIMAGE hImage, unsigned long* lpPix, signed short x, signed short y, TGAFMT Format, unsigned char nExtra) { TGAIMAGE* lpImage=hImage; TGAORIENT nSrcOrient=lpImage?TGA_IMAGE_ORIGIN(lpImage->Header.nImageDesc):0; TGAFMT nSrcFormat=0; unsigned short iHeight=0, iWidth=0; unsigned long nSource=0; unsigned long nSourceColor=0, nSourceCMEntry=0; if(!lpImage) return 0; iHeight=lpImage->Header.nHeight; iWidth=lpImage->Header.nWidth; if(x>=iWidth) x=iWidth-1; if(y>=iHeight) y=iHeight-1; if(x<0) x=0; if(y<0) y=0; switch(nSrcOrient) { case TGAORIENT_BOTTOMLEFT: nSource=iWidth*(iHeight-y-1) + x; break; case TGAORIENT_BOTTOMRIGHT: nSource=iWidth*(iHeight-1-y) + (iWidth-x-1); break; case TGAORIENT_TOPLEFT: nSource=iWidth*y + x; break; case TGAORIENT_TOPRIGHT: nSource=iWidth*y + (iWidth-x-1); break; default: return 0; } nSource*=lpImage->Header.nBitsPerPixel/8; memcpy(&nSourceColor, (void*)((unsigned int)lpImage->ImageData+nSource), lpImage->Header.nBitsPerPixel/8); if(lpImage->DataFmt==TGAFMT_PALETTE) { nSourceCMEntry=nSourceColor; nSourceColor=0; memcpy(&nSourceColor, (void*)((unsigned int)lpImage->ColorMap+nSourceCMEntry*(lpImage->Header.nCMEntrySize/8)), (lpImage->Header.nCMEntrySize/8)); nSrcFormat=lpImage->ColorMapFmt; } else nSrcFormat=lpImage->DataFmt; TGA_ChangeBitDepth(&nSourceColor, nSrcFormat, Format, nExtra); if(lpPix) *lpPix=nSourceColor; return 1; } int TGA_GetPixelFilter( HTGAIMAGE hImage, unsigned short nSampleLevel, unsigned long* lpPix, unsigned short x, unsigned short y, TGAFMT Format, unsigned char nExtra) { unsigned long* lpPixels; unsigned short over=0, under=0; unsigned long i=0; unsigned long nCTR=0, nCTG=0, nCTB=0, nCTA=0; unsigned long nNumPix=0; nNumPix=(unsigned long)pow((double)2, (double)(nSampleLevel+1)); lpPixels=malloc(nNumPix*sizeof(unsigned long)); if(nNumPix<=1 || !lpPixels || nSampleLevel==0) { if(lpPixels) free(lpPixels); return TGA_GetPixel( hImage, lpPix, x, y, Format, nExtra); } for(under=0, i=0; under<(nNumPix/2); under++) { for(over=0; over<(nNumPix/2); over++, i++) { if(i>=nNumPix) break; lpPixels[i]=0; TGA_GetPixel(hImage, &lpPixels[i], (short)(x+over/*-nNumPix/4*/), (short)(y+under/*-nNumPix/4*/), TGAFMT_A8R8G8B8, nExtra); } } for(i=0; i<(nNumPix); i++) { nCTA+=(0xFF000000&lpPixels[i])>>24; nCTR+=(0x00FF0000&lpPixels[i])>>16; nCTG+=(0x0000FF00&lpPixels[i])>>8; nCTB+=(0x000000FF&lpPixels[i])>>0; } free(lpPixels); nCTA/=(nNumPix); nCTR/=(nNumPix); nCTG/=(nNumPix); nCTB/=(nNumPix); nCTA<<=24; nCTR<<=16; nCTG<<=8; nCTB<<=0; if(lpPix) { *lpPix=(nCTA|nCTR|nCTG|nCTB); TGA_ChangeBitDepth(lpPix, TGAFMT_A8R8G8B8, Format, nExtra); } return 1; } int TGA_CopyBits( HTGAIMAGE hImage, void* lpOut, TGAORIENT nOrient, TGAFMT destFormat, unsigned short nWidth, unsigned short nHeight, unsigned short nPitch, unsigned char nExtra) { return TGA_CopyBitsStretch( hImage, TGAFILTER_NONE, lpOut, nOrient, destFormat, nWidth, nHeight, nPitch, nExtra); } int TGA_CopyBitsStretch( HTGAIMAGE hImage, TGAFILTER Filter, void* lpOut, TGAORIENT nOrient, TGAFMT Format, unsigned short nWidth, unsigned short nHeight, unsigned short nPitch, unsigned char nExtra) { TGAIMAGE* lpImage=hImage; unsigned short x=0, y=0; unsigned char nDestBitDepth=0; unsigned long nPix=0, nCMEntry=0; unsigned long nDest=0; float fWidthRatio=0.0f, fHeightRatio=0.0f; float fSrcX=0.0f, fSrcY=0.0f; unsigned short nMipLevel=0; if(!lpImage) return 0; switch(Format) { case TGAFMT_PALETTE: nDestBitDepth=8; break; case TGAFMT_X1R5G5B5: case TGAFMT_R5G6B5: nDestBitDepth=16; break; case TGAFMT_R8G8B8: nDestBitDepth=24; break; case TGAFMT_A8R8G8B8: nDestBitDepth=32; break; } if(nPitch==0) nPitch=nWidth*nDestBitDepth; fWidthRatio=(float)(lpImage->Header.nWidth-1)/(float)(nWidth-1); fHeightRatio=(float)(lpImage->Header.nHeight-1)/(float)(nHeight-1); if(Filter==TGAFILTER_LINEAR) { short nAveRatio=(short)(fWidthRatio+fHeightRatio)/2; nMipLevel=0; while((nAveRatio/=2)>0) nMipLevel++; } else { nMipLevel=0; } for(y=0; y<nHeight; y++) { for(x=0; x<nWidth; x++) { switch(nOrient) { case TGAORIENT_BOTTOMLEFT: nDest=nPitch*(nHeight-(y+1))+x*(nDestBitDepth/8); break; case TGAORIENT_BOTTOMRIGHT: nDest=nPitch*(nHeight-1-y) + (nWidth-x-1)*(nDestBitDepth/8); break; case TGAORIENT_TOPLEFT: nDest=y*nPitch + x*(nDestBitDepth/8); //nDest=nWidth*y + x; break; case TGAORIENT_TOPRIGHT: nDest=nPitch*y + (nWidth-x-1)*(nDestBitDepth/8); //nDest=nWidth*y + (nWidth-x-1); break; default: return 0; } //nDest*=nBitDepth/8; nPix=0x00000000l; /* We now need to calculate where we actually want to get the pixel from. */ fSrcX=x*fWidthRatio; fSrcY=y*fHeightRatio; TGA_GetPixelFilter(hImage, nMipLevel, &nPix, (short)fSrcX, (short)fSrcY, Format, nExtra); memcpy((void*)((unsigned int)lpOut+nDest), &nPix, nDestBitDepth/8); } } return 1; } int TGA_GetDesc( HTGAIMAGE hImage, TGA_DESC* lpDescript) { LPTGAIMAGE lpImage=hImage; if(!lpImage || !lpDescript) return 0; lpDescript->Width=lpImage->Header.nWidth; lpDescript->Height=lpImage->Header.nHeight; lpDescript->BitsPerPixel=lpImage->Header.nBitsPerPixel; lpDescript->NumCMEntries=lpImage->Header.nNumCMEntries; lpDescript->ColorMapBitDepth=lpImage->Header.nCMEntrySize; return 1; } <file_sep>/games/Legacy-Engine/Source/engine/ld_sys.cpp //ld_sys.cpp - Debugging functions - note that all graphics drawing functions //here are bo no means optimized. #include <d3d9.h> #include "ML_lib.h" #include "common.h" typedef struct COLOR_VERTEX{ float x, y, z; lg_dword color; }COLOR_VERTEX; typedef struct COLOR_VERTEX2{ ml_vec3 pos; lg_dword color; }COLOR_VERTEX2; #define COLOR_VERTEX_FVF (D3DFVF_XYZ|D3DFVF_DIFFUSE) void LD_DrawTris(IDirect3DDevice9* pDevice, ml_vec3* pPoints, lg_dword nTriCount) { pDevice->SetFVF(COLOR_VERTEX_FVF); //pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); COLOR_VERTEX2 tri[3]; for(lg_dword i=0; i<nTriCount; i++) { const lg_dword CLR_COUNT=4; lg_dword clr; if((i%CLR_COUNT)==0) { clr=0xFFFF0000; } else if((i%CLR_COUNT)==1) { clr=0xFF00FF00; } else if((i%CLR_COUNT)==2) { clr=0xFF0000FF; } else if((i%CLR_COUNT)==3) { clr=0xFF00FFFF; } lg_dword clr1=0xFF00FF00, clr2=0xFFFF0000, clr3=0xFF0000FF; tri[0].pos=pPoints[i*3]; tri[0].color=clr; tri[1].pos=pPoints[i*3+1]; tri[1].color=clr; tri[2].pos=pPoints[i*3+2]; tri[2].color=clr; pDevice->DrawPrimitiveUP( D3DPT_TRIANGLELIST, 1, tri, sizeof(COLOR_VERTEX2)); } /* pDevice->DrawPrimitiveUP( D3DPT_TRIANGLELIST, nTriCount, pPoints, sizeof(ML_VEC3)); */ } void LD_DrawVec(IDirect3DDevice9* pDevice, ML_VEC3* pOrigin, ML_VEC3* pVec) { COLOR_VERTEX vVec[2]; vVec[0].x=pOrigin->x; vVec[0].y=pOrigin->y; vVec[0].z=pOrigin->z; vVec[0].color=0xFFFFFFFF; vVec[1].x=pOrigin->x+pVec->x; vVec[1].y=pOrigin->y+pVec->y; vVec[1].z=pOrigin->z+pVec->z; vVec[1].color=0xFFFFFFFF; //Render the Line. ML_MAT matIdent; ML_MatIdentity(&matIdent); DWORD dwAlpha; pDevice->GetRenderState(D3DRS_ALPHABLENDENABLE, &dwAlpha); if(dwAlpha) pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE); pDevice->SetTexture(0, NULL); pDevice->SetTransform(D3DTS_WORLD, (D3DMATRIX*)&matIdent); pDevice->SetFVF(COLOR_VERTEX_FVF); pDevice->DrawPrimitiveUP(D3DPT_LINESTRIP, 1, &vVec, sizeof(COLOR_VERTEX)); if(dwAlpha) pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, dwAlpha); } void LD_DrawAABB(IDirect3DDevice9* pDevice, ML_AABB* pBox, D3DCOLOR Color) { COLOR_VERTEX vAABB[16]; for(lg_dword i=0; i<16; i++) { vAABB[i].color=Color; } vAABB[0].x=pBox->v3Min.x; vAABB[0].y=pBox->v3Min.y; vAABB[0].z=pBox->v3Min.z; vAABB[1].x=pBox->v3Min.x; vAABB[1].y=pBox->v3Max.y; vAABB[1].z=pBox->v3Min.z; vAABB[2].x=pBox->v3Min.x; vAABB[2].y=pBox->v3Max.y; vAABB[2].z=pBox->v3Max.z; vAABB[3].x=pBox->v3Max.x; vAABB[3].y=pBox->v3Max.y; vAABB[3].z=pBox->v3Max.z; vAABB[4].x=pBox->v3Max.x; vAABB[4].y=pBox->v3Max.y; vAABB[4].z=pBox->v3Min.z; vAABB[5].x=pBox->v3Max.x; vAABB[5].y=pBox->v3Min.y; vAABB[5].z=pBox->v3Min.z; vAABB[6].x=pBox->v3Max.x; vAABB[6].y=pBox->v3Min.y; vAABB[6].z=pBox->v3Max.z; vAABB[7].x=pBox->v3Min.x; vAABB[7].y=pBox->v3Min.y; vAABB[7].z=pBox->v3Max.z; vAABB[8].x=pBox->v3Min.x; vAABB[8].y=pBox->v3Min.y; vAABB[8].z=pBox->v3Min.z; vAABB[9].x=pBox->v3Max.x; vAABB[9].y=pBox->v3Min.y; vAABB[9].z=pBox->v3Min.z; vAABB[10].x=pBox->v3Max.x; vAABB[10].y=pBox->v3Min.y; vAABB[10].z=pBox->v3Max.z; vAABB[11].x=pBox->v3Max.x; vAABB[11].y=pBox->v3Max.y; vAABB[11].z=pBox->v3Max.z; vAABB[12].x=pBox->v3Max.x; vAABB[12].y=pBox->v3Max.y; vAABB[12].z=pBox->v3Min.z; vAABB[13].x=pBox->v3Min.x; vAABB[13].y=pBox->v3Max.y; vAABB[13].z=pBox->v3Min.z; vAABB[14].x=pBox->v3Min.x; vAABB[14].y=pBox->v3Max.y; vAABB[14].z=pBox->v3Max.z; vAABB[15].x=pBox->v3Min.x; vAABB[15].y=pBox->v3Min.y; vAABB[15].z=pBox->v3Max.z; //Render the AABB. ML_MAT matIdent; ML_MatIdentity(&matIdent); DWORD dwAlpha; pDevice->GetRenderState(D3DRS_ALPHABLENDENABLE, &dwAlpha); if(dwAlpha) pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE); pDevice->SetTexture(0, NULL); pDevice->SetTransform(D3DTS_WORLD, (D3DMATRIX*)&matIdent); pDevice->SetFVF(COLOR_VERTEX_FVF); pDevice->DrawPrimitiveUP(D3DPT_LINESTRIP, 15, &vAABB, sizeof(COLOR_VERTEX)); if(dwAlpha) pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, dwAlpha); } <file_sep>/games/Legacy-Engine/Scrapped/plugins/lw3DWS/lw3DWS.cpp // lw3DWS.cpp : Defines the initialization routines for the DLL. // #include "stdafx.h" #include "lw3DWS.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // //TODO: If this DLL is dynamically linked against the MFC DLLs, // any functions exported from this DLL which call into // MFC must have the AFX_MANAGE_STATE macro added at the // very beginning of the function. // // For example: // // extern "C" BOOL PASCAL EXPORT ExportedFunction() // { // AFX_MANAGE_STATE(AfxGetStaticModuleState()); // // normal function body here // } // // It is very important that this macro appear in each // function, prior to any calls into MFC. This means that // it must appear as the first statement within the // function, even before any object variable declarations // as their constructors may generate calls into the MFC // DLL. // // Please see MFC Technical Notes 33 and 58 for additional // details. // // Clw3DWSApp BEGIN_MESSAGE_MAP(Clw3DWSApp, CWinApp) END_MESSAGE_MAP() // Clw3DWSApp construction Clw3DWSApp::Clw3DWSApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } // The one and only Clw3DWSApp object Clw3DWSApp theApp; // Clw3DWSApp initialization BOOL Clw3DWSApp::InitInstance() { CWinApp::InitInstance(); return TRUE; } void WS_FUNC PluginClass(wsByte* pIn, wsDword nInSize, wsByte* pOut, wsDword nOutSize) { wsDword nType=PLUGIN_EXPORT; memcpy(pOut, &nType, 4); } void WS_FUNC PluginDescription(wsByte* pIn, wsDword nInSize, wsByte* pOut, wsDword nOutSize) { wsChar szTemp[]="Export Legacy World (*.lw)"" ("__DATE__" "__TIME__")"; memcpy(pOut, szTemp, sizeof(szTemp)); } void WS_FUNC PluginFileExtension(wsByte* pIn, wsDword nInSize, wsByte* pOut, wsDword nOutSize) { wsChar szTemp[]="lw"; memcpy(pOut, szTemp, sizeof(szTemp)); } void WS_FUNC PluginLabel(wsByte* pIn, wsDword nInSize, wsByte* pOut, wsDword nOutSize) { wsChar szTemp[]="Legacy World (*.lw)"; memcpy(pOut, szTemp, sizeof(szTemp)); } void WS_FUNC PluginExport(wsByte* pIn, wsDword nInSize, wsByte* pOut, wsDword nOutSize) { CString szTemp; wsChar* szFilename=(wsChar*)(pIn+4); wsDword nDataOffset=0; memcpy(&nDataOffset, pIn, 4); wsByte* pData=(wsByte*)nDataOffset; szTemp.Format("Data: 0x%08X", nDataOffset); AfxMessageBox(szTemp); //wsByte* pData=(wsByte*)(*(wsDword)pIn); //wsByte* pData; //memcpy((void*)*pData, pIn, 4); AfxMessageBox(szFilename); szTemp.Format("The size is: %u", nOutSize); AfxMessageBox(szTemp); CFile fout; if(!fout.Open(szFilename, CFile::modeWrite|CFile::modeCreate)) return; fout.Write(pData, 249140); fout.Close(); } /* void PluginExport(unsigned char* inbuffer, int insize, unsigned char* outbuffer, int outsize) { char buffer[1024]; unsigned char* MapData=(unsigned char*)*((unsigned int *)inbuffer); unsigned short* mapversion = (unsigned short*) MapData; unsigned char* mapflags = (unsigned char*) (MapData+2); int* name_count = (int*) (MapData+3); int* name_offset = (int*) (MapData+7); int* object_count = (int*) (MapData+11); int* object_offset = (int*) (MapData+15); char** NameTable=new char*[*name_count]; MapData=(unsigned char*)*((unsigned int *)inbuffer)+*name_offset; for(int i=0;i<*name_count;++i) { NameTable[i]=(char*)MapData; MapData+=strlen(NameTable[i])+1; sprintf(buffer,"%s",NameTable[i]); MessageBox(NULL,buffer,"PluginExport",MB_OK); } MapData=(unsigned char*)*((unsigned int *)inbuffer)+*object_offset; for(int i=0;i<*object_count;++i) { sprintf(buffer,"Object %d %s size %d",i, NameTable[*((unsigned int*)MapData)-1], *((int*)MapData+1)); MessageBox(NULL,buffer,"PluginExport",MB_OK); MapData+=(*((int*)MapData+1))+8; } FILE* exp = fopen((const char*)inbuffer+4,"wb"); fwrite((unsigned char*)*((unsigned int *)inbuffer)+*object_offset,sizeof(unsigned char),512,exp); fclose(exp); delete[] NameTable; } */<file_sep>/games/Legacy-Engine/Source/LMEdit/LMEditView.h // LMEditView.h : interface of the CLMEditView class // #pragma once class CLMEditView : public CView { friend class CLMEditDoc; protected: // create from serialization only CLMEditView(); DECLARE_DYNCREATE(CLMEditView) // Attributes public: CLMEditDoc* GetDocument() const; // Operations public: // Overrides public: virtual void OnDraw(CDC* pDC); // overridden to draw this view virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual BOOL OnPreparePrinting(CPrintInfo* pInfo); virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo); // Implementation public: virtual ~CLMEditView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif private: typedef enum _MESH_RENDER_MODE { MESH_RENDER_DEFAULT=0, MESH_RENDER_WIREFRAME=ID_MESH_WIREFRAME, MESH_RENDER_FLATSHADED=ID_MESH_FLATSHADED, MESH_RENDER_SMOOTHSHADED=ID_MESH_SMOOTHSHADED, MESH_RENDER_TEXTURED=ID_MESH_TEXTURED }MESH_RENDER_MODE; //Helper member variables private: IDirect3D9* m_pD3D; IDirect3DDevice9* m_pDevice; BOOL m_bRenderSkel; int m_nMouseX; int m_nMouseY; const DWORD m_nBBWidth; const DWORD m_nBBHeight; MESH_RENDER_MODE m_nMeshRenderMode; //Helper member functions private: int InitD3D(void); int DestroyD3D(void); BOOL SetRenderModes(void); void UpdateMenu(void); LONG GetWidth(void); LONG GetHeight(void); int Render3DScene(BOOL bPrinter); void RenderToDC(CDC* pDC); public: BOOL ProcessAnimation(void); // Generated message map functions protected: DECLARE_MESSAGE_MAP() //Message map functions: afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); virtual void OnPrint(CDC* pDC, CPrintInfo* pInfo); afx_msg void OnAnimationShowskeleton(); afx_msg void OnMeshSmoothshaded(); afx_msg void OnMeshFlatshaded(); afx_msg void OnMeshTextured(); afx_msg void OnMeshWireframe(); afx_msg void OnDestroy(); afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnAnimationAnimationRange(UINT nID); afx_msg void OnUpdateMeshRenderMode(CCmdUI* pCmdUI); private: // The current animation to render. DWORD m_nAnim; afx_msg void OnAnimationDefaultmesh(); protected: virtual void OnUpdate(CView* /*pSender*/, LPARAM /*lHint*/, CObject* /*pHint*/); public: afx_msg void OnRButtonDown(UINT nFlags, CPoint point); public: afx_msg void OnContextMenu(CWnd* /*pWnd*/, CPoint /*point*/); public: afx_msg void OnUpdateAnimationShowskeleton(CCmdUI *pCmdUI); D3DXMATRIX m_matWorld; D3DXMATRIX m_matView; public: void ResetView(void); public: afx_msg BOOL OnMouseWheel(UINT nFlags, short zDelta, CPoint pt); }; #ifndef _DEBUG // debug version in LMEditView.cpp inline CLMEditDoc* CLMEditView::GetDocument() const { return reinterpret_cast<CLMEditDoc*>(m_pDocument); } #endif <file_sep>/games/Legacy-Engine/Scrapped/tools/Texview2/src/Texture.cpp // Texture.cpp: implementation of the CTexture class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Texview2.h" #include "Texture.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CTexture::CTexture(): m_hTGAImage(NULL), m_nWidth(0), m_nHeight(0) { } CTexture::~CTexture() { Unload(); } void CTexture::Unload() { m_bmImage.DeleteObject(); IMG_Delete(m_hTGAImage); m_hTGAImage=NULL; } BOOL CTexture::Load(LPTSTR szFilename) { Unload(); m_hTGAImage=IMG_Open(szFilename); if(m_hTGAImage) return TRUE; else return FALSE; } BOOL CTexture::CreateCBitmap(int cx, int cy, IMGFILTER filter, CDC* pdc, DWORD Flags) { /* The idea behind converting an imaged to a DDB that can be used with windows is the get necessary data and use CreateDIBitmap with specified info. */ HBITMAP hFinal=NULL; LPVOID lpImageData=NULL; BITMAPINFOHEADER bmih; BITMAPINFO bmi; IMG_DESC descript; unsigned char nExtra=255; //unsigned short finalwidth=0, finalheight=0; memset(&bmih, 0, sizeof(BITMAPINFOHEADER)); memset(&bmi, 0, sizeof(BITMAPINFO)); if(!m_hTGAImage) return FALSE; IMG_GetDesc( m_hTGAImage, &descript); m_nWidth=cx?cx:descript.Width; m_nHeight=cy?cy:descript.Height; lpImageData=malloc(m_nWidth*m_nHeight*4); if(!lpImageData) { return FALSE; } //Set up the destination rect. IMG_DEST_RECT rcd={0}; rcd.nWidth=m_nWidth; rcd.nHeight=m_nHeight; rcd.nPitch=m_nWidth*4; rcd.nFormat=IMGFMT_A8R8G8B8; rcd.nOrient=IMGORIENT_BOTTOMLEFT; rcd.rcCopy.top=0; rcd.rcCopy.left=0; rcd.rcCopy.right=m_nWidth; rcd.rcCopy.bottom=m_nHeight; rcd.pImage=(img_void*)lpImageData; IMG_CopyBits( m_hTGAImage, &rcd, filter, NULL, 0xFF); int i=0; //If we want the alpha channel we simply copy the alpha //value into all other values. This will give us the gray //scale image we need. if(CHECK_FLAG(Flags, BC_ACHANNEL)) { ARGBVALUE colrBG={0, 0, 0, 0xFF}; DWORD bgclr=CHECK_FLAG(Flags, BC_USEAPPBG)?GetSysColor(COLOR_APPWORKSPACE):0xFF000000; memcpy(&colrBG, &bgclr, 4); ARGBVALUE* pColVals=(ARGBVALUE*)lpImageData; for(i=0; i<(m_nWidth*m_nHeight); i++) { //If we want to render both the image and the alpah channel //we do an alpha blend. if(CHECK_FLAG(Flags, BC_IMAGE)) { //newColor = backColor + (overlayColor – backColor) * (alphaByte div 255) pColVals[i].r=pColVals[i].r+(colrBG.r-pColVals[i].r)*(255-pColVals[i].a)/255; pColVals[i].g=pColVals[i].g+(colrBG.g-pColVals[i].g)*(255-pColVals[i].a)/255; pColVals[i].b=pColVals[i].b+(colrBG.b-pColVals[i].b)*(255-pColVals[i].a)/255; } else { //If not we use white as the image color and do the same alpha blend op. pColVals[i].r=255+(colrBG.r-255)*(255-pColVals[i].a)/255; pColVals[i].g=255+(colrBG.g-255)*(255-pColVals[i].a)/255; pColVals[i].b=255+(colrBG.b-255)*(255-pColVals[i].a)/255; } } } bmih.biSize=sizeof(BITMAPINFOHEADER); bmih.biWidth=m_nWidth; bmih.biHeight=m_nHeight; bmih.biPlanes=1; bmih.biBitCount=32; bmih.biCompression=BI_RGB; bmih.biSizeImage=m_nWidth*m_nHeight*4;//BI_RGB; bmih.biXPelsPerMeter=0; bmih.biYPelsPerMeter=0; bmih.biClrUsed=0; bmih.biClrImportant=0; bmi.bmiHeader=bmih; hFinal=CreateDIBitmap( pdc->m_hDC, &bmih, CBM_INIT, lpImageData, &bmi, DIB_RGB_COLORS); free(lpImageData); m_bmImage.m_hObject=hFinal; return TRUE; } BOOL CTexture::DrawBitmap(int x, int y, CDC *pdc) { if(!m_bmImage.m_hObject) return FALSE; BITMAP bm; m_bmImage.GetBitmap(&bm); CDC cImageDC; cImageDC.CreateCompatibleDC(pdc); CBitmap* bmOld=(CBitmap*)cImageDC.SelectObject(&m_bmImage); int xOffset=x; int yOffset=y; pdc->StretchBlt( 0, 0, bm.bmWidth-xOffset, bm.bmHeight-yOffset, &cImageDC, xOffset, yOffset, bm.bmWidth-xOffset, bm.bmHeight-yOffset, SRCCOPY); cImageDC.SelectObject(bmOld); cImageDC.DeleteDC(); return TRUE; } void CTexture::GetBitmapDims(int *pWidth, int *pHeight) { *pWidth=m_nWidth; *pHeight=m_nHeight; } <file_sep>/games/Sometimes-Y/SometimesY/SYGame.cpp #include "StdAfx.h" #include "SYGame.h" CSYGame::CSYGame(void) : m_bGameRunning(FALSE) , m_nGameSizeX(0), m_nGameSizeY(0) , m_GameMatrix(NULL) { EndGame(); } CSYGame::~CSYGame(void) { EndGame(); } BOOL CSYGame::StartGame(LPCTSTR szGameFile) { EndGame(); //For now this is just a dummy game creator m_nGameSizeX=10; m_nGameSizeY=10; m_GameMatrix = new Block[m_nGameSizeX*m_nGameSizeY]; for(DWORD i=0; i<m_nGameSizeX*m_nGameSizeY; i++) { m_GameMatrix[i].nType=BLOCK_UNUSABLE; m_GameMatrix[i].nStatus=STATUS_FIXED; m_GameMatrix[i].bValid=FALSE; } SetBlock(2, 2, BLOCK_EMPTY, STATUS_EMPTY); SetBlock(3, 2, BLOCK_EMPTY, STATUS_EMPTY); SetBlock(4, 2, BLOCK_EMPTY, STATUS_EMPTY); SetBlock(2, 3, BLOCK_EMPTY, STATUS_EMPTY); SetBlock(3, 3, BLOCK_O, STATUS_FIXED); SetBlock(4, 3, BLOCK_EMPTY, STATUS_EMPTY); SetBlock(2, 4, BLOCK_EMPTY, STATUS_EMPTY); SetBlock(3, 4, BLOCK_EMPTY, STATUS_EMPTY); SetBlock(4, 4, BLOCK_EMPTY, STATUS_EMPTY); //SetBlock(9, 9, BLOCK_EMPTY, STATUS_EMPTY); m_nTypeAvail[BLOCK_A]=2; m_nTypeAvail[BLOCK_E]=2; m_nTypeAvail[BLOCK_I]=2; m_nTypeAvail[BLOCK_O]=0; m_nTypeAvail[BLOCK_U]=1; m_nTypeAvail[BLOCK_Y]=1; UpdateGameStatus(); m_bGameRunning=TRUE; return TRUE; } void CSYGame::EndGame() { m_nGameSizeX=0; m_nGameSizeY=0; for(DWORD i=0; i<6; i++) { m_nTypeAvail[i]=0; } if(m_GameMatrix) { delete[]m_GameMatrix; m_GameMatrix=NULL; } m_bGameRunning=FALSE; } CSYGame::PLACE_RESULT CSYGame::PlaceLetter(CSYGame::BLOCK_TYPE nLetter, DWORD nX, DWORD nY, LPTSTR szOutMsg) { if(m_nTypeAvail[nLetter]==0) return CSYGame::PLACE_BAD; const Block* pBlk = GetBlock(nX, nY); if(pBlk->nType==BLOCK_UNUSABLE || pBlk->nType!=BLOCK_EMPTY) return CSYGame::PLACE_BAD; SetBlock(nX, nY, nLetter, STATUS_PLACED); m_nTypeAvail[nLetter]--; UpdateGameStatus(); return CSYGame::PLACE_OK; } BOOL CSYGame::RemoveLetter(DWORD nX, DWORD nY) { const Block* pBlk = GetBlock(nX, nY); if(pBlk->nType==BLOCK_UNUSABLE || pBlk->nStatus==STATUS_FIXED || pBlk->nType==BLOCK_EMPTY) return FALSE; m_nTypeAvail[pBlk->nType]++; SetBlock(nX, nY, BLOCK_EMPTY, STATUS_EMPTY); UpdateGameStatus(); return TRUE; } void CSYGame::GetSize(DWORD& x, DWORD& y) { x=m_nGameSizeX; y=m_nGameSizeY; } const CSYGame::Block* CSYGame::GetBlock(const DWORD x, const DWORD y) { static const Block blkEmpty={BLOCK_UNUSABLE, STATUS_EMPTY, FALSE}; if(!m_bGameRunning || x>=m_nGameSizeX || y>=m_nGameSizeY) { return &blkEmpty; } else { return &m_GameMatrix[x+y*m_nGameSizeX]; } } void CSYGame::GetAvailLetters(DWORD* pCounts) { for(DWORD i=0; i<6; i++) { pCounts[i]=this->m_nTypeAvail[i]; } } void CSYGame::SetBlock(DWORD x, DWORD y, CSYGame::BLOCK_TYPE nType, CSYGame::BLOCK_STATUS nStatus) { if(x>=m_nGameSizeX || y>=m_nGameSizeY) return; m_GameMatrix[x+y*m_nGameSizeX].nType=nType; m_GameMatrix[x+y*m_nGameSizeX].nStatus=nStatus; m_GameMatrix[x+y*m_nGameSizeX].bValid=FALSE; } void CSYGame::SetBlockValid(DWORD x, DWORD y, BOOL bValid) { if(x>=m_nGameSizeX || y>=m_nGameSizeY) return; m_GameMatrix[x+y*m_nGameSizeX].bValid=bValid; } void CSYGame::UpdateGameStatus() { for(DWORD x=0; x<m_nGameSizeX; x++) { for(DWORD y=0; y<m_nGameSizeY; y++) { const Block* pBlk = GetBlock(x, y); switch(pBlk->nType) { case BLOCK_A: SetBlockValid(x, y, CheckA(x, y)); break; case BLOCK_E: SetBlockValid(x, y, CheckE(x, y)); break; case BLOCK_I: SetBlockValid(x, y, CheckI(x, y)); break; case BLOCK_O: SetBlockValid(x, y, CheckO(x, y)); break; case BLOCK_U: SetBlockValid(x, y, CheckU(x, y)); break; case BLOCK_Y: SetBlockValid(x, y, CheckY(x, y)); break; //By default we aren't checking anything that isn't //a letter. } } } } BOOL CSYGame::CheckA(DWORD x, DWORD y) { BLOCK_TYPE sides[4]; GetSides(x, y, sides); BOOL bResult=FALSE; //A must share a side with an A or U, and not O for(DWORD i=0; i<4; i++) { if(sides[i]==BLOCK_O) return FALSE; if(sides[i]==BLOCK_A || sides[i]==BLOCK_U) bResult=TRUE; } return bResult; } BOOL CSYGame::CheckE(DWORD x, DWORD y) { BLOCK_TYPE sides[4]; GetSides(x, y, sides); BOOL bResult=FALSE; DWORD nSideCount=0; //Must side 3 or more letters, cannot side with U. for(DWORD i=0; i<4; i++) { if(sides[i]==BLOCK_U) return FALSE; if(sides[i]!=BLOCK_EMPTY && sides[i]!=BLOCK_UNUSABLE) { nSideCount++; } } return (nSideCount>=3)?TRUE:FALSE; } BOOL CSYGame::CheckI(DWORD x, DWORD y) { BLOCK_TYPE sides[4]; GetSides(x, y, sides); //Cannot share a side with I, O, U. for(DWORD i=0; i<4; i++) { if(sides[i]==BLOCK_I || sides[i]==BLOCK_O || sides[i]==BLOCK_U) return FALSE; } return TRUE; } BOOL CSYGame::CheckO(DWORD x, DWORD y) { BLOCK_TYPE sides[4]; GetSides(x, y, sides); BOOL bResult=FALSE; //Must side E cannot side A for(DWORD i=0; i<4; i++) { if(sides[i]==BLOCK_A) return FALSE; if(sides[i]==BLOCK_E) bResult=TRUE; } return bResult; } BOOL CSYGame::CheckU(DWORD x, DWORD y) { BLOCK_TYPE sides[4]; GetSides(x, y, sides); //Cannot side E or I for(DWORD i=0; i<4; i++) { if(sides[i]==BLOCK_E || sides[i]==BLOCK_I) return FALSE; } return TRUE; } BOOL CSYGame::CheckY(DWORD x, DWORD y) { BLOCK_TYPE sides[4]; GetSides(x, y, sides); //No rules return TRUE; } void CSYGame::GetSides(DWORD x, DWORD y, CSYGame::BLOCK_TYPE* sides) { const Block* pBlkSide; //Top pBlkSide=GetBlock(x, y-1); sides[0]=pBlkSide->nType; //Right pBlkSide=GetBlock(x+1, y); sides[1]=pBlkSide->nType; //Bottom pBlkSide=GetBlock(x, y+1); sides[2]=pBlkSide->nType; //Left pBlkSide=GetBlock(x-1, y); sides[3]=pBlkSide->nType; }<file_sep>/games/Legacy-Engine/Source/engine/lx_ent_template.cpp #include "lx_sys.h" void LX_ETemplateStart(void* userData, const XML_Char* name, const XML_Char** atts); void LX_ETemplateEnd(void* userData, const XML_Char* name); struct ET_DATA { lg_dword nCount; lx_ent_template* pTemplate; }; lx_ent_template* LX_LoadEntTemplate(const lg_path szXMLFile, lg_dword* pCount) { ET_DATA data; data.nCount=0; data.pTemplate=LG_NULL; LX_Process(szXMLFile, LX_ETemplateStart, LX_ETemplateEnd, LG_NULL, &data); *pCount=data.nCount; return data.pTemplate; } lg_void LX_DestroyEntTemplate(lx_ent_template* pTemplate) { LG_SafeDeleteArray(pTemplate); } void LX_ETemplateStart(void* userData, const XML_Char* name, const XML_Char** atts) { ET_DATA* pData=(ET_DATA*)userData; LX_START_TAG LX_TAG(ent_template) { if(pData->pTemplate) LG_SafeDeleteArray(pData->pTemplate); LX_START_ATTR LX_ATTR_DWORD(pData->nCount, count) LX_END_ATTR if(pData->nCount) { pData->pTemplate=new lx_ent_template[pData->nCount]; } } LX_TAG(ent_type) { lg_dword nID; lg_path szPath; LX_START_ATTR LX_ATTR_DWORD(nID, id) LX_ATTR_STRING(szPath, script, LG_MAX_PATH) LX_END_ATTR if(nID<pData->nCount) { pData->pTemplate[nID].nID=nID; LG_strncpy(pData->pTemplate[nID].szScript, szPath, LG_MAX_PATH); } } LX_END_TAG } void LX_ETemplateEnd(void* userData, const XML_Char* name) { }<file_sep>/games/Legacy-Engine/Source/lm_sys/lm_skel2.cpp #include "lm_skel.h" #include "ML_lib.h" #include "lg_func.h" //Alright here is the skeleton class. //Further this needs to support some kind of //mechanism for pointing out different animations //based on a range of animations. //Also need to change the way the model gets rendered. //Either CLegacyMesh needs to have a RenderWithSkel funciton. //Or CLSkel2 needs to have a RenderModel functions. CLSkel2::CLSkel2(): CLMBase(), m_nID(0), m_nVersion(0), m_nNumJoints(0), m_nNumKeyFrames(0), m_pBaseSkeleton(LG_NULL), m_pFrames(LG_NULL), m_nNumAnims(0), m_pAnims(LG_NULL) { m_szSkelName[0]=0; } CLSkel2::~CLSkel2() { Unload(); } lg_dword CLSkel2::GetNumAnims() { return m_nNumAnims; } lg_dword CLSkel2::GetNumJoints() { return m_nNumJoints; } lg_dword CLSkel2::GetNumKeyFrames() { return m_nNumKeyFrames; } lg_bool CLSkel2::IsLoaded() { return LG_CheckFlag(m_nFlags, LM_FLAG_LOADED); } lg_dword CLSkel2::GetParentBoneRef(lg_dword nBone) { return m_pBaseSkeleton[nBone].nParent; } lg_void CLSkel2::Unload() { DeallocateMemory(); m_nID=0; m_nVersion=0; m_nNumJoints=0; m_nNumKeyFrames=0; m_nFlags=0; m_nNumAnims=0; } #if 0 //The read and write LF2 functions are used for the legacy mesh //and legacy skel serialize methods when the LF2 file system is in //use. lg_uint CLSkel2::ReadLF2(void* buffer, lg_uint size, lg_uint count, void* stream) { return LF_Read((LF_FILE3)stream, buffer, size*count); } lg_bool CLSkel2::Load(lf_path szFilename) { Unload(); LF_FILE3 fIn=LF_Open(szFilename, LF_ACCESS_READ, LF_OPEN_EXISTING); if(!fIn) return LG_FALSE; lg_bool bResult=Serialize(fIn, ReadLF2, LG_TRUE); if(!bResult) Unload(); m_bLoaded=bResult; //We will now get all the calculations for the extra data (the local //and final matrices for the base skeleton and keyframes). //this->CalcExData(); if(m_bLoaded) { CalcExData(); } LF_Close(fIn); return m_bLoaded; } #endif #if 0 lg_bool CLSkel2::Load(void* file, LM_RW_FN read) { //Unload in case a skeleton is already loaded. Unload(); lg_bool bResult=Serialize( file, read, LG_TRUE); if(!bResult) Unload(); //pcb->close(file); m_bLoaded=bResult; //We will now get all the calculations for the extra data (the local //and final matrices for the base skeleton and keyframes). //this->CalcExData(); if(m_bLoaded) { CalcExData(); } return m_bLoaded; } lg_bool CLSkel2::Save(void* file, LM_RW_FN write) { if(!m_bLoaded) return LG_FALSE; if(!m_pBaseSkeleton || !m_pFrames) return LG_FALSE; if(!file) return LG_FALSE; return Serialize( file, write, LG_FALSE); } #endif lg_bool CLSkel2::Serialize( lg_void* file, ReadWriteFn read_or_write, RW_MODE mode) { lg_dword i=0, j=0; //Read or Write the file header. read_or_write(file, &m_nID, 4); read_or_write(file, &m_nVersion, 4); read_or_write(file, m_szSkelName, 32); read_or_write(file, &m_nNumJoints, 4); read_or_write(file, &m_nNumKeyFrames, 4); read_or_write(file, &m_nNumAnims, 4); if((m_nID != LM_SKEL_ID) || (m_nVersion != LM_SKEL_VER)) return LG_FALSE; //Allocate memory if we are loading. if(mode==RW_READ) if(!AllocateMemory())return LG_FALSE; //Read or write the base skeleton. for(i=0; i<m_nNumJoints; i++) { read_or_write(file, &m_pBaseSkeleton[i], SkelJoint::SKEL_JOINT_SIZE_IN_FILE); } //Read or write the key frames. for(i=0; i<m_nNumKeyFrames; i++) { for(j=0; j<m_nNumJoints; j++) { read_or_write(file, &m_pFrames[i].LocalPos[j], sizeof(SkelJointPos)); } //Write the bounding box. read_or_write(file, &m_pFrames[i].aabbBox, sizeof(ML_AABB)); } //Read or write the animation information. for(i=0; i<m_nNumAnims; i++) { read_or_write(file, &m_pAnims[i], sizeof(SkelAnim)); } return LG_TRUE; } const ml_aabb* CLSkel2::GetMinsAndMaxes(ml_aabb* pBounds) { //This only gets the mins and the maxes for the default frame, it //does not get mins and maxes for keyframes. ml_aabb bounds; lg_dword i=0; bounds.v3Min.x=m_pBaseSkeleton[0].matFinal._41; bounds.v3Max.x=m_pBaseSkeleton[0].matFinal._41; bounds.v3Min.y=m_pBaseSkeleton[0].matFinal._42; bounds.v3Max.y=m_pBaseSkeleton[0].matFinal._42; bounds.v3Min.z=m_pBaseSkeleton[0].matFinal._43; bounds.v3Max.z=m_pBaseSkeleton[0].matFinal._43; for(i=1; i<m_nNumJoints; i++) { bounds.v3Min.x=LG_Min(bounds.v3Min.x, m_pBaseSkeleton[i].matFinal._41); bounds.v3Max.x=LG_Max(bounds.v3Max.x, m_pBaseSkeleton[i].matFinal._41); bounds.v3Min.y=LG_Min(bounds.v3Min.y, m_pBaseSkeleton[i].matFinal._42); bounds.v3Max.y=LG_Max(bounds.v3Max.y, m_pBaseSkeleton[i].matFinal._42); bounds.v3Min.z=LG_Min(bounds.v3Min.z, m_pBaseSkeleton[i].matFinal._43); bounds.v3Max.z=LG_Max(bounds.v3Max.z, m_pBaseSkeleton[i].matFinal._43); } *pBounds=bounds; return pBounds; } const CLSkel2::SkelAnim* CLSkel2::GetAnim(lg_dword n) { n=LG_Clamp(n, 0, m_nNumAnims-1); return &m_pAnims[n]; } lg_dword CLSkel2::GetFrameFromTime(lg_dword nAnim, float fTime, float* pFrameTime, lg_dword* pFrame2) { #define PREP_MAX_RANGE 100.0f if(!m_nNumAnims) return 0; nAnim=LG_Clamp(nAnim, 0, m_nNumAnims-1); fTime=LG_Clamp(fTime, 0.0f, PREP_MAX_RANGE); float fFrame; lg_dword nFrame1, nFrame2; if(LG_CheckFlag(m_pAnims[nAnim].nFlags, SkelAnim::ANIM_FLAG_LOOPBACK)) { if(fTime>=50.0f) fTime=100.0f-fTime; fFrame=m_pAnims[nAnim].nFirstFrame + ((float)m_pAnims[nAnim].nNumFrames-1-0.000001f) * fTime/(PREP_MAX_RANGE*0.5f); } else { fFrame=m_pAnims[nAnim].nFirstFrame + ((float)m_pAnims[nAnim].nNumFrames-0.000001f) * fTime/(PREP_MAX_RANGE); } nFrame1=(lg_dword)fFrame; nFrame2=nFrame1>=(m_pAnims[nAnim].nFirstFrame+m_pAnims[nAnim].nNumFrames-1)?m_pAnims[nAnim].nFirstFrame:nFrame1+1; if(pFrameTime) *pFrameTime=fFrame-nFrame1; if(pFrame2) *pFrame2=nFrame2; return nFrame1; } ML_AABB* CLSkel2::GenerateAABB(ML_AABB* pOut, lg_dword nFrame1, lg_dword nFrame2, float t) { if(!pOut) return pOut; nFrame1=LG_Clamp(nFrame1, 1, m_nNumKeyFrames); nFrame2=LG_Clamp(nFrame2, 1, m_nNumKeyFrames); t=LG_Clamp(t, 0.0f, 1.0f); //We should probably have an AABB for frame 0 (the default frame). ML_AABB *a, *b; a=&m_pFrames[nFrame1-1].aabbBox; b=&m_pFrames[nFrame2-1].aabbBox; pOut->v3Min.x=a->v3Min.x+(b->v3Min.x-a->v3Min.x)*t; pOut->v3Min.y=a->v3Min.y+(b->v3Min.y-a->v3Min.y)*t; pOut->v3Min.z=a->v3Min.z+(b->v3Min.z-a->v3Min.z)*t; pOut->v3Max.x=a->v3Max.x+(b->v3Max.x-a->v3Max.x)*t; pOut->v3Max.y=a->v3Max.y+(b->v3Max.y-a->v3Max.y)*t; pOut->v3Max.z=a->v3Max.z+(b->v3Max.z-a->v3Max.z)*t; return pOut; } ML_MAT* CLSkel2::GenerateJointTransform(ML_MAT* pOut, lg_dword nJoint, lg_dword nFrame1, lg_dword nFrame2, float t) { if(!pOut) return LG_NULL; nJoint=LG_Clamp(nJoint, 0, m_nNumJoints-1); nFrame1=LG_Clamp(nFrame1, 0, m_nNumKeyFrames); nFrame2=LG_Clamp(nFrame2, 0, m_nNumKeyFrames); t=LG_Clamp(t, 0.0f, 1.0f); const ML_MAT *pM1, *pM2; ML_MAT MI; ML_MatIdentity(&MI); pM1=nFrame1>0?m_pFrames[nFrame1-1].GetFinalMat(nJoint):&MI; pM2=nFrame2>0?m_pFrames[nFrame2-1].GetFinalMat(nJoint):&MI; return ML_MatSlerp( pOut, (ML_MAT*)pM1, (ML_MAT*)pM2, t); } //This second version of GenerateJointTransform uses a second skeleton to generate //the transform. Note that both skeletons should be compatible with each other and //have the same base skeleton, or the transformation may not be pretty. ML_MAT* CLSkel2::GenerateJointTransform(ML_MAT* pOut, lg_dword nJoint, lg_dword nFrame1, lg_dword nFrame2, float t, CLSkel2* pSkel2) { if(!pOut) return LG_NULL; nJoint=LG_Clamp(nJoint, 0, m_nNumJoints-1); nFrame1=LG_Clamp(nFrame1, 0, m_nNumKeyFrames); nFrame2=LG_Clamp(nFrame2, 0, pSkel2->m_nNumKeyFrames); t=LG_Clamp(t, 0.0f, 1.0f); const ML_MAT *pM1, *pM2; ML_MAT MI; ML_MatIdentity(&MI); pM1=nFrame1>0?m_pFrames[nFrame1-1].GetFinalMat(nJoint):&MI; pM2=nFrame2>0?pSkel2->m_pFrames[nFrame2-1].GetFinalMat(nJoint):&MI; return ML_MatSlerp( pOut, (ML_MAT*)pM1, (ML_MAT*)pM2, t); } const ML_MAT* CLSkel2::GetBaseTransform(lg_dword nJoint) { nJoint=LG_Clamp(nJoint, 0, m_nNumJoints-1); return &m_pBaseSkeleton[nJoint].matFinal; } lg_bool CLSkel2::AllocateMemory() { lg_dword i=0, j=0; //Deallocate memory first just in case, //note that because the poitners are set to null in //the constructor it is okay to call this before they //are initialized. DeallocateMemory(); //Allocate memory for the frames and base skeleton. //m_pKeyFrames=new LMESH_KEYFRAME[m_nNumKeyFrames]; m_pFrames=new SkelFrame[m_nNumKeyFrames]; if(!m_pFrames) return LG_FALSE; for(i=0; i<m_nNumKeyFrames;i++) { if(!m_pFrames[i].Initialize(m_nNumJoints)) { LG_SafeDeleteArray(m_pFrames); return LG_FALSE; } } m_pBaseSkeleton=new SkelJoint[m_nNumJoints]; if(!m_pBaseSkeleton) { LG_SafeDeleteArray(m_pFrames); return LG_FALSE; } m_pAnims=new SkelAnim[m_nNumAnims]; if(!m_pAnims) { LG_SafeDeleteArray(m_pFrames); LG_SafeDeleteArray(m_pBaseSkeleton); return LG_FALSE; } return LG_TRUE; } void CLSkel2::DeallocateMemory() { LG_SafeDeleteArray(m_pBaseSkeleton); LG_SafeDeleteArray(m_pFrames); LG_SafeDeleteArray(m_pAnims); } lg_dword CLSkel2::GetNumFrames() { return m_nNumKeyFrames; } lg_bool CLSkel2::CalcExData() { lg_dword i=0, j=0; if(!LG_CheckFlag(m_nFlags, LM_FLAG_LOADED)) return LG_FALSE; //Firstly we must convert Euler angles for the base skeleton and //keyframes to matrices. //Read the base skeleton. for(i=0; i<m_nNumJoints; i++) { //Now create the rotation matrixes (in the final format the rotation //matrices will probably be stored instead of the euler angles. EulerToMatrix((ML_MAT*)&m_pBaseSkeleton[i].matLocal, (float*)&m_pBaseSkeleton[i].fRot); //Now stick the translation into the matrix. m_pBaseSkeleton[i].matLocal._41=m_pBaseSkeleton[i].fPos[0]; m_pBaseSkeleton[i].matLocal._42=m_pBaseSkeleton[i].fPos[1]; m_pBaseSkeleton[i].matLocal._43=m_pBaseSkeleton[i].fPos[2]; m_pBaseSkeleton[i].nJointRef=i; } //Read the key frames. for(i=0; i<m_nNumKeyFrames; i++) { for(j=0; j<m_nNumJoints; j++) { EulerToMatrix(&m_pFrames[i].Local[j], (float*)&m_pFrames[i].LocalPos[j].fRot); m_pFrames[i].Local[j]._41=m_pFrames[i].LocalPos[j].fPos[0]; m_pFrames[i].Local[j]._42=m_pFrames[i].LocalPos[j].fPos[1]; m_pFrames[i].Local[j]._43=m_pFrames[i].LocalPos[j].fPos[2]; } } //Calculate the final matrices for the base skeleton. //This is simply a matter of multiplying each joint by //all of it's parent's matrices. for(i=0; i<m_nNumJoints; i++) { SkelJoint* pTemp=&m_pBaseSkeleton[i]; m_pBaseSkeleton[i].matFinal=pTemp->matLocal; while(pTemp->nParent) { pTemp=&m_pBaseSkeleton[pTemp->nParent-1]; ML_MatMultiply((ML_MAT*)&m_pBaseSkeleton[i].matFinal, (ML_MAT*)&m_pBaseSkeleton[i].matFinal, (ML_MAT*)&m_pBaseSkeleton[pTemp->nJointRef].matLocal); } } //We calculate the final transformation matrix for each joint for each //frame now, that way we don't have to calculate them on the fly. It //takes more memory this way, but the real time rendering is faster because //it isn't necessary to calculate each frames matrix every frame, it is only //necessary to interploate the joint matrixes for the given frame. //For each joint... for(i=0; i<m_nNumJoints; i++) { //For each frame for each joint... for(j=0; j<m_nNumKeyFrames; j++) { //1. Obtain the base joint for that joint. SkelJoint* pTemp=&m_pBaseSkeleton[i]; //2. Start out by making the final translation for the frame the local frame joint //location multiplyed the by the local base joint. //ML_MatMultiply((ML_MAT*)&m_pKeyFrames[j].pJointPos[i].Final, (ML_MAT*)&m_pKeyFrames[j].pJointPos[i].Local, (ML_MAT*)&pTemp->Local); ML_MatMultiply((ML_MAT*)&m_pFrames[j].Final[i], &m_pFrames[j].Local[i], &pTemp->matLocal); //3. Then if the joint has a parent... while(pTemp->nParent) { //3 (cont'd). It is necessary to multiply the final frame matrix //by the same calculation in step 2 (frame pos for the frame * local pos for the frame). pTemp=&m_pBaseSkeleton[pTemp->nParent-1]; ML_MAT MT; ML_MatMultiply( (ML_MAT*)&m_pFrames[j].Final[i], (ML_MAT*)&m_pFrames[j].Final[i], ML_MatMultiply(&MT, (ML_MAT*)&m_pFrames[j].Local[pTemp->nJointRef], (ML_MAT*)&pTemp->matLocal)); } //4. Fianlly the final position needs to be multiplied by the //final base position's inverse so that the transformation is //relative to the joint's location and not to 0,0,0. ML_MAT MI; ML_MatInverse(&MI, LG_NULL, &m_pBaseSkeleton[i].matFinal); ML_MatMultiply((ML_MAT*)&m_pFrames[j].Final[i], &MI, (ML_MAT*)&m_pFrames[j].Final[i]); } } return LG_TRUE; } ML_MAT* CLSkel2::EulerToMatrix(ML_MAT* pOut, float* pEuler) { ML_MAT MX, MY, MZ; ML_MatRotationX(&MX, -pEuler[0]); ML_MatRotationY(&MY, -pEuler[1]); ML_MatRotationZ(&MZ, -pEuler[2]); return ML_MatMultiply( pOut, &MX, ML_MatMultiply(&MY, &MY, &MZ)); } /////////////////////////////// /// SkelFrame Member Methods /// /////////////////////////////// CLSkel2::SkelFrame::SkelFrame(): Local(LG_NULL), Final(LG_NULL), m_nNumJoints(0), LocalPos(LG_NULL) { } CLSkel2::SkelFrame::SkelFrame(lg_dword nNumJoints): Local(LG_NULL), Final(LG_NULL), m_nNumJoints(0), LocalPos(LG_NULL) { Initialize(nNumJoints); } CLSkel2::SkelFrame::~SkelFrame() { LG_SafeDeleteArray(Local); LG_SafeDeleteArray(Final); LG_SafeDeleteArray(LocalPos); } lg_bool CLSkel2::SkelFrame::Initialize(lg_dword nNumJoints) { LG_SafeDeleteArray(Local); LG_SafeDeleteArray(Final); LG_SafeDeleteArray(LocalPos); m_nNumJoints=nNumJoints; Local=new ML_MAT[nNumJoints]; Final=new ML_MAT[nNumJoints]; LocalPos=new SkelJointPos[nNumJoints]; if(!Local || !Final || !LocalPos) return LG_FALSE; float f[3]={0.0f, 0.0f, 0.0f}; for(lg_dword i=0; i<nNumJoints; i++) SetLocalMat(i, f, f); return LG_TRUE; } lg_dword CLSkel2::SkelFrame::GetNumJoints() { return m_nNumJoints; } const ML_MAT* CLSkel2::SkelFrame::GetFinalMat(lg_dword nJoint) { nJoint=LG_Clamp(nJoint, 0, m_nNumJoints-1); return &Final[nJoint]; } const ML_MAT* CLSkel2::SkelFrame::GetLocalMat(lg_dword nJoint) { nJoint=LG_Clamp(nJoint, 0, m_nNumJoints-1); return &Local[nJoint]; } lg_bool CLSkel2::SkelFrame::SetFinalMat(lg_dword nJoint, ML_MAT* pM) { if(nJoint>=m_nNumJoints) return LG_FALSE; Final[nJoint]=*pM; return LG_TRUE; } lg_bool CLSkel2::SkelFrame::SetLocalMat(lg_dword nJoint, float* position, float* rotation) { if(nJoint>=m_nNumJoints) return LG_FALSE; LocalPos[nJoint].fPos[0]=position[0]; LocalPos[nJoint].fPos[1]=position[1]; LocalPos[nJoint].fPos[2]=position[2]; LocalPos[nJoint].fRot[0]=rotation[0]; LocalPos[nJoint].fRot[1]=rotation[1]; LocalPos[nJoint].fRot[2]=rotation[2]; CLSkel2::EulerToMatrix(&Local[nJoint], rotation); Local[nJoint]._41=position[0]; Local[nJoint]._42=position[1]; Local[nJoint]._43=position[2]; return LG_TRUE; } lg_bool CLSkel2::SkelFrame::SetLocalMat(lg_dword nJoint, ML_MAT* pM) { if(nJoint>=m_nNumJoints) return LG_FALSE; Local[nJoint]=*pM; return LG_TRUE; } <file_sep>/samples/D3DDemo/code/MD3Base/MD3ObjectMesh.cpp #define D3D_MD3 #include <d3dx9.h> #include <stdio.h> #include "defines.h" #include "functions.h" #include "MD3.h" CMD3ObjectMesh::CMD3ObjectMesh() { m_lppObjTex=NULL; m_bLoaded=FALSE; } CMD3ObjectMesh::~CMD3ObjectMesh() { Clear(); } HRESULT CMD3ObjectMesh::Clear() { LONG lNumMesh=0; DWORD i=0; if(!m_bLoaded) return S_FALSE; m_meshObject.GetNumMeshes(&lNumMesh); for(i=0; i<(DWORD)lNumMesh; i++){ SAFE_RELEASE(m_lppObjTex[i]); } SAFE_FREE(m_lppObjTex); m_TexDB.ClearDB(); m_meshObject.ClearMD3(); return S_OK; } HRESULT CMD3ObjectMesh::TextureExtension(LPDIRECT3DDEVICE9 lpDevice, char szShader[MAX_PATH]) { DWORD dwLen=0, i=0, j=0; char szTemp[MAX_PATH]; HRESULT hr=0; //First attempt to load the name provided. hr=m_TexDB.AddTexture(lpDevice, szShader); if(SUCCEEDED(hr)){ RemoveDirectoryFromStringA(szShader, szShader); return S_OK; } dwLen=strlen(szShader); for(i=0, j=0; i<dwLen; i++, j++){ if(szShader[i]=='.'){ szTemp[j]=szShader[i]; szTemp[j+1]=0; break; } szTemp[j]=szShader[i]; } //Attempt to replace the extension till we successfully load. strcpy(szShader, szTemp); strcpy(szTemp, szShader); strcat(szTemp, "JPG"); hr=m_TexDB.AddTexture(lpDevice, szTemp); if(SUCCEEDED(hr)){ strcpy(szShader, szTemp); RemoveDirectoryFromStringA(szShader, szShader); return S_OK; } strcpy(szTemp, szShader); strcat(szTemp, "BMP"); hr=m_TexDB.AddTexture(lpDevice, szTemp); if(SUCCEEDED(hr)){ strcpy(szShader, szTemp); RemoveDirectoryFromStringA(szShader, szShader); return S_OK; } strcpy(szTemp, szShader); strcat(szTemp, "PNG"); hr=m_TexDB.AddTexture(lpDevice, szTemp); if(SUCCEEDED(hr)){ strcpy(szShader, szTemp); RemoveDirectoryFromStringA(szShader, szShader); return S_OK; } strcpy(szTemp, szShader); strcat(szTemp, "DIB"); hr=m_TexDB.AddTexture(lpDevice, szTemp); if(SUCCEEDED(hr)){ strcpy(szShader, szTemp); RemoveDirectoryFromStringA(szShader, szShader); return S_OK; } strcpy(szTemp, szShader); strcat(szTemp, "DDS"); hr=m_TexDB.AddTexture(lpDevice, szTemp); if(SUCCEEDED(hr)){ strcpy(szShader, szTemp); RemoveDirectoryFromStringA(szShader, szShader); return S_OK; } strcpy(szTemp, szShader); strcat(szTemp, "TGA"); hr=m_TexDB.AddTexture(lpDevice, szTemp); if(SUCCEEDED(hr)){ strcpy(szShader, szTemp); RemoveDirectoryFromStringA(szShader, szShader); return S_OK; } return E_FAIL; } HRESULT CMD3ObjectMesh::Load(LPDIRECT3DDEVICE9 lpDevice, char szFile[], MD3DETAIL nDetail) { LONG lNumMesh=0; DWORD i=0; char szShader[MAX_QPATH]; char szTexName[MAX_PATH]; char szPath[MAX_PATH]; char szExt[7]; char szFileName[MAX_PATH]; DWORD dwLen=0; GetDirectoryFromStringA(szPath, szFile); strcpy(szFileName, szFile); if(nDetail==DETAIL_LOW) strcpy(szExt, "_2.md3"); else if(nDetail==DETAIL_MEDIUM) strcpy(szExt, "_1.md3"); else strcpy(szExt, ".md3"); dwLen=strlen(szFile); for(i=0; i<dwLen; i++){ if(szFileName[i]=='.') break; } szFileName[i]=0; strcat(szFileName, szExt); if(FAILED(m_meshObject.LoadMD3A(szFileName, NULL, lpDevice, D3DPOOL_DEFAULT))){ if(nDetail==DETAIL_MEDIUM || nDetail==DETAIL_LOW) return Load(lpDevice, szFile, DETAIL_HIGH); return E_FAIL; } m_meshObject.GetNumMeshes(&lNumMesh); m_lppObjTex=(LPDIRECT3DTEXTURE9*)malloc(sizeof(LPDIRECT3DTEXTURE9)*lNumMesh); if(m_lppObjTex==NULL){ m_meshObject.ClearMD3(); return E_FAIL; } //Get the textures. for(i=0; i<(DWORD)lNumMesh; i++){ m_meshObject.GetShader(i+1, 1, szShader, NULL); RemoveDirectoryFromStringA(szShader, szShader); sprintf(szTexName, "%s%s", szPath, szShader); if(SUCCEEDED(TextureExtension(lpDevice, szTexName))){ m_TexDB.GetTexture(szTexName, &m_lppObjTex[i]); }else{ m_lppObjTex[i]=NULL; } } m_bLoaded=TRUE; return S_OK; } HRESULT CMD3ObjectMesh::Invalidate() { if(!m_bLoaded) return S_FALSE; return m_meshObject.Invalidate(); } HRESULT CMD3ObjectMesh::Validate(LPDIRECT3DDEVICE9 lpDevice) { if(!m_bLoaded) return S_FALSE; return m_meshObject.Validate(); } HRESULT CMD3ObjectMesh::Render(LPDIRECT3DDEVICE9 lpDevice , const D3DMATRIX& SavedWorldMatrix ) { LONG lNumMesh=0; DWORD i=0; D3DXMATRIX WorldMatrix, Orientation, Translation; if(!m_bLoaded) return S_FALSE; D3DXMatrixIdentity(&WorldMatrix); D3DXMatrixIdentity(&Orientation); D3DXMatrixRotationX(&Translation, 1.5f*D3DX_PI); Orientation*=Translation; D3DXMatrixRotationY(&Translation, 0.5f*D3DX_PI); Orientation*=Translation; Orientation*=SavedWorldMatrix; WorldMatrix*=Orientation; lpDevice->SetTransform(D3DTS_WORLD, &WorldMatrix); m_meshObject.GetNumMeshes(&lNumMesh); for(i=0; i<(DWORD)lNumMesh; i++){ m_meshObject.RenderWithTexture( m_lppObjTex[i], i+1, 0.0f, 0, 0, 0); } lpDevice->SetTransform(D3DTS_WORLD, &SavedWorldMatrix); return S_OK; }<file_sep>/games/Legacy-Engine/Source/common/common.h #ifndef __COMMON_H__ #define __COMMON_H__ #ifdef _DEBUG #define CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #endif//_DEBUG #ifdef __cplusplus extern "C"{ #endif /* __cplusplus */ #include "lg_types.h" /******************************** Disable some of VCs warnings *********************************/ #pragma warning(disable: 4267) #pragma warning(disable: 4996) #define L_CHECK_FLAG(var, flag) ((var&flag)) #define LG_Max(v1, v2) ((v1)>(v2))?(v1):(v2) #define LG_Min(v1, v2) ((v1)<(v2))?(v1):(v2) #define LG_Clamp(v1, min, max) ( (v1)>(max)?(max):(v1)<(min)?(min):(v1) ) /******************************* Legacy Engine Helper Macros. ********************************/ /* L_safe_free is a macro to safely free allocated memory. */ #ifndef L_safe_free #define L_safe_free(p) {if(p){LG_Free(p);(p)=LG_NULL;}} #endif /* SAFE_FREE */ #ifndef L_safe_delete_array #define L_safe_delete_array(p) {if(p){delete [] (p);(p)=LG_NULL;}} #endif //L_safe_delete_array #ifndef L_safe_delete #define L_safe_delete(p) {if(p){delete (p);(p)=LG_NULL;}} #endif //L_safe_delete /* L_safe_release is to release com objects safely. */ #ifdef __cplusplus #define L_safe_release(p) {if(p){(p)->Release();(p)=LG_NULL;}} #else /* __cplusplus */ #define L_safe_release(p) {if(p){(p)->lpVtbl->Release((p));(p)=LG_NULL;}} #endif /* __cplusplus */ /**************************************** Legacy Engine replacement functions. ****************************************/ unsigned long L_strncpy(char* szOut, const char* szIn, unsigned long nMax); char* L_strncat(char* szDest, const char* szSrc, unsigned long nMax); int L_strnicmp(const char* szOne, const char* szTwo, unsigned long nNum); float L_atovalue(char* string); signed long L_atol(char* string); float L_atof(char* string); unsigned long L_axtol(char* string); lg_dword L_strlenA(const lg_char* string); lg_dword L_strlenW(const lg_wchar* string); int L_mkdir(const char* szDir); char* L_strtokA(char* strToken, char* strDelimit, char cIgIns); lg_wchar* L_strtokW(lg_wchar* strToken, lg_wchar* strDelimit, lg_wchar cIgIns); #ifdef UNICODE #define L_strlen L_strlenW #else !UNICODE #define L_strlen L_strlenA #endif /************************************* Legacy Engine special functions. *************************************/ //L_GetPathFromPath returns the [drive:\]path\to\file portion of a [drive:\]path\to\file\name.ext. //eg. c:\My Documents\readme.txt ==> c:\My Documents\ OR base\textures\face.tga ==> base\textures\. //includes the trailing \ or /. char* L_GetPathFromPath(char* szDir, const char* szFilename); //L_GetShortNameFromPath returns the name portion of a [drive:\]path\to\file\name.ext. //eg. c:\My Documents\readme.txt ==> readme OR base\textures\face.tga ==> face. lg_char* L_GetShortNameFromPath(lg_char* szName, const char* szFilename); //Same as above but with the extension. lg_char* L_GetNameFromPath(lg_char* szName, const char* szFilename); void Debug_printfA(lg_char* format, ...); void Debug_printfW(lg_wchar_t* format, ...); #ifdef _UNICODE #define Debug_printf Debug_printfW #else _UNICODE #define Debug_printf Debug_printfA #endif _UNICODE #ifdef _DEBUG #define L_BEGIN_D_DUMP {_CrtMemState s1, s2, s3;_CrtMemCheckpoint(&s1); #define L_END_D_DUMP(txt) _CrtMemCheckpoint(&s2);\ _CrtMemDifference(&s3, &s1, &s2);\ OutputDebugString("MEMORY USAGE FOR: \""txt"\":\n");\ _CrtMemDumpStatistics(&s3);} #else /*_DEBUG*/ #define L_BEGIN_D_DUMP #define L_END_D_DUMP(txt) #endif /*_DEBUG*/ #ifdef __cplusplus } #endif /* __cplusplus */ #endif /*__COMMON_H__*/<file_sep>/games/Joes/Readme.txt Joes Copter: Flight of the Fittest v1.02 Copyright (C) 1999, <NAME> for Beem Software This folder includes: Joes1.exe - Joes Copter executables. Readme.txt - This file. Instructions: I believe the controls are as follows '8' Up '2' Down '4' Left '6' Right ESC EXIT SPACEBAR shoot ========================================================== ==== Version History === ==== for Joes Copter: Flight of the Fittest === ========================================================== v1.03 (March 21, 2006) Finally fixed the bug where if you fired at the edge of the screen the game would crash. v1.02 Controls actually work now. Some fireing issues ESC exits. Used SUB Functions for the intro and graphicsloading. v1.01 Used LOCATE function to place the text. v1.00 Onriginal release really lousy. Controls don't work properly.<file_sep>/games/Explor2002/Source/ExplorED/Wxplored.cpp /* wxplored.cpp - ExplorED for Windows Author: <NAME> for Beem Software Language: C++ Win32 API Version x.xxW */ /* Note to self: Be sure to prompt whether or not to save when quitting. Impliment property editing: either shift click or right click. Make sure if an invalid map is loaded a, no bug occurs. Rather the utility reports it, and asks to open a new map. */ #define NOCHILD #define MAXFILENAMELEN _MAX_PATH //#define MAXX 15 //#define MAXY 15 #define MAXX explormap.getMapWidth() #define MAXY explormap.getMapHeight() #define EDWNDSIZE 15 #define TWIDTH 40 #include <windows.h> #include <stdio.h> //#include <winreg.h> #include "wxplored.h" #include "mapboard.h" #include "resource.h" #ifndef NOCHILD char edAppName[]="mainWnd"; char edStatWinName[]="statWnd"; #endif //nochild char edEditWinName[]="editWnd"; static HWND hEditWnd=NULL; EXPLORMAP explormap; int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow) { MSG msg; #ifndef NOCHILD HWND hMainWnd; #endif //HWND hStatWnd; HACCEL hAccel; int errcode; TCHAR temperrmessage[100]; #ifndef NOCHILD if(!RegisterWindowClass())return 0; #endif if(!RegisterEditWindowClass())return 0; //if(!RegisterStatusWindowClass())return 0; //The following code will take the command line perameters //MessageBox(NULL, lpszCmdLine, "Notice", MB_OK); if(!(strlen(lpszCmdLine)<1)){ //errcode=explormap.openMap(lpszCmdLine); strcpy(explormap.boardname, lpszCmdLine); errcode=explormap.openMap(explormap.boardname); if(errcode!=0){ sprintf(temperrmessage, "Error #%i: Could not open map", errcode); MessageBox(NULL, temperrmessage, "Error Opening Map", MB_OK); return -1; } }else{ strcpy(explormap.boardname, "default.map"); errcode=explormap.openMap(explormap.boardname); if(errcode!=0){ sprintf(temperrmessage, "Error #%i: Could not open previously used map", errcode); MessageBox(NULL, temperrmessage, "Error Opening Map", MB_OK); return -1; } } #ifndef NOCHILD hMainWnd=CreateWindowEx(WS_EX_CLIENTEDGE|WS_EX_CONTROLPARENT|WS_EX_CONTEXTHELP, edAppName, "ExplorED", WS_DLGFRAME|WS_SYSMENU|WS_CAPTION|WS_MINIMIZEBOX|WS_SIZEBOX| WS_MAXIMIZEBOX|WS_THICKFRAME, CW_USEDEFAULT, CW_USEDEFAULT, 640,//GetSystemMetrics(SM_CXSCREEN),// 540, 480,//GetSystemMetrics(SM_CYSCREEN)-GetSystemMetrics(SM_CYCAPTION), //520, NULL, NULL, hInstance, NULL); #endif //nochild #ifdef NOCHILD hEditWnd=CreateWindow(edEditWinName, "ExplorED", WS_DLGFRAME|WS_SYSMENU|WS_CAPTION|WS_MINIMIZEBOX,//|WS_SIZEBOX| //WS_MAXIMIZEBOX|WS_THICKFRAME, CW_USEDEFAULT, CW_USEDEFAULT, TWIDTH*EDWNDSIZE+GetSystemMetrics(SM_CXSIZEFRAME)+GetSystemMetrics(SM_CXHSCROLL), TWIDTH*EDWNDSIZE+GetSystemMetrics(SM_CYSIZEFRAME)+GetSystemMetrics(SM_CYVSCROLL)+GetSystemMetrics(SM_CYCAPTION)+GetSystemMetrics(SM_CYMENUSIZE), NULL, NULL, hInstance, NULL); #endif //NOCHILD #ifndef NOCHILD DWORD editStyles=WS_CHILDWINDOW|WS_BORDER|WS_DLGFRAME|WS_SYSMENU|WS_MINIMIZEBOX|WS_VSCROLL|WS_HSCROLL; hEditWnd=CreateWindowEx(WS_EX_WINDOWEDGE, edEditWinName, "Edit Window", WS_CHILD|editStyles, 20, 20, TWIDTH*EDWNDSIZE,//+GetSystemMetrics(SM_CXHSCROLL)+GetSystemMetrics(SM_CXSIZEFRAME), TWIDTH*EDWNDSIZE,//+GetSystemMetrics(SM_CYVSCROLL)+GetSystemMetrics(SM_CYSIZEFRAME)+GetSystemMetrics(SM_CYCAPTION), hMainWnd, NULL, hInstance, NULL); #endif //NOCHILD //char buf[100]; //GetClientRect(hEditWnd, &desiredRect); //sprintf(buf, "Width: %i\nHeight: %i", desiredRect.right, desiredRect.bottom); //MessageBox(NULL, buf, "Note", MB_OK); /*hStatWnd=CreateWindowEx(NULL, edStatWinName, "Status Window", WS_BORDER|WS_DLGFRAME|WS_SYSMENU, CW_USEDEFAULT, CW_USEDEFAULT, 100, 100, hMainWnd, NULL, hInstance, NULL);*/ #ifndef NOCHILD ShowWindow(hMainWnd, nCmdShow); UpdateWindow(hMainWnd); #endif ShowWindow(hEditWnd, nCmdShow); UpdateWindow(hEditWnd); //UpdateWindow(hStatWnd); //SetFocus(hEditWnd); //ShowWindow(hStatWnd, SW_SHOWNORMAL); //if(!IsChild(hMainWnd, hEditWnd))return 0;//return if child window not successfully created hAccel=LoadAccelerators(hInstance, MAKEINTRESOURCE(IDR_ACCELERATOR1)); while(TRUE){ if(!GetMessage(&msg, NULL, 0, 0)){ //MessageBox(NULL, "Successfully Quit", "Notice", MB_OK); return msg.wParam; } if(!TranslateAccelerator(msg.hwnd, hAccel, &msg)){ TranslateMessage(&msg); DispatchMessage(&msg); } } } #ifndef NOCHILD LRESULT MainWindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { char bufmsg[100]; switch(uMsg){ case WM_CREATE:{ sprintf(bufmsg, "ExplorED - [%s]", explormap.boardname); SetWindowText(hWnd, bufmsg);break; } case WM_DESTROY:PostQuitMessage(0);break; case WM_COMMAND: MainCommandProc(hWnd, LOWORD(wParam), HIWORD(wParam), (HWND)lParam);break; case WM_PAINT: RECT vWindow; GetClientRect(hWnd, &vWindow); PAINTSTRUCT ps; HDC hDc; hDc=BeginPaint(hWnd, &ps); FillRect(hDc, &vWindow, HBRUSH(COLOR_APPWORKSPACE+1)); EndPaint(hWnd, &ps); break; case WM_SETFOCUS: SetFocus(hEditWnd); break; default: return DefWindowProc(hWnd,uMsg,wParam,lParam); } return 0L; } #endif //NOCHILD /* LRESULT StatWindowProc(HWND hWnd, unsigned msg, WORD wParam, LONG lParam) { HDC hDc; PAINTSTRUCT ps; char buf[100]; int i; switch(msg) { case WM_CREATE:break; case WM_DESTROY:break; case WM_PAINT:{ hDc=BeginPaint(hWnd, &ps); TEXTMETRIC tMetric; GetTextMetrics(hDc, &tMetric); sprintf(buf, "Tile Type: %i", explormap.getTileStat(1, 1)); TextOut(hDc, 0, 0, buf, strlen(buf)); for(i=1; i<=explormap.getNumProperty();i++){ sprintf(buf, "Property %i: %i", i, explormap.getTileStat(1, 1, i)); TextOut(hDc, 0, i*tMetric.tmHeight, buf, strlen(buf)); } EndPaint(hWnd, &ps); DeleteObject(hDc); } default: return DefWindowProc(hWnd, msg, wParam, lParam); } return 0L; } */ LRESULT EditWindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { POINTS mpoint; RECT vWindow; GetClientRect(hWnd, &vWindow); switch (msg) { #ifdef NOCHILD case WM_DESTROY:PostQuitMessage(0);break; #else case WM_DESTROY:break; #endif case WM_CREATE: UpdateScrollBar(hWnd); #ifdef NOCHILD char bufmsg[1024]; sprintf(bufmsg, "ExplorED - [%s]", explormap.boardname); SetWindowText(hWnd, bufmsg);break; #endif //NOCHILD break; case WM_LBUTTONDOWN: //This does not work correctly now mpoint=MAKEPOINTS(lParam); if(TranslatePoints(hWnd, mpoint)){ SCROLLINFO si; si.cbSize=sizeof(si); si.fMask=SIF_ALL; GetScrollInfo(hWnd, SB_VERT, &si); int vPos=si.nPos; GetScrollInfo(hWnd, SB_HORZ, &si); int hPos=si.nPos; explormap.boardEdit(mpoint.x+hPos, mpoint.y+vPos); RedrawWindow(hWnd,NULL,NULL,RDW_INVALIDATE); } break; case WM_PAINT:{ SCROLLINFO si; si.cbSize=sizeof(si); si.fMask=SIF_ALL; GetScrollInfo(hWnd, SB_HORZ, &si); int horzPos=si.nPos; GetScrollInfo(hWnd, SB_VERT, &si); int vertPos=si.nPos; EditWindowPaint(hWnd, horzPos, vertPos); break; } case WM_VSCROLL:{ //vertical or y position scrolling VertScrollManager(hWnd, LOWORD(wParam)); RedrawWindow(hWnd, NULL, NULL, RDW_INVALIDATE); }break; case WM_HSCROLL:{ //horizontal or x position scrolling HorzScrollManager(hWnd, LOWORD(wParam)); RedrawWindow(hWnd, NULL, NULL, RDW_INVALIDATE); }break; case WM_COMMAND: #ifdef NOCHILD MainCommandProc(hWnd, LOWORD(wParam), HIWORD(wParam), (HWND)lParam);break; #endif NOCHILD default:return DefWindowProc(hWnd, msg, wParam, lParam); } return 0L; } BOOL TranslatePoints(HWND hWnd, POINTS &points){ /* for(int i=0;i<EDWNDSIZE;i++){ if(i*TWIDTH<points.x&&points.x<TWIDTH*(i+1))points.x=i+1; if(i*TWIDTH<points.y&&points.y<TWIDTH*(i+1))points.y=i+1; } */ /* for(int i=0, int j=1;i<EDWNDSIZE*TWIDTH;i+=TWIDTH, j++){ if((points.x>i)&&(points.x<=i+TWIDTH))points.x=j; if((i<points.y)&&(points.y<=i+TWIDTH))points.y=j; } */ RECT rect; GetClientRect(hWnd, &rect); int cxBlock = rect.right/EDWNDSIZE; int cyBlock = rect.bottom/EDWNDSIZE; int x = points.x/cxBlock; int y = points.y/cxBlock; points.x=x+1; points.y=y+1; if(points.x>EDWNDSIZE)return FALSE; if(points.y>EDWNDSIZE)return FALSE; if(points.x<1)return FALSE; if(points.y<1)return FALSE; return TRUE; } BOOL UpdateScrollBar(HWND hWnd){ SCROLLINFO si; si.cbSize=sizeof(si); si.fMask=SIF_ALL; si.nMin=0; si.nMax=explormap.getMapWidth()-1; si.nPage=EDWNDSIZE; si.nPos=0; SetScrollInfo(hWnd, SB_HORZ, &si, TRUE); si.nMax=explormap.getMapHeight()-1; SetScrollInfo(hWnd, SB_VERT, &si, TRUE); return TRUE; } BOOL VertScrollManager(HWND hWnd, WORD nScrollCode) { SCROLLINFO si; si.cbSize=sizeof(si); si.fMask=SIF_ALL; GetScrollInfo(hWnd, SB_VERT, &si); switch (nScrollCode){ case SB_PAGEDOWN: case SB_LINEDOWN: if(si.nPos<=si.nMax-EDWNDSIZE)si.nPos++; break; case SB_PAGEUP: case SB_LINEUP: if(si.nPos>0)si.nPos--; break; case SB_BOTTOM: si.nPos=si.nMax; break; case SB_TOP: si.nPos=0; break; case SB_THUMBTRACK: si.nPos=si.nTrackPos; break; default: break; } si.fMask=SIF_POS; SetScrollInfo(hWnd, SB_VERT, &si, TRUE); return TRUE; } BOOL HorzScrollManager(HWND hWnd, WORD nScrollCode) { SCROLLINFO si; si.cbSize=sizeof(si); si.fMask=SIF_ALL; GetScrollInfo(hWnd, SB_HORZ, &si); switch (nScrollCode){ case SB_PAGERIGHT: case SB_LINERIGHT: if(si.nPos<=si.nMax-EDWNDSIZE)si.nPos++; break; case SB_PAGELEFT: case SB_LINELEFT: if(si.nPos>0)si.nPos--; break; case SB_RIGHT: si.nPos=si.nMax; break; case SB_LEFT: si.nPos=0; break; case SB_THUMBTRACK: si.nPos=si.nTrackPos; break; default: break; } si.fMask=SIF_POS; SetScrollInfo(hWnd, SB_HORZ, &si, TRUE); return TRUE; } BOOL MainCommandProc(HWND hMainWnd, WORD wCommand, WORD wNotify, HWND hControl) { char tempfilename[_MAX_PATH]; char buf[100]; int errvalue; switch (wCommand) { /* The File Menu */ case CM_FILEEXIT: DestroyWindow(hMainWnd); return 0; case CM_FILENEW: return 0; case CM_FILESAVE_AS: if (GetSaveFileName(hMainWnd, explormap.boardname)==TRUE){ //sprintf(temp, "Filename was:%s", tempfilename); //MessageBox(hMainWnd, temp, "Notice", MB_OK); //strcpy(explormap.boardname, tempfilename); sprintf(buf, "ExplorED - [%s]", explormap.boardname); SetWindowText(hMainWnd, buf); }else return 0; //Fall through and actually write to disk case CM_FILESAVE: if((explormap.saveMap(explormap.boardname)==0)) MessageBox(hMainWnd, "File Saved Successfully", "Notice", MB_OK|MB_ICONINFORMATION); return 0; case CM_FILEPRINT: return 0; case CM_FILEOPEN: strcpy(tempfilename, explormap.boardname); if(GetOpenFileName(hMainWnd, tempfilename)==TRUE){ //sprintf(temp, "Filename was:%s", tempfilename); //MessageBox(hMainWnd, temp, "Notice", MB_OK); //strcpy(explormap.boardname, tempfilename); if((errvalue=explormap.openMap(tempfilename))==0){ strcpy(explormap.boardname, tempfilename); RedrawWindow(hMainWnd, NULL,NULL, RDW_INVALIDATE); sprintf(buf, "ExplorED - [%s]", explormap.boardname); SetWindowText(hMainWnd, buf); }else{ //If fails to open map it reopens the previous map sprintf(buf, "Error %i: Map was invalid.", errvalue); MessageBox(hMainWnd, buf, "Warning Notice", MB_OK|MB_ICONWARNING); if(explormap.openMap(explormap.boardname)!=0){ //If the last used map fails we bail out. MessageBox(hMainWnd, "Could Not Reopen Current map", "Error Notice", MB_OK|MB_ICONERROR); PostQuitMessage(0); } RedrawWindow(hMainWnd, NULL, NULL, RDW_INVALIDATE); } }else return 0; UpdateScrollBar(GetWindow(hMainWnd, GW_CHILD)); return 0; } return FALSE; } int GetSaveFileName(HWND hWnd, char *filename) { OPENFILENAME ofn; ZeroMemory(&ofn, sizeof(OPENFILENAME)); ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = hWnd; ofn.lpstrFilter = "Map Files (*.map)\0*.map\0All Files (*.*)\0*.*\0"; ofn.lpstrFile = filename; ofn.nMaxFile = MAXFILENAMELEN; ofn.lpstrTitle = "Save Map As..."; ofn.Flags = OFN_OVERWRITEPROMPT|OFN_HIDEREADONLY|OFN_NONETWORKBUTTON; return GetSaveFileName(&ofn); } int GetOpenFileName(HWND hWnd, char *filename) { OPENFILENAME ofn; ZeroMemory(&ofn, sizeof(OPENFILENAME)); ofn.lStructSize = sizeof( OPENFILENAME ); ofn.hwndOwner = hWnd; // An invalid hWnd causes non-modality ofn.lpstrFilter = "Map Files (*.map)\0*.map\0All Files (*.*)\0*.*\0"; ofn.lpstrFile = filename; // Stores the result in this variable ofn.nMaxFile = MAXFILENAMELEN; ofn.lpstrTitle = "Open Map"; // Title for dialog ofn.Flags = OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_PATHMUSTEXIST; return GetOpenFileName(&ofn); } void EditWindowPaint(HWND hWnd, int minX, int minY)//, HDC hDc) { int i; int j; HDC hDc; PAINTSTRUCT ps; RECT vWindow; GetClientRect(hWnd, &vWindow); #define NODEFPAINT #ifndef NODEFPAINT const short blockheight=(vWindow.bottom)/EDWNDSIZE; const short blockwidth=(vWindow.right)/EDWNDSIZE; #else #define blockheight (vWindow.bottom)/EDWNDSIZE #define blockwidth (vWindow.right)/EDWNDSIZE #endif HBITMAP wallbitmap=(HBITMAP)LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(WALL_BITMAP), IMAGE_BITMAP, 0, 0, LR_DEFAULTCOLOR); HBITMAP doorbitmap=(HBITMAP)LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(DOOR_BITMAP), IMAGE_BITMAP, 0, 0, LR_DEFAULTCOLOR); HBITMAP blankbitmap=(HBITMAP)LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(BLANK_BITMAP), IMAGE_BITMAP, 0, 0, LR_DEFAULTCOLOR); hDc=BeginPaint(hWnd, &ps); //if(USINGXP)FillRect(hDc, &vWindow, (HBRUSH)GetStockObject(WHITE_BRUSH)); //#define PAINTGRID #ifdef PAINTGRID HPEN hpen; HGDIOBJ hpenOld; #define GRIDCOLOR RGB(0,0,0) hpen=CreatePen(PS_SOLID,2, GRIDCOLOR); hpenOld=SelectObject(hDc, hpen); //FillRect(hDc, &vWindow, (HBRUSH)GetStockObject(WHITE_BRUSH)); //Painting The Grid for(i=0; i<=EDWNDSIZE; i++){ MoveToEx(hDc, i*blockwidth, 0, NULL); LineTo(hDc, i*blockwidth, vWindow.bottom); } for(i=0; i<=EDWNDSIZE;i++){ MoveToEx(hDc, 0,i*blockheight, NULL); LineTo(hDc, vWindow.right, i*blockheight); } #endif //Paint the board for(j=minY;j<=EDWNDSIZE+minY;j++){ for(i=minX;i<=EDWNDSIZE+minX;i++){ switch (explormap.getTileStat(i, j)) { case 10: DrawState(hDc, NULL, NULL, (LPARAM)wallbitmap, 0, (i-1-minX)*blockwidth, (j-1-minY)*blockheight, 0, 0, DST_BITMAP|DSS_NORMAL); break; case 20: DrawState(hDc, NULL, NULL, (LPARAM)doorbitmap, 0, (i-1-minX)*blockwidth, (j-1-minY)*blockheight, 0, 0, DST_BITMAP|DSS_NORMAL); break; default: DrawState(hDc, NULL, NULL, (LPARAM)blankbitmap, 0, (i-1-minX)*blockwidth, (j-1-minY)*blockheight, 0, 0, DST_BITMAP|DSS_NORMAL); break; } } } EndPaint(hWnd, &ps); #ifdef PAINTGRID SelectObject(hDc, hpenOld); DeleteObject(hpen); #endif DeleteObject(wallbitmap); DeleteObject(doorbitmap); DeleteObject(blankbitmap); } #ifndef NOCHILD BOOL RegisterWindowClass(void) { WNDCLASSEX wndClass; ZeroMemory(&wndClass, sizeof(WNDCLASSEX)); wndClass.cbSize=sizeof(WNDCLASSEX); wndClass.style=NULL; wndClass.lpfnWndProc=(WNDPROC)MainWindowProc; wndClass.cbClsExtra=0; wndClass.cbWndExtra=0; wndClass.hInstance=GetModuleHandle(NULL); wndClass.hIcon=LoadIcon(wndClass.hInstance, MAKEINTRESOURCE(ICON_1)); wndClass.hCursor=LoadCursor(NULL, IDC_ARROW); wndClass.hbrBackground=(HBRUSH)(COLOR_APPWORKSPACE+1); wndClass.lpszMenuName=MAKEINTRESOURCE(MENU_MAIN); wndClass.lpszClassName=edAppName; wndClass.hIconSm=NULL; if(!RegisterClassEx(&wndClass))return FALSE; return TRUE; } #endif //nochild BOOL RegisterEditWindowClass(void) { WNDCLASSEX wndClassB; ZeroMemory(&wndClassB, sizeof(WNDCLASSEX)); wndClassB.cbSize=sizeof(WNDCLASSEX); #ifdef NOCHILD wndClassB.style=NULL; #else wndClassB.style=CS_HREDRAW|CS_VREDRAW|CS_NOCLOSE; #endif wndClassB.lpfnWndProc=(WNDPROC)EditWindowProc; wndClassB.cbClsExtra=0; wndClassB.cbWndExtra=0; wndClassB.hInstance=GetModuleHandle(NULL); wndClassB.hIcon=LoadIcon(wndClassB.hInstance, MAKEINTRESOURCE(IDI_ICON3)); wndClassB.hCursor=LoadCursor(NULL, IDC_CROSS); wndClassB.hbrBackground=(HBRUSH)GetStockObject(WHITE_BRUSH); #ifdef NOCHILD wndClassB.lpszMenuName=MAKEINTRESOURCE(MENU_MAIN); #else wndClassB.lpszMenuName=NULL; #endif //nochild wndClassB.lpszClassName=edEditWinName; wndClassB.hIconSm=NULL; if(!RegisterClassEx(&wndClassB))return FALSE; return TRUE; } /* BOOL RegisterStatusWindowClass(void) { WNDCLASSEX wndClass; ZeroMemory(&wndClass, sizeof(WNDCLASSEX)); wndClass.cbSize=sizeof(WNDCLASSEX); wndClass.style=CS_HREDRAW|CS_VREDRAW; wndClass.lpfnWndProc=(WNDPROC)StatWindowProc; wndClass.cbClsExtra=0; wndClass.cbWndExtra=0; wndClass.hInstance=GetModuleHandle(NULL); wndClass.hIcon=LoadIcon(wndClass.hInstance, MAKEINTRESOURCE(IDI_ICON3)); wndClass.hCursor=LoadCursor(NULL, IDC_ARROW); wndClass.hbrBackground=(HBRUSH)GetStockObject(WHITE_BRUSH); wndClass.lpszMenuName=NULL; wndClass.lpszClassName=edStatWinName; wndClass.hIconSm=NULL; if(!RegisterClassEx(&wndClass))return FALSE; return TRUE; } */ <file_sep>/games/Legacy-Engine/Source/engine/ls_sndfile.h #ifndef __LS_SNDFILE_H__ #define __LS_SNDFILE_H__ #include <windows.h> #include "common.h" class CLSndFile { private: struct SNDCALLBACKS{ void* (*Snd_CreateFromDisk)(char*); /*void* (*Snd_CreateFromData)(void*, lg_dword);*/ lg_bool (*Snd_Delete)(void*); lg_dword (*Snd_Read)(void*, void*, lg_dword); lg_bool (*Snd_Reset)(void*); WAVEFORMATEX* (*Snd_GetFormat)(void*, WAVEFORMATEX*); lg_dword (*Snd_GetSize)(void*); lg_bool (*Snd_IsEOF)(void*); }; SNDCALLBACKS m_CB; lg_void* m_pSnd; lg_dword m_nChannels; lg_dword m_nBitsPerSample; lg_dword m_nSamplesPerSecond; lg_dword m_nDataSize; lg_bool m_bOpen; void SetupCallbacks(lg_str szType); public: CLSndFile(); ~CLSndFile(); lg_bool Open(lg_str szFilename); void Close(); lg_dword Read(lg_void* pBuffer, lg_dword nSize); lg_bool Reset(); lg_dword GetNumChannels(); lg_dword GetBitsPerSample(); lg_dword GetSamplesPerSecond(); lg_dword GetDataSize(); lg_bool IsEOF(); }; #endif __LS_SNDFILE_H__<file_sep>/games/Legacy-Engine/Scrapped/libs/ML_lib2008April/ML_vec3C.c #include "ML_lib.h" ML_VEC4* ML_FUNC ML_Vec3TransformArray(ML_VEC4* pOut, ml_uint nOutStride, const ML_VEC3* pV, ml_uint nInStride, const ML_MAT* pM, ml_uint nNum) { ml_uint i; for(i=0; i<nNum; i++) ML_Vec3Transform((ML_VEC4*)((ml_byte*)pOut+i*nOutStride), (ML_VEC3*)((ml_byte*)pV+i*nInStride), pM); return pOut; } ML_VEC3* ML_FUNC ML_Vec3TransformCoordArray(ML_VEC3* pOut, ml_uint nOutStride, const ML_VEC3* pV, ml_uint nInStride, const ML_MAT* pM, ml_uint nNum) { ml_uint i; for(i=0; i<nNum; i++) ML_Vec3TransformCoord((ML_VEC3*)((ml_byte*)pOut+i*nOutStride), (ML_VEC3*)((ml_byte*)pV+i*nInStride), pM); return pOut; } ML_VEC3* ML_FUNC ML_Vec3TransformNormalArray(ML_VEC3* pOut, ml_uint nOutStride, const ML_VEC3* pV, ml_uint nInStride, const ML_MAT* pM, ml_uint nNum) { ml_uint i; for(i=0; i<nNum; i++) ML_Vec3TransformNormal((ML_VEC3*)((ml_byte*)pOut+i*nOutStride), (ML_VEC3*)((ml_byte*)pV+i*nInStride), pM); return pOut; }<file_sep>/games/Legacy-Engine/Source/lc_sys2/lc_cinterface.cpp #include <stdarg.h> #include <stdio.h> #include <string.h> #include "lc_con.h" #include "lc_sys2.h" #include "lc_cvar.h" #include "common.h" CConsole* g_pCon=LG_NULL; CCvarList* g_pCvars=LG_NULL; extern "C" { void LC_FUNC LC_ListCvars(const lg_char* szLimit) { if(!g_pCon || !g_pCvars) return; g_pCon->Print("Registered cvars:"); lg_cvar* cvar=g_pCvars->GetFirst(); while(cvar) { if(szLimit) { if(strnicmp(szLimit, cvar->szName, strlen(szLimit))!=0) { cvar=g_pCvars->GetNext(); continue; } } g_pCon->Printf(" %s (\"%s\", %.2f, %d)", cvar->szName, cvar->szValue, cvar->fValue, cvar->nValue); cvar=g_pCvars->GetNext(); } } lg_bool LC_FUNC LC_Init() { if(g_pCon) { g_pCon->Print("LC_Init WARNING: Console has already been initialized."); return LG_TRUE; } g_pCon=new CConsole; if(g_pCvars) { g_pCon->Print("LC_Init WARNING: Cvars have already been initialized."); } g_pCvars=new CCvarList; if(g_pCon && g_pCvars) return LG_TRUE; else { L_safe_delete(g_pCon); L_safe_delete(g_pCvars); return LG_FALSE; } } void LC_FUNC LC_Shutdown() { L_safe_delete(g_pCvars); L_safe_delete(g_pCon); } void LC_FUNC LC_SetCommandFunc(LC_CMD_FUNC pfn, lg_void* pExtra) { if(!g_pCon) return; g_pCon->SetCommandFunc(pfn, pExtra); } void LC_FUNC LC_Print(lg_char* szText) { if(!g_pCon) return; g_pCon->Print(szText); } void LC_FUNC LC_Printf(lg_char* szFormat, ...) { if(!g_pCon) return; va_list arglist; va_start(arglist, szFormat); _vsnprintf(CConsole::s_szTemp, LC_MAX_LINE_LEN, szFormat, arglist); va_end(arglist); LC_Print(CConsole::s_szTemp); } void LC_FUNC LC_SendCommand(const lg_char* szCmd) { if(!g_pCon) return; g_pCon->SendCommand((lg_char*)szCmd); } void LC_FUNC LC_SendCommandf(lg_char* szFormat, ...) { if(!g_pCon) return; va_list arglist; va_start(arglist, szFormat); _vsnprintf(CConsole::s_szTemp, LC_MAX_LINE_LEN, szFormat, arglist); va_end(arglist); LC_SendCommand(CConsole::s_szTemp); } const lg_char* LC_FUNC LC_GetLine(lg_dword nRef, const lg_bool bStartWithNew) { if(!g_pCon) return LG_NULL; return g_pCon->GetLine(nRef, bStartWithNew); } const lg_char* LC_FUNC LC_GetOldestLine() { if(!g_pCon) return LG_NULL; return g_pCon->GetOldestLine(); } const lg_char* LC_FUNC LC_GetNewestLine() { if(!g_pCon) return LG_NULL; return g_pCon->GetNewestLine(); } const lg_char* LC_FUNC LC_GetNextLine() { if(!g_pCon) return LG_NULL; return g_pCon->GetNextLine(); } lg_bool LC_FUNC LC_RegisterCommand(lg_char* szCmd, lg_dword nID, lg_char* szHelpString) { if(!g_pCon) return LG_NULL; return g_pCon->RegisterCommand(szCmd, nID, szHelpString); } void LC_FUNC LC_ListCommands() { if(!g_pCon) return; g_pCon->ListCommands(); } const lg_char* LC_FUNC LC_GetArg(lg_dword nParam, lg_void* pParams) { return CConsole::GetArg(nParam, pParams); } lg_bool LC_FUNC LC_CheckArg(const lg_char* string, lg_void* args) { return CConsole::CheckArg(string, args); } void LC_FUNC LC_Clear() { if(!g_pCon) return; g_pCon->Clear(); } lg_dword LC_FUNC LC_GetNumLines() { if(!g_pCon) return 0; return g_pCon->m_nLineCount; } const lg_char* LC_FUNC LC_GetActiveLine() { if(!g_pCon) return LG_NULL; return g_pCon->GetActiveLine(); } void LC_FUNC LC_OnChar(lg_char c) { if(!g_pCon) return; g_pCon->OnChar(c); } lg_cvar* LC_FUNC CV_Register(const lg_char* szName, const lg_char* szValue, lg_dword Flags) { if(!g_pCvars) return LG_NULL; lg_cvar* pCvar=g_pCvars->Register(szName, szValue, Flags); if(pCvar) LC_Printf("Registered \"%s\" (\"%s\", %.2f, %d).", pCvar->szName, pCvar->szValue, pCvar->fValue, pCvar->nValue); else LC_Printf("CV_Register ERROR: Could not register \"%s\", check name.", szName); return pCvar; } lg_bool LC_FUNC CV_Define_l(lg_char* szDef, lg_long nValue) { if(!g_pCvars) return LG_FALSE; return g_pCvars->Define(szDef, nValue); } lg_bool LC_FUNC CV_Define_f(const lg_char* szDef, lg_float fValue) { if(!g_pCvars) return LG_FALSE; return g_pCvars->Define((lg_char*)szDef, fValue); } lg_cvar* LC_FUNC CV_Get(const lg_char* szName) { if(!g_pCvars) return LG_NULL; return g_pCvars->Get(szName); } void LC_FUNC CV_Set(lg_cvar* cvar, const lg_char* szValue) { if(!g_pCvars || !cvar) return; return CCvarList::Set(cvar, (lg_char*)szValue, &g_pCvars->m_Defs); } void LC_FUNC CV_Set_l(lg_cvar* cvar, lg_long nValue) { if(!cvar) return; return CCvarList::Set(cvar, nValue); } void LC_FUNC CV_Set_f(lg_cvar* cvar, lg_float fValue) { if(!cvar) return; return CCvarList::Set(cvar, fValue); } LC_EXP lg_cvar* LC_FUNC CV_GetFirst() { if(!g_pCvars) return LG_NULL; return g_pCvars->GetFirst(); } LC_EXP lg_cvar* LC_FUNC CV_GetNext() { if(!g_pCvars) return LG_NULL; return g_pCvars->GetNext(); } } //extern "C" #if 0 #ifdef _DEBUG #include <windows.h> #include <crtdbg.h> #include <common.h> #include "lg_malloc.h" BOOL WINAPI DllMain(HINSTANCE hInst, DWORD fdwReason, LPVOID lpReserved) { static _CrtMemState s1, s2, s3; switch(fdwReason) { //case DLL_THREAD_ATTACH: case DLL_PROCESS_ATTACH: _CrtMemCheckpoint(&s1); break; //case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: Debug_printf("lc_sys2 Shutdown...\n"); OutputDebugString("MEMORY USAGE FOR \"lc_sys2.dll\"\"\n"); _CrtMemCheckpoint(&s2); _CrtMemDifference(&s3, &s1, &s2); _CrtMemDumpStatistics(&s3); _CrtDumpMemoryLeaks(); LG_MemDbgOutput(); break; } return TRUE; } #endif /*_DEBUG*/ #endif<file_sep>/games/Legacy-Engine/Source/engine/wnd_sys/wnd_window.h #pragma once #include "lg_types.h" #include "lv_img2d.h" #include "lv_sys.h" namespace wnd_sys{ class CWindow: private CElementD3D{ private: lg_long m_nX, m_nY; //The position. lg_long m_nWidth, m_nHeight; //Width and height of window. lg_dword m_nFlags; CLImg2D m_Img; public: //FLAGS static const lg_dword WND_CREATED=0x00000001; public: CWindow(); ~CWindow(); void Create(lg_long nX, lg_long nY, lg_long nWidth, lg_long nHeight); void Destroy(); void Render(); }; } //namespace wnd_sys<file_sep>/games/Legacy-Engine/Source/common/lg_func.h /* lg_func.h - Additional functions for the usage in the legacy engine. */ #ifndef __LG_FUNC_H__ #define __LG_FUNC_H__ #include "lg_types.h" /******************************** Disable some of VCs warnings *********************************/ #pragma warning(disable: 4267) #pragma warning(disable: 4996) #ifdef __cplusplus extern "C"{ #endif __cplusplus #define LG_CheckFlag(var, flag) (var&flag) #define LG_SetFlag(var, flag) (var|=flag) #define LG_UnsetFlag(var, flag) (var&=~flag) #define LG_Max(v1, v2) ((v1)>(v2))?(v1):(v2) #define LG_Min(v1, v2) ((v1)<(v2))?(v1):(v2) #define LG_Clamp(v1, min, max) ( (v1)>(max)?(max):(v1)<(min)?(min):(v1) ) /******************************* Legacy Engine Helper Macros. ********************************/ /* L_safe_free is a macro to safely free allocated memory. */ #ifndef LG_SafeFree #define LG_SafeFree(p) {if(p){LG_Free(p);(p)=LG_NULL;}} #endif /* LG_SafeFree */ #ifndef LG_SafeDeleteArray #define LG_SafeDeleteArray(p) {if(p){delete [] (p);(p)=LG_NULL;}} #endif /* LG_SafeDeleteArray */ #ifndef LG_SafeDelete #define LG_SafeDelete(p) {if(p){delete (p);(p)=LG_NULL;}} #endif /* LG_SafeDelete */ /* L_safe_release is to release com objects safely. */ #ifdef __cplusplus #define LG_SafeRelease(p) {if(p){(p)->Release();(p)=LG_NULL;}} #else /* __cplusplus */ #define LG_SafeRelease(p) {if(p){(p)->lpVtbl->Release((p));(p)=LG_NULL;}} #endif /* __cplusplus */ /* LG_strncpy & LG_wcsncpy Notes: Same as c runtime functions strncpy & wcsncpy but insures that a null termination character is appended. */ lg_char* LG_strncpy(lg_char* strDest, const lg_char* strSrc, lg_size_t count); lg_wchar_t* LG_wcsncpy(lg_wchar_t* strDest, const lg_wchar_t* strSrc, lg_size_t count); /* Just a filename manipulation function, gets just the name of the file and not the path or extension. */ lg_char* LG_GetShortNameFromPathA(lg_char* szName, const lg_char* szFilename); /*LG_RandomSeed PRE:N/A POST: Sets the seed for the LG_Random* functions. */ void LG_RandomSeed(lg_uint Seed); /*LG_RandomFloat PRE:Any float values are fine. POST:A random number float is returned with the value between fMin and fMax, inclusive. */ lg_float LG_RandomFloat(lg_float fMin, lg_float fMax); /*LG_RandomLong PRE:Any long values are fine. POST: A random long is returned between nMin and nMac inclusive. */ lg_long LG_RandomLong(lg_long nMin, lg_long nMax); /*LG_Hash - hasing Function*/ lg_dword LG_Hash(lg_char* szString); /*LG_HashFilename - Hashes only the filename, ignores directories.*/ lg_dword LG_HashFilename(lg_char* szPath); #ifdef __cplusplus } /* extern "C" */ #endif __cplusplus #endif __LG_FUNC_H__<file_sep>/games/Legacy-Engine/Source/engine/lv_img2d.cpp #include <d3dx9.h> #include "common.h" #include "lv_img2d.h" #include "lf_sys2.h" #include "lg_func.h" #include "lg_tmgr.h" lg_dword g_ViewWidth=0, g_ViewHeight=0; lg_bool g_bDrawingStarted=LG_FALSE; /************************************************* *** CLImg2D - The Legacy Engine 2D Image Class *** *************************************************/ CLImg2D::CLImg2D(): m_pDevice(0), m_pTexture(0), m_pVB(0), m_dwWidth(0), m_dwHeight(0), m_bIsColor(0), m_bFromTexture(0), m_pCreate(0), m_dwTransparent(0) { memset(m_Vertices, 0, sizeof(m_Vertices)); memset(m_szFilename, 0, sizeof(m_szFilename)); memset(&m_rcSrc, 0, sizeof(m_rcSrc)); } CLImg2D::~CLImg2D() { Delete(); } void CLImg2D::Delete() { /* Release the texture and VB. */ //L_safe_release(m_pTexture); m_pTexture=0; L_safe_release(m_pVB); L_safe_release(m_pDevice); m_pDevice=0; m_pTexture=0; m_pVB=0; m_dwWidth=0; m_dwHeight=0; m_bIsColor=0; m_bFromTexture=0; m_pCreate=0; m_dwTransparent=0; memset(m_Vertices, 0, sizeof(m_Vertices)); memset(m_szFilename, 0, sizeof(m_szFilename)); memset(&m_rcSrc, 0, sizeof(m_rcSrc)); } lg_bool CLImg2D::CreateFromFile( IDirect3DDevice9* lpDevice, char* szFilename, lg_rect* rcSrc, lg_dword dwWidth, lg_dword dwHeight, lg_dword dwTransparent) { Delete(); HRESULT hr=0; if(!lpDevice) return LG_FALSE; m_pTexture=NULL; m_pVB=NULL; m_pCreate=LG_NULL; m_dwWidth=dwWidth; m_dwHeight=dwHeight; LG_strncpy(m_szFilename, szFilename, LG_MAX_PATH); m_dwTransparent=dwTransparent; if(rcSrc) memcpy(&m_rcSrc, rcSrc, sizeof(lg_rect)); else memset(&m_rcSrc, 0, sizeof(lg_rect)); m_pDevice=lpDevice; m_pDevice->AddRef(); m_bIsColor=LG_FALSE; m_bFromTexture=LG_FALSE; /* Create the texture and vertex buffer by validating the image.*/ if(!Validate(LG_NULL)) { L_safe_release(m_pDevice); return LG_FALSE; } return LG_TRUE; } lg_bool CLImg2D::CreateFromColor( IDirect3DDevice9* lpDevice, lg_dword dwWidth, lg_dword dwHeight, lg_dword dwColor) { Delete(); HRESULT hr=0; if(!lpDevice) return LG_FALSE; m_pTexture=LG_NULL; m_pVB=LG_NULL; m_dwHeight=dwHeight; m_dwWidth=dwWidth; m_bIsColor=LG_TRUE; SetVertices(LG_NULL, 0.0f, 0.0f, (float)dwWidth, (float)dwHeight); m_pDevice=lpDevice; m_pDevice->AddRef(); /* Set the color. */ m_Vertices[0].Diffuse=dwColor; m_Vertices[1].Diffuse=dwColor; m_Vertices[2].Diffuse=dwColor; m_Vertices[3].Diffuse=dwColor; /* Create the vertex buffer by validate image. */ if(!Validate(LG_NULL)) { //L_safe_release(m_pTexture); m_pTexture=0; L_safe_release(m_pDevice); return LG_FALSE; } return LG_TRUE; } lg_bool CLImg2D::Render(float x, float y) { HRESULT hr=0; D3DXMATRIX TempMatrix; if(!m_pVB) return FALSE; /* The start stop drawing function needs to be called prior to 2D rendering. */ if(!g_bDrawingStarted) return LG_FALSE; D3DXMatrixIdentity(&TempMatrix); D3DXMatrixTranslation(&TempMatrix, x-(float)(g_ViewWidth/2), (float)(g_ViewHeight/2)-y, 0.0f); m_pDevice->SetTransform(D3DTS_WORLD, &TempMatrix); /* Set the texture. */ //m_pDevice->SetTexture(0, (LPDIRECT3DBASETEXTURE9)m_pTexture); CLTMgr::TM_SetTexture(m_pTexture, 0); /* Render the image. */ m_pDevice->SetStreamSource(0, m_pVB, 0, sizeof(LV2DIMGVERTEX)); m_pDevice->DrawPrimitive(D3DPT_TRIANGLEFAN, 0, 2); return LG_TRUE; } lg_bool CLImg2D::Validate(void* pExtra) { HRESULT hr=0; LPVOID lpVertices=LG_NULL; LF_FILE3 fin=LG_NULL; D3DSURFACE_DESC TexDesc; lg_rect* rcSrc=LG_NULL; if(m_pVB) return LG_FALSE; if(m_bFromTexture && pExtra) { memcpy(&m_pTexture, pExtra, sizeof(tm_tex)); //m_pTexture=(tm_tex)pExtra; //IDirect3DTexture9_AddRef(m_pTexture); } /* Reload the texture. */ if(!m_bIsColor) { if(!m_bFromTexture) { /* if(!Tex_Load( m_pDevice, m_szFilename, D3DPOOL_DEFAULT, m_dwTransparent, LG_TRUE, &m_pTexture)) return LG_FALSE; */ m_pTexture=CLTMgr::TM_LoadTex(m_szFilename, CLTMgr::TM_FORCENOMIP);//Tex_Load2(m_szFilename, LG_TRUE); if(!m_pTexture) return LG_FALSE; } memset(&TexDesc, 0, sizeof(TexDesc)); #if 0 m_pTexture->GetLevelDesc(0, &TexDesc); if(m_dwHeight==-1) m_dwHeight=TexDesc.Height; if(m_dwWidth==-1) m_dwWidth=TexDesc.Width; if(m_rcSrc.bottom==0 && m_rcSrc.right==0) rcSrc=LG_NULL; else rcSrc=&m_rcSrc; #endif SetVertices( rcSrc, (float)TexDesc.Width, (float)TexDesc.Height, (float)m_dwWidth, (float)m_dwHeight); } /* Create the vertex buffer. */ hr=m_pDevice->CreateVertexBuffer( sizeof(LV2DIMGVERTEX)*4, 0, LV2DIMGVERTEX_TYPE, D3DPOOL_DEFAULT, &m_pVB, NULL); if(LG_FAILED(hr)) { //L_safe_release(m_pTexture); m_pTexture=0; return LG_FALSE; } /* Copy over the transformed vertices. */ hr=m_pVB->Lock(0, sizeof(LV2DIMGVERTEX)*4, &lpVertices, 0); if(LG_FAILED(hr)) { //L_safe_release(m_pTexture); m_pTexture=0; return LG_FALSE; } memcpy(lpVertices, &m_Vertices, sizeof(LV2DIMGVERTEX)*4); hr=m_pVB->Unlock(); return LG_TRUE; } void CLImg2D::Invalidate() { /* Release the vertex buffer and texture.*/ //L_safe_release(m_pTexture); m_pTexture=0; L_safe_release(m_pVB); } __inline void CLImg2D::SetVertices( lg_rect* rcSrc, float fTexWidth, float fTexHeight, float fWidth, float fHeight) { /* If no src rectangle was passed we use the whole thing. Otherwise we adjust the texture coordinates appropriately.*/ if(!rcSrc) { m_Vertices[0].tu= m_Vertices[3].tu=0.0f; m_Vertices[1].tu= m_Vertices[2].tu=1.0f; m_Vertices[2].tv= m_Vertices[3].tv=1.0f; m_Vertices[0].tv= m_Vertices[1].tv=0.0f; } else { float fxscale=fTexWidth; m_Vertices[0].tu= m_Vertices[3].tu=(float)rcSrc->left/fTexWidth; m_Vertices[1].tu= m_Vertices[2].tu=(float)(rcSrc->right+rcSrc->left)/fTexWidth; m_Vertices[2].tv= m_Vertices[3].tv=(float)(rcSrc->bottom+rcSrc->top)/fTexHeight; m_Vertices[0].tv= m_Vertices[1].tv=(float)(rcSrc->top)/fTexHeight; } /* Set all the z values to 0.0f. */ m_Vertices[0].z= m_Vertices[1].z= m_Vertices[2].z= m_Vertices[3].z=0.0f; /* Set all the diffuse to white. */ m_Vertices[0].Diffuse= m_Vertices[1].Diffuse= m_Vertices[2].Diffuse= m_Vertices[3].Diffuse=0xFFFFFFFFl; /* Set up the initial vertices. */ m_Vertices[0].x=0.0f; m_Vertices[0].y=0.0f; m_Vertices[1].x=fWidth; m_Vertices[1].y=0.0f; m_Vertices[2].x=fWidth; m_Vertices[2].y=-fHeight; m_Vertices[3].x=0.0f; m_Vertices[3].y=-fHeight; } /* The StartStopDrawing function is used to start or stop drawing, the idea behind it is that it saves a few values, sets up the transformation matrices for use with 2d drawing, and when you stop drawing, it restores some of the saved values. */ lg_bool CLImg2D::StartStopDrawing(IDirect3DDevice9* lpDevice, lg_dword Width, lg_dword Height, lg_bool bStart) { static lg_dword dwPrevFVF=0; static lg_dword dwOldCullMode=0; static lg_dword dwOldAA=0; //static LPDIRECT3DVERTEXSHADER9 lpOldVS=NULL; static lg_dword dwOldAlphaEnable=0, dwOldSrcBlend=0, dwOldDestBlend=0, dwOldAlphaA=0; static lg_dword dwOldZEnable=0; static lg_dword dwOldLighting=0; static lg_dword dwOldMipFilter=0; static lg_dword dwOldMinFilter=0; static lg_dword dwOldMagFilter=0; static lg_dword dwOldFill=0; if(bStart) { /* Initialize all the projection matrices for 2d drawing. */ D3DXMATRIX TempMatrix; g_ViewWidth=Width; g_ViewHeight=Height; D3DXMatrixOrthoLH(&TempMatrix, (float)Width, (float)Height, 0.0f, 1.0f); //D3DXMatrixIdentity(&TempMatrix); lpDevice->SetTransform(D3DTS_PROJECTION, &TempMatrix); lpDevice->SetTransform(D3DTS_VIEW, D3DXMatrixIdentity(&TempMatrix)); /* Save the old filter modes. */ IDirect3DDevice9_GetSamplerState(lpDevice, 0, D3DSAMP_MAGFILTER, &dwOldMagFilter); IDirect3DDevice9_GetSamplerState(lpDevice, 0, D3DSAMP_MINFILTER, &dwOldMinFilter); IDirect3DDevice9_GetSamplerState(lpDevice, 0, D3DSAMP_MIPFILTER, &dwOldMipFilter); IDirect3DDevice9_SetSamplerState(lpDevice, 0, D3DSAMP_MAGFILTER, D3DTEXF_POINT); IDirect3DDevice9_SetSamplerState(lpDevice, 0, D3DSAMP_MINFILTER, D3DTEXF_NONE); IDirect3DDevice9_SetSamplerState(lpDevice, 0, D3DSAMP_MIPFILTER, D3DTEXF_NONE); /* Save some rendering state values, they will be restored when this function is called with bStart set to FALSE. */ lpDevice->GetRenderState(D3DRS_LIGHTING, &dwOldLighting); lpDevice->SetRenderState(D3DRS_LIGHTING, FALSE); /* Get and set FVF. */ lpDevice->GetFVF(&dwPrevFVF); lpDevice->SetFVF(LV2DIMGVERTEX_TYPE); /* Get and set vertex shader. */ //lpDevice->lpVtbl->GetVertexShader(lpDevice, &lpOldVS); //lpDevice->lpVtbl->SetVertexShader(lpDevice, NULL); /* Get and set cull mode. */ lpDevice->GetRenderState(D3DRS_CULLMODE, &dwOldCullMode); lpDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW); /* Set alpha blending. */ lpDevice->GetRenderState(D3DRS_ALPHABLENDENABLE, &dwOldAlphaEnable); lpDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); lpDevice->GetRenderState(D3DRS_SRCBLEND, &dwOldSrcBlend); lpDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); lpDevice->GetRenderState(D3DRS_DESTBLEND, &dwOldDestBlend); lpDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); lpDevice->GetTextureStageState(0, D3DTSS_ALPHAARG1, &dwOldAlphaA); lpDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); /* Get and set z-buffer status. */ lpDevice->GetRenderState(D3DRS_ZENABLE, &dwOldZEnable); lpDevice->SetRenderState(D3DRS_ZENABLE, FALSE); lpDevice->GetRenderState(D3DRS_MULTISAMPLEANTIALIAS, &dwOldAA); lpDevice->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, LG_FALSE); lpDevice->GetRenderState(D3DRS_FILLMODE, &dwOldFill); IDirect3DDevice9_SetRenderState(lpDevice, D3DRS_FILLMODE, D3DFILL_SOLID); g_bDrawingStarted=LG_TRUE; } else { /* Restore all saved values. */ lpDevice->SetFVF(dwPrevFVF); //lpDevice->SetVertexShader(lpOldVS); lpDevice->SetRenderState(D3DRS_CULLMODE, dwOldCullMode); /* Restore alpha blending state. */ lpDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, dwOldAlphaEnable); lpDevice->SetRenderState(D3DRS_SRCBLEND, dwOldSrcBlend); lpDevice->SetRenderState(D3DRS_DESTBLEND, dwOldDestBlend); lpDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, dwOldAlphaA); /* Restore Z-Buffering status. */ lpDevice->SetRenderState(D3DRS_ZENABLE, dwOldZEnable); lpDevice->SetRenderState(D3DRS_LIGHTING, dwOldLighting); lpDevice->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, dwOldAA); IDirect3DDevice9_SetRenderState(lpDevice, D3DRS_FILLMODE, dwOldFill); IDirect3DDevice9_SetSamplerState(lpDevice, 0, D3DSAMP_MAGFILTER, dwOldMagFilter); IDirect3DDevice9_SetSamplerState(lpDevice, 0, D3DSAMP_MINFILTER, dwOldMinFilter); IDirect3DDevice9_SetSamplerState(lpDevice, 0, D3DSAMP_MIPFILTER, dwOldMipFilter); g_bDrawingStarted=LG_FALSE; } return LG_TRUE; } <file_sep>/games/Legacy-Engine/Source/engine/ls_stream.h #ifndef __LS_STREAM_H__ #define __LS_STREAM_H__ #include <al/al.h> #include "ls_sndfile.h" #include "lt_sys.h" //The sound stream class is primarily used for background //music, but can also be used for long portions of audio such //as dialogs, etc... class CLSndStream { private: ALuint m_Buffers[2]; ALuint m_Source; ALenum m_nFormat; CLSndFile m_cSndFile; lg_void* m_pTempBuffer; //Buffer to hold a few seconds worth of data lg_dword m_nTempBufferSize; lg_bool m_bOpen; lg_bool m_bLoop; lg_bool m_bPlaying; lg_bool m_bPaused; __inline lg_bool CheckError(); lg_bool UpdateBuffer(ALuint buffer); public: CLSndStream(); ~CLSndStream(); lg_bool Load(lg_str szPath); void Close(); void Play(lg_bool bLoop=LG_TRUE); void Stop(); void Pause(); void Update(); void SetVolume(lg_int nVolume); }; #endif __LS_STREAM_H__<file_sep>/samples/D3DDemo/code/GFX3D9/BeemConsole.c /* BeemConsole.c - Functionality for the Beem Console(tm). Copyright (c) 2003 <NAME> */ #define MAX_CHARSPERLINE 100 #define LINE_BUFFER_SIZE 500 #include <d3dx9.h> #include <stdio.h> #include "GFX3D9.h" #include "resource.h" /* ================================= Command Parsing Helper functions. =================================*/ BOOL BeemParseGetFloat( FLOAT * lpValue, LPSTR szParams, WORD wParam) { char szTemp[100]; if(!BeemParseGetParam(szTemp, szParams, wParam)){ *lpValue=0.0f; return FALSE; } *lpValue=(FLOAT)atof(szTemp); return TRUE; } BOOL BeemParseGetInt( LONG * lpValue, LPSTR szParams, WORD wParam) { char szTemp[100]; if(!BeemParseGetParam(szTemp, szParams, wParam)){ *lpValue=0; return FALSE; } *lpValue=atol(szTemp); return TRUE; } BOOL BeemParseGetString( LPSTR szStringOut, LPSTR szString) { DWORD dwLen=0, i=0, j=0; BOOL bInQuotes=FALSE; BOOL bFoundString=FALSE; dwLen=strlen(szString); for(i=0, j=0; i<dwLen; i++){ if(bInQuotes){ if(szString[i]=='\"'){ bFoundString=TRUE; break; } szStringOut[j]=szString[i]; j++; }else{ if(szString[i]=='\"') bInQuotes=TRUE; } } szStringOut[j]=0; if(bFoundString) return TRUE; else return FALSE; } BOOL BeemParseGetParam( LPSTR szParamOut, LPSTR szParams, WORD wParam) { DWORD dwLen=0, i=0, j=0; BOOL bFoundParam=FALSE; if(wParam < 1) return FALSE; dwLen=strlen(szParams); /* Find the space char corresponding with the param. */ wParam--; for(i=0, j=0; i<dwLen; i++){ if(wParam==0){ if(szParams[i]==' ') break; szParamOut[j]=szParams[i]; j++; }else{ if(szParams[i]==' '){ wParam--; } } } szParamOut[j]=0; if(strlen(szParamOut) < 1 ) return FALSE; else return TRUE; } /* ========================= Beem Console Private Data =========================*/ typedef struct tagBEEMENTRY{ LPSTR lpstrText; struct tagBEEMENTRY * lpNext; }BEEMENTRY, *LPBEEMENTRY; typedef struct tagBEEMCONSOLE{ DWORD dwNumEntries; BEEMENTRY * lpActiveEntry; BEEMENTRY * lpEntryList; LPCOMMAND CommandFunction; HD3DFONT ConsoleFont; HD3DIMAGE ConsoleBG; BOOL bConsoleActive; BOOL bDeactivating; LONG lPosition; DWORD dwScrollPos; DWORD dwLastUpdate; LPDIRECT3DDEVICE9 lpDevice; }BEEMCONSOLE, *LPBEEMCONSOLE; /* Beem Console Private Functions declarations. */ BOOL BeemConsoleRemoveLastEntry( HBEEMCONSOLE lpConsole); BOOL BeemConsoleSimpleParse( char szCommand[MAX_CHARSPERLINE], char szParams[MAX_CHARSPERLINE], char szIgnore[128], LPSTR szLineIn); BOOL BeemConsoleEraseInput( HBEEMCONSOLE lpConsole); /* ============================== BeemConsole Private Functions. ==============================*/ BOOL BeemConsoleRemoveLastEntry( HBEEMCONSOLE lpConsole) { LPBEEMENTRY lpCurrent=NULL; LPBEEMENTRY lpPrev=NULL; if(!lpConsole) return FALSE; if(((LPBEEMCONSOLE)lpConsole)->lpEntryList==NULL) return FALSE; lpCurrent=((LPBEEMCONSOLE)lpConsole)->lpEntryList; if(lpCurrent->lpNext==NULL) return TRUE; while(lpCurrent->lpNext){ lpPrev=lpCurrent; lpCurrent=lpCurrent->lpNext; } /* Remove the last entry and set it's previous entry as the last entry. */ SAFE_FREE(lpCurrent->lpstrText); SAFE_FREE(lpCurrent); lpPrev->lpNext=NULL; ((LPBEEMCONSOLE)lpConsole)->dwNumEntries--; return TRUE; } BOOL BeemConsoleEraseInput( HBEEMCONSOLE lpConsole) { if(lpConsole==NULL) return FALSE; if(!((LPBEEMCONSOLE)lpConsole)->lpActiveEntry) return FALSE; ((LPBEEMCONSOLE)lpConsole)->lpActiveEntry->lpstrText[0]=0; return TRUE; } BOOL BeemConsoleSimpleParse( char szCommand[MAX_CHARSPERLINE], char szParams[MAX_CHARSPERLINE], char szIgnore[128], LPSTR szLineIn) { char szTemp[MAX_CHARSPERLINE]; DWORD dwLen=0, i=0, j=0, k=0, dwSpaces=0; BOOL bFoundChar=FALSE, bIgnore=FALSE; DWORD dwIgnoreLen=0; dwLen=strlen(szLineIn); dwIgnoreLen=strlen(szIgnore); /* First thing to do is remove any excess spaces. */ for(i=0; i<dwLen; i++, bIgnore=FALSE){ if(!bFoundChar) if(szLineIn[i]!=' ') bFoundChar=TRUE; if(bFoundChar){ for(k=0; k<dwIgnoreLen; k++){ if(szLineIn[i]==szIgnore[k]) bIgnore=TRUE; } if(bIgnore){ if(dwSpaces==0){ szTemp[j]=' '; j++; dwSpaces++; continue; }else{ dwSpaces++; continue; } }else{ dwSpaces=0; } szTemp[j]=szLineIn[i]; j++; } } szTemp[j]=0; dwLen=strlen(szTemp); /* Get the command (the first word). */ for(i=0, j=0; i<dwLen; i++, j++){ if(szTemp[i]==' ') break; szCommand[j]=szTemp[i]; } szCommand[j]=0; /* Get the parameters. */ j++; i++; for(j=0 ; i<dwLen; i++, j++){ szParams[j]=szTemp[i]; } szParams[j]=0; return TRUE; } /* ============================== Beem Console Public Functions. ==============================*/ HBEEMCONSOLE CreateBeemConsole( LPDIRECT3DDEVICE9 lpDevice, HD3DFONT lpFont, HD3DIMAGE lpConsoleBG, LPCOMMAND CommandFunction) { LPBEEMCONSOLE lpConsole=NULL; HANDLE hBGImage=NULL; HRSRC hRsrc=NULL; LPVOID lpData=NULL; LPDIRECT3DTEXTURE9 lpBGTexture=NULL; HINSTANCE hInst=NULL; lpConsole=malloc(sizeof(BEEMCONSOLE)); if(lpConsole==NULL) return NULL; hInst=GetModuleHandleA("GFX3D9.DLL"); /* If the console background image was NULL we load the default one from memory. */ if(lpConsoleBG==NULL){ /* Should load default bg. */ hRsrc=FindResourceA( hInst, MAKEINTRESOURCE(IDR_CONSOLEIMG), "binary"); if(hRsrc==NULL) return NULL; hBGImage=LoadResource( hInst, hRsrc); if(hBGImage==NULL) return NULL; lpData=LockResource(hBGImage); if(FAILED(D3DXCreateTextureFromFileInMemory( lpDevice, lpData, SizeofResource(hInst, hRsrc), &lpBGTexture))) { FreeResource(hBGImage); return NULL; } FreeResource(hBGImage); lpConsole->ConsoleBG=CreateD3DImageFromTexture( lpDevice, -1, -1, lpBGTexture); if(lpConsole->ConsoleBG==NULL) { lpBGTexture->lpVtbl->Release(lpBGTexture); return NULL; } lpBGTexture->lpVtbl->Release(lpBGTexture); } lpConsole->lpActiveEntry=NULL; lpConsole->lpEntryList=NULL; lpConsole->CommandFunction=CommandFunction; /* If the console image was not NULL we copy it. */ if(lpConsoleBG!=NULL){ lpConsole->ConsoleBG=CopyD3DImage(lpConsoleBG); } if(lpFont!=NULL){ lpConsole->ConsoleFont=CopyD3DFont(lpDevice, lpFont); }else{ lpConsole->ConsoleFont=GetD3DFontDefault(lpDevice); SetD3DFontSize(lpConsole->ConsoleFont, 8, 16); } /* Set some initial values for the console. */ lpConsole->bConsoleActive=FALSE; lpConsole->lPosition=0; lpConsole->bDeactivating=FALSE; lpConsole->dwNumEntries=0; lpConsole->dwScrollPos=0; lpConsole->lpDevice=lpDevice; lpConsole->lpDevice->lpVtbl->AddRef(lpConsole->lpDevice); lpConsole->dwLastUpdate=timeGetTime(); /* Add a blank entry. */ AddBeemConsoleEntry((HBEEMCONSOLE)lpConsole, ""); return (HBEEMCONSOLE)lpConsole; } BOOL DeleteBeemConsole( HBEEMCONSOLE lpConsole) { LPBEEMENTRY lpCurrent=NULL, lpNext=NULL; /* Delete the list of entrys. */ if(!lpConsole) return FALSE; lpCurrent=((LPBEEMCONSOLE)lpConsole)->lpEntryList; while(lpCurrent!=NULL){ lpNext=lpCurrent->lpNext; /* Clear the text string. */ SAFE_FREE(lpCurrent->lpstrText); /* Clear the entry. */ SAFE_FREE(lpCurrent); lpCurrent=lpNext; } ((LPBEEMCONSOLE)lpConsole)->lpActiveEntry=NULL; /* Delete the bg, and font. */ DeleteD3DImage(((LPBEEMCONSOLE)lpConsole)->ConsoleBG); DeleteD3DFont(((LPBEEMCONSOLE)lpConsole)->ConsoleFont); ((LPBEEMCONSOLE)lpConsole)->CommandFunction=NULL; ((LPBEEMCONSOLE)lpConsole)->lpDevice->lpVtbl->Release(((LPBEEMCONSOLE)lpConsole)->lpDevice); SAFE_FREE(lpConsole); return TRUE; } BOOL ScrollBeemConsole( HBEEMCONSOLE lpConsole, LONG lScrollDist) { #define MIN_ENTRIES_PER_SCREEN 2 if(lpConsole==NULL) return FALSE; if(!((LPBEEMCONSOLE)lpConsole)->bConsoleActive) return TRUE; if(((LPBEEMCONSOLE)lpConsole)->dwNumEntries <= (MIN_ENTRIES_PER_SCREEN-1)){ ((LPBEEMCONSOLE)lpConsole)->dwScrollPos=0; return TRUE; } if( (LONG)(((LPBEEMCONSOLE)lpConsole)->dwScrollPos+lScrollDist) > (LONG)(((LPBEEMCONSOLE)lpConsole)->dwNumEntries-(MIN_ENTRIES_PER_SCREEN))){ ((LPBEEMCONSOLE)lpConsole)->dwScrollPos=((LPBEEMCONSOLE)lpConsole)->dwNumEntries-(MIN_ENTRIES_PER_SCREEN); return TRUE; } if( (LONG)(((LPBEEMCONSOLE)lpConsole)->dwScrollPos+lScrollDist) < 0){ ((LPBEEMCONSOLE)lpConsole)->dwScrollPos=0; return TRUE; } ((LPBEEMCONSOLE)lpConsole)->dwScrollPos+=lScrollDist; return TRUE; } BOOL BeemConsoleClearEntries( HBEEMCONSOLE lpConsole) { LPBEEMENTRY lpCurrent=NULL; LPBEEMENTRY lpNext=NULL; if(!lpConsole) return FALSE; lpCurrent=((LPBEEMCONSOLE)lpConsole)->lpEntryList; while(lpCurrent!=NULL){ lpNext=lpCurrent->lpNext; /* Clear the text string. */ SAFE_FREE(lpCurrent->lpstrText); /* Clear the entry. */ SAFE_FREE(lpCurrent); lpCurrent=lpNext; } ((LPBEEMCONSOLE)lpConsole)->lpEntryList=NULL; ((LPBEEMCONSOLE)lpConsole)->lpActiveEntry=NULL; ((LPBEEMCONSOLE)lpConsole)->dwNumEntries=0; ((LPBEEMCONSOLE)lpConsole)->dwScrollPos=0; AddBeemConsoleEntry(lpConsole, ""); return TRUE; } BOOL SendBeemConsoleMessage( HBEEMCONSOLE lpConsole, LPSTR szMessage) { char szTemp[MAX_CHARSPERLINE]; if(!lpConsole) return FALSE; /* Save the current line. */ strcpy(szTemp, ((LPBEEMCONSOLE)lpConsole)->lpActiveEntry->lpstrText); /* Copy in the new line. */ strcpy(((LPBEEMCONSOLE)lpConsole)->lpActiveEntry->lpstrText, szMessage); /* Re-Add the old line. */ return AddBeemConsoleEntry( lpConsole, szTemp); } BOOL SendBeemConsoleCommand( HBEEMCONSOLE hConsole, LPSTR szCommandLine) { char szParams[MAX_CHARSPERLINE]; char szCommand[MAX_CHARSPERLINE]; char szParseIgnore[]=" ,()"; DWORD dwLen=0; dwLen=strlen(szCommandLine); if(dwLen>0){ /* First thing to do is a simple parse on the command. */ if(!BeemConsoleSimpleParse(szCommand, szParams, szParseIgnore, szCommandLine)){ SendBeemConsoleMessage(hConsole, "ERROR: COULD NOT PERFORM SIMPLE PARSE!"); }else{ if(((LPBEEMCONSOLE)hConsole)->CommandFunction==NULL){ SendBeemConsoleMessage(hConsole, "ERROR: NO COMMAND PARSER LOADED!"); }else{ if(!((LPBEEMCONSOLE)hConsole)->CommandFunction(szCommand, szParams, hConsole)) SendBeemConsoleMessage(hConsole, "--- ERROR: COULD NOT PARSE COMMAND ---"); } } }else{ SendBeemConsoleMessage(hConsole, ""); } return TRUE; } BOOL AddBeemConsoleEntry( HBEEMCONSOLE lpConsole, LPSTR szEntry) { LPBEEMENTRY lpCurrent=NULL; if(!lpConsole) return FALSE; lpCurrent=((LPBEEMCONSOLE)lpConsole)->lpEntryList; ((LPBEEMCONSOLE)lpConsole)->lpEntryList=malloc(sizeof(BEEMENTRY)); if(((LPBEEMCONSOLE)lpConsole)->lpEntryList==NULL){ ((LPBEEMCONSOLE)lpConsole)->lpEntryList=lpCurrent; return FALSE; } ((LPBEEMCONSOLE)lpConsole)->lpEntryList->lpstrText=malloc(sizeof(char)*MAX_CHARSPERLINE); if(((LPBEEMCONSOLE)lpConsole)->lpEntryList->lpstrText==NULL){ SAFE_FREE(((LPBEEMCONSOLE)lpConsole)->lpEntryList); ((LPBEEMCONSOLE)lpConsole)->lpEntryList=lpCurrent; } ((LPBEEMCONSOLE)lpConsole)->lpEntryList->lpNext=lpCurrent; ((LPBEEMCONSOLE)lpConsole)->lpActiveEntry=((LPBEEMCONSOLE)lpConsole)->lpEntryList; strcpy(((LPBEEMCONSOLE)lpConsole)->lpEntryList->lpstrText, szEntry); ((LPBEEMCONSOLE)lpConsole)->dwNumEntries++; if(((LPBEEMCONSOLE)lpConsole)->dwNumEntries > LINE_BUFFER_SIZE) BeemConsoleRemoveLastEntry(lpConsole); return TRUE; } BOOL InvalidateBeemConsole( HBEEMCONSOLE lpConsole) { if(!lpConsole) return FALSE; InvalidateD3DImage(((LPBEEMCONSOLE)lpConsole)->ConsoleBG); InvalidateD3DFont(((LPBEEMCONSOLE)lpConsole)->ConsoleFont); return TRUE; } BOOL ValidateBeemConsole( HBEEMCONSOLE lpConsole) { if(!lpConsole) return FALSE; ValidateD3DImage(((LPBEEMCONSOLE)lpConsole)->ConsoleBG); ValidateD3DFont(((LPBEEMCONSOLE)lpConsole)->ConsoleFont); return TRUE; } BOOL ToggleActivateBeemConsole( HBEEMCONSOLE lpConsole) { if(!lpConsole) return FALSE; /* If we weren't active, then we set to active. */ if(!((LPBEEMCONSOLE)lpConsole)->bConsoleActive){ ((LPBEEMCONSOLE)lpConsole)->bDeactivating=FALSE; ((LPBEEMCONSOLE)lpConsole)->bConsoleActive=TRUE; }else{ if(((LPBEEMCONSOLE)lpConsole)->bDeactivating) ((LPBEEMCONSOLE)lpConsole)->bDeactivating=FALSE; else ((LPBEEMCONSOLE)lpConsole)->bDeactivating=TRUE; } return TRUE; } BOOL RenderBeemConsole( HBEEMCONSOLE lpConsole) { LONG lYOffset=0; LONG lStringPos=0; WORD wFontWidth=0, wFontHeight=0; DWORD i=0; BOOL bFoundEntry=FALSE; DWORD dwScrollDist=0, dwTimeElapsed=0; D3DVIEWPORT9 ViewPort; LPBEEMENTRY lpCurrent=NULL; char szActiveString[MAX_CHARSPERLINE+1]; if(!lpConsole) return FALSE; if(!((LPBEEMCONSOLE)lpConsole)->bConsoleActive){ ((LPBEEMCONSOLE)lpConsole)->dwLastUpdate=timeGetTime(); return TRUE; } ((LPBEEMCONSOLE)lpConsole)->lpDevice->lpVtbl->GetViewport(((LPBEEMCONSOLE)lpConsole)->lpDevice, &ViewPort); /* Figure out the scroll distance. */ /* It should take approximately 1/2 sec. to scroll down completely. */ dwTimeElapsed=timeGetTime()-((LPBEEMCONSOLE)lpConsole)->dwLastUpdate; if(dwTimeElapsed) ((LPBEEMCONSOLE)lpConsole)->dwLastUpdate=timeGetTime(); #define CONSOLE_SCROLL_SPEED 500 dwScrollDist=(DWORD)(dwTimeElapsed * ( (FLOAT)(ViewPort.Height/2)/(FLOAT)CONSOLE_SCROLL_SPEED )); if(((LPBEEMCONSOLE)lpConsole)->bDeactivating){ if(((LPBEEMCONSOLE)lpConsole)->lPosition<=0){ ((LPBEEMCONSOLE)lpConsole)->lPosition=0; ((LPBEEMCONSOLE)lpConsole)->bConsoleActive=FALSE; return TRUE; } ((LPBEEMCONSOLE)lpConsole)->lPosition-=dwScrollDist; }else{ ((LPBEEMCONSOLE)lpConsole)->lPosition+=dwScrollDist; if(((LPBEEMCONSOLE)lpConsole)->lPosition>(LONG)(ViewPort.Height/2)) ((LPBEEMCONSOLE)lpConsole)->lPosition=ViewPort.Height/2; } GetD3DFontDims(((LPBEEMCONSOLE)lpConsole)->ConsoleFont, &wFontWidth, &wFontHeight); /* We first set the string position to the bottom of the console. */ lStringPos=(ViewPort.Height/2)-wFontHeight; lYOffset=ViewPort.Height/2-((LPBEEMCONSOLE)lpConsole)->lPosition; /* Render the console position. */ RenderD3DImageEx( ((LPBEEMCONSOLE)lpConsole)->ConsoleBG, 0, 0-lYOffset, ViewPort.Width, ViewPort.Height/2, 0, 0, GetD3DImageWidth(((LPBEEMCONSOLE)lpConsole)->ConsoleBG), GetD3DImageHeight(((LPBEEMCONSOLE)lpConsole)->ConsoleBG)); /* Render each line. */ /* Render active entry first. */ RenderD3DFontChar( ((LPBEEMCONSOLE)lpConsole)->ConsoleFont, 0, lStringPos-lYOffset, ']'); /* If there is no entry we return. */ if(!((LPBEEMCONSOLE)lpConsole)->lpActiveEntry) return TRUE; /* Create and render the active string. */ sprintf(szActiveString, "%s_", ((LPBEEMCONSOLE)lpConsole)->lpActiveEntry->lpstrText); RenderD3DFontString( ((LPBEEMCONSOLE)lpConsole)->ConsoleFont, wFontWidth, lStringPos-lYOffset, szActiveString); if(((LPBEEMCONSOLE)lpConsole)->dwScrollPos>0){ lStringPos-=wFontHeight; for(i=0; i<ViewPort.Width; i+=wFontWidth*5){ RenderD3DFontChar( ((LPBEEMCONSOLE)lpConsole)->ConsoleFont, i, lStringPos-lYOffset, '^'); } } lStringPos-=wFontHeight; /* Get the second line and render until no strings are left, or no space is left on the screen. */ lpCurrent=((LPBEEMCONSOLE)lpConsole)->lpEntryList; lpCurrent=lpCurrent->lpNext; if( lpCurrent!=NULL && ((LPBEEMCONSOLE)lpConsole)->dwScrollPos > 0) lpCurrent=lpCurrent->lpNext; i=0; bFoundEntry=FALSE; while(lpCurrent){ if(bFoundEntry){ RenderD3DFontString( ((LPBEEMCONSOLE)lpConsole)->ConsoleFont, wFontWidth, lStringPos-lYOffset, lpCurrent->lpstrText); lStringPos-=wFontHeight; /* Break if no rendering room left. */ if((lStringPos-lYOffset)<(0-wFontHeight)) break; }else{ if(i>=((LPBEEMCONSOLE)lpConsole)->dwScrollPos){ bFoundEntry=TRUE; continue; } i++; } lpCurrent=lpCurrent->lpNext; } return TRUE; } BOOL BeemConsoleOnChar( HBEEMCONSOLE lpConsole, char cChar) { DWORD dwLen=0; if(lpConsole==NULL) return FALSE; /* If console is not active bail. */ if(!((LPBEEMCONSOLE)lpConsole)->bConsoleActive) return TRUE; /* If no active entry, then add an entry. */ if(((LPBEEMCONSOLE)lpConsole)->lpActiveEntry==NULL) AddBeemConsoleEntry(lpConsole, ""); dwLen=strlen(((LPBEEMCONSOLE)lpConsole)->lpActiveEntry->lpstrText); /* Do any necessary actions depending on cChar. */ switch(cChar) { case VK_RETURN: SendBeemConsoleCommand(lpConsole, ((LPBEEMCONSOLE)lpConsole)->lpActiveEntry->lpstrText); BeemConsoleEraseInput(lpConsole); break; case VK_BACK: if(dwLen>0){ /* Remove last char, and add null-termination. */ ((LPBEEMCONSOLE)lpConsole)->lpActiveEntry->lpstrText[dwLen-1]=0; } break; default: /* The funcion made it here if a standard key was pressed. */ /* Break if line has reached it's max limit. */ if(dwLen >= (MAX_CHARSPERLINE-1)) return FALSE; /* Add the char into the string and a null-termination. */ if((cChar >= ' ') && (cChar <= '~')){ ((LPBEEMCONSOLE)lpConsole)->lpActiveEntry->lpstrText[dwLen]=cChar; ((LPBEEMCONSOLE)lpConsole)->lpActiveEntry->lpstrText[dwLen+1]=0; } break; }; return TRUE; }<file_sep>/games/Legacy-Engine/Source/engine/lp_physx2.cpp #if 0 #include <NxCooking.h> #include <NxCapsuleController.h> #include "lp_physx2.h" #include "lg_err.h" #include "lg_err_ex.h" #include "lw_entity.h" #include "lw_map.h" #pragma comment(lib, "PhysXLoader.lib") #pragma comment(lib, "NxCooking.lib") #pragma comment(lib, "NxCharacter.lib") void CLPhysPhysX::Init(lg_dword nMaxBodies) { //Create the SDK: m_pSDK=NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, LG_NULL/*&m_Alloc*/, &m_Out); LG_ASSERT(m_pSDK, "Could not initialize NVIDIA PhysX."); //Controller manager creation: m_pCtrlrMgr=NxCreateControllerManager(&m_Alloc); LG_ASSERT(m_pCtrlrMgr, "Could not initialize NVIDIA PhysX Controller Manager."); //Initialize mesh cooking (For maps). //LG_ASSERT(NxInitCooking(), "Could not initalize NVIDIA PhysX Mesh Cooking."); m_pCooking=NxGetCookingLib(NX_PHYSICS_SDK_VERSION); LG_ASSERT(m_pCooking->NxInitCooking(&m_Alloc, &m_Out), "Could not initialize NVIDIA PhysX Cooking."); //Set some default parameters (we can use cvars for these if we want). m_pSDK->setParameter(NX_SKIN_WIDTH, 0.001f); /* m_pSDK->setParameter(NX_VISUALIZATION_SCALE, 1); m_pSDK->setParameter(NX_VISUALIZE_COLLISION_SHAPES, 1); m_pSDK->setParameter(NX_VISUALIZE_ACTOR_AXES, 1); */ #ifdef _DEBUG m_pSDK->getFoundationSDK().getRemoteDebugger()->connect("localhost", 5425); #endif _DEBUG //Now we create the scene NxSceneDesc sd; NxSceneLimits lim; lim.maxNbActors=nMaxBodies; lim.maxNbBodies=nMaxBodies; sd.setToDefault(); sd.gravity.set(0.0f, 0.0f, 0.0f); sd.flags |= NX_SF_ENABLE_ACTIVETRANSFORMS; //We want to use active transforms. sd.limits=&lim; //sd.braodPhase=NX_BROADPHASE_COHERENT; //sd.collisionDetection=NxTrue; m_pScene=m_pSDK->createScene(sd); LG_ASSERT(m_pScene, "Could not initialize NVIDIA PhysX scence.") //Setup the default material: NxMaterial* pDM = m_pScene->getMaterialFromIndex(0); pDM->setRestitution(0.0f); pDM->setStaticFriction(0.7f); pDM->setDynamicFriction(0.5f); NxMaterialDesc mtrDesc; mtrDesc.restitution=0.0f; mtrDesc.dynamicFriction=1.0f; mtrDesc.staticFriction=0.0f; m_pMtrInt=m_pScene->createMaterial(mtrDesc); mtrDesc.restitution=0.0f; mtrDesc.dynamicFriction=0.5f; mtrDesc.staticFriction=0.7f; m_pMtrMap=m_pScene->createMaterial(mtrDesc); m_pActrMap=LG_NULL; m_nATs=0; m_pATs=LG_NULL; } void CLPhysPhysX::Shutdown() { if(m_pActrMap) { m_pScene->releaseActor(*m_pActrMap); m_pActrMap=LG_NULL; } //Releaset the materials: m_pScene->releaseMaterial(*m_pMtrInt); m_pMtrInt=LG_NULL; m_pScene->releaseMaterial(*m_pMtrMap); m_pMtrMap=LG_NULL; //Release the scene m_pSDK->releaseScene(*m_pScene); m_pScene=LG_NULL; //Release controller manager: NxReleaseControllerManager(m_pCtrlrMgr); //Release cooking: m_pCooking->NxCloseCooking(); m_pCooking=LG_NULL; //Finally we destroy the SDK. m_pSDK->release(); m_pSDK=LG_NULL; } lg_void* CLPhysPhysX::AddIntelligentBody(lg_void* pEnt, lp_body_info* pInfo) { NxController* pCtrlr; NxCapsuleControllerDesc crd; crd.setToDefault(); crd.radius=(pInfo->m_aabbBody.v3Max.x-pInfo->m_aabbBody.v3Min.x)*0.5f; crd.height=(pInfo->m_aabbBody.v3Max.y-pInfo->m_aabbBody.v3Min.y)-2.0f*crd.radius; //CtrlrDesc.materialIndex=m_pMtrInt->getMaterialIndex(); crd.position.set(pInfo->m_matPos._41, pInfo->m_matPos._42, pInfo->m_matPos._43); crd.upDirection=NX_Y; crd.slopeLimit=0; crd.stepOffset=0.5f; #if 0 NxCapsuleControllerDesc desc; NxVec3 tmp = startPos[i]; desc.position.x = tmp.x; desc.position.y = tmp.y; desc.position.z = tmp.z; desc.radius = gInitialRadius * scale; desc.height = gInitialHeight * scale; desc.upDirection = NX_Y; // desc.slopeLimit = cosf(NxMath::degToRad(45.0f)); desc.slopeLimit = 0; desc.skinWidth = SKINWIDTH; desc.stepOffset = 0.5; desc.stepOffset = gInitialRadius * 0.5 * scale; // desc.stepOffset = 0.01f; // desc.stepOffset = 0; // Fixes some issues // desc.stepOffset = 10; desc.callback = &gControllerHitReport; gManager->createController(&scene, desc); #endif /* //Now that we have the shape, let's set the offset of it. ML_MAT matDims; ML_MatIdentity(&matDims); //When setting the offset of the shape, it is necessary to realize //that the legacy defintion of a shape places the object standing //on top of the XZ plane, therefore we need only add the offset of //the x and z dimensions, however for the y direction we need to move //the shape up one half of it's height, then add the offset. matDims._41=pInfo->m_fShapeOffset[0]; matDims._42=(pInfo->m_aabbBody.v3Max.y-pInfo->m_aabbBody.v3Min.y)*0.5f+pInfo->m_fShapeOffset[1]; matDims._43=pInfo->m_fShapeOffset[2]; CtrlrDesc.localPose.setColumnMajor44((NxReal*)&matDims); */ pCtrlr=m_pCtrlrMgr->createController(m_pScene, crd); NxActor* pActor = pCtrlr->getActor(); pActor->userData=pEnt; return pCtrlr; /* NxActor* pActor = (NxActor*)AddDynamicBody(pEnt, pInfo); return pActor; */ } lg_void* CLPhysPhysX::AddDynamicBody(lg_void* pEnt, lp_body_info* pInfo) { NxActorDesc ad; NxBodyDesc bd; NxCapsuleShapeDesc csd; NxBoxShapeDesc bsd; NxShapeDesc* pShape=LG_NULL; //Create the shape: switch(pInfo->m_nShape) { default: case PHYS_SHAPE_BOX: bsd.setToDefault(); //The dimensions are radii, so we multiply the dimensions by half. bsd.dimensions.set( (pInfo->m_aabbBody.v3Max.x-pInfo->m_aabbBody.v3Min.x)*0.5f, (pInfo->m_aabbBody.v3Max.y-pInfo->m_aabbBody.v3Min.y)*0.5f, (pInfo->m_aabbBody.v3Max.z-pInfo->m_aabbBody.v3Min.z)*0.5f); pShape=&bsd; break; case PHYS_SHAPE_CAPSULE: csd.setToDefault(); csd.radius=(pInfo->m_aabbBody.v3Max.x-pInfo->m_aabbBody.v3Min.x)*0.5f; csd.height=(pInfo->m_aabbBody.v3Max.y-pInfo->m_aabbBody.v3Min.y)-2.0f*csd.radius; pShape=&csd; break; /* case PHYS_SHAPE_CYLINDER: break; case PHYS_SHAPE_SPHERE: break; */ } if(LG_CheckFlag(pInfo->m_nAIPhysFlags, AI_PHYS_INT)) { pShape->materialIndex=m_pMtrInt->getMaterialIndex(); } //Now that we have the shape, let's set the offset of it. ML_MAT matDims; ML_MatIdentity(&matDims); //When setting the offset of the shape, it is necessary to realize //that the legacy defintion of a shape places the object standing //on top of the XZ plane, therefore we need only add the offset of //the x and z dimensions, however for the y direction we need to move //the shape up one half of it's height, then add the offset. matDims._41=pInfo->m_fShapeOffset[0]; matDims._42=(pInfo->m_aabbBody.v3Max.y-pInfo->m_aabbBody.v3Min.y)*0.5f+pInfo->m_fShapeOffset[1]; matDims._43=pInfo->m_fShapeOffset[2]; pShape->localPose.setColumnMajor44((NxReal*)&matDims); //Setup the body description for the actor: bd.setToDefault(); bd.linearDamping=0.5f; bd.angularDamping=2.0f; if(LG_CheckFlag(pInfo->m_nAIPhysFlags, AI_PHYS_INT)) { LG_SetFlag(bd.flags, NX_BF_FROZEN_ROT_X); LG_SetFlag(bd.flags, NX_BF_FROZEN_ROT_Z); LG_SetFlag(bd.flags, NX_BF_FROZEN_ROT_Y); } //Setup //if(LG_CheckFlag(pInfo->m_nAIPhysFlags, AI_PHYS_INT)) // LG_SetFlag(bd.flags, NX_BF_KINEMATIC); /* ML_MatIdentity(&matDims); //Not really sure if this center of mass stuff is correct at this time matDims._41=pInfo->m_fMassCenter[0]; matDims._42=(pInfo->m_aabbBody.v3Max.y-pInfo->m_aabbBody.v3Min.y)*0.5f+pInfo->m_fMassCenter[1]; matDims._43=pInfo->m_fMassCenter[2]; bd.massLocalPose.setColumnMajor44((NxReal*)&matDims); */ bd.mass=pInfo->m_fMass; //Setup the actor description: ad.setToDefault(); ad.shapes.pushBack(pShape); ad.body=&bd; ad.globalPose.setColumnMajor44((NxReal*)&pInfo->m_matPos); //Create the body, attach the ent to it and return the body: NxActor* pActor = m_pScene->createActor(ad); pActor->userData=pEnt; return pActor; } lg_void* CLPhysPhysX::AddBody(lg_void* pEnt, lp_body_info* pInfo) { /* if(LG_CheckFlag(pInfo->m_nAIPhysFlags, AI_PHYS_INT)) return AddIntelligentBody(pEnt, pInfo); else */ return AddDynamicBody(pEnt, pInfo); } void CLPhysPhysX::RemoveBody(lg_void* pBody) { NxActor* pActor=(NxActor*)pBody; m_pScene->releaseActor(*pActor); #if 0 m_pScene->simulate(0.0f); m_pScene->flushStream(); m_pScene->fetchResults(NX_RIGID_BODY_FINISHED, LG_TRUE); #endif } void CLPhysPhysX::SetupWorld(lg_void* pWorldMap) { CLMap* pMap=(CLMap*)pWorldMap; if(m_pActrMap) { m_pScene->releaseActor(*m_pActrMap); m_pActrMap=LG_NULL; } //If null was passed as the parameter it means we //no longer want the world. if(!pMap) return; CLNxMemStream stream(1024); #if 1 NxTriangleMeshDesc desc; desc.numTriangles=pMap->m_nGeoTriCount;//pMap->m_nVertexCount/3; desc.numVertices=pMap->m_nGeoTriCount*3;//pMap->m_nVertexCount; desc.pointStrideBytes=sizeof(ML_VEC3); desc.points=pMap->m_pGeoTris;//pMap->m_pVertexes; NxActorDesc actorDesc; NxTriangleMeshShapeDesc triShape; stream.Reset(); lg_bool status = m_pCooking->NxCookTriangleMesh(desc, stream); stream.Reset(); triShape.meshData=m_pSDK->createTriangleMesh(stream); actorDesc.shapes.pushBack(&triShape); triShape.materialIndex=m_pMtrMap->getMaterialIndex(); m_pActrMap=m_pScene->createActor(actorDesc); #else NxActorDesc ad; NxConvexMeshDesc cmd; ad.setToDefault(); for(lg_dword i=0; i<pMap->m_nGeoBlockCount; i++) { cmd.setToDefault(); cmd.numVertices=pMap->m_pGeoBlocks[i].nVertexCount; cmd.pointStrideBytes=sizeof(LW_GEO_VERTEX); cmd.points=pMap->m_pGeoBlocks[i].pVerts; cmd.flags=NX_CF_COMPUTE_CONVEX; stream.Reset(); lg_bool bRes=m_pCooking->NxCookConvexMesh(cmd, stream); stream.Reset(); if(bRes) { NxConvexShapeDesc csd; csd.meshData=m_pSDK->createConvexMesh(stream); if(csd.meshData) { ad.shapes.push_back(&csd); } } } m_pActrMap=m_pScene->createActor(ad); #endif } void CLPhysPhysX::SetGravity(ML_VEC3* pGrav) { m_pScene->setGravity((NxVec3&)*pGrav); } void CLPhysPhysX::Simulate(lg_float fTimeStepSec) { //Do the updates, really I don't want to loop through every actor //but I don't know if there is a way to loop only through bodies that //are awake. static NxU32 nActCount; static NxActor** ppActors; nActCount=m_pScene->getNbActors(); ppActors=m_pScene->getActors(); for(NxU32 i=0; i<nActCount; ++i) { if(!ppActors[i]->isSleeping()) { //We need to update the actors based on info from the server. UpdateFromSrv(ppActors[i]); } } // Get the Active Transforms from the scene m_nATs=0; m_pATs = m_pScene->getActiveTransforms(m_nATs); m_pScene->simulate((NxReal)fTimeStepSec); //We only need to update objects if they are moving: if(m_nATs && m_pATs) { for(NxU32 i=0; i<m_nATs; ++i) { UpdateToSrv(m_pATs[i].actor, (lg_srv_ent*)m_pATs[i].userData, &m_pATs[i].actor2World); } } m_pScene->flushStream(); m_pScene->fetchResults(NX_RIGID_BODY_FINISHED, LG_TRUE); } void CLPhysPhysX::SetBodyFlag(lg_void* pBody, lg_dword nFlagID, lg_dword nValue){} void CLPhysPhysX::SetBodyVector(lg_void* pBody, lg_dword nVecID, ML_VEC3* pVec){} void CLPhysPhysX::SetBodyFloat(lg_void* pBody, lg_dword nFloatID, lg_float fValue){} void CLPhysPhysX::SetBodyPosition(lg_void* pBody, ML_MAT* pMat) { } lg_void* CLPhysPhysX::GetBodySaveInfo(lg_void* pBody, lg_dword* pSize) { return LG_NULL; } lg_void* CLPhysPhysX::LoadBodySaveInfo(lg_void* pData, lg_dword nSize) { return LG_NULL; } void CLPhysPhysX::UpdateFromSrv(NxActor* pSrc) { static NxMat34 mat34; static NxMat33 mat33; static NxVec3 v3T; static ML_MAT matT; lg_srv_ent* pEnt=(lg_srv_ent*)pSrc->userData; if(LG_CheckFlag(pEnt->m_pAI->PhysFlags(), AI_PHYS_DIRECT_LINEAR)) { /* mat34.M.id(); mat34.t.set((NxVec3&)pEnt->m_v3Thrust); mat34*=pSrc->getGlobalPosition(); */ v3T=pSrc->getGlobalPosition(); v3T.add(v3T, (NxVec3&)pEnt->m_v3Thrust); pSrc->setGlobalPosition(v3T); } else { pSrc->addForce(*(NxVec3*)&pEnt->m_v3Thrust, NX_FORCE); pSrc->addForce(*(NxVec3*)&pEnt->m_v3Impulse, NX_IMPULSE); } if(LG_CheckFlag(pEnt->m_pAI->PhysFlags(), AI_PHYS_DIRECT_ANGULAR)) { ML_MatRotationAxis(&matT, &pEnt->m_v3Torque, ML_Vec3Length(&pEnt->m_v3Torque)); mat34.setColumnMajor44((NxF32*)&matT); mat33=mat34.M; mat33*=pSrc->getGlobalOrientation(); pSrc->setGlobalOrientation(mat33); //pSrc->addTorque(*(NxVec3*)&pEnt->m_v3Torque, NX_VELOCITY_CHANGE); } else { pSrc->addTorque(*(NxVec3*)&pEnt->m_v3Torque); } pEnt->m_v3Thrust=s_v3Zero; pEnt->m_v3Torque=s_v3Zero; pEnt->m_v3Impulse=s_v3Zero; } void CLPhysPhysX::UpdateToSrv(NxActor* pSrc, lg_srv_ent* pEnt, NxMat34* pPos) { //We first check to make sure the ent isn't blank, //because if we are using active transforms, and the entity //was deleted, the pointer to the entitiy will still //exist, but it won't actually exist (and pSrc would not //be a valid actor). if(LG_CheckFlag(pEnt->m_nFlags1, pEnt->EF_1_BLANK)) return; //Err_Printf("Calling: %s", pEnt->m_szObjScript); pPos->getColumnMajor44((NxF32*)&pEnt->m_matPos); pSrc->getShapes()[0]->getWorldBounds((NxBounds3&)pEnt->m_aabbBody); static NxVec3 v3; v3 = pSrc->getLinearVelocity(); pEnt->m_v3Vel=*(ML_VEC3*)&v3; v3 = pSrc->getAngularVelocity(); pEnt->m_v3AngVel=*(ML_VEC3*)&v3; ML_Vec3TransformNormalArray( pEnt->m_v3Face, sizeof(ML_VEC3), s_v3StdFace, sizeof(ML_VEC3), &pEnt->m_matPos, 3); //Call the post physics AI routine. pEnt->m_pAI->PostPhys(pEnt); } /****************** *** CXOut class *** ******************/ void CLPhysPhysX::CXOut::reportError(NxErrorCode code, const char* message, const char* file, int line) { Err_Printf("PhysX: ERROR: %d: %s (%s.%d)", code, message, file, line); } NxAssertResponse CLPhysPhysX::CXOut::reportAssertViolation(const char* message, const char* file, int line) { Err_Printf("PhysX: ASSERT VIOLATION: %s (%s.%d)", message, file, line); return NX_AR_BREAKPOINT; } void CLPhysPhysX::CXOut::print(const char* message) { Err_Printf("PhysX: %s", message); } /******************************** *** The file stream for PhysX *** ********************************/ CLPhysPhysX::CLNxStream::CLNxStream(const lg_char filename[], lg_bool bLoad): m_File(LG_NULL) { Open(filename, bLoad); } CLPhysPhysX::CLNxStream::~CLNxStream() { Close(); } NxU8 CLPhysPhysX::CLNxStream::readByte()const { NxU8 b; LF_Read(m_File, &b, 1); return b; } NxU16 CLPhysPhysX::CLNxStream::readWord()const { NxU16 b; LF_Read(m_File, &b, 2); return b; } NxU32 CLPhysPhysX::CLNxStream::readDword()const { NxU32 b; LF_Read(m_File, &b, 4); return b; } NxReal CLPhysPhysX::CLNxStream::readFloat()const { NxReal b; LF_Read(m_File, &b, 4); return b; } NxF64 CLPhysPhysX::CLNxStream::readDouble()const { NxF64 b; LF_Read(m_File, &b, 8); return b; } void CLPhysPhysX::CLNxStream::readBuffer(void* buffer, NxU32 size)const { LF_Read(m_File, buffer, size); } NxStream& CLPhysPhysX::CLNxStream::storeByte(NxU8 n) { LF_Write(m_File, &n, 1); return *this; } NxStream& CLPhysPhysX::CLNxStream::storeWord(NxU16 w) { LF_Write(m_File, &w, 2); return *this; } NxStream& CLPhysPhysX::CLNxStream::storeDword(NxU32 d) { LF_Write(m_File, &d, 4); return *this; } NxStream& CLPhysPhysX::CLNxStream::storeFloat(NxReal f) { LF_Write(m_File, &f, 4); return *this; } NxStream& CLPhysPhysX::CLNxStream::storeDouble(NxF64 f) { LF_Write(m_File, &f, 8); return *this; } NxStream& CLPhysPhysX::CLNxStream::storeBuffer(const void* buffer, NxU32 size) { LF_Write(m_File, (lf_void*)buffer, size); return *this; } void CLPhysPhysX::CLNxStream::Open(const lg_char filename[], lg_bool bLoad) { Close(); m_File=LF_Open(filename, LF_ACCESS_READ|LF_ACCESS_WRITE, bLoad?LF_OPEN_EXISTING:LF_CREATE_ALWAYS); } void CLPhysPhysX::CLNxStream::Close() { if(m_File) { LF_Close(m_File); m_File=LG_NULL; } } /********************************** *** The memory stream for PhysX *** **********************************/ CLPhysPhysX::CLNxMemStream::CLNxMemStream(lg_dword nSize) : m_File(0) { Open(nSize); } CLPhysPhysX::CLNxMemStream::~CLNxMemStream() { Close(); } void CLPhysPhysX::CLNxMemStream::Open(lg_dword nSize) { Close(); m_File.Open(nSize); } void CLPhysPhysX::CLNxMemStream::Close() { m_File.Close(); } void CLPhysPhysX::CLNxMemStream::Reset() { m_File.Seek(m_File.MEM_SEEK_BEGIN, 0); } NxU8 CLPhysPhysX::CLNxMemStream::readByte()const { NxU8 b; readBuffer(&b, 1); return b; } NxU16 CLPhysPhysX::CLNxMemStream::readWord()const { NxU16 b; readBuffer(&b, 2); return b; } NxU32 CLPhysPhysX::CLNxMemStream::readDword()const { NxU32 b; readBuffer(&b, 4); return b; } NxReal CLPhysPhysX::CLNxMemStream::readFloat()const { NxReal b; readBuffer(&b, 4); return b; } NxF64 CLPhysPhysX::CLNxMemStream::readDouble()const { NxF64 b; readBuffer(&b, 8); return b; } void CLPhysPhysX::CLNxMemStream::readBuffer(void* buffer, NxU32 size)const { //Because of the const qualifier (which is required by the NxStream //template, we need to derefernce, the memory file, so that we can //call a non const method on it, it's rediculously retarded, but //we don't have much choice. (*(CLMemFile*)&m_File).Read(buffer, size); } NxStream& CLPhysPhysX::CLNxMemStream::storeByte(NxU8 n) { return storeBuffer(&n, 1); } NxStream& CLPhysPhysX::CLNxMemStream::storeWord(NxU16 w) { return storeBuffer(&w, 2); } NxStream& CLPhysPhysX::CLNxMemStream::storeDword(NxU32 d) { return storeBuffer(&d, 4); } NxStream& CLPhysPhysX::CLNxMemStream::storeFloat(NxReal f) { return storeBuffer(&f, 4); } NxStream& CLPhysPhysX::CLNxMemStream::storeDouble(NxF64 f) { return storeBuffer(&f, 8); } NxStream& CLPhysPhysX::CLNxMemStream::storeBuffer(const void* buffer, NxU32 size) { //Should probably resize if we don't //have a big enough file. if((m_File.Tell()+size)>m_File.Size()) { m_File.Resize(m_File.Size()*2); } m_File.Write(buffer, size); return *this; } /****************************** *** The allocator for PhysX *** ******************************/ #include "lg_malloc.h" void * CLPhysPhysX::CXAlloc::malloc(NxU32 size) { return LG_Malloc(size); } void * CLPhysPhysX::CXAlloc::mallocDEBUG(NxU32 size,const char *fileName, int line) { return this->malloc(size); } void * CLPhysPhysX::CXAlloc::realloc(void * memory, NxU32 size) { this->free(memory); return LG_Malloc(size); } void CLPhysPhysX::CXAlloc::free(void * memory) { LG_Free(memory); } #endif<file_sep>/tools/CornerBin/CornerBin/CBSettings.h #pragma once class CCBSettings { public: CCBSettings(void); ~CCBSettings(void); public: struct SSettings { CString m_strFullIcon; CString m_strEmptyIcon; CString m_strToolTip; DWORD m_bEmptyPrompt; DWORD m_bOpenRBOnDblClk; DWORD m_nUpdateFreq; DWORD m_bSimpleMenu; }; private: SSettings m_Settings; public: BOOL LoadSettings(void); BOOL SaveSettings(void); LPCTSTR GetFullIcon(void); LPCTSTR GetEmptyIcon(void); BOOL GetEmptyPrompt(void); BOOL GetOpenOnDblClk(void); void SetSettings(const SSettings* pSettings); LPCTSTR GetTooTip(void); DWORD GetUpdateFreq(void); BOOL GetSimpleMenu(void); private: static void LoadARegString(CString& strOut, CRegKey* pKey, LPCTSTR strName, LPCTSTR strDefault); static void LoadARegDword(DWORD& nOut, CRegKey* pKey, LPCTSTR strName, DWORD nDefault); public: void GetSettings(SSettings* pSettingsOut); }; <file_sep>/games/Legacy-Engine/Source/engine/lg_xml.c #include "lg_xml.h" #include "lg_malloc.h" void* XML_Alloc(size_t size) { return LG_Malloc((lgm_size_t)size); } void* XML_Realloc(void* ptr, size_t size) { LG_Free(ptr); return LG_Malloc((lgm_size_t)size); } void XML_Free(void* ptr) { if(ptr) LG_Free(ptr); } XML_Parser XML_ParserCreate_LG(const XML_Char *encoding) { XML_Memory_Handling_Suite ms; ms.malloc_fcn=XML_Alloc; ms.realloc_fcn=XML_Realloc; ms.free_fcn=XML_Free; return XML_ParserCreate_MM(0, &ms, 0); }<file_sep>/Misc/DBXExporter/DBXExporter/oedbx/library/dbxIndexedInfo.cpp //*************************************************************************************** #define AS_OE_IMPLEMENTATION #include <oedbx/dbxIndexedInfo.h> //*************************************************************************************** DbxIndexedInfo::DbxIndexedInfo(InStream ins, int4 address) { init(); Address = address; try { readIndexedInfo(ins); } catch(const DbxException & E) { delete[] Buffer; throw; } } DbxIndexedInfo::~DbxIndexedInfo() { delete[] Buffer; } void DbxIndexedInfo::init() { BodyLength = 0; ObjectLength = 0; Entries = Counter = 0; Buffer = 0; Indexes = 0; for(int1 i=0;i<MaxIndex;++i) { Begin[i] = 0; Length[i] = 0; } } void DbxIndexedInfo::readIndexedInfo(InStream ins) { int4 temp[3]; ins.seekg(Address); ins.read((char *)temp, 12); if(!ins) throw DbxException("Error reading from input stream !"); if(Address != temp[0]) throw DbxException("Wrong object marker !"); BodyLength = temp[1]; ObjectLength = *( (int2 *)(temp+2) ); //temp[2]& 0xffff; Entries = *(((int1 *)(temp+2))+2); //(temp[2]>>16) & 0xff; Counter = *(((int1 *)(temp+2))+3); //(temp[2]>>24) & 0xff; Buffer = new int1[BodyLength]; ins.read((char *)Buffer, BodyLength); if(!ins) throw DbxException("Error reading from input stream !"); bool isIndirect = false; int1 lastIndirect = 0; int1 * data = Buffer + (Entries<<2); for(int1 i = 0; i<Entries; ++i) { int4 value = ((int4 *)Buffer)[i]; bool isDirect = value & 0x80; // Data stored direct int1 index = (int1) (value & 0x7f); // Low byte is the index value >>= 8 ; // Value the rest if(index>=MaxIndex) throw DbxException("Index to big !"); if(isDirect) SetIndex(index, Buffer+(i<<2)+1, 3); else { SetIndex(index, data+value); if(isIndirect) SetEnd(lastIndirect, data+value); isIndirect = true; lastIndirect = index; } Indexes |= 1<<index; } if(isIndirect)SetEnd(lastIndirect, Buffer+BodyLength); } //*************************************************************************************** void DbxIndexedInfo::SetIndex(int1 index, int1 * begin, int4 length) { if(index<MaxIndex) { Begin[index] = begin; Length[index] = length; } } void DbxIndexedInfo::SetEnd(int1 index, int1 * end) { if(index<MaxIndex) Length[index] = end - Begin[index]; } //*************************************************************************************** int1 * DbxIndexedInfo::GetValue(int1 index, int4 * length) const { if(index>=MaxIndex) throw DbxException("Index to big !"); *length = Length[index]; return Begin[index]; } //*************************************************************************************** const char * DbxIndexedInfo::GetString(int1 index) const { if(index>=MaxIndex) throw DbxException("Index to big !"); return (char *)Begin[index]; } //*************************************************************************************** int4 DbxIndexedInfo::GetValue(int1 index) const { if(index>=MaxIndex) throw DbxException("Index to big !"); int4 length = Length[index], value = 0; int1 * data = Begin[index]; if(data) { value = *((int4 *)data); // length>4 ignored if(length<4) value &= (1<<(length<<3))-1; } return value; } //*************************************************************************************** void DbxIndexedInfo::ShowResults(OutStream outs) const { outs << std::endl << "indexed info at : 0x" << std::hex<< Address << std::endl; outs << " Length of the index data field : 0x"<< std::hex<< BodyLength << std::endl; outs << " Entries in the index field : 0x"<< std::hex<< ((int)Entries)<< std::endl; outs << " Counter : 0x"<< std::hex<< ((int)Counter)<< std::endl; outs << " Indexes : 0x"<< std::hex<< Indexes << std::endl; for(int1 i = 0; i<MaxIndex;++i) if(Indexes & (1<<i)) { int4 length = 0; int1 * data = GetValue(i, &length); outs << std::left << std::setw(40) << GetIndexText(i) << " : "; if(data) switch (GetIndexDataType(i)) { case dtString : outs << data; break; case dtDateTime : outs << FileTime2String(data); break; case dtInt4 : outs << "0x" << std::hex << GetValue(i); break; default : outs << "0x" << length << std::endl; rows2File(outs,0,data,length); } outs << std::endl; } } <file_sep>/games/Legacy-Engine/Source/engine/lg_err_ex.h #ifndef __LG_ERR_EX_H__ #define __LG_ERR_EX_H__ #define LG_ERR_MSG_SIZE 1024 #include "lg_types.h" typedef enum _LG_ERR { LG_ERR_UNKNOWN=0, LG_ERR_DEFAULT, LG_ERR_OUTOFMEMORY, LG_ERR_INVALID_PARAM, LG_ERR_UNEEDED_CLASS, LG_ERR_ASSERT_FAIL, LG_ERR_ERRCOUNT }LG_ERR; #define LG_ERROR(type, msg) CLError(type, __FILE__, __LINE__, msg) #define LG_ASSERT(p, msg) if(!p){throw CLError(LG_ERR_ASSERT_FAIL, __FILE__, __LINE__, msg);} /* #define LG_ERR_DEFAULT 0x00000001 #define LG_ERR_OUTOFMEMORY 0x00000002 */ class CLError { private: char m_szError[LG_ERR_MSG_SIZE+1]; LG_ERR m_nErrorCode; public: //CLError(); CLError(LG_ERR nErrorCode, char* szFilename, lg_dword nLine, char* szMsg=LG_NULL); /* CLError(char* szError, lg_dword nErrorCode); CLError(char* szError, lg_dword nErrorCode, char* szFile, lg_dword nLine); */ void Catenate(LG_ERR nErrorCode, char* szFile, lg_dword nLine, char* szMsg=LG_NULL); //void Catenate(char* szError, lg_dword nErrorCode, char* szFile, lg_dword nLine); void Catenate(char* Format, ...); const char* GetMsg(); }; #define ERROR_CODE(code, msg) CLError(code, __FILE__, __LINE__, msg) #endif __LG_ERR_EX_H__<file_sep>/games/Legacy-Engine/Source/lf_sys2/lf_bdio.c /* lf_bdio.c - Basic Disk Input Output. These functions should be used internally only, and not by outside systems. Copyright (C) 2007 <NAME> */ /* NOTE: The bdio functions should be altered according to the operating system that the lf_sys2 library is being compiled for, this file is designed for windows operating systems (in all practicality the fopen, fclose, etc stdc functions could have been used, but the windows methods prove more stable for windows computers. */ #include <windows.h> #include "lf_bdio.h" /* Basic DIO stuff, should only be used internally only. */ typedef struct _BDIO{ HANDLE hFile; }BDIO; BDIO_FILE BDIO_OpenA(lf_cstr szFilename, BDIO_CREATE_MODE nMode, lf_dword nAccess) { BDIO* pFile=LF_NULL; lf_dword dwDesiredAccess=0; lf_dword dwCreateDisposition=0; lf_dword dwFlagsAndAttributes=0; dwDesiredAccess|=LF_CHECK_FLAG(nAccess, BDIO_ACCESS_READ)?GENERIC_READ:0; dwDesiredAccess|=LF_CHECK_FLAG(nAccess, BDIO_ACCESS_WRITE)?GENERIC_WRITE:0; pFile=LF_Malloc(sizeof(BDIO)); if(!pFile) return LF_NULL; pFile->hFile=LF_NULL; switch(nMode) { case BDIO_CREATE_ALWAYS: dwCreateDisposition=CREATE_ALWAYS; break; case BDIO_CREATE_NEW: dwCreateDisposition=CREATE_NEW; break; case BDIO_OPEN_ALWAYS: dwCreateDisposition=OPEN_ALWAYS; break; case BDIO_OPEN_EXISTING: dwCreateDisposition=OPEN_EXISTING; break; } dwFlagsAndAttributes=FILE_ATTRIBUTE_NORMAL; if(LF_CHECK_FLAG(nAccess, BDIO_ACCESS_TEMP)) { dwFlagsAndAttributes=FILE_FLAG_DELETE_ON_CLOSE|FILE_ATTRIBUTE_TEMPORARY; } pFile->hFile=CreateFileA( szFilename, dwDesiredAccess, FILE_SHARE_READ, NULL, dwCreateDisposition, dwFlagsAndAttributes, NULL); if(pFile->hFile==INVALID_HANDLE_VALUE) { LF_Free(pFile); return LF_NULL; } return pFile; } BDIO_FILE BDIO_OpenW(lf_cwstr szFilename, BDIO_CREATE_MODE nMode, lf_dword nAccess) { BDIO* pFile=LF_NULL; lf_dword dwDesiredAccess=0; lf_dword dwCreateDisposition=0; lf_dword dwFlagsAndAttributes=0; dwDesiredAccess|=LF_CHECK_FLAG(nAccess, BDIO_ACCESS_READ)?GENERIC_READ:0; dwDesiredAccess|=LF_CHECK_FLAG(nAccess, BDIO_ACCESS_WRITE)?GENERIC_WRITE:0; pFile=LF_Malloc(sizeof(BDIO)); if(!pFile) return LF_NULL; pFile->hFile=LF_NULL; switch(nMode) { case BDIO_CREATE_ALWAYS: dwCreateDisposition=CREATE_ALWAYS; break; case BDIO_CREATE_NEW: dwCreateDisposition=CREATE_NEW; break; case BDIO_OPEN_ALWAYS: dwCreateDisposition=OPEN_ALWAYS; break; case BDIO_OPEN_EXISTING: dwCreateDisposition=OPEN_EXISTING; break; } dwFlagsAndAttributes=FILE_ATTRIBUTE_NORMAL; if(LF_CHECK_FLAG(nAccess, BDIO_ACCESS_TEMP)) { dwFlagsAndAttributes=FILE_FLAG_DELETE_ON_CLOSE|FILE_ATTRIBUTE_TEMPORARY; } pFile->hFile=CreateFileW( szFilename, dwDesiredAccess, FILE_SHARE_READ, NULL, dwCreateDisposition, dwFlagsAndAttributes, NULL); if(pFile->hFile==INVALID_HANDLE_VALUE) { LF_Free(pFile); return LF_NULL; } return pFile; } lf_bool BDIO_Close(BDIO_FILE File) { BDIO* pFile=File; lf_bool bResult=CloseHandle(pFile->hFile); LF_Free(pFile); return bResult; } lf_dword BDIO_Read(BDIO_FILE File, lf_dword nSize, void* pOutBuffer) { BDIO* pFile=File; lf_dword dwRead=0; if(ReadFile(pFile->hFile, pOutBuffer, nSize, &dwRead, NULL)) return dwRead; else return 0; } lf_dword BDIO_Write(BDIO_FILE File, lf_dword nSize, void* pInBuffer) { BDIO* pFile=File; lf_dword dwWrote=0; if(WriteFile(pFile->hFile, pInBuffer, nSize, &dwWrote, NULL)) return dwWrote; else return 0; } lf_dword BDIO_Tell(BDIO_FILE File) { BDIO* pFile=File; return SetFilePointer( pFile->hFile, 0, NULL, FILE_CURRENT); } lf_dword BDIO_Seek(BDIO_FILE File, lf_long nOffset, BDIO_SEEK_MODE nOrigin) { BDIO* pFile=File; lf_dword dwMoveMethod=0; switch(nOrigin) { case BDIO_SEEK_BEGIN: dwMoveMethod=FILE_BEGIN; break; case BDIO_SEEK_CURRENT: dwMoveMethod=FILE_CURRENT; break; case BDIO_SEEK_END: dwMoveMethod=FILE_END; break; } return SetFilePointer( pFile->hFile, nOffset, NULL, dwMoveMethod); } lf_dword BDIO_GetSize(BDIO_FILE File) { BDIO* pFile=File; lf_large_integer nFileSize={0,0}; nFileSize.dwLowPart=GetFileSize(pFile->hFile, &nFileSize.dwHighPart); if(nFileSize.dwHighPart) return 0xFFFFFFFF; else return nFileSize.dwLowPart; } BDIO_FILE LF_SYS2_EXPORTS BDIO_OpenTempFileA(BDIO_CREATE_MODE nMode, lf_dword nAccess) { lf_pathA szTempPath, szTempFile; GetTempPathA(LF_MAX_PATH, szTempPath); GetTempFileNameA(szTempPath, "BDIO", 0, szTempFile); return BDIO_OpenA(szTempFile, nMode, nAccess|BDIO_ACCESS_TEMP); } BDIO_FILE LF_SYS2_EXPORTS BDIO_OpenTempFileW(BDIO_CREATE_MODE nMode, lf_dword nAccess) { lf_pathW szTempPath, szTempFile; GetTempPathW(LF_MAX_PATH, szTempPath); GetTempFileNameW(szTempPath, L"BDIO", 0, szTempFile); return BDIO_OpenW(szTempFile, nMode, nAccess|BDIO_ACCESS_TEMP); } /* Directory manipulation...*/ lf_bool LF_SYS2_EXPORTS BDIO_ChangeDirA(lf_cstr szDir) { return SetCurrentDirectoryA(szDir); } lf_bool LF_SYS2_EXPORTS BDIO_ChangeDirW(lf_cwstr szDir) { return SetCurrentDirectoryW(szDir); } lf_dword LF_SYS2_EXPORTS BDIO_GetCurrentDirA(lf_str szDir, lf_dword nSize) { return GetCurrentDirectoryA(nSize, szDir); } lf_dword LF_SYS2_EXPORTS BDIO_GetCurrentDirW(lf_wstr szDir, lf_dword nSize) { return GetCurrentDirectoryW(nSize, szDir); } /* BDIO_GetFullPathname converts a filename to it's full path according to the current directory */ lf_dword LF_SYS2_EXPORTS BDIO_GetFullPathNameW(lf_pathW szPath, const lf_pathW szFilename) { return GetFullPathNameW(szFilename, LF_MAX_PATH, szPath, NULL); } lf_dword LF_SYS2_EXPORTS BDIO_GetFullPathNameA(lf_pathA szPath, const lf_pathA szFilename) { return GetFullPathNameA(szFilename, LF_MAX_PATH, szPath, NULL);; } //Find File functions for finding all files in a directory. BDIO_FIND LF_SYS2_EXPORTS BDIO_FindFirstFileW(lf_cwstr szFilename, BDIO_FIND_DATAW* pFindData) { HANDLE hFindFile; WIN32_FIND_DATAW findData; hFindFile=FindFirstFileW(szFilename, &findData); if(INVALID_HANDLE_VALUE==hFindFile) return LF_NULL; pFindData->nFileSize.dwHighPart=findData.nFileSizeHigh; pFindData->nFileSize.dwLowPart=findData.nFileSizeLow; wcsncpy(pFindData->szFilename, findData.cFileName, LF_MAX_PATH); pFindData->bNormal=LF_CHECK_FLAG(findData.dwFileAttributes, FILE_ATTRIBUTE_NORMAL); pFindData->bDirectory=LF_CHECK_FLAG(findData.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY); pFindData->bHidden=LF_CHECK_FLAG(findData.dwFileAttributes, FILE_ATTRIBUTE_HIDDEN); pFindData->bReadOnly=LF_CHECK_FLAG(findData.dwFileAttributes, FILE_ATTRIBUTE_READONLY); return hFindFile; } lf_bool LF_SYS2_EXPORTS BDIO_FindNextFileW(BDIO_FIND hFindFile, BDIO_FIND_DATAW* pFindData) { WIN32_FIND_DATAW findData; lf_bool bResult=FindNextFileW((HANDLE)hFindFile, &findData); if(!bResult) return bResult; pFindData->nFileSize.dwHighPart=findData.nFileSizeHigh; pFindData->nFileSize.dwLowPart=findData.nFileSizeLow; wcsncpy(pFindData->szFilename, findData.cFileName, LF_MAX_PATH); pFindData->bNormal=LF_CHECK_FLAG(findData.dwFileAttributes, FILE_ATTRIBUTE_NORMAL); pFindData->bDirectory=LF_CHECK_FLAG(findData.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY); pFindData->bHidden=LF_CHECK_FLAG(findData.dwFileAttributes, FILE_ATTRIBUTE_HIDDEN); pFindData->bReadOnly=LF_CHECK_FLAG(findData.dwFileAttributes, FILE_ATTRIBUTE_READONLY); return bResult; } BDIO_FIND LF_SYS2_EXPORTS BDIO_FindFirstFileA(lf_cstr szFilename, BDIO_FIND_DATAA* pFindData) { HANDLE hFindFile; WIN32_FIND_DATAA findData; hFindFile=FindFirstFileA(szFilename, &findData); if(INVALID_HANDLE_VALUE==hFindFile) return LF_NULL; pFindData->nFileSize.dwHighPart=findData.nFileSizeHigh; pFindData->nFileSize.dwLowPart=findData.nFileSizeLow; strncpy(pFindData->szFilename, findData.cFileName, LF_MAX_PATH); pFindData->bNormal=LF_CHECK_FLAG(findData.dwFileAttributes, FILE_ATTRIBUTE_NORMAL); pFindData->bDirectory=LF_CHECK_FLAG(findData.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY); pFindData->bHidden=LF_CHECK_FLAG(findData.dwFileAttributes, FILE_ATTRIBUTE_HIDDEN); pFindData->bReadOnly=LF_CHECK_FLAG(findData.dwFileAttributes, FILE_ATTRIBUTE_READONLY); return hFindFile; } lf_bool LF_SYS2_EXPORTS BDIO_FindNextFileA(BDIO_FIND hFindFile, BDIO_FIND_DATAA* pFindData) { WIN32_FIND_DATAA findData; lf_bool bResult=FindNextFileA((HANDLE)hFindFile, &findData); if(!bResult) return bResult; pFindData->nFileSize.dwHighPart=findData.nFileSizeHigh; pFindData->nFileSize.dwLowPart=findData.nFileSizeLow; strncpy(pFindData->szFilename, findData.cFileName, LF_MAX_PATH); pFindData->bNormal=LF_CHECK_FLAG(findData.dwFileAttributes, FILE_ATTRIBUTE_NORMAL); pFindData->bDirectory=LF_CHECK_FLAG(findData.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY); pFindData->bHidden=LF_CHECK_FLAG(findData.dwFileAttributes, FILE_ATTRIBUTE_HIDDEN); pFindData->bReadOnly=LF_CHECK_FLAG(findData.dwFileAttributes, FILE_ATTRIBUTE_READONLY); return bResult; } lf_bool LF_SYS2_EXPORTS BDIO_FindClose(BDIO_FIND hFindFile) { return FindClose((HANDLE)hFindFile); }<file_sep>/Misc/DBXExporter/DBXExporter/oedbx/library/dbxMessage.cpp //*************************************************************************************** #define AS_OE_IMPLEMENTATION #include <oedbx/dbxMessage.h> //*************************************************************************************** DbxMessage::DbxMessage(InStream ins, int4 address) { Address = address; init(); try { readMessageText(ins); } catch(const DbxException & E) { delete[] Text; throw; } } DbxMessage::~DbxMessage() { delete[] Text; } void DbxMessage::init() { Length = 0; Text = 0; } void DbxMessage::readMessageText(InStream ins) { int4 address = Address, header[4]; char * pos; while(address) { ins.seekg(address); ins.read((char *)header, 0x10); if(!ins) throw DbxException("Error reading from input stream !"); if(address!=header[0]) throw DbxException("Wrong object marker !"); Length += header[2]; address = header[3]; } if(Length==0) throw DbxException("No text found !"); pos = Text = new char[Length+1]; // +1 to terminate the text with 0x00 address = Address; while(address) { ins.seekg(address); ins.read((char *)header, 0x10); ins.read(pos, header[2]); if(!ins) throw DbxException("Error reading from input stream !"); address = header[3]; pos += header[2]; } *pos = 0; // terminate the text with 0x00 } void DbxMessage::Convert() { int4 i=0, j=0; for(;i<=Length;++i) { if(Text[i]!='\r') Text[j++] = Text[i]; } if(j) --j; Length = j; } //*************************************************************************************** void DbxMessage::ShowResults(OutStream outs) const { int4 headerLines, bodyLines; Analyze(headerLines, bodyLines); outs << std::endl << "message at : 0x" << std::hex << Address << std::endl << " length : 0x" << std::hex << Length << std::endl << " header lines : 0x" << std::hex << headerLines << std::endl << " body lines : 0x" << std::hex << bodyLines << std::endl << std::endl; rows2File(outs,0,(int1 *)Text,Length); //outs << "..." << std::endl << Text << std::endl << "..." << std::endl; } void DbxMessage::Analyze(int4 & headerLines, int4 & bodyLines) const { headerLines = bodyLines = 0; if(Length==0) return; bool isHeader = true; char * pos = Text, * to = Text + Length; headerLines = 1; while(pos!=to) { if(*pos == 0x0a) { if(isHeader) if(pos-Text>=2) if(*(pos-2)==0x0a) isHeader = false; if(isHeader) ++headerLines; else ++bodyLines; } ++pos; } } //*************************************************************************************** <file_sep>/games/Legacy-Engine/Source/engine/ls_wav.h /* ls_wav.h - Header for WAVE file reading. Copyright (c) 2006, <NAME> */ #ifndef __LS_WAV_H__ #define __LS_WAV_H__ #include <windows.h> #include "common.h" #ifdef __cplusplus extern "C"{ #endif /*__cplusplus*/ lg_void* Wav_CreateFromDisk(lg_str szFilename); /*lg_void* Wav_CreateFromData(void* lpData, lg_dword dwDataSize);*/ lg_bool Wav_Delete(lg_void* lpWave); lg_dword Wav_Read(lg_void* lpWave, void* lpDest, lg_dword dwSizeToRead); lg_bool Wav_Reset(lg_void* lpWave); WAVEFORMATEX* Wav_GetFormat(lg_void* lpWave, WAVEFORMATEX* lpFormat); lg_dword Wav_GetSize(lg_void* lpWave); lg_bool Wav_IsEOF(lg_void* lpWave); #ifdef __cplusplus } #endif /*__cplusplus*/ #endif /* __LS_WAV_H__ */<file_sep>/Misc/ls_wav.c /* ls_wav.c - Fucntions for reading WAVE files. Copyright (c) 2006, <NAME>. */ #include <lf_sys2.h> #include "common.h" #include "ls_wav.h" //#include "ls_load.h" //#include "lg_err.h" #include "lg_malloc.h" typedef struct _WAVEFILE{ WAVEFORMATEX m_Format; HMMIO m_hmmio; MMCKINFO m_ck; MMCKINFO m_ckRiff; lg_dword m_dwSize; lg_dword m_ReadPos; lg_bool m_bEOF; lg_bool m_bLoaded; }WAVEFILE, *PWAVEFILE; LRESULT CALLBACK LS_MMIOProc( LPSTR lpmmioinfo, UINT uMsg, LPARAM lParam1, LPARAM lParam2); lg_bool Wav_OpenMMIO(WAVEFILE* lpWave); lg_bool Wav_ReadMMIO(WAVEFILE* lpWave); lg_void* Wav_CreateFromDisk(lg_str szFilename) { WAVEFILE* lpNew=LG_NULL; MMIOINFO mmioInfo; lpNew=LG_Malloc(sizeof(WAVEFILE)); if(!lpNew) return LG_NULL; memset(lpNew, 0, sizeof(WAVEFILE)); // Open the wave file from disk. memset(&mmioInfo, 0, sizeof(mmioInfo)); mmioInfo.pIOProc=LS_MMIOProc; lpNew->m_hmmio=mmioOpen(szFilename, &mmioInfo, MMIO_ALLOCBUF|MMIO_READ); if(lpNew->m_hmmio==LG_NULL) { LG_Free(lpNew); return LG_NULL; } if(!Wav_OpenMMIO(lpNew)) { mmioClose(lpNew->m_hmmio, 0); LG_Free(lpNew); return LG_NULL; } return lpNew; } /* WAVEFILE* Wav_CreateFromData(void* lpData, lg_dword dwDataSize) { WAVEFILE* lpNew=LG_NULL; MMIOINFO mmioInfo; lpNew=LG_Malloc(sizeof(WAVEFILE)); if(!lpNew) return LG_NULL; memset(lpNew, 0, sizeof(WAVEFILE)); memset(&mmioInfo, 0, sizeof(MMIOINFO)); mmioInfo.fccIOProc = FOURCC_MEM; mmioInfo.cchBuffer = dwDataSize; mmioInfo.pchBuffer = (char*)lpData; // Open the memory buffer lpNew->m_hmmio = mmioOpen(NULL, &mmioInfo, MMIO_READ); if(!lpNew->m_hmmio) { LG_Free(lpNew); return LG_NULL; } if(!Wav_OpenMMIO(lpNew)) { mmioClose(lpNew->m_hmmio, 0); LG_Free(lpNew); return LG_NULL; } return lpNew; } */ lg_bool Wav_Delete(lg_void* lpWave) { WAVEFILE* lpWaves=(WAVEFILE*)lpWave; if(!lpWaves->m_hmmio) return LG_FALSE; mmioClose(lpWaves->m_hmmio, 0); LG_Free(lpWaves); return LG_TRUE; } lg_dword Wav_Read(lg_void* lpWave, void* lpDest, lg_dword dwSizeToRead) { WAVEFILE* lpWaves=(WAVEFILE*)lpWave; MMIOINFO mmioinfoIn; //Current status of m_hmmio. //Data member specifying how many bytes to actually //read out of the wave file. lg_dword dwDataIn=0; char* lpWaveBuffer=LG_NULL; lg_dword dwStreamRead=0; lg_dword dwRead=0; lg_dword dwCopySize=0; if(!lpWave || !lpDest) return 0; if(!lpWaves->m_hmmio) return 0; if(0 != mmioGetInfo(lpWaves->m_hmmio, &mmioinfoIn, 0)) return 0; //If were not decompressing data, we can directly //use the buffer passed in to this function. lpWaveBuffer=(char*)lpDest; dwDataIn=dwSizeToRead; if(dwDataIn > lpWaves->m_ck.cksize) dwDataIn=lpWaves->m_ck.cksize; lpWaves->m_ck.cksize -= dwDataIn; while(dwRead<dwDataIn) { //Copy the bytes from teh io to the buffer. if(0 != mmioAdvance( lpWaves->m_hmmio, &mmioinfoIn, MMIO_READ)) { return LG_FALSE; } if(mmioinfoIn.pchNext == mmioinfoIn.pchEndRead) { return LG_FALSE; } //Perform the copy. dwCopySize = (lg_dword)(mmioinfoIn.pchEndRead - mmioinfoIn.pchNext); dwCopySize = dwCopySize > (dwDataIn-dwRead) ? (dwDataIn-dwRead) : dwCopySize; memcpy(lpWaveBuffer+dwRead, mmioinfoIn.pchNext, dwCopySize); dwRead += dwCopySize; mmioinfoIn.pchNext += dwCopySize; } if(0 != mmioSetInfo( lpWaves->m_hmmio, &mmioinfoIn, 0)) { return LG_FALSE; } if(lpWaves->m_ck.cksize == 0) lpWaves->m_bEOF=TRUE; return dwDataIn; } lg_bool Wav_Reset(lg_void* lpWave) { WAVEFILE* lpWaves=(WAVEFILE*)lpWave; if(!lpWave) return LG_FALSE; lpWaves->m_bEOF=LG_FALSE; if(lpWaves->m_hmmio == LG_NULL) return LG_FALSE; //Seek to the data. if(-1 == mmioSeek( lpWaves->m_hmmio, lpWaves->m_ckRiff.dwDataOffset + sizeof(FOURCC), SEEK_SET)) { return LG_FALSE; } //Search the input file for teh 'data' chunk. lpWaves->m_ck.ckid = mmioFOURCC('d', 'a', 't', 'a'); if(0 != mmioDescend( lpWaves->m_hmmio, &lpWaves->m_ck, &lpWaves->m_ckRiff, MMIO_FINDCHUNK)) { return LG_FALSE; } return LG_TRUE; } WAVEFORMATEX* Wav_GetFormat(lg_void* lpWave, WAVEFORMATEX* lpFormat) { WAVEFILE* lpWaves=(WAVEFILE*)lpWave; if(!lpWave || !lpWaves->m_bLoaded) return LG_FALSE; if(lpFormat) { memcpy(lpFormat, &lpWaves->m_Format, sizeof(WAVEFORMATEX)); return lpFormat; } else return &lpWaves->m_Format; } lg_dword Wav_GetSize(lg_void* lpWave) { WAVEFILE* lpWaves=(WAVEFILE*)lpWave; if(!lpWave) return 0; else return lpWaves->m_dwSize; } lg_bool Wav_IsEOF(lg_void* lpWave) { WAVEFILE* lpWaves=(WAVEFILE*)lpWave; if(!lpWave) return LG_TRUE; else return lpWaves->m_bEOF; } lg_bool Wav_OpenMMIO(WAVEFILE* lpWave) { if(!Wav_ReadMMIO(lpWave)) { return LG_FALSE; } //Reset the file to prepare for reading if(!Wav_Reset(lpWave)) { return LG_FALSE; } lpWave->m_dwSize=lpWave->m_ck.cksize; return LG_TRUE; } lg_bool Wav_ReadMMIO(WAVEFILE* lpWave) { //Chunk info for general use. MMCKINFO ckIn; //Temp PCM structure to load in. PCMWAVEFORMAT pcmWaveFormat; //Make sure this structure has been deallocated. //SAFE_DELETE_ARRAY(m_pwfx); if(mmioSeek(lpWave->m_hmmio, 0, SEEK_SET) == -1) return LG_FALSE; if((0 != mmioDescend( lpWave->m_hmmio, &lpWave->m_ckRiff, NULL, 0))) { return LG_FALSE; } //Check to make sure this is a valid wave file. if((lpWave->m_ckRiff.ckid != FOURCC_RIFF) || (lpWave->m_ckRiff.fccType != mmioFOURCC('W', 'A', 'V', 'E'))) { return LG_FALSE; } //Search the input file for the 'fmt' chunk. ckIn.ckid = mmioFOURCC('f', 'm', 't', ' '); if(0 != mmioDescend( lpWave->m_hmmio, &ckIn, &lpWave->m_ckRiff, MMIO_FINDCHUNK)) { return LG_FALSE; } //The 'fmt ' chunk will be at least //as large as PCMWAVEFORMAT if there are //extra parameters at the end, we'll ignore them. if(ckIn.cksize < (LONG) sizeof(PCMWAVEFORMAT)) return LG_FALSE; //Read the 'fmt ' chunk into pcmWaveFormat. if(mmioRead( lpWave->m_hmmio, (HPSTR)&pcmWaveFormat, sizeof(PCMWAVEFORMAT)) != sizeof(PCMWAVEFORMAT)) { return LG_FALSE; } //Only handling PCM formats. if(pcmWaveFormat.wf.wFormatTag == WAVE_FORMAT_PCM) { memcpy( &lpWave->m_Format, &pcmWaveFormat, sizeof(PCMWAVEFORMAT)); lpWave->m_Format.cbSize = 0; } else { //NON PCM wave would be handled here. return LG_FALSE; } //Ascend teh input file out of the 'fmt ' chucnk. if(0 != mmioAscend(lpWave->m_hmmio, &ckIn, 0)) { //SAFE_DELETE(m_pwfx); return LG_FALSE; } lpWave->m_bLoaded=LG_TRUE; return LG_TRUE; } /* LS_MMIOProc is the mmio reading procedure that will read from the Legacy file system. It should work I think. This code is not bug proof by any means so it still needs some work. */ LRESULT CALLBACK LS_MMIOProc(LPSTR lpmmioinfo, UINT uMsg, LPARAM lParam1, LPARAM lParam2) { LPMMIOINFO info=(LPMMIOINFO)lpmmioinfo; switch(uMsg) { case MMIOM_OPEN: { LF_FILE3 lpIn=LG_NULL; /* When we open a wave file, we don't open it with the LF_ACCESS_MEMORY attribute, this is because we may want to stream from the disk.*/ lpIn=LF_Open((char*)lParam1, LF_ACCESS_READ, LF_OPEN_EXISTING); if(!lpIn) return MMIOERR_CANNOTOPEN; info->hmmio=lpIn; return MMSYSERR_NOERROR; } case MMIOM_CLOSE: LF_Close((LF_FILE3)info->hmmio); return 0; case MMIOM_READ: { lg_dword nNumRead=0; nNumRead=LF_Read((LF_FILE3)info->hmmio, (int*)lParam1, (lg_dword)lParam2); return nNumRead; } case MMIOM_SEEK: { lg_long nType=0; if(lParam2==SEEK_SET) nType=LF_SEEK_BEGIN; else if(lParam2==SEEK_END) nType=LF_SEEK_END; else if(lParam2==SEEK_CUR) nType=LF_SEEK_CURRENT; LF_Seek((LF_FILE3)info->hmmio, nType, (lg_long)lParam1); return 0; } case MMIOM_WRITE: case MMIOM_WRITEFLUSH: //Err_Printf("Writing to MMIO is not supported in the Legacy Engine."); return -1; default: return -1; } return 0; }<file_sep>/tools/MConvert/Source/resource.h //{{NO_DEPENDENCIES}} // Microsoft Developer Studio generated include file. // Used by MConvert.rc // #define IDD_MAINDIAG 101 #define IDI_ICON1 102 #define IDD_MDLG2 103 #define ID_AMOUNT 1003 #define ID_CONVRATE 1004 #define ID_CONVERSION 1006 #define IDC_COMBO1 1008 #define IDC_COMBO2 1009 #define IDC_EDIT1 1011 #define IDC_STATIC1 1013 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 106 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1014 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif <file_sep>/games/Legacy-Engine/Scrapped/old/lp_newton.h #ifndef __LP_NEWTON_H__ #define __LP_NEWTON_H__ #include "Newton/Newton.h" #include "lg_types.h" #include "lw_map.h" class CElementNewton { private: //The Newton Game Dynamics physics model for the world... static NewtonBody* s_pWorldBody; public: static NewtonWorld* s_pNewtonWorld; static void Initialize(); static void Shutdown(); static void Simulate(lg_float fSeconds); static void SetupWorld(CLWorldMap* pMap); static lg_int MTR_DEFAULT; static lg_int MTR_LEVEL; static lg_int MTR_CHARACTER; static lg_int MTR_OBJECT; }; #endif __LP_NEWTON_H__<file_sep>/samples/Project5/src/bcol/BColException.java /* <NAME> CS 2420-002 BStackException - an Exception calss for BStack. */ package bcol; public class BColException extends Exception{ private String m_strError; /* POST: Creates a new instance of BStackException */ public BColException() { m_strError="Unknown Error"; } /* POST: Creates a new instance of BStackException with str as the error message.*/ public BColException(String str){ m_strError=str; } /* POST:Returns a string representation of the error. */ public String toString(){ return "BStack ERROR: " + m_strError; } } <file_sep>/games/Legacy-Engine/Scrapped/tools/larchiver/la_sys.h /* la_sys.h - the legacy archive file format. */ #ifndef __LA_SYS_H__ #define __LA_SYS_H__ #ifdef __cplusplus extern "C"{ #endif /* __cplusplus */ #define MAX_A_PATH (260) #define LARCHIVE_TYPE (*(unsigned long*)"LPK1") typedef void* HLARCHIVE; HLARCHIVE Arc_Open(char* szFilename); int Arc_Close(HLARCHIVE hArchive); unsigned long Arc_Extract(HLARCHIVE hArchive, char* szFile, void** lpBuffer); unsigned long Arc_GetNumFiles(HLARCHIVE hArchive); const char* Arc_GetFilename(HLARCHIVE hArchive, unsigned long nFile); unsigned long Arc_GetFileSize(HLARCHIVE hArchive, char* szFile); int Arc_Archive(char* szArchive, char* szPath, char* szPersist); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __LA_SYS_H__ */<file_sep>/games/Legacy-Engine/Source/engine/lg_list_stack.h /* lg_list_stack.h - The CLListStack is a special type of list that works as both a stack and a linked list. It is designed to be used with anything, but all classes it contains must have the base type of LSItem. This is designed to work both as a stack and as a linked list. In that way it has a broad range of uses. It is was primarily designed to hold various lists of entities. */ #ifndef __LG_LIST_STACK_H__ #define __LG_LIST_STACK_H__ #include "lg_types.h" struct CLListStack { public: //All items to be stored in the list stack must inherit from //CLListStack::LSItem. If they don't they can't be stored in //the list. LG_CACHE_ALIGN struct LSItem { LSItem* m_pNext; LSItem* m_pPrev; lg_dword m_nItemID; lg_dword m_nListStackID; }; private: //We keep track of the ID of this list, this ID is generated //to be unique from any other lists. const lg_dword m_nID; public: //It is necessary to keep track of a few items in the list. //The list is designed to be transversed either way. //The members are public, so they can be accessed directly, for //transversals. LSItem* m_pFirst; LSItem* m_pLast; lg_dword m_nCount; public: /* PRE: Before usage there must be a master list of nodes. The CLListStack only manages nodes, it does not create or destroy them. POST: The list will be ready to use. */ CLListStack(); /* PRE: N/A POST: No longer usable. */ ~CLListStack(); /* PRE: N/A POST: If there was a node available it is returned and removed from the list. If there was no node, then NULL is returned. */ LSItem* Pop(); /* PRE: N/A POST: Returns the first available item in the list, or null if there is no first item, does not remove it from the list. */ LSItem* Peek(); /* PRE: pNode should not be in pList, and it should be removed from any other list that it might be in. POST: pNode will be added to the beginning of the list. */ void Push(LSItem* pNode); /* PRE: pNode should be in this list. POST: pNode is removed. Note that if pNode was in a CLListStack, but not the one on which Remove was called, nothing will happen. */ void Remove(LSItem* pNode); /* PRE: N/A POST: Returns TRUE if the list is empty. */ lg_bool IsEmpty(); /* PRE: N/A POST: Clears the list. */ void Clear(); /* PRE: N/A POST: Puts all the items in the list into this list stack, usefull when first creating a list. */ void Init(LSItem* pList, lg_dword nCount, lg_dword nItemSize); private: //We keep track of the next id to be used when another list is created, //this is incremented each time we create a new list. static lg_dword s_nNextID; }; #endif __LG_LIST_STACK_H__<file_sep>/tools/img_lib/img_lib2/img_lib/img_cb.c /* img_cb.c - Callback functions for opening the functions. */ #include "img_private.h" //img_lib callback functions. typedef struct _img_file{ img_dword nSize; img_dword nPointer; img_void* pData; }img_file; img_void* img_file_open(img_void* pData, img_dword nSize) { img_file* pFile=malloc(sizeof(img_file)); if(!pFile) return IMG_NULL; memset(pFile, 0, sizeof(img_file)); pFile->nSize=nSize; pFile->pData=pData; pFile->nPointer=0; return pFile; } img_int img_file_close(img_void* stream) { img_file* pFile=stream; /* It isn't necessary to free pFile->nData. becase that data should be freed elsewhere.*/ if(pFile)free(pFile); return 0; } img_int img_file_seek(img_void* stream, img_long offset, img_int origin) { img_file* pFile=stream; if(!pFile) return 0; switch(origin) { case IMG_SEEK_SET: pFile->nPointer=offset; break; case IMG_SEEK_CUR: pFile->nPointer+=offset; break; case IMG_SEEK_END: pFile->nPointer=pFile->nSize+offset; break; } pFile->nPointer=IMG_CLAMP(pFile->nPointer, 0, pFile->nSize); return pFile->nPointer; } img_long img_file_tell(img_void* stream) { img_file* pFile=stream; if(!pFile) return 0; return pFile->nPointer; } img_uint img_file_read(img_void* buffer, img_uint size, img_uint count, img_void* stream) { img_dword nBytesToRead=0; img_file* pFile=stream; if(!pFile) return 0; nBytesToRead=count*size; if((pFile->nPointer+nBytesToRead)>pFile->nSize) { nBytesToRead=pFile->nSize-pFile->nPointer; } memcpy(buffer, (void*)((img_uint)pFile->pData+pFile->nPointer), nBytesToRead); pFile->nPointer+=nBytesToRead; return nBytesToRead; }<file_sep>/Misc/DBXExporter/DBXExporter/oedbx/library/dbxFolderList.cpp //*************************************************************************************** #define AS_OE_IMPLEMENTATION #include <oedbx/dbxFolderList.h> //*************************************************************************************** DbxFolderList::DbxFolderList(InStream ins, int4 address) { Address = address; readFolderList(ins); } void DbxFolderList::readFolderList(InStream ins) { ins.seekg(Address); ins.read((char *)Buffer, DbxFolderListSize); if(!ins) throw DbxException("Error reading object from input stream !"); if(Address!=Buffer[0]) throw DbxException("Wrong object marker !"); } //*************************************************************************************** void DbxFolderList::ShowResults(OutStream outs) const { outs << std::endl << "FolderList : " << std::endl << " Address : 0x" << std::hex << Address << std::endl; rows2File(outs,Address,(int1 *)Buffer, DbxFolderListSize); } //*************************************************************************************** <file_sep>/tools/ListingGen/ListingGen/Lister.h #ifndef __LISTER_H__ #define __LISTER_H__ #include <windows.h> #define SAFE_DELETE_ARRAY(p) {if(p){delete[]p;p=NULL;}} class CLister; typedef CLister* (*FPOBTAINLISTER)(); class CLister { private: public: CLister(){} virtual ~CLister(){} virtual BOOL RunDialog(HWND hwndParent)=0; virtual BOOL CreateListing(char szFilename[MAX_PATH])=0; virtual BOOL SaveListing(char szFilename[MAX_PATH])=0; virtual BOOL LoadListing(char szFilename[MAX_PATH])=0; }; #endif //__LISTER_H__<file_sep>/games/Legacy-Engine/Scrapped/tools/Texview2/src/ChildView.h // ChildView.h : interface of the CChildView class // ///////////////////////////////////////////////////////////////////////////// #if !defined(AFX_CHILDVIEW_H__D24ED702_83BE_45D8_BB31_9B370B519989__INCLUDED_) #define AFX_CHILDVIEW_H__D24ED702_83BE_45D8_BB31_9B370B519989__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "texture.h" ///////////////////////////////////////////////////////////////////////////// // CChildView window class CChildView : public CWnd { // Construction public: CChildView(); // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CChildView) protected: virtual BOOL PreCreateWindow(CREATESTRUCT& cs); //}}AFX_VIRTUAL // Implementation public: void UpdateImage(); void SetFilter(IMGFILTER filter); void SetBitmapSize(int cx, int cy); BOOL LoadTexture(LPTSTR szFilename); virtual ~CChildView(); // Generated message map functions protected: //{{AFX_MSG(CChildView) afx_msg void OnPaint(); afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg void OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar); afx_msg void OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar); afx_msg void OnViewAlphachannel(); afx_msg void OnViewImage(); afx_msg void OnViewBlackbg(); //}}AFX_MSG DECLARE_MESSAGE_MAP() private: int m_nImageHeight; int m_nImageWidth; BOOL m_bBlackBG; BOOL m_bShowImage; BOOL m_bAlphaChannel; CTexture m_texImage; IMGFILTER m_nFilter; void UpdateScrollBars(BOOL bResetToZero); }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_CHILDVIEW_H__D24ED702_83BE_45D8_BB31_9B370B519989__INCLUDED_) <file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/lv_img2d.h #ifndef __LV_2DIMG_H__ #define __LV_2DIMG_H__ #include <d3d9.h> #include "common.h" #define LV2DIMGVERTEX_TYPE \ ( \ D3DFVF_XYZ| \ D3DFVF_DIFFUSE| \ D3DFVF_TEX1 \ ) typedef struct _LV2DIMGVERTEX{ float x, y, z; L_dword Diffuse; float tu, tv; }LV2DIMGVERTEX, *LPLV2DIMGVERTEX; #ifdef __cplusplus extern "C"{ #endif /*__cplusplus*/ typedef struct _LV2DIMAGE{ IDirect3DTexture9* lpTexture; //Image texture. IDirect3DVertexBuffer9* lpVB; //Vertex buffer for image. LV2DIMGVERTEX Vertices[4]; //Vertices for image. L_dword dwWidth; //Width of image. L_dword dwHeight; //Height of image. L_bool bIsColor; //Color of image, if there is a color. L_bool bFromTexture; //If the image is from a texture. IDirect3DDevice9* lpDevice; //Device that was used to create the image. struct _LV2DIMAGE* lpCreate;//A pointer to the image that created this one. char szFilename[260]; //The name of the texture for reloading. L_dword dwTransparent; L_rect rcSrc; }LV2DIMAGE, *LPLV2DIMAGE; L_bool L2DI_StartStopDrawing( IDirect3DDevice9* lpDevice, L_dword ViewWidth, L_dword ViewHeight, L_bool bStart); LV2DIMAGE* L2DI_CreateFromFile( IDirect3DDevice9* lpDevice, char* szFilename, L_rect* rcSrc, L_dword dwWidth, L_dword dwHeight, L_dword dwTransparent); LV2DIMAGE* L2DI_CreateFromImage( LV2DIMAGE* lpImageSrc, L_rect* rsrc, L_dword dwWidth, L_dword dwHeight, L_dword dwTransparent); LV2DIMAGE* L2DI_CreateFromTexture( IDirect3DDevice9* lpDevice, L_rect* rcSrc, L_dword dwWidth, L_dword dwHeight, LPDIRECT3DTEXTURE9 lpTexture, L_pvoid pExtra); LV2DIMAGE* L2DI_CreateFromColor( IDirect3DDevice9* lpDevice, L_dword dwWidth, L_dword dwHeight, L_dword dwColor); L_bool L2DI_Invalidate(LV2DIMAGE* hImage); L_bool L2DI_Validate(LV2DIMAGE* hImage, IDirect3DDevice9* lpDevice, void* pExtra); L_bool L2DI_Delete(LV2DIMAGE* hImage); L_bool L2DI_Render( LV2DIMAGE* hImage, IDirect3DDevice9* lpDevice, float x, float y); /* L_bool L2DI_RenderEx( LV2DIMAGE* hImage, L_rect* rcDest, L_rect* rcSrc); L_bool L2DI_RenderRelativeEx( LV2DIMAGE* hImage, float fXDest, float fYDest, float fWidthDest, float fHeightDest, L_rect* rcSrc); */ #ifdef __cplusplus } #endif /*__cplusplus*/ #endif /* __LV_2DIMG_H__ */<file_sep>/tools/img_lib/TexView3/TexView3View.cpp // TexView3View.cpp : implementation of the CTexView3View class // #include "stdafx.h" #include "TexView3.h" #include "TexView3Doc.h" #include "TexView3View.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CTexView3View IMPLEMENT_DYNCREATE(CTexView3View, CScrollView) BEGIN_MESSAGE_MAP(CTexView3View, CScrollView) // Standard printing commands ON_COMMAND(ID_FILE_PRINT, &CScrollView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, &CScrollView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, &CScrollView::OnFilePrintPreview) ON_COMMAND_RANGE(ID_TEXTURE_IMAGE, ID_TEXTURE_ALPHAONLY, &CTexView3View::OnTextureAlphaMode) ON_WM_ERASEBKGND() ON_UPDATE_COMMAND_UI(ID_TEXTURE_IMAGE, &CTexView3View::OnUpdateTextureImage) ON_UPDATE_COMMAND_UI(ID_TEXTURE_IMAGEWITHALPHA, &CTexView3View::OnUpdateTextureImagewithalpha) ON_UPDATE_COMMAND_UI(ID_TEXTURE_ALPHAONLY, &CTexView3View::OnUpdateTextureAlphaonly) ON_COMMAND(ID_TEXTURE_REPEATING, &CTexView3View::OnTextureRepeating) ON_UPDATE_COMMAND_UI(ID_TEXTURE_REPEATING, &CTexView3View::OnUpdateTextureRepeating) ON_UPDATE_COMMAND_UI(ID_TEXTURE_LINEARFILTER, &CTexView3View::OnUpdateTextureLinearfilter) ON_UPDATE_COMMAND_UI(ID_TEXTURE_POINTFILTER, &CTexView3View::OnUpdateTexturePointfilter) ON_COMMAND_RANGE(ID_TEXTURE_LINEARFILTER, ID_TEXTURE_POINTFILTER, &CTexView3View::OnTextureFilter) END_MESSAGE_MAP() // CTexView3View construction/destruction CTexView3View::CTexView3View() : m_bTextureRepeat(FALSE) , m_nWidth(0) , m_nHeight(0) , m_nAlphaMode(CTexView3Doc::BC_IMAGE) , m_nFilter(IMGFILTER_LINEAR) { // TODO: add construction code here } CTexView3View::~CTexView3View() { } BOOL CTexView3View::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs return CScrollView::PreCreateWindow(cs); } // CTexView3View drawing void CTexView3View::OnDraw(CDC* pDC) { CTexView3Doc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; //int cx, cy; //pDoc->GetImageSize(&cx, &cy); CRect rcw; GetClientRect(&rcw); if(m_bTextureRepeat) { for(int i=0; i<rcw.Width()/m_nWidth+1; i++) { for(int j=0; j<rcw.Height()/m_nHeight+1; j++) DrawBitmap(i*m_nWidth, j*m_nHeight, pDC); } return; } int cx, cy; cx=rcw.Width()>m_nWidth?(rcw.right-m_nWidth)/2:0; cy=rcw.Height()>m_nHeight?(rcw.bottom-m_nHeight)/2:0; DrawBitmap(cx, cy, pDC); } // CTexView3View printing BOOL CTexView3View::OnPreparePrinting(CPrintInfo* pInfo) { // default preparation return DoPreparePrinting(pInfo); } void CTexView3View::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add extra initialization before printing } void CTexView3View::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add cleanup after printing } // CTexView3View diagnostics #ifdef _DEBUG void CTexView3View::AssertValid() const { CScrollView::AssertValid(); } void CTexView3View::Dump(CDumpContext& dc) const { CScrollView::Dump(dc); } CTexView3Doc* CTexView3View::GetDocument() const // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CTexView3Doc))); return (CTexView3Doc*)m_pDocument; } #endif //_DEBUG // CTexView3View message handlers void CTexView3View::OnUpdate(CView* /*pSender*/, LPARAM /*lHint*/, CObject* /*pHint*/) { SetScrollSizes(MM_TEXT, CSize(m_nWidth, m_nHeight)); RedrawWindow(); } void CTexView3View::OnInitialUpdate() { CScrollView::OnInitialUpdate(); //Initially we create a default bitmap, //m_nWidth and m_nHeight and m_nAlphaMode were set to initial values //in the constructor. RebuildBitmap(); SetScrollSizes(MM_TEXT, CSize(m_nWidth, m_nHeight)); ResizeParentToFit(TRUE); } BOOL CTexView3View::OnEraseBkgnd(CDC* pDC) { // Set brush to desired background color CBrush backBrush(CTexView3Doc::BG_COLOR); //backBrush.m_hObject=GetStockObject(LTGRAY_BRUSH); // Save old brush CBrush* pOldBrush = pDC->SelectObject(&backBrush); CRect rect; pDC->GetClipBox(&rect); // Erase the area needed pDC->PatBlt(rect.left, rect.top, rect.Width(), rect.Height(), PATCOPY); pDC->SelectObject(pOldBrush); return TRUE; //return CScrollView::OnEraseBkgnd(pDC); } void CTexView3View::OnTextureAlphaMode(UINT nID) { CTexView3Doc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; DWORD nNewMode=0; switch(nID) { case ID_TEXTURE_IMAGE: nNewMode=CTexView3Doc::BC_IMAGE; break; case ID_TEXTURE_IMAGEWITHALPHA: nNewMode=CTexView3Doc::BC_ACHANNEL|CTexView3Doc::BC_IMAGE; break; case ID_TEXTURE_ALPHAONLY: nNewMode=CTexView3Doc::BC_ACHANNEL; break; } //If the mode hasn't changed we //don't need to do anything. if(nNewMode==m_nAlphaMode) return; m_nAlphaMode=nNewMode; RebuildBitmap(); } void CTexView3View::OnUpdateTextureImage(CCmdUI *pCmdUI) { if(CHECK_FLAG(CTexView3Doc::BC_IMAGE, m_nAlphaMode) && !(CHECK_FLAG(CTexView3Doc::BC_ACHANNEL, m_nAlphaMode))) pCmdUI->SetCheck(TRUE); else pCmdUI->SetCheck(FALSE); } void CTexView3View::OnUpdateTextureImagewithalpha(CCmdUI *pCmdUI) { if(CHECK_FLAG(CTexView3Doc::BC_IMAGE, m_nAlphaMode) && (CHECK_FLAG(CTexView3Doc::BC_ACHANNEL, m_nAlphaMode))) pCmdUI->SetCheck(TRUE); else pCmdUI->SetCheck(FALSE); } void CTexView3View::OnUpdateTextureAlphaonly(CCmdUI *pCmdUI) { if(!CHECK_FLAG(CTexView3Doc::BC_IMAGE, m_nAlphaMode) && (CHECK_FLAG(CTexView3Doc::BC_ACHANNEL, m_nAlphaMode))) pCmdUI->SetCheck(TRUE); else pCmdUI->SetCheck(FALSE); } void CTexView3View::OnTextureRepeating() { m_bTextureRepeat=!m_bTextureRepeat; if(m_bTextureRepeat) SetScrollSizes(MM_TEXT, CSize(0, 0)); else SetScrollSizes(MM_TEXT, CSize(m_nWidth, m_nHeight)); RedrawWindow(); } void CTexView3View::OnUpdateTextureRepeating(CCmdUI *pCmdUI) { pCmdUI->SetCheck(m_bTextureRepeat); } BOOL CTexView3View::DrawBitmap(int x, int y, CDC* pDC) { if(!m_bmImg.m_hObject) return FALSE; CDC cImageDC; cImageDC.CreateCompatibleDC(NULL); CBitmap* bmOld=(CBitmap*)cImageDC.SelectObject(&m_bmImg); if(!pDC->IsPrinting()) { pDC->BitBlt( x, y, m_nWidth, m_nHeight, &cImageDC, 0, 0, SRCCOPY); } else { BOOL bResult=0; CDC dcImg; dcImg.CreateCompatibleDC(&cImageDC); CBitmap bmImg, *bmOld; bmImg.CreateCompatibleBitmap(&cImageDC, pDC->GetDeviceCaps(HORZRES), pDC->GetDeviceCaps(VERTRES)); bmOld=dcImg.SelectObject(&bmImg); //Adjust the width and height to fit the whole image on a page: DWORD nWidth=0, nHeight=0; if(m_nWidth<m_nHeight) { nHeight=pDC->GetDeviceCaps(VERTRES); nWidth=m_nWidth*pDC->GetDeviceCaps(VERTRES)/m_nHeight; } else { nWidth=pDC->GetDeviceCaps(HORZRES); nHeight=m_nHeight*pDC->GetDeviceCaps(HORZRES)/m_nWidth; } x=0; y=0; //Center the image horizontally on the page. if(nWidth<pDC->GetDeviceCaps(HORZRES)) x=(pDC->GetDeviceCaps(HORZRES)-nWidth)/2; //We could also center the image vertically, //but i think it looks better if it is at the top of the page. //if(nHeight<pDC->GetDeviceCaps(VERTRES)) // y=(pDC->GetDeviceCaps(VERTRES)-nHeight)/2; bResult=dcImg.StretchBlt( 0, 0, nWidth, nHeight, &cImageDC, 0, 0, m_nWidth, m_nHeight, SRCCOPY); bResult=pDC->BitBlt( x, y, nWidth, nHeight, &dcImg, 0, 0, SRCCOPY); dcImg.SelectObject(bmOld); dcImg.DeleteDC(); bmImg.DeleteObject(); } cImageDC.SelectObject(bmOld); cImageDC.DeleteDC(); return TRUE; } void CTexView3View::OnUpdateTextureLinearfilter(CCmdUI *pCmdUI) { pCmdUI->SetCheck(m_nFilter==IMGFILTER_LINEAR); } void CTexView3View::OnUpdateTexturePointfilter(CCmdUI *pCmdUI) { pCmdUI->SetCheck(m_nFilter==IMGFILTER_POINT); } void CTexView3View::OnTextureFilter(UINT nID) { switch(nID) { case ID_TEXTURE_LINEARFILTER: if(m_nFilter==IMGFILTER_LINEAR) return; m_nFilter=IMGFILTER_LINEAR; break; case ID_TEXTURE_POINTFILTER: if(m_nFilter==IMGFILTER_POINT) return; m_nFilter=IMGFILTER_POINT; break; } RebuildBitmap(); } void CTexView3View::RebuildBitmap(void) { CTexView3Doc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; m_bmImg.DeleteObject(); pDoc->CreateCBitmap(&m_bmImg, &m_nWidth, &m_nHeight, m_nFilter, CTexView3Doc::BC_USEAPPBG|m_nAlphaMode); RedrawWindow(); } <file_sep>/tools/GFX/GFXG8/D3DSetup.c #include <windowsx.h> #include "GFXG8.h" BOOL ValidateDevice( LPDIRECT3DDEVICE8 * lppDevice, LPDIRECT3DSURFACE8 * lppBackSurface, D3DPRESENT_PARAMETERS d3dpp, POOLFN fpReleasePool, POOLFN fpRestorePool) { HRESULT hr=0; if(!*lppDevice)return FALSE; if(FAILED(hr=IDirect3DDevice8_TestCooperativeLevel((*lppDevice)))){ if(hr == D3DERR_DEVICELOST)return TRUE; if(hr == D3DERR_DEVICENOTRESET){ if(*lppBackSurface){ IDirect3DSurface8_Release((*lppBackSurface)); *lppBackSurface=NULL; } if(fpReleasePool) fpReleasePool(); if(FAILED(IDirect3DDevice8_Reset((*lppDevice), &d3dpp))){ return FALSE; } if(FAILED(IDirect3DDevice8_GetBackBuffer( (*lppDevice), 0, D3DBACKBUFFER_TYPE_MONO, lppBackSurface )))return FALSE; IDirect3DDevice8_Clear( (*lppDevice), 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0, 0, 200), 1.0f, 0); if(fpRestorePool) fpRestorePool(); } } return TRUE; } HRESULT InitD3D( HWND hwndTarget, DWORD dwWidth, DWORD dwHeight, BOOL bWindowed, D3DFORMAT Format, LPDIRECT3D8 lpD3D, LPDIRECT3DDEVICE8 * lpDevice, D3DPRESENT_PARAMETERS * lpSavedPP, LPDIRECT3DSURFACE8 * lpBackBuffer) { D3DPRESENT_PARAMETERS d3dpp; D3DDISPLAYMODE d3ddm; HRESULT hr=0; if((*lpDevice)) IDirect3DDevice8_Release((*lpDevice)); ZeroMemory(&d3dpp, sizeof(d3dpp)); hr=IDirect3D8_GetAdapterDisplayMode( lpD3D, D3DADAPTER_DEFAULT, &d3ddm); if(FAILED(hr)){ return E_FAIL; } d3dpp.BackBufferWidth=dwWidth; d3dpp.BackBufferHeight=dwHeight; d3dpp.BackBufferFormat=bWindowed ? d3ddm.Format : Format; d3dpp.BackBufferCount=1; d3dpp.MultiSampleType=D3DMULTISAMPLE_NONE; d3dpp.SwapEffect=D3DSWAPEFFECT_DISCARD; d3dpp.hDeviceWindow=hwndTarget; d3dpp.Windowed=bWindowed; d3dpp.EnableAutoDepthStencil=TRUE; d3dpp.AutoDepthStencilFormat=D3DFMT_D16; d3dpp.FullScreen_RefreshRateInHz=0; d3dpp.FullScreen_PresentationInterval = bWindowed ? 0 : D3DPRESENT_INTERVAL_IMMEDIATE; d3dpp.Flags=D3DPRESENTFLAG_LOCKABLE_BACKBUFFER; hr=IDirect3D8_CreateDevice( lpD3D, D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwndTarget, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, lpDevice); if(FAILED(hr)){ return E_FAIL; } *lpSavedPP=d3dpp; if(FAILED(IDirect3DDevice8_GetBackBuffer( (*lpDevice), 0, D3DBACKBUFFER_TYPE_MONO, lpBackBuffer))) { return E_FAIL; } return S_OK; } BOOL CorrectWindowSize( HWND hWnd, DWORD nWidth, DWORD nHeight, BOOL bWindowed, HMENU hMenu){ if(bWindowed){ /* Make sure window styles are correct */ RECT rcWork; RECT rc; DWORD dwStyle; if(hMenu) SetMenu(hWnd, hMenu); dwStyle=GetWindowStyle(hWnd); dwStyle &= ~WS_POPUP; dwStyle |= WS_SYSMENU|WS_OVERLAPPED|WS_CAPTION | WS_DLGFRAME | WS_MINIMIZEBOX; SetWindowLong(hWnd, GWL_STYLE, dwStyle); SetRect(&rc, 0, 0, nWidth, nHeight); AdjustWindowRectEx(&rc, GetWindowStyle(hWnd), GetMenu(hWnd)!=NULL, GetWindowExStyle(hWnd)); SetWindowPos( hWnd, NULL, 0, 0, rc.right-rc.left, rc.bottom-rc.top, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE ); SetWindowPos( hWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE ); /* Make sure our window does not hang outside of the work area */ SystemParametersInfo( SPI_GETWORKAREA, 0, &rcWork, 0 ); GetWindowRect( hWnd, &rc ); if( rc.left < rcWork.left ) rc.left = rcWork.left; if( rc.top < rcWork.top ) rc.top = rcWork.top; SetWindowPos( hWnd, NULL, rc.left, rc.top, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE ); return TRUE; }else return TRUE; } HRESULT CopySurfaceToSurface16( RECT * lpSourceRect, LPDIRECT3DSURFACE8 lpSourceSurf, POINT * lpDestPoint, LPDIRECT3DSURFACE8 lpDestSurf, BOOL bTransparent, D3DCOLOR ColorKey) { HRESULT r=0; D3DLOCKED_RECT LockedSource; D3DLOCKED_RECT LockedDest; RECT SourceRect; POINT DestPoint; D3DSURFACE_DESC d3dsdSource; D3DSURFACE_DESC d3dsdDest; WORD * lpSourceData=NULL; WORD * lpDestData=NULL; int SourceOffset=0, DestOffset=0; int y=0, x=0; /* Make sure surfaces exist. */ if(!lpSourceSurf || !lpDestSurf)return E_POINTER; /* Prepare destination and source values. */ lpSourceSurf->lpVtbl->GetDesc(lpSourceSurf, &d3dsdSource); lpDestSurf->lpVtbl->GetDesc(lpDestSurf, &d3dsdDest); if(lpSourceRect) SourceRect = *lpSourceRect; else SetRect(&SourceRect, 0, 0, d3dsdSource.Width, d3dsdSource.Height); if(lpDestPoint) DestPoint = *lpDestPoint; else{ DestPoint.x=DestPoint.y=0; } /* Do a series of checks to make sure the parameters were valid. */ if(DestPoint.x<0)return E_FAIL; if(DestPoint.x>(int)d3dsdDest.Width)return E_FAIL; if(DestPoint.y<0)return E_FAIL; if(DestPoint.y>(int)d3dsdDest.Height)return E_FAIL; if(SourceRect.top<0)return E_FAIL; if(SourceRect.left<0)return E_FAIL; if(SourceRect.bottom>(int)d3dsdSource.Height)return E_FAIL; if(SourceRect.right>(int)d3dsdSource.Width)return E_FAIL; if((DestPoint.x+(SourceRect.right-SourceRect.left))>(int)d3dsdDest.Width)return E_FAIL; if((DestPoint.y+(SourceRect.bottom-SourceRect.top))>(int)d3dsdDest.Height)return E_FAIL; if((DestPoint.x+(SourceRect.left))<0)return E_FAIL; if((DestPoint.y+(SourceRect.top))<0)return E_FAIL; /* Lock the surfaces. */ r=lpSourceSurf->lpVtbl->LockRect(lpSourceSurf, &LockedSource, 0, D3DLOCK_READONLY); if(FAILED(r))return E_FAIL; r=lpDestSurf->lpVtbl->LockRect(lpDestSurf, &LockedDest, 0, 0); if(FAILED(r)){ lpSourceSurf->lpVtbl->UnlockRect(lpSourceSurf); return E_FAIL; } /* Adjust pitch to match a 4 bytes value for each pixel. */ LockedSource.Pitch /=2; LockedDest.Pitch /= 2; /* Obtain 16 bit pointer to data. */ lpSourceData = (WORD*)LockedSource.pBits; lpDestData = (WORD*)LockedDest.pBits; /* Prepare the appropriate offset. */ SourceOffset = SourceRect.left+LockedSource.Pitch*SourceRect.top; DestOffset = DestPoint.x+LockedDest.Pitch*DestPoint.y; /* Write the data pixel by pixel. */ for(y=0; y<(SourceRect.bottom-SourceRect.top); y++){ for(x=0; x<(SourceRect.right-SourceRect.left); x++){ if(bTransparent){ if(lpSourceData[SourceOffset]!=ColorKey){ lpDestData[DestOffset]=lpSourceData[SourceOffset]; } } else{ lpDestData[DestOffset]=lpSourceData[SourceOffset]; } DestOffset++; SourceOffset++; } SourceOffset += LockedSource.Pitch-(SourceRect.right-SourceRect.left); DestOffset += LockedDest.Pitch-(SourceRect.right-SourceRect.left); } /* Unlock the rectangles now that were through. */ lpSourceSurf->lpVtbl->UnlockRect(lpSourceSurf); lpDestSurf->lpVtbl->UnlockRect(lpDestSurf); return S_OK; } HRESULT CopySurfaceToSurface32( RECT * lpSourceRect, LPDIRECT3DSURFACE8 lpSourceSurf, POINT * lpDestPoint, LPDIRECT3DSURFACE8 lpDestSurf, BOOL bTransparent, D3DCOLOR ColorKey) { HRESULT r=0; D3DLOCKED_RECT LockedSource; D3DLOCKED_RECT LockedDest; RECT SourceRect; POINT DestPoint; D3DSURFACE_DESC d3dsdSource; D3DSURFACE_DESC d3dsdDest; DWORD * lpSourceData=NULL; DWORD * lpDestData=NULL; int SourceOffset=0, DestOffset=0; int y=0, x=0; /* Make sure surfaces exist. */ if(!lpSourceSurf || !lpDestSurf)return E_POINTER; /* Prepare destination and source values. */ lpSourceSurf->lpVtbl->GetDesc(lpSourceSurf, &d3dsdSource); lpDestSurf->lpVtbl->GetDesc(lpDestSurf, &d3dsdDest); if(lpSourceRect) SourceRect = *lpSourceRect; else SetRect(&SourceRect, 0, 0, d3dsdSource.Width, d3dsdSource.Height); if(lpDestPoint) DestPoint = *lpDestPoint; else{ DestPoint.x=DestPoint.y=0; } /* Do a series of checks to make sure the parameters were valid. */ if(DestPoint.x<0)return E_FAIL; if(DestPoint.x>(int)d3dsdDest.Width)return E_FAIL; if(DestPoint.y<0)return E_FAIL; if(DestPoint.y>(int)d3dsdDest.Height)return E_FAIL; if(SourceRect.top<0)return E_FAIL; if(SourceRect.left<0)return E_FAIL; if(SourceRect.bottom>(int)d3dsdSource.Height)return E_FAIL; if(SourceRect.right>(int)d3dsdSource.Width)return E_FAIL; if((DestPoint.x+(SourceRect.right-SourceRect.left))>(int)d3dsdDest.Width)return E_FAIL; if((DestPoint.y+(SourceRect.bottom-SourceRect.top))>(int)d3dsdDest.Height)return E_FAIL; if((DestPoint.x+(SourceRect.left))<0)return E_FAIL; if((DestPoint.y+(SourceRect.top))<0)return E_FAIL; /* Lock the surfaces. */ r=lpSourceSurf->lpVtbl->LockRect(lpSourceSurf, &LockedSource, 0, D3DLOCK_READONLY); if(FAILED(r))return E_FAIL; r=lpDestSurf->lpVtbl->LockRect(lpDestSurf, &LockedDest, 0, 0); if(FAILED(r)){ lpSourceSurf->lpVtbl->UnlockRect(lpSourceSurf); return E_FAIL; } /* Adjust pitch to match a 4 bytes value for each pixel. */ LockedSource.Pitch /=4; LockedDest.Pitch /= 4; /* Obtain 32 bit pointer to data. */ lpSourceData = (DWORD*)LockedSource.pBits; lpDestData = (DWORD*)LockedDest.pBits; /* Prepare the appropriate offset. */ SourceOffset = SourceRect.left+LockedSource.Pitch*SourceRect.top; DestOffset = DestPoint.x+LockedDest.Pitch*DestPoint.y; /* Write the data pixel by pixel. */ for(y=0; y<(SourceRect.bottom-SourceRect.top); y++){ for(x=0; x<(SourceRect.right-SourceRect.left); x++){ if(bTransparent){ if(lpSourceData[SourceOffset]!=ColorKey){ lpDestData[DestOffset]=lpSourceData[SourceOffset]; } } else{ lpDestData[DestOffset]=lpSourceData[SourceOffset]; } DestOffset++; SourceOffset++; } SourceOffset += LockedSource.Pitch-(SourceRect.right-SourceRect.left); DestOffset += LockedDest.Pitch-(SourceRect.right-SourceRect.left); } /* Unlock the rectangles now that were through. */ lpSourceSurf->lpVtbl->UnlockRect(lpSourceSurf); lpDestSurf->lpVtbl->UnlockRect(lpDestSurf); return S_OK; } HRESULT CopySurfaceToSurface( LPDIRECT3DDEVICE8 lpDevice, RECT * lpSourceRect, LPDIRECT3DSURFACE8 lpSourceSurf, POINT * lpDestPoint, LPDIRECT3DSURFACE8 lpDestSurf, BOOL bTransparent, D3DCOLOR ColorKey) { D3DSURFACE_DESC descSrc, descDest; IDirect3DSurface8_GetDesc( lpSourceSurf, &descSrc); IDirect3DSurface8_GetDesc( lpDestSurf, &descDest); if(descDest.Format != descSrc.Format) return E_FAIL; if(bTransparent){ if(descDest.Format==D3DFMT_R5G6B5) return CopySurfaceToSurface16( lpSourceRect, lpSourceSurf, lpDestPoint, lpDestSurf, bTransparent, ColorKey); else return CopySurfaceToSurface32( lpSourceRect, lpSourceSurf, lpDestPoint, lpDestSurf, bTransparent, ColorKey); }else{ return IDirect3DDevice8_CopyRects( lpDevice, lpSourceSurf, lpSourceRect, 1, lpDestSurf, lpDestPoint); } } <file_sep>/games/Explor2002/Source/Game/tilemgr.h #ifndef __TILEMGR_H__ #define __TILEMGR_H__ #include "tiles.h" #include "bmp.h" #include "defines.h" class CTileSet{ private: CTileObject *m_cTiles[NUM_TILES]; //CBitmapReader bitmap; public: CTileSet(); ~CTileSet(); BOOL draw(LPDIRECTDRAWSURFACE dest, int index, int x, int y); void InitTileObjects(); BOOL GetImages(CBitmapReader *bitmap); BOOL Restore(); BOOL Release(); //BOOL LoadImageFile(char *filename); }; #endif<file_sep>/games/Legacy-Engine/Source/engine/lv_con.cpp #include <stdio.h> #include "lv_con.h" #include "lg_err.h" #include "lt_sys.h" #include "lg_cvars.h" #include "lg_func.h" #include "../lc_sys2/lc_sys2.h" #define CONSOLE_WIDTH 640.0f #define CONSOLE_HEIGHT 480.0f /********************************************** *** The Legacy Game Visual Console (CLVCon) *** **********************************************/ CLVCon::CLVCon(): m_lpFont(LG_NULL), m_dwViewHeight(0), m_dwFontHeight(0), //m_hConsole(LG_NULL), m_pDevice(LG_NULL), m_bActive(0), m_bDeactivating(0), m_fPosition(0.0f), m_nScrollPos(0), m_dwLastUpdate(0), m_bCaretOn(LG_FALSE), m_dwLastCaretChange(0), m_bFullMode(LG_FALSE) { m_szMessage[0]=0; } CLVCon::CLVCon(IDirect3DDevice9* pDevice): m_lpFont(LG_NULL), m_dwViewHeight(0), m_dwFontHeight(0), m_pDevice(LG_NULL), m_bActive(0), m_bDeactivating(0), m_fPosition(0.0f), m_nScrollPos(0), m_dwLastUpdate(0), m_bCaretOn(LG_FALSE), m_dwLastCaretChange(0), m_bFullMode(LG_FALSE) { m_szMessage[0]=0; Create(pDevice); } CLVCon::~CLVCon() { Delete(); } lg_bool CLVCon::IsActive() { return m_bActive; } void CLVCon::SetMessage(lg_dword nSlot, lg_char* szMessage) { lg_char* szTemp=nSlot==1?m_szMessage:m_szMessage2; if(szMessage==LG_NULL) szTemp[0]=0; else LG_strncpy(szTemp, szMessage, 127); } lg_bool CLVCon::Create(IDirect3DDevice9* pDevice) { Delete(); D3DVIEWPORT9 ViewPort; lg_pstr szBGTexture=CV_Get(CVAR_lc_BG)->szValue; lg_dword dwFontWidth=0, dwFontHeight=0; /*We need to get the font size and convert it to a componet size.*/ FontStringToSize( &dwFontHeight, &dwFontWidth, CV_Get(CVAR_lc_FontSize)->szValue); pDevice->GetViewport(&ViewPort); m_dwViewHeight=ViewPort.Height; m_dwFontHeight=dwFontHeight; /* Attempt to laod the background. */ lg_bool bResult=m_Background.CreateFromFile( pDevice, szBGTexture, LG_NULL, (lg_dword)CONSOLE_WIDTH, (lg_dword)CONSOLE_HEIGHT, 0x00000000); /* If we can't create a background from a texture, we attempt to do it from a color. */ if(!bResult) { Err_Printf("Could not load texture from \"%s\" for console background, using color.", szBGTexture); bResult=m_Background.CreateFromColor( pDevice, (lg_dword)CONSOLE_WIDTH, (lg_dword)CONSOLE_HEIGHT, 0xFF8080FF); } if(!bResult) { Err_Printf("Could not load console background, failing."); return LG_FALSE; } // Attemp to load a font for the console. if(0)//CVar_GetValue(cvars, "lc_UseLegacyFont", LG_NULL) || CVar_GetValue(cvars, "v_Force16BitTextures", LG_NULL)) { Err_Printf("Using Legacy Font"); lg_dword dwWidthInFile=0, dwHeightInFile=0; FontStringToSize(&dwHeightInFile, &dwWidthInFile, CV_Get(CVAR_lc_LegacyFontSizeInFile)->szValue); if(!dwFontWidth) dwFontWidth=dwFontHeight/2; /* m_pFont=Font_Create2( pDevice, CVar_Get(cvars, "lc_LegacyFont", LG_NULL), (lg_byte)dwFontWidth, (lg_byte)dwFontHeight, LG_FALSE, (lg_byte)dwWidthInFile, (lg_byte)dwHeightInFile, 0); */ m_lpFont=CLFont::Create( pDevice, CV_Get(CVAR_lc_LegacyFont)->szValue, (lg_byte)dwFontWidth, (lg_byte)dwFontHeight, LG_FALSE, (lg_byte)dwWidthInFile, (lg_byte)dwHeightInFile, 0); } else { m_lpFont=CLFont::Create( pDevice, "fixedsys",//CVar_Get(cvars, "lc_Font", LG_NULL), (lg_byte)dwFontWidth, (lg_byte)dwFontHeight, LG_TRUE, 0, 0, (0xFF<<24)|CV_Get(CVAR_lc_FontColor)->nValue); /* m_pFont=Font_Create2( pDevice, CVar_Get(cvars, "lc_Font", LG_NULL), (lg_byte)dwFontWidth, (lg_byte)dwFontHeight, LG_TRUE, 0, 0, (0xFF<<24)|(lg_dword)CVar_GetValue(cvars, "lc_FontColor", LG_NULL)); */ } /* if(!m_lpFont) { Err_Printf("Could not load font for console, failing."); //L2DI_Delete(m_pBackground); m_Background.Delete(); return LG_FALSE; } */ /* Attach the console */ /* Set the last time the console was updated to now. */ m_dwLastUpdate=LT_GetTimeMS(); /* We need to set a few starting values for the console. */ m_bCaretOn=LG_TRUE; m_dwLastCaretChange=LT_GetTimeMS(); m_bActive=LG_FALSE; m_bDeactivating=LG_TRUE; m_fPosition=0.0f; m_bFullMode=LG_FALSE; m_pDevice=pDevice; pDevice->AddRef(); return LG_TRUE; } void CLVCon::Delete() { /* Delete the bg and the font. */ m_Background.Delete(); if(m_lpFont) { m_lpFont->Delete(); delete m_lpFont; m_lpFont=LG_NULL; } /* Delete the console itself. */ L_safe_release(m_pDevice); m_lpFont=LG_NULL; m_dwViewHeight=0; m_dwFontHeight=0; //m_hConsole=LG_NULL; m_pDevice=LG_NULL; m_bActive=0; m_bDeactivating=0; m_fPosition=0.0f; m_nScrollPos=0; m_dwLastUpdate=0; m_bCaretOn=LG_FALSE; m_dwLastCaretChange=0; m_bFullMode=LG_FALSE; } lg_bool CLVCon::Render() { float fRenderPos=0; lg_dword i=0; lg_long nStart=0; lg_long nCharHeight=0; /* Update the position, and activity of the console. */ UpdatePos(); m_dwLastUpdate=LT_GetTimeMS(); if(m_szMessage[0]!=0 || m_szMessage2!=0) { m_lpFont->Begin(); m_lpFont->DrawString(m_szMessage, 0, 0); m_lpFont->DrawString(m_szMessage2, 0, 8); m_lpFont->End(); } if(!m_bActive || !m_pDevice) return LG_TRUE; nCharHeight=m_dwFontHeight;//16;//lpVCon->lpFont->m_dwFontHeight; /* Render the background at the position. */ CLImg2D::StartStopDrawing(m_pDevice, (lg_long)CONSOLE_WIDTH, (lg_long)CONSOLE_HEIGHT, LG_TRUE); m_Background.Render(0.0f, m_fPosition-CONSOLE_HEIGHT); CLImg2D::StartStopDrawing(m_pDevice, 0, 0, LG_FALSE); /* Now render all visible text. */ /* First we render the active entry. */ //Font_GetDims(m_pFont, &fontdims); lg_bool bD3DFont=LG_FALSE; m_lpFont->GetDims(LG_NULL, LG_NULL, &bD3DFont); if(bD3DFont) fRenderPos=m_fPosition*m_dwViewHeight/CONSOLE_HEIGHT-nCharHeight-8; else fRenderPos=m_fPosition-nCharHeight-8; m_lpFont->Begin(); { char szTemp[1024]; _snprintf(szTemp, 1022, "]%s", LC_GetActiveLine()); if(m_bCaretOn) strncat(szTemp, "_", 1); m_lpFont->DrawString( szTemp, 8, (lg_long)fRenderPos); } fRenderPos-=nCharHeight; if(m_nScrollPos) { m_lpFont->DrawString( "^ ^ ^ ^", 8, (lg_long)fRenderPos); nStart=2; fRenderPos-=nCharHeight; } else nStart=0; const lg_char* szLine=LC_GetLine(nStart+m_nScrollPos, LG_TRUE); while(fRenderPos>=(-nCharHeight) && szLine) { m_lpFont->DrawString( (char*)szLine, 8, (lg_long)fRenderPos); szLine=LC_GetNextLine(); fRenderPos-=nCharHeight; } m_lpFont->End(); return LG_TRUE; } lg_bool CLVCon::Validate() { if(!m_pDevice) return LG_FALSE; m_Background.Validate(LG_NULL); m_lpFont->Validate(); D3DVIEWPORT9 ViewPort; m_pDevice->GetViewport(&ViewPort); m_dwViewHeight=ViewPort.Height; return LG_TRUE; } lg_bool CLVCon::Invalidate() { m_Background.Invalidate(); m_lpFont->Invalidate(); return LG_TRUE; } void CLVCon::Toggle() { m_bDeactivating=!m_bDeactivating; if(!m_bDeactivating) m_bActive=LG_TRUE; } /* VCon_OnChar - processes input through the graphical console, it checks to see if it should activate/deactive and then it checks to see if it is active. If it isn't active it won't do anything, if it is, it can scoll up the entry list, and it will pass any other data to the actual console. */ lg_bool CLVCon::OnCharA(char c) { if(!m_bActive) return LG_TRUE; if(c==CON_KEY1 || c==CON_KEY2) { Toggle(); return LG_TRUE; } /* There are two special coes, LK_PAGEUP and LK_PAGEDOWN that are passed from win_sys.c when the pageup and pagedown keys are pressed, that way the console can know if it should scroll up or down. */ switch(c) { case LK_PAGEUP: m_nScrollPos++; if(m_nScrollPos>=(lg_long)LC_GetNumLines()-2)//((lg_long)Con_GetNumEntries(m_hConsole)-2)) m_nScrollPos=(lg_long)LC_GetNumLines()-2;//Con_GetNumEntries(m_hConsole)-2; break; case LK_PAGEDOWN: m_nScrollPos--; if(m_nScrollPos<0) m_nScrollPos=0; break; case LK_END: m_nScrollPos=0; break; default: LC_OnChar(c); break; } return LG_TRUE; } lg_bool CLVCon::UpdatePos() { float fElapsedTime=0; float fScrollDist=0.0f; if(!m_bActive) return LG_FALSE; if((LT_GetTimeMS()-m_dwLastCaretChange)>GetCaretBlinkTime()) { m_bCaretOn=!m_bCaretOn; m_dwLastCaretChange=LT_GetTimeMS(); } /* In case the console is cleared we make sure teh current console position is allowed. */ if(m_nScrollPos>(lg_long)LC_GetNumLines()) m_nScrollPos=0; fElapsedTime=(float)(LT_GetTimeMS()-m_dwLastUpdate); fScrollDist=fElapsedTime/1.5f; if(m_bDeactivating) { if(m_fPosition<=0.0f) { m_fPosition=0.0f; m_bActive=LG_FALSE; return LG_TRUE; } m_fPosition-=fScrollDist; } else { m_fPosition+=fScrollDist; if(m_fPosition>(CONSOLE_HEIGHT/(2-m_bFullMode))) m_fPosition=(CONSOLE_HEIGHT/(2-m_bFullMode)); } return LG_TRUE; } __inline void CLVCon::FontStringToSize(lg_dword* pHeight, lg_dword* pWidth, lg_pstr szString) { lg_dword dwLen=L_strlen(szString); lg_bool bFoundHeight=LG_FALSE; char szHeight[32]; lg_pstr szWidth=LG_NULL; lg_dword i=0; if(dwLen<1) { *pWidth=0; *pHeight=16; } for(i=0; i<dwLen; i++) { if(!bFoundHeight) { if(szString[i]=='X' || szString[i]=='x') { bFoundHeight=LG_TRUE; szHeight[i]=0; szWidth=&szString[i+1]; break; } szHeight[i]=szString[i]; } } *pHeight=L_atol(szHeight); *pWidth=L_atol(szWidth); return; } <file_sep>/games/Legacy-Engine/Scrapped/old/lv_d3dfont.h /* lv_font.h - Header for the legacy font functionality. */ #ifndef __LV_D3DFONT_H__ #define __LV_D3DFONT_H__ #include <d3dx9.h> #include "lv_img2d.h" #ifdef __cplusplus extern "C"{ #endif /* __cplusplus */ typedef struct _LVFONT{ ID3DXFont* m_lpFont; ID3DXSprite* m_lpSurface; L_dword m_dwFontWidth; L_dword m_dwFontHeight; L_bool m_bDrawing; }LVFONT, *LPLVFONT; LVFONT* Font_Create( IDirect3DDevice9* lpDevice, char* szFontName, L_dword dwWidth, L_dword dwHeight, L_dword dwWeight); L_bool Font_Delete(LVFONT* lpFont); L_bool Font_DrawString( LVFONT* lpFont, char* szString, L_long x, L_long y); L_bool Font_Validate(LVFONT* lpFont, IDirect3DDevice9* lpDevice); L_bool Font_Invalidate(LVFONT* lpFont); L_bool Font_Begin(LVFONT* lpFont); L_bool Font_End(LVFONT* lpFont); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /*__LV_D3DFONT_H__*/<file_sep>/games/Legacy-Engine/Scrapped/libs/lc_sys1/lc_win.c #include <windows.h> #include "lc_sys.h" #define CD_LINES 15 #define CD_FONTSIZE 15 #define ID_QUITBUTTON 103 #define ID_TEXTEDIT 102 LRESULT CALLBACK EntryProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { static HFONT hFont=NULL; static HLCONSOLE hConsole=NULL; static BOOL bBlinkOn=0; static BOOL bHasFocus=0; #define BLINKER_TIMER (0x12001200) switch(uMsg) { case WM_DESTROY: KillTimer(hwnd, BLINKER_TIMER); break; case WM_SETFOCUS: bHasFocus=TRUE; break; case WM_KILLFOCUS: bHasFocus=FALSE; break; case WM_TIMER: if(wParam==BLINKER_TIMER) { bBlinkOn=!bBlinkOn; InvalidateRect(hwnd, NULL, TRUE); } break; case WM_CREATE: /* Get the font that was passed over here. */ hFont=((LPCREATESTRUCT)lParam)->lpCreateParams; SetTimer(hwnd, BLINKER_TIMER, GetCaretBlinkTime(), NULL); break; case WM_USER_INSTALLCONSOLE: hConsole=(HLCONSOLE)lParam; /* Fall through and update. */ case WM_USER_UPDATE: InvalidateRect(hwnd, NULL, TRUE); break; case WM_LBUTTONDOWN: case WM_RBUTTONDOWN: SetFocus(hwnd); break; case WM_CHAR: Con_OnChar(hConsole, (WORD)wParam); SendMessage(GetParent(hwnd), WM_USER_UPDATE, 0, 0); break; case WM_PAINT: { HDC hdc=NULL; PAINTSTRUCT ps; RECT wrc; TEXTMETRIC tm; char szString[1024]; HFONT hOldFont=NULL; int i=0, j=0; unsigned long nNumEntries=0; GetClientRect(hwnd, &wrc); nNumEntries=Con_GetNumEntries(hConsole); hdc=BeginPaint(hwnd, &ps); hOldFont=SelectObject(hdc, hFont); GetTextMetrics(hdc, &tm); if(hConsole) { Con_GetEntry(hConsole, 1, szString); if(bBlinkOn && bHasFocus) strcat(szString, "_"); TextOut(hdc, 0, 0, szString, strlen(szString)); } SelectObject(hdc, hOldFont); EndPaint(hwnd, &ps); break; } default: return DefWindowProc(hwnd, uMsg, wParam, lParam); } return 0l; } LRESULT CALLBACK ConsoleProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { static HFONT hFont=NULL; SCROLLINFO si; static HLCONSOLE hConsole=NULL; switch(uMsg) { case WM_CREATE: { unsigned long nEntries=Con_GetNumEntries(hConsole); si.cbSize=sizeof(SCROLLINFO); si.fMask=SIF_ALL; si.nMin=1; si.nMax=nEntries; si.nPos=nEntries; si.nTrackPos=0; si.nPage=(CD_LINES+1); SetScrollInfo(hwnd, SB_VERT, &si, TRUE); /* Get the font that was passed over here. */ hFont=((LPCREATESTRUCT)lParam)->lpCreateParams; break; } case WM_USER_INSTALLCONSOLE: hConsole=(HLCONSOLE)lParam; /* Fall through and update. */ case WM_USER_UPDATE: si.cbSize=sizeof(SCROLLINFO); si.fMask=SIF_POS; GetScrollInfo(hwnd, SB_VERT, &si); si.fMask=SIF_RANGE|SIF_POS|SIF_PAGE; si.nMax=Con_GetNumEntries(hConsole); si.nMin=1; si.nPage=(CD_LINES+1); si.nPos=si.nMax; SetScrollInfo(hwnd, SB_VERT, &si, TRUE); InvalidateRect(hwnd, NULL, TRUE); break; case WM_VSCROLL: { si.cbSize=sizeof(SCROLLINFO); si.fMask=SIF_ALL; GetScrollInfo(hwnd, SB_VERT, &si); SetScrollInfo(hwnd, SB_VERT, &si, TRUE); switch(LOWORD(wParam)) { case SB_PAGEDOWN: si.nPos+=si.nPage/2; break; case SB_LINEDOWN: si.nPos++; break; case SB_PAGEUP: si.nPos-=si.nPage/2; break; case SB_LINEUP: si.nPos--; break; case SB_THUMBPOSITION: case SB_THUMBTRACK: si.nPos=si.nTrackPos; break; case SB_TOP: si.nPos=si.nMin; break; case SB_BOTTOM: si.nPos=si.nMax; break; } SetScrollInfo(hwnd, SB_VERT, &si, TRUE); RedrawWindow(hwnd, NULL, NULL, RDW_ERASE|RDW_INVALIDATE); break; } case WM_PAINT: { HDC hdc=NULL; PAINTSTRUCT ps; RECT wrc; TEXTMETRIC tm; HFONT hOldFont=NULL; char szString[1024]; int i=0, j=0; unsigned long nNumEntries=0; GetClientRect(hwnd, &wrc); nNumEntries=Con_GetNumEntries(hConsole); hdc=BeginPaint(hwnd, &ps); hOldFont=SelectObject(hdc, hFont); GetTextMetrics(hdc, &tm); /* Update the scroll info. */ si.cbSize=sizeof(SCROLLINFO); si.fMask=SIF_POS|SIF_PAGE|SIF_RANGE; GetScrollInfo(hwnd, SB_VERT, &si); for(i=nNumEntries-(si.nPos+si.nPage-2)+1, j=1; ((j<=(int)si.nPage) && (i<=(int)nNumEntries)); i++, j++) { strcpy(szString, Con_GetEntry(hConsole, i, NULL)); TextOut(hdc, 0, wrc.bottom-(tm.tmHeight*j), szString, strlen(szString)); } SelectObject(hdc, hOldFont); EndPaint(hwnd, &ps); break; } case WM_DESTROY: break; default: return DefWindowProc(hwnd, uMsg, wParam, lParam); } return 0l; } LRESULT CALLBACK LCWindowProc(HWND hwnd,UINT uMsg,WPARAM wParam,LPARAM lParam) { static HWND hwndConsole=NULL; static HWND hwndEntry=NULL; static HFONT hFont=NULL; static HLCONSOLE hConsole=NULL; static HWND hwndQuitButton=NULL; switch(uMsg) { case WM_CREATE: { char szConsoleText[]="ConsoleWindow"; char szEntryText[]="EntryWindow"; HINSTANCE hInst=GetModuleHandle(NULL); RECT rcMainWindow; WNDCLASS wc; wc.cbClsExtra=0; wc.cbWndExtra=0; wc.hbrBackground=GetStockObject(WHITE_BRUSH); wc.hCursor=LoadCursor(NULL, IDC_ARROW); wc.hIcon=NULL; wc.hInstance=hInst; wc.lpfnWndProc=ConsoleProc; wc.lpszClassName=szConsoleText; wc.lpszMenuName=NULL; wc.style=CS_VREDRAW|CS_HREDRAW; RegisterClass(&wc); GetClientRect(hwnd, &rcMainWindow); /* Select the font we want. */ hFont=CreateFont( CD_FONTSIZE, 0, 0, 0, FW_DEMIBOLD, FALSE, FALSE, FALSE, ANSI_CHARSET, 0, 0, DEFAULT_QUALITY, DEFAULT_PITCH, "Courier New"); hwndConsole=CreateWindow( szConsoleText, szConsoleText, WS_CHILD|WS_VSCROLL|WS_VISIBLE, 5, 5, rcMainWindow.right-10, CD_LINES*CD_FONTSIZE, hwnd, NULL, hInst, hFont); UpdateWindow(hwnd); ShowWindow(hwnd, SW_SHOWNORMAL); wc.cbClsExtra=0; wc.cbWndExtra=0; wc.hbrBackground=GetStockObject(WHITE_BRUSH); wc.hCursor=LoadCursor(NULL, IDC_ARROW); wc.hIcon=NULL; wc.hInstance=hInst; wc.lpfnWndProc=EntryProc; wc.lpszClassName=szEntryText; wc.lpszMenuName=NULL; wc.style=CS_VREDRAW|CS_HREDRAW; RegisterClass(&wc); hwndEntry=CreateWindowEx( WS_EX_CLIENTEDGE, szEntryText, szEntryText, WS_CHILD|WS_VISIBLE, 5, CD_LINES*CD_FONTSIZE+10, rcMainWindow.right-10, 20, hwnd, (HMENU)ID_TEXTEDIT, hInst, hFont); UpdateWindow(hwndEntry); ShowWindow(hwndEntry, SW_SHOWNORMAL); hwndQuitButton=CreateWindow( "BUTTON", "Quit", WS_CHILD|WS_VISIBLE, (rcMainWindow.right-75)/2, rcMainWindow.bottom-25-10, 75, 25, hwnd, (HMENU)ID_QUITBUTTON, hInst, 0); SetFocus(hwndEntry); return DefWindowProc(hwnd, uMsg, wParam, lParam); break; } case WM_USER_INSTALLCONSOLE: hConsole=(HLCONSOLE)lParam; SendMessage(hwndConsole, WM_USER_INSTALLCONSOLE, wParam, lParam); SendMessage(hwndEntry, WM_USER_INSTALLCONSOLE, wParam, lParam); /* And fall through and update. */ case WM_USER_UPDATE: SendMessage(hwndConsole, WM_USER_UPDATE, 0, 0); SendMessage(hwndEntry, WM_USER_UPDATE, 0, 0); break; case WM_COMMAND: { switch(LOWORD(wParam)) { case ID_QUITBUTTON: SendMessage(hwnd, WM_CLOSE, 0, 0); break; default: break; } break; } case WM_SETFOCUS: case WM_ACTIVATEAPP: SetFocus(hwndEntry); break; case WM_CLOSE: DestroyWindow(hwnd); break; case WM_DESTROY: DestroyWindow(hwndConsole); DeleteObject(hFont); PostQuitMessage(0); default: return DefWindowProc(hwnd, uMsg, wParam, lParam); } return 0l; } void* Con_CreateDlgBox() { #ifdef NDEBUG char szLCText[]="Legacy Console"; #else /*NDEBUG*/ char szLCText[]="Debug Legacy Console"; #endif /*NDEBUG*/ WNDCLASS wc; HINSTANCE hInstance=GetModuleHandle("lconsole.dll"); wc.cbClsExtra=0; wc.cbWndExtra=0; wc.hbrBackground=(HBRUSH)COLOR_WINDOW; wc.hCursor=LoadCursor(NULL, IDI_APPLICATION); wc.hIcon=0; wc.hInstance=hInstance; wc.lpfnWndProc=LCWindowProc; wc.lpszClassName=szLCText; wc.lpszMenuName=NULL; wc.style=0; RegisterClass(&wc); return CreateWindow( szLCText, szLCText, WS_SYSMENU|WS_MINIMIZEBOX, CW_USEDEFAULT, CW_USEDEFAULT, 400, 320, NULL, NULL, hInstance, 0); } <file_sep>/tools/PodSyncPrep/src/podsyncp/PodSyncPView.java /* * PodSyncPView.java */ package podsyncp; import org.jdesktop.application.Action; import org.jdesktop.application.ResourceMap; import org.jdesktop.application.SingleFrameApplication; import org.jdesktop.application.FrameView; import org.jdesktop.application.TaskMonitor; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Timer; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; /** * The application's main frame. */ public class PodSyncPView extends FrameView implements ActionListener, WarningI { public PodSyncPView(SingleFrameApplication app) { super(app); m_strWarning = ""; initComponents(); //this.setComponent(mainPanel); // status bar initialization - message timeout, idle icon and busy animation, etc ResourceMap resourceMap = getResourceMap(); int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout"); messageTimer = new Timer(messageTimeout, new ActionListener() { public void actionPerformed(ActionEvent e) { statusMessageLabel.setText(""); } }); messageTimer.setRepeats(false); int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate"); for (int i = 0; i < busyIcons.length; i++) { busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]"); } busyIconTimer = new Timer(busyAnimationRate, new ActionListener() { public void actionPerformed(ActionEvent e) { busyIconIndex = (busyIconIndex + 1) % busyIcons.length; statusAnimationLabel.setIcon(busyIcons[busyIconIndex]); } }); idleIcon = resourceMap.getIcon("StatusBar.idleIcon"); statusAnimationLabel.setIcon(idleIcon); progressBar.setVisible(false); // connecting action tasks to status bar via TaskMonitor TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext()); taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent evt) { String propertyName = evt.getPropertyName(); if ("started".equals(propertyName)) { if (!busyIconTimer.isRunning()) { statusAnimationLabel.setIcon(busyIcons[0]); busyIconIndex = 0; busyIconTimer.start(); } progressBar.setVisible(true); progressBar.setIndeterminate(true); } else if ("done".equals(propertyName)) { busyIconTimer.stop(); statusAnimationLabel.setIcon(idleIcon); progressBar.setVisible(false); progressBar.setValue(0); } else if ("message".equals(propertyName)) { String text = (String) (evt.getNewValue()); statusMessageLabel.setText((text == null) ? "" : text); messageTimer.restart(); } else if ("progress".equals(propertyName)) { int value = (Integer) (evt.getNewValue()); progressBar.setVisible(true); progressBar.setIndeterminate(false); progressBar.setValue(value); } } }); m_settings = new Settings(this); m_mgr = new SyncManager(this, m_settings); m_listA = new DragList(m_mgr, SyncManager.Location.ASSIGNED); m_listU = new DragList(m_mgr, SyncManager.Location.UNASSIGNED); m_scrollA = new JScrollPane(m_listA); m_scrollU = new JScrollPane(m_listU); m_panelButtons = new JPanel(); m_btnDoIt = new JButton("Process Files"); //m_panelButtons.add(new JButton("^")); //m_panelButtons.add(new JButton("V")); m_panelButtons.add(m_btnDoIt); m_btnDoIt.addActionListener(this); m_txtWarning = new JTextArea(); m_txtWarning.setColumns(60); m_txtWarning.setRows(5); m_txtWarning.setLineWrap(false); m_txtWarning.setEditable(false); m_scrollWarning = new JScrollPane(m_txtWarning); m_panelButtons.add(m_scrollWarning); tabPrep.add(m_scrollA); tabPrep.add(m_panelButtons); tabPrep.add(m_scrollU); tabWindow.setTitleAt(0, "Download"); tabWindow.setTitleAt(1, "Prep"); DLPanel p = new DLPanel(); tabDownload.add(p); /* mainPanel.add(m_scrollA); mainPanel.add(m_panelButtons); mainPanel.add(m_scrollU); */ m_mgr.printWarning("Initialized."); } @Action public void showAboutBox() { if (aboutBox == null) { JFrame mainFrame = PodSyncPApp.getApplication().getMainFrame(); aboutBox = new PodSyncPAboutBox(mainFrame); aboutBox.setLocationRelativeTo(mainFrame); } PodSyncPApp.getApplication().show(aboutBox); } @Action public void showSettingsBox() { JFrame mainFrame = PodSyncPApp.getApplication().getMainFrame(); SettingsBox setBox = new SettingsBox(mainFrame, true, m_settings); setBox.setLocationRelativeTo(mainFrame); PodSyncPApp.getApplication().show(setBox); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { menuBar = new javax.swing.JMenuBar(); javax.swing.JMenu fileMenu = new javax.swing.JMenu(); javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem(); settingsMenu = new javax.swing.JMenu(); editMenuItem = new javax.swing.JMenuItem(); javax.swing.JMenu helpMenu = new javax.swing.JMenu(); javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem(); statusPanel = new javax.swing.JPanel(); javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator(); statusMessageLabel = new javax.swing.JLabel(); statusAnimationLabel = new javax.swing.JLabel(); progressBar = new javax.swing.JProgressBar(); mainPanel = new javax.swing.JPanel(); tabWindow = new javax.swing.JTabbedPane(); tabDownload = new javax.swing.JPanel(); tabPrep = new javax.swing.JPanel(); menuBar.setName("menuBar"); // NOI18N org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(podsyncp.PodSyncPApp.class).getContext().getResourceMap(PodSyncPView.class); fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N fileMenu.setName("fileMenu"); // NOI18N javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(podsyncp.PodSyncPApp.class).getContext().getActionMap(PodSyncPView.class, this); exitMenuItem.setAction(actionMap.get("quit")); // NOI18N exitMenuItem.setName("exitMenuItem"); // NOI18N fileMenu.add(exitMenuItem); menuBar.add(fileMenu); settingsMenu.setText(resourceMap.getString("settingsMenu.text")); // NOI18N settingsMenu.setName("settingsMenu"); // NOI18N editMenuItem.setAction(actionMap.get("showSettingsBox")); // NOI18N editMenuItem.setText(resourceMap.getString("editMenuItem.text")); // NOI18N editMenuItem.setName("editMenuItem"); // NOI18N settingsMenu.add(editMenuItem); menuBar.add(settingsMenu); helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N helpMenu.setName("helpMenu"); // NOI18N aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N aboutMenuItem.setName("aboutMenuItem"); // NOI18N helpMenu.add(aboutMenuItem); menuBar.add(helpMenu); statusPanel.setName("statusPanel"); // NOI18N statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N statusMessageLabel.setName("statusMessageLabel"); // NOI18N statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N progressBar.setName("progressBar"); // NOI18N javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel); statusPanel.setLayout(statusPanelLayout); statusPanelLayout.setHorizontalGroup( statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 604, Short.MAX_VALUE) .addGroup(statusPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(statusMessageLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 434, Short.MAX_VALUE) .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(statusAnimationLabel) .addContainerGap()) ); statusPanelLayout.setVerticalGroup( statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(statusPanelLayout.createSequentialGroup() .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(statusMessageLabel) .addComponent(statusAnimationLabel) .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(3, 3, 3)) ); mainPanel.setAutoscrolls(true); mainPanel.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); mainPanel.setName("mainPanel"); // NOI18N mainPanel.setLayout(new java.awt.GridLayout(1, 1)); tabWindow.setName("tabWindow"); // NOI18N tabDownload.setName("tabDownload"); // NOI18N tabWindow.addTab(resourceMap.getString("tabDownload.TabConstraints.tabTitle"), tabDownload); // NOI18N tabPrep.setName("tabPrep"); // NOI18N tabPrep.setLayout(new java.awt.GridLayout(3, 1)); tabWindow.addTab(resourceMap.getString("tabPrep.TabConstraints.tabTitle"), tabPrep); // NOI18N mainPanel.add(tabWindow); setComponent(mainPanel); setMenuBar(menuBar); setStatusBar(statusPanel); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JMenuItem editMenuItem; private javax.swing.JPanel mainPanel; private javax.swing.JMenuBar menuBar; private javax.swing.JProgressBar progressBar; private javax.swing.JMenu settingsMenu; private javax.swing.JLabel statusAnimationLabel; private javax.swing.JLabel statusMessageLabel; private javax.swing.JPanel statusPanel; private javax.swing.JPanel tabDownload; private javax.swing.JPanel tabPrep; private javax.swing.JTabbedPane tabWindow; // End of variables declaration//GEN-END:variables private final Timer messageTimer; private final Timer busyIconTimer; private final Icon idleIcon; private final Icon[] busyIcons = new Icon[15]; private int busyIconIndex = 0; private JDialog aboutBox; private SyncManager m_mgr; private DragList m_listU; private DragList m_listA; private JScrollPane m_scrollU; private JScrollPane m_scrollA; private JPanel m_panelButtons; private JButton m_btnDoIt; private JScrollPane m_scrollWarning; private JTextArea m_txtWarning; private Settings m_settings; private String m_strWarning; public void actionPerformed(ActionEvent e) { if (e.getSource() == m_btnDoIt) { JFrame mainFrame = PodSyncPApp.getApplication().getMainFrame(); WaitWindow wnd = new WaitWindow(mainFrame, m_mgr); m_listA.updateListData(); m_listU.updateListData(); } } public void setWarning(String str) { m_strWarning = str; //JOptionPane.showMessageDialog(null, str, null, JOptionPane.WARNING_MESSAGE); if (m_txtWarning != null) { m_txtWarning.setText(m_strWarning); } } public void appendWarning(String str) { m_strWarning += str; setWarning(m_strWarning); } } <file_sep>/tools/GFX/GFXG7Demo/Main.cpp /* BaseGFXG7.exe - Example of implimentation of GFXG7 Copyright (c) 2003, <NAME> */ #include <ddraw.h> #include <tchar.h> #include <windows.h> #include <windowsx.h> #include "gfxg7.h" #define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } } #define SAFE_DELETE_ARRAY(p) { if(p) { delete[] (p); (p)=NULL; } } #define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } } //DirectDraw globals LPDIRECTDRAW7 g_lpDDraw=NULL; LPDIRECTDRAWSURFACE7 g_lpPrimary=NULL; LPDIRECTDRAWSURFACE7 g_lpBackBuffer=NULL; //Necessary globals BOOL bActiveApp=TRUE; BOOL g_bWindowed=FALSE; //Data about the interface RECT g_rcWindow; DWORD g_dwTransparentColor=0; DWORD g_dwWidth=0; DWORD g_dwHeight=0; DWORD g_dwColorDepth=0; //Image declarations CImage7 TestImage; CImage7 TestBackground; /* ShutDownApp() should shut down anything that needs to be shut down. In this case all DirectDraw objects are released. */ void ShutDownApp(){ //need to release all DirectDraw objects //Release the test image. TestImage.Release(); TestBackground.Release(); //Make sure to release back buffer before primary. SAFE_RELEASE(g_lpBackBuffer); SAFE_RELEASE(g_lpPrimary); //Set cooperative level back to normal. g_lpDDraw->SetCooperativeLevel(NULL, DDSCL_NORMAL); SAFE_RELEASE(g_lpDDraw); } /* RestoreGraphics() Should be used any time the surfaces are lost. Generally if the primary surface has been lost, all other surfaces are lost. Note the PageFlip() function to see when this function is used. */ HRESULT RestoreGraphics(){ //restore all surfaces g_lpDDraw->RestoreAllSurfaces(); //optionally we could restore all surfaces separateley /* g_lpPrimary->Restore(); g_lpBackBuffer->Restore(); TestImage.Restore(); */ //now reload images into surfaces TestImage.ReloadImageIntoSurface(); TestBackground.ReloadImageIntoSurface(); return S_OK; } /* RenderObjects() is where all rendering should take place. The first part of the code clears out the back buffer. After that anything that the programmer wants to be drawn should be specified. All drawing should go to the back buffer, as drawing to the primary surface will create unpleasing results. */ HRESULT RenderObjects(){ //Make sure the buffers exist because if they don't, //the blitting won't work! if( (!g_lpBackBuffer) || (!g_lpPrimary))return E_FAIL; //First thing we'll do is clear the buffer. DDBLTFX ddbltfx; ZeroMemory(&ddbltfx, sizeof(ddbltfx)); ddbltfx.dwSize = sizeof(ddbltfx); ddbltfx.dwFillColor = 0x00FFFFFFL; //Fill backbuffer as white. g_lpBackBuffer->Blt(NULL, NULL, NULL, DDBLT_COLORFILL, &ddbltfx ); //Now we render our test image. //Render test background first. TestBackground.DrawImage(g_lpBackBuffer, 0, 0); //The following code finds out where the mouse is in relation //to the window, I do this in order to display the image where //the mouse is. POINT ps; GetCursorPos(&ps); ps.x-=g_rcWindow.left+(TestImage.GetWidth()/2); ps.y-=g_rcWindow.top+(TestImage.GetHeight()/2); //Render to the back buffer, PageFlip() will copy onto the //Primary surface. Most of the time the DrawPrefered() //method works the same as DrawClippedImage. So either //can be use. If DrawImage() is used the image will not //clip and it will dissapear if even part of it goes //past the edge of the viewport. For that reason, either //DrawPrefered() or DrawClippedImage() should be used. TestImage.DrawPrefered(g_lpBackBuffer, ps.x, ps.y); return S_OK; } /* GameLoop() is a demonstration of how the game works. In an actual game this function would also call object animation functions, call a function to get input, etc... For this example the function calls RenderObjects() then PageFlip(). */ HRESULT GameLoop(){ RenderObjects(); return PageFlip( g_lpPrimary, g_lpBackBuffer, g_bWindowed, &g_rcWindow, RestoreGraphics); } /* MainWndProc() is the procedures specifed for the application window any programmer with knowledge of windows programming should understand this. */ LRESULT CALLBACK MainWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam){ switch(uMsg) { case WM_CREATE: break; case WM_ACTIVATEAPP: bActiveApp=wParam; break; case WM_KEYDOWN: //If escape is pressed we exit. if(((int)wParam==27)) SendMessage(hwnd, WM_CLOSE, 0, 0); break; case WM_MOVE: //When the window is moved we need to update //its rectangle. GFXG7 provides this function. //This will ensure that the Backbuffer is //properly display in windows mode. UpdateBounds(g_bWindowed, hwnd, &g_rcWindow); break; case WM_CLOSE: DestroyWindow(hwnd); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hwnd, uMsg, wParam, lParam); } return 0l; } /* WinMain() is the entry point for this application. In this case I first create and register a windows class. Then I Initialize DirectDraw. After that I demonstrate house a CDirectDrawImage (of GFXG7) should be created. Then go into the main message loop. */ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { MSG msg; HWND hWnd=NULL; WNDCLASSEX wc; HACCEL hAccel=NULL; static TCHAR szAppName[] = TEXT("BaseGFXG7"); wc.cbSize=sizeof(wc); wc.style = CS_HREDRAW|CS_VREDRAW|CS_OWNDC; wc.cbClsExtra=0; wc.cbWndExtra=0; wc.lpfnWndProc=MainWndProc; wc.hInstance=hInstance; wc.hbrBackground=(HBRUSH)GetStockObject(DKGRAY_BRUSH); wc.hIcon = NULL; wc.hIconSm = NULL; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.lpszMenuName=NULL; wc.lpszClassName=szAppName; if(!RegisterClassEx(&wc)){ MessageBox( NULL, TEXT("This program requires Windows NT!"), TEXT("Notice"), MB_OK|MB_ICONERROR); return 0; } hWnd = CreateWindowEx( WS_EX_TOPMOST, szAppName, szAppName, WS_POPUP|WS_SYSMENU|WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, 512, 512, NULL, NULL, hInstance, NULL); //Initialize all interface data g_bWindowed=TRUE; g_dwTransparentColor=RGB(255, 0, 255); g_dwWidth=640; g_dwHeight=480; g_dwColorDepth=16; //Startup DirectDraw. //This function will initiate the DirectDraw object, //Create primary and secondary surfaces, convert //the transparent color to DirectDraw compatible //color, and adjust the window rect. It also //gets a pointer of the DirectDraw object, and //transparent color for use with the CDirectDrawImage //class (See documentation). if(FAILED(InitDirectDraw( &g_lpDDraw, &g_lpPrimary, &g_lpBackBuffer, hWnd, g_bWindowed, g_dwWidth, g_dwHeight, g_dwColorDepth, &g_rcWindow, &g_dwTransparentColor)))return E_FAIL; //At this point if in FullScreen mode we will hide the cursor //Note that if you activate mouse support using DirectInput //the mouse will not be shown, and you do not need to hide //the cursor yourself. if(!g_bWindowed)ShowCursor(FALSE); ShowWindow(hWnd, nShowCmd); SetFocus(hWnd); AdjustWindowSize(hWnd, g_dwWidth, g_dwHeight, g_bWindowed, NULL); //This is the method to create an image. Any subsequent calls //of this function (or any other CDirectDrawImage::CreateImageXXXXX) //will erase the current image and put the new image in it's place. //This method only supports Device Independant Bitmaps (*.DIB, *.BMP) //that is standard bitmaps. TestImage.CreateImageBM(g_lpDDraw, g_dwTransparentColor, TEXT("TestImage.bmp"), 0, 0, 100, 100, 100, 100, NULL); //This is another method for loading an image. HBITMAP hBitmap=0; hBitmap=(HBITMAP)LoadImage(NULL, TEXT("bg.bmp"), IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE); TestBackground.CreateImageBMInMemory(g_lpDDraw, g_dwTransparentColor, hBitmap, 0, 0, 256, 256, 640, 480, NULL); DeleteObject(hBitmap); if(hWnd==NULL)return 0; while(TRUE){ if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)){ if(msg.message==WM_QUIT) break; TranslateMessage(&msg); DispatchMessage(&msg); }else{ if(bActiveApp)GameLoop();else WaitMessage(); } } ShutDownApp(); //If we were in FullScreen mode we now need to show the cursor. if(!g_bWindowed)ShowCursor(TRUE); return msg.wParam; }<file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/filesys/la_arc.c /* la_arc.c - Functions for archiving Legacy Archive files. Copyright (c) 2006, <NAME> */ /* Compression by "zlib" version 1.2.3, July 18th, 2005 Copyright (C) 1995-2005 <NAME> and <NAME> */ #include <stdio.h> #include <memory.h> #include <malloc.h> #include <io.h> #ifdef _DEBUG #include <stdlib.h> #include <crtdbg.h> #endif /*_DEBUG*/ #include <common.h> #include "lf_sys.h" #include "zlib\zlib.h" ARCENTRY2* Arc_BuildTreeFiles(char* szPath, unsigned long* pNumFiles); int Arc_DeleteDirTree(ARCENTRY2* list); unsigned long Arc_CreateDirTree(ARCENTRY2** list, char* szDirectory); int Arc_WriteZLIBData(void* uncmpdata, ARCENTRY2* entry, FILE* fout); int Arc_BuildArchiveFile( ARCENTRY2* lpList, char* szOut, unsigned long nCount, int bCompress, PERCENTAGEFUNC pPercentageFunc); /************************************ The archvie compression utility. *************************************/ /* Arc_Archive - The export function, takes an output filename, a tree path, and a Percentage function pointer, to build the archive. */ int Arc_Archive( char* szArchive, char* szPath, unsigned long dwFlags, PERCENTAGEFUNC pPercentageFunc) { ARCENTRY2* lpTree=NULL; ARCENTRY2* lpTest=NULL; unsigned long nNumFiles=0; int bResult=0, bCompress=0; lpTree=Arc_BuildTreeFiles(szPath, &nNumFiles); /* nNumFiles=Arc_CreateDirTree(&lpTree, szPath); */ if(!lpTree) return 0; if(pPercentageFunc) pPercentageFunc(0, 5, ""); if(nNumFiles<1) { Arc_DeleteDirTree(lpTree); return 0; } if(L_CHECK_FLAG(dwFlags, ARCHIVE_COMPRESS)) bCompress=1; else bCompress=0; bResult=Arc_BuildArchiveFile(lpTree, szArchive, nNumFiles, bCompress, pPercentageFunc); Arc_DeleteDirTree(lpTree); return bResult; } /* Arc_BuildArchiveFile - uses the data in the ARCENTRY22 linked list and takes all those filenames and puts all those files in the specified archive.*/ int Arc_BuildArchiveFile( ARCENTRY2* lpList, char* szOut, unsigned long nCount, int bCompress, PERCENTAGEFUNC pPercentageFunc) { ARCENTRY2* entry=NULL; ARCHEADER Header={LARCHIVE_TYPE, ARC_VERSION, nCount}; //const unsigned long nType=LARCHIVE_TYPE; //const unsigned long nVersion=101; FILE* fout=NULL; FILE* fin=NULL; void* data=NULL; unsigned long nOffset=0; unsigned long nPercentage=0; unsigned long nNumArchived=0; unsigned long nWritePos=0; fout=L_fopen(szOut, "wb+"); if(!fout) return 0; L_fwrite(&Header.m_nType, 1, 4, fout); L_fwrite(&Header.m_nVersion, 1, 4, fout); L_fwrite(&Header.m_nCount, 1, 4, fout); nOffset=ARCHEADER_SIZE+(ARCENTRY2_SIZE)*nCount; for(entry=lpList; entry; entry=entry->m_next) { entry->m_nOffset=nOffset; nOffset+=entry->m_nUncmpSize; entry->m_nInfoOffset=L_ftell(fout); entry->m_nCmpSize=entry->m_nUncmpSize; if(bCompress) entry->m_nType=ARCHTYPE_ZLIBC; else entry->m_nType=ARCHTYPE_DEFAULT; L_fwrite(&entry->m_szFilename, 1, MAX_F_PATH, fout); L_fwrite(&entry->m_nType, 1, 4, fout); L_fwrite(&entry->m_nOffset, 1, 4, fout); L_fwrite(&entry->m_nInfoOffset, 1, 4, fout); L_fwrite(&entry->m_nCmpSize, 1, 4, fout); L_fwrite(&entry->m_nUncmpSize, 1, 4, fout); } for(entry=lpList; entry; entry=entry->m_next) { printf( "encrypting %s, %i bytes at %i (%i)\n", entry->m_szFilename, entry->m_nUncmpSize, L_ftell(fout), entry->m_nOffset); nPercentage=(unsigned long)(((float)nNumArchived/(float)nCount)*95.0f+5.0f); if(pPercentageFunc) pPercentageFunc(0, nPercentage, entry->m_szFilename); fin=L_fopen(entry->m_szFilename, "rb"); if(!fin) { printf( "Could not open \"%s\" possible access violation.\n", entry->m_szFilename); if(L_fseek(fout, entry->m_nUncmpSize, SEEK_CUR)) { printf("Could not write zeroes for empty file, archive is corrupt!\n"); L_fclose(fout); return 0; } continue; } data=malloc(entry->m_nUncmpSize); if(!data) { printf("Could not allocate memory for archiving \"%s\"\n", entry->m_szFilename); if(L_fseek(fout, entry->m_nUncmpSize, SEEK_CUR)) { printf("Could not write zeroes for empty file, archive is corrupt!\n"); L_fclose(fout); L_fclose(fin); return 0; } L_fclose(fin); continue; } /* Read the data into the buffer. */ L_fread(data, 1, entry->m_nUncmpSize, fin); L_fclose(fin); /* Save the position we are writing too. */ entry->m_nOffset=L_ftell(fout); switch(entry->m_nType) { case ARCHTYPE_ZLIBC: { if(Arc_WriteZLIBData(data, entry, fout)) break; else entry->m_nType=ARCHTYPE_DEFAULT; } default: case ARCHTYPE_DEFAULT: L_fwrite(data, 1, entry->m_nUncmpSize, fout); break; } /* Free the data. */ free(data); /* Now we need to go back to the data and adjust the file offset position. */ /* We need to change some of the data that was saved in the directory tree. */ L_fseek(fout, entry->m_nInfoOffset+MAX_F_PATH, SEEK_SET); L_fwrite(&entry->m_nType, 1, 4, fout); L_fwrite(&entry->m_nOffset, 1, 4, fout); L_fwrite(&entry->m_nInfoOffset, 1, 4, fout); L_fwrite(&entry->m_nCmpSize, 1, 4, fout); L_fwrite(&entry->m_nUncmpSize, 1, 4, fout); L_fseek(fout, 0, SEEK_END); nNumArchived++; nPercentage=(unsigned long)(((float)nNumArchived/(float)nCount)*95.0f+5.0f); if(pPercentageFunc) pPercentageFunc(0, nPercentage, entry->m_szFilename); } L_fclose(fout); return 1; } int Arc_WriteZLIBData(void* uncmpdata, ARCENTRY2* entry, FILE* fout) { void* cmpdata=NULL; cmpdata=malloc(entry->m_nUncmpSize); if(!cmpdata) return 0; entry->m_nCmpSize=entry->m_nUncmpSize; if(compress(cmpdata, &entry->m_nCmpSize, uncmpdata, entry->m_nUncmpSize)!=Z_OK) { free(cmpdata); return 0; } L_fwrite(cmpdata, 1, entry->m_nCmpSize, fout); free(cmpdata); return 1; } /* Arc_CreateDirTree - Builds a ARCENTRY22 with all the files it can find in the specified directory. Including files in subdirectories. */ unsigned long Arc_CreateDirTree(ARCENTRY2** list, char* szDirectory) { long Handle=0; char szPath[MAX_F_PATH]; struct _finddata_t data; unsigned long nNumArchived=0; ARCENTRY2 * tempentry=NULL; _snprintf(szPath, MAX_F_PATH-1, "%s\\*.*", szDirectory); memset(&data, 0, sizeof(data)); Handle=_findfirst(szPath, &data); if(Handle==-1) { return 0; } do { /* If the found item is a subdirectory we archive all the files in that directory, unless it is the ..\ or .\ directories. */ if(L_CHECK_FLAG(data.attrib, _A_SUBDIR)) { if(L_strnicmp("..", data.name, 0) || L_strnicmp(".", data.name, 0)) continue; _snprintf(szPath, MAX_F_PATH-1, "%s\\%s", szDirectory, data.name); nNumArchived+=Arc_CreateDirTree(list, szPath); } else { _snprintf(szPath, MAX_F_PATH-1, "%s\\%s", szDirectory, data.name); tempentry=malloc(sizeof(ARCENTRY2)); if(!tempentry) return nNumArchived; L_strncpy(tempentry->m_szFilename, szPath, MAX_F_PATH); tempentry->m_nUncmpSize=data.size; tempentry->m_nCmpSize=data.size; tempentry->m_nOffset=0; tempentry->m_nInfoOffset=0; tempentry->m_next=*list; *list=tempentry; nNumArchived++; } } while(_findnext(Handle, &data)!=-1); _findclose(Handle); return nNumArchived; } /* Calls Arc_CreateDirTree to create ARCENTRY22. */ ARCENTRY2* Arc_BuildTreeFiles(char* szPath, unsigned long* pNumFiles) { ARCENTRY2* lpEntry=NULL; *pNumFiles=Arc_CreateDirTree(&lpEntry, szPath); return lpEntry; } /* Deletes the dir tree created with Arc_CreateDirTree*/ int Arc_DeleteDirTree(ARCENTRY2* list) { ARCENTRY2* temp=NULL; ARCENTRY2* entry=NULL; entry=list; while(entry) { temp=entry->m_next; free(entry); entry=temp; } return 1; }<file_sep>/samples/D3DDemo/code/resource.h #define IDI_DXICON 101 #define IDR_CONSOLEIMG 102 #define IDB_DEFFONT 103 <file_sep>/samples/D3DDemo/data/conni/README.txt ================================================================================ Miss Connecticut 2nd place in "Lowpoly lovedoll contest" plug-in Player model for Quake3 Arena ================================================================================ Title : Conni Description : Miss Connecticut 2nd place in "Lowpoly lovedoll contest" plug-in Player model for Quake3 Arena Model Artist: : <NAME> / Funcom Oslo Skin Artist: : <NAME> / Funcom Oslo Animation Artist: : <NAME> / Id Software Sounds courtesy of: : <NAME> / Id Software Additional Credits to : Id Software for creating Quake 3, <NAME> at Id for all their help in making this happen. ENJOY! http://home.telia.no/vebsart ================================================================================ <file_sep>/samples/D3DDemo/code/MD3Base/MD3TexDB.h #ifndef __MD3TEXDB_H__ #define __MD3TEXDB_H__ #include <d3d9.h> typedef struct tagMD3TEXTURE { LPDIRECT3DTEXTURE9 lpTexture; char szTextureName[MAX_PATH]; }MD3TEXTURE; #ifdef __cplusplus class CMD3Texture { private: MD3TEXTURE m_Texture; CMD3Texture * m_lpNext; public: CMD3Texture(); ~CMD3Texture(); CMD3Texture * GetNext(); void SetNext(CMD3Texture * lpNext); void SetTexture(MD3TEXTURE * lpTexture); void GetTexture(MD3TEXTURE * lpTexture); }; #endif /* __cplusplus */ #endif /* __MD3TEXDB_H__ */ <file_sep>/games/Legacy-Engine/Scrapped/libs/ML_lib2008April/ML_matC.c /* ML_matC - The matrix functions written in C code, for assembly code see ML_mat.nasm. */ //#include <xmmintrin.h> #include "ML_lib.h" #include "ML_mat.h" ML_MAT* ML_FUNC ML_MatRotationAxis(ML_MAT* pOut, const ML_VEC3* pAxis, float fAngle) { //From <NAME> & <NAME> ml_float s, c; ml_float a, ax, ay, az; //We need a unit vector for the rotation, we'll assume it isn't a 0 vector: ML_VEC3 v3Axis; if(!fAngle) return ML_MatIdentity(pOut); ML_Vec3Normalize(&v3Axis, pAxis); //Get sin an cosin of rotation angle s=ML_sincosf(fAngle, &c); //Compute 1 - cos(theta) and some common subexpressions a = 1.0f - c; ax = a * v3Axis.x; ay = a * v3Axis.y; az = a * v3Axis.z; //Set the matrix elements. There is still a little more //opportunity for optimization due to the many common //subexpressions. We'll let the compiler handle that... pOut->_11 = ax*v3Axis.x + c; pOut->_12 = ax*v3Axis.y + v3Axis.z*s; pOut->_13 = ax*v3Axis.z - v3Axis.y*s; pOut->_14 = 0; pOut->_21 = ay*v3Axis.x - v3Axis.z*s; pOut->_22 = ay*v3Axis.y + c; pOut->_23 = ay*v3Axis.z + v3Axis.x*s; pOut->_24 = 0; pOut->_31 = az*v3Axis.x + v3Axis.y*s; pOut->_32 = az*v3Axis.y - v3Axis.x*s; pOut->_33 = az*v3Axis.z + c; pOut->_34 = 0; pOut->_41 = pOut->_42 = pOut->_43 = 0; pOut->_44 = 1; return pOut; } ML_MAT* ML_FUNC ML_MatLookAtLH(ML_MAT* pOut, const ML_VEC3* pEye, const ML_VEC3* pAt, const ML_VEC3* pUp) { /* zaxis = normal(At - Eye) xaxis = normal(cross(Up, zaxis)) yaxis = cross(zaxis, xaxis) xaxis.x yaxis.x zaxis.x 0 xaxis.y yaxis.y zaxis.y 0 xaxis.z yaxis.z zaxis.z 0 -dot(xaxis, eye) -dot(yaxis, eye) -dot(zaxis, eye) l */ ML_VEC3 zaxis, xaxis, yaxis; ML_Vec3Normalize(&zaxis, ML_Vec3Subtract(&zaxis, pAt, pEye)); ML_Vec3Normalize(&xaxis, ML_Vec3Cross(&xaxis, pUp, &zaxis)); ML_Vec3Cross(&yaxis, &zaxis, &xaxis); pOut->_11=xaxis.x; pOut->_12=yaxis.x; pOut->_13=zaxis.x; pOut->_14=0.0f; pOut->_21=xaxis.y; pOut->_22=yaxis.y; pOut->_23=zaxis.y; pOut->_24=0.0f; pOut->_31=xaxis.z; pOut->_32=yaxis.z; pOut->_33=zaxis.z; pOut->_34=0.0f; pOut->_41=-ML_Vec3Dot(&xaxis, pEye); pOut->_42=-ML_Vec3Dot(&yaxis, pEye); pOut->_43=-ML_Vec3Dot(&zaxis, pEye); pOut->_44=1.0f; return pOut; } ML_MAT* ML_FUNC ML_MatPerspectiveFovLH(ML_MAT* pOut, float fovy, float Aspect, float zn, float zf) { float yScale=1.0f/ML_tanf(fovy/2.0f); float xScale=yScale/Aspect; pOut->_11=xScale; pOut->_12=pOut->_13=pOut->_14=0.0f; pOut->_21=0.0f; pOut->_22=yScale; pOut->_23=0.0f; pOut->_24=0.0f; pOut->_31=0.0f; pOut->_32=0.0f; pOut->_33=zf/(zf-zn); pOut->_34=1.0f; pOut->_41=0.0f; pOut->_42=0.0f; pOut->_43=zn*zf/(zn-zf); pOut->_44=0.0f; return pOut; } ML_MAT* ML_FUNC ML_MatRotationYawPitchRoll(ML_MAT* pOut, float Yaw, float Pitch, float Roll) { float cosx, sinx, cosy, siny, cosz, sinz; sinx=ML_sincosf(Pitch, &cosx); siny=ML_sincosf(Yaw, &cosy); sinz=ML_sincosf(Roll, &cosz); pOut->_11=cosz*cosy+sinz*sinx*siny; pOut->_12=sinz*cosx; pOut->_13=cosz*-siny+sinz*sinx*cosy; pOut->_14=0.0f; pOut->_21=-sinz*cosy+cosz*sinx*siny; pOut->_22=cosz*cosx; pOut->_23=sinz*siny+cosz*sinx*cosy; pOut->_24=0.0f; pOut->_31=cosx*siny; pOut->_32=-sinx; pOut->_33=cosx*cosy; pOut->_34=0.0f; pOut->_41=pOut->_42=pOut->_43=0.0f; pOut->_44=1.0f; return pOut; /* Cos(z).Cos(y) + Sin(z).Sin(x).Sin(y) Sin(z).Cos(x) Cos(z).-Sin(y) + Sin(z).Sin(x).Cos(y) -Sin(z).Cos(y) + Cos(z).Sin(x).Sin(y) Cos(z).Cos(x) Sin(z).Sin(y) + Cos(z).Sin(x).Cos(y) Cos(x).Sin(y) -Sin(x) Cos(x).Cos(y) */ /* ML_MAT matTmpX, matTmpY, matTmpZ; ML_MatRotationX(&matTmpX, Pitch); ML_MatRotationY(&matTmpY, Yaw); ML_MatRotationZ(&matTmpZ, Roll); ML_MatMultiply(pOut, &matTmpZ, &matTmpX); ML_MatMultiply(pOut, pOut, &matTmpY); */ /* ML_MatRotationZ(pOut, Roll); ML_MatRotationX(&matTmp, Yaw); ML_MatMultiply(pOut, &matTmp, pOut); ML_MatRotationY(&matTmp, Pitch); ML_MatMultiply(pOut, &matTmp, pOut); */ } ML_MAT* ML_FUNC ML_MatScaling(ML_MAT* pOut, float sx, float sy, float sz) { pOut->_11=sx; pOut->_22=sy; pOut->_33=sz; pOut->_44=1.0f; pOut->_12=pOut->_13=pOut->_14=0.0f; pOut->_21=pOut->_23=pOut->_24=0.0f; pOut->_31=pOut->_32=pOut->_34=0.0f; pOut->_41=pOut->_42=pOut->_43=0.0f; return pOut; } float ML_FUNC ML_MatDeterminant(ML_MAT* pM) { return pM->_11*(pM->_22*pM->_33-pM->_23*pM->_32) + pM->_12*(pM->_23*pM->_31-pM->_21*pM->_33) + pM->_13*(pM->_21*pM->_32-pM->_22*pM->_31); } /* C Code Using Cramer's Rule Provided by Intel (tm) */ ML_MAT* ML_FUNC ML_MatInverse_F(ML_MAT* pOut, float* pDet, ML_MAT* pM) { float tmp[12]; /* temp array for pairs */ float src[16]; /* array of transpose source matrix */ float det; /* determinant */ int i, j; float* mat=(float*)pM; float* dst=(float*)pOut; /* transpose matrix */ for (i = 0; i < 4; i++) { src[i] = mat[i*4]; src[i + 4] = mat[i*4 + 1]; src[i + 8] = mat[i*4 + 2]; src[i + 12] = mat[i*4 + 3]; } /* calculate pairs for first 8 elements (cofactors) */ tmp[0] = src[10] * src[15]; tmp[1] = src[11] * src[14]; tmp[2] = src[9] * src[15]; tmp[3] = src[11] * src[13]; tmp[4] = src[9] * src[14]; tmp[5] = src[10] * src[13]; tmp[6] = src[8] * src[15]; tmp[7] = src[11] * src[12]; tmp[8] = src[8] * src[14]; tmp[9] = src[10] * src[12]; tmp[10] = src[8] * src[13]; tmp[11] = src[9] * src[12]; /* calculate first 8 elements (cofactors) */ dst[0] = tmp[0]*src[5] + tmp[3]*src[6] + tmp[4]*src[7]; dst[0] -= tmp[1]*src[5] + tmp[2]*src[6] + tmp[5]*src[7]; dst[1] = tmp[1]*src[4] + tmp[6]*src[6] + tmp[9]*src[7]; dst[1] -= tmp[0]*src[4] + tmp[7]*src[6] + tmp[8]*src[7]; dst[2] = tmp[2]*src[4] + tmp[7]*src[5] + tmp[10]*src[7]; dst[2] -= tmp[3]*src[4] + tmp[6]*src[5] + tmp[11]*src[7]; dst[3] = tmp[5]*src[4] + tmp[8]*src[5] + tmp[11]*src[6]; dst[3] -= tmp[4]*src[4] + tmp[9]*src[5] + tmp[10]*src[6]; dst[4] = tmp[1]*src[1] + tmp[2]*src[2] + tmp[5]*src[3]; dst[4] -= tmp[0]*src[1] + tmp[3]*src[2] + tmp[4]*src[3]; dst[5] = tmp[0]*src[0] + tmp[7]*src[2] + tmp[8]*src[3]; dst[5] -= tmp[1]*src[0] + tmp[6]*src[2] + tmp[9]*src[3]; dst[6] = tmp[3]*src[0] + tmp[6]*src[1] + tmp[11]*src[3]; dst[6] -= tmp[2]*src[0] + tmp[7]*src[1] + tmp[10]*src[3]; dst[7] = tmp[4]*src[0] + tmp[9]*src[1] + tmp[10]*src[2]; dst[7] -= tmp[5]*src[0] + tmp[8]*src[1] + tmp[11]*src[2]; /* calculate pairs for second 8 elements (cofactors) */ tmp[0] = src[2]*src[7]; tmp[1] = src[3]*src[6]; tmp[2] = src[1]*src[7]; tmp[3] = src[3]*src[5]; tmp[4] = src[1]*src[6]; tmp[5] = src[2]*src[5]; tmp[6] = src[0]*src[7]; tmp[7] = src[3]*src[4]; tmp[8] = src[0]*src[6]; tmp[9] = src[2]*src[4]; tmp[10] = src[0]*src[5]; tmp[11] = src[1]*src[4]; /* calculate second 8 elements (cofactors) */ dst[8] = tmp[0]*src[13] + tmp[3]*src[14] + tmp[4]*src[15]; dst[8] -= tmp[1]*src[13] + tmp[2]*src[14] + tmp[5]*src[15]; dst[9] = tmp[1]*src[12] + tmp[6]*src[14] + tmp[9]*src[15]; dst[9] -= tmp[0]*src[12] + tmp[7]*src[14] + tmp[8]*src[15]; dst[10] = tmp[2]*src[12] + tmp[7]*src[13] + tmp[10]*src[15]; dst[10]-= tmp[3]*src[12] + tmp[6]*src[13] + tmp[11]*src[15]; dst[11] = tmp[5]*src[12] + tmp[8]*src[13] + tmp[11]*src[14]; dst[11]-= tmp[4]*src[12] + tmp[9]*src[13] + tmp[10]*src[14]; dst[12] = tmp[2]*src[10] + tmp[5]*src[11] + tmp[1]*src[9]; dst[12]-= tmp[4]*src[11] + tmp[0]*src[9] + tmp[3]*src[10]; dst[13] = tmp[8]*src[11] + tmp[0]*src[8] + tmp[7]*src[10]; dst[13]-= tmp[6]*src[10] + tmp[9]*src[11] + tmp[1]*src[8]; dst[14] = tmp[6]*src[9] + tmp[11]*src[11] + tmp[3]*src[8]; dst[14]-= tmp[10]*src[11] + tmp[2]*src[8] + tmp[7]*src[9]; dst[15] = tmp[10]*src[10] + tmp[4]*src[8] + tmp[9]*src[9]; dst[15]-= tmp[8]*src[9] + tmp[11]*src[10] + tmp[5]*src[8]; /* calculate determinant */ if(pDet) det=*pDet; else det=src[0]*dst[0]+src[1]*dst[1]+src[2]*dst[2]+src[3]*dst[3]; /* calculate matrix inverse */ if(det==0.0f) return (ML_MAT*)dst; det = 1.0f/det; for (j = 0; j < 16; j++) dst[j] *= det; return (ML_MAT*)dst; } /* C Code Using Cramer's Rule and SIMD Provided by Intel (tm) */ /* ML_MAT* ML_MatInverse_SSE(ML_MAT* pOut, float* pDet, ML_MAT* pM) { __m128 minor0, minor1, minor2, minor3; __m128 row0, row1, row2, row3; __m128 det, tmp1; float* src=(float*)pM; float* dst=(float*)pOut; tmp1 = _mm_loadh_pi(_mm_loadl_pi(tmp1, (__m64*)(src)), (__m64*)(src+ 4)); row1 = _mm_loadh_pi(_mm_loadl_pi(row1, (__m64*)(src+8)), (__m64*)(src+12)); row0 = _mm_shuffle_ps(tmp1, row1, 0x88); row1 = _mm_shuffle_ps(row1, tmp1, 0xDD); tmp1 = _mm_loadh_pi(_mm_loadl_pi(tmp1, (__m64*)(src+ 2)), (__m64*)(src+ 6)); row3 = _mm_loadh_pi(_mm_loadl_pi(row3, (__m64*)(src+10)), (__m64*)(src+14)); row2 = _mm_shuffle_ps(tmp1, row3, 0x88); row3 = _mm_shuffle_ps(row3, tmp1, 0xDD); // ----------------------------------------------- tmp1 = _mm_mul_ps(row2, row3); tmp1 = _mm_shuffle_ps(tmp1, tmp1, 0xB1); minor0 = _mm_mul_ps(row1, tmp1); minor1 = _mm_mul_ps(row0, tmp1); tmp1 = _mm_shuffle_ps(tmp1, tmp1, 0x4E); minor0 = _mm_sub_ps(_mm_mul_ps(row1, tmp1), minor0); minor1 = _mm_sub_ps(_mm_mul_ps(row0, tmp1), minor1); minor1 = _mm_shuffle_ps(minor1, minor1, 0x4E); // ----------------------------------------------- tmp1 = _mm_mul_ps(row1, row2); tmp1 = _mm_shuffle_ps(tmp1, tmp1, 0xB1); minor0 = _mm_add_ps(_mm_mul_ps(row3, tmp1), minor0); minor3 = _mm_mul_ps(row0, tmp1); tmp1 = _mm_shuffle_ps(tmp1, tmp1, 0x4E); minor0 = _mm_sub_ps(minor0, _mm_mul_ps(row3, tmp1)); minor3 = _mm_sub_ps(_mm_mul_ps(row0, tmp1), minor3); minor3 = _mm_shuffle_ps(minor3, minor3, 0x4E); // ----------------------------------------------- tmp1 = _mm_mul_ps(_mm_shuffle_ps(row1, row1, 0x4E), row3); tmp1 = _mm_shuffle_ps(tmp1, tmp1, 0xB1); row2 = _mm_shuffle_ps(row2, row2, 0x4E); minor0 = _mm_add_ps(_mm_mul_ps(row2, tmp1), minor0); minor2 = _mm_mul_ps(row0, tmp1); tmp1 = _mm_shuffle_ps(tmp1, tmp1, 0x4E); minor0 = _mm_sub_ps(minor0, _mm_mul_ps(row2, tmp1)); minor2 = _mm_sub_ps(_mm_mul_ps(row0, tmp1), minor2); minor2 = _mm_shuffle_ps(minor2, minor2, 0x4E); // ----------------------------------------------- tmp1 = _mm_mul_ps(row0, row1); tmp1 = _mm_shuffle_ps(tmp1, tmp1, 0xB1); minor2 = _mm_add_ps(_mm_mul_ps(row3, tmp1), minor2); minor3 = _mm_sub_ps(_mm_mul_ps(row2, tmp1), minor3); tmp1 = _mm_shuffle_ps(tmp1, tmp1, 0x4E); minor2 = _mm_sub_ps(_mm_mul_ps(row3, tmp1), minor2); minor3 = _mm_sub_ps(minor3, _mm_mul_ps(row2, tmp1)); // ----------------------------------------------- tmp1 = _mm_mul_ps(row0, row3); tmp1 = _mm_shuffle_ps(tmp1, tmp1, 0xB1); minor1 = _mm_sub_ps(minor1, _mm_mul_ps(row2, tmp1)); minor2 = _mm_add_ps(_mm_mul_ps(row1, tmp1), minor2); tmp1 = _mm_shuffle_ps(tmp1, tmp1, 0x4E); minor1 = _mm_add_ps(_mm_mul_ps(row2, tmp1), minor1); minor2 = _mm_sub_ps(minor2, _mm_mul_ps(row1, tmp1)); // ----------------------------------------------- tmp1 = _mm_mul_ps(row0, row2); tmp1 = _mm_shuffle_ps(tmp1, tmp1, 0xB1); minor1 = _mm_add_ps(_mm_mul_ps(row3, tmp1), minor1); minor3 = _mm_sub_ps(minor3, _mm_mul_ps(row1, tmp1)); tmp1 = _mm_shuffle_ps(tmp1, tmp1, 0x4E); minor1 = _mm_sub_ps(minor1, _mm_mul_ps(row3, tmp1)); minor3 = _mm_add_ps(_mm_mul_ps(row1, tmp1), minor3); // ----------------------------------------------- det = _mm_mul_ps(row0, minor0); det = _mm_add_ps(_mm_shuffle_ps(det, det, 0x4E), det); det = _mm_add_ss(_mm_shuffle_ps(det, det, 0xB1), det); tmp1 = _mm_rcp_ss(det); det = _mm_sub_ss(_mm_add_ss(tmp1, tmp1), _mm_mul_ss(det, _mm_mul_ss(tmp1, tmp1))); det = _mm_shuffle_ps(det, det, 0x00); minor0 = _mm_mul_ps(det, minor0); _mm_storel_pi((__m64*)(src), minor0); _mm_storeh_pi((__m64*)(src+2), minor0); minor1 = _mm_mul_ps(det, minor1); _mm_storel_pi((__m64*)(src+4), minor1); _mm_storeh_pi((__m64*)(src+6), minor1); minor2 = _mm_mul_ps(det, minor2); _mm_storel_pi((__m64*)(src+ 8), minor2); _mm_storeh_pi((__m64*)(src+10), minor2); minor3 = _mm_mul_ps(det, minor3); _mm_storel_pi((__m64*)(src+12), minor3); _mm_storeh_pi((__m64*)(src+14), minor3); return (ML_MAT*)dst; } */ ML_MAT* ML_FUNC ML_MatSlerp(ML_MAT* pOut, ML_MAT* pM1, ML_MAT* pM2, float t) { ML_MAT *pXOut=pOut, *pXM1=pM1, *pXM2=pM2; ML_QUAT Q1, Q2; float x=pXM1->_41+t*(pXM2->_41-pXM1->_41); float y=pXM1->_42+t*(pXM2->_42-pXM1->_42); float z=pXM1->_43+t*(pXM2->_43-pXM1->_43); ML_QuatRotationMat(&Q1, pM1); ML_QuatRotationMat(&Q2, pM2); ML_QuatSlerp(&Q1, &Q1, &Q2, t); ML_MatRotationQuat(pXOut, &Q1); pXOut->_41=x; pXOut->_42=y; pXOut->_43=z; return pOut; } <file_sep>/games/Legacy-Engine/Source/engine/lp_physx2.h #if 0 #ifndef __LP_PHYSX2_H__ #define __LP_PHYSX2_H__ #include <NxPhysics.h> #include <NxStream.h> #include <NxControllerManager.h> #include "lp_sys2.h" #include "lf_sys2.h" #include "lg_mem_file.h" #include "lw_entity.h" class CLPhysPhysX: public CLPhys { //Internally used classes: private: /* The following is the output stream, it allows output from the PhysX SDK to be sent to the console. */ class CXOut: public NxUserOutputStream { virtual void reportError(NxErrorCode code, const char* message, const char* file, int line); virtual NxAssertResponse reportAssertViolation(const char* message, const char* file, int line); virtual void print(const char* message); }; class CLNxStream: public NxStream { private: LF_FILE3 m_File; public: CLNxStream(const lg_char filename[], lg_bool bLoad); virtual ~CLNxStream(); virtual NxU8 readByte()const; virtual NxU16 readWord()const; virtual NxU32 readDword()const; virtual NxReal readFloat()const; virtual NxF64 readDouble()const; virtual void readBuffer(void* buffer, NxU32 size)const; virtual NxStream& storeByte(NxU8 n); virtual NxStream& storeWord(NxU16 w); virtual NxStream& storeDword(NxU32 d); virtual NxStream& storeFloat(NxReal f); virtual NxStream& storeDouble(NxF64 f); virtual NxStream& storeBuffer(const void* buffer, NxU32 size); void Open(const lg_char filename[], lg_bool bLoad); void Close(); }; class CLNxMemStream: public NxStream { private: CLMemFile m_File; public: CLNxMemStream(lg_dword nSize); virtual ~CLNxMemStream(); virtual NxU8 readByte()const; virtual NxU16 readWord()const; virtual NxU32 readDword()const; virtual NxReal readFloat()const; virtual NxF64 readDouble()const; virtual void readBuffer(void* buffer, NxU32 size)const; virtual NxStream& storeByte(NxU8 n); virtual NxStream& storeWord(NxU16 w); virtual NxStream& storeDword(NxU32 d); virtual NxStream& storeFloat(NxReal f); virtual NxStream& storeDouble(NxF64 f); virtual NxStream& storeBuffer(const void* buffer, NxU32 size); void Open(lg_dword nSize); void Close(); void Reset(); }; class CXAlloc : public NxUserAllocator { public: void * malloc(NxU32 size); void * mallocDEBUG(NxU32 size,const char *fileName, int line); void * realloc(void * memory, NxU32 size); void free(void * memory); }; //Member variables: private: CXOut m_Out; CXAlloc m_Alloc; NxPhysicsSDK* m_pSDK; NxScene* m_pScene; NxActor* m_pActrMap; //Character controller manager: NxControllerManager* m_pCtrlrMgr; //Cooking library: NxCookingInterface* m_pCooking; //Active transform vars NxU32 m_nATs; NxActiveTransform* m_pATs; //Some materials NxMaterial* m_pMtrInt; //Material for intelligent objects. NxMaterial* m_pMtrMap; //Material for the map. //Overridden member methods: public: virtual void Init(lg_dword nMaxBodies); virtual void Shutdown(); virtual lg_void* AddBody(lg_void* pEnt, lp_body_info* pInfo); virtual void RemoveBody(lg_void* pBody); virtual void SetupWorld(lg_void* pWorldMap); virtual void SetGravity(ML_VEC3* pGrav); virtual void Simulate(lg_float fTimeStepSec); virtual void SetBodyFlag(lg_void* pBody, lg_dword nFlagID, lg_dword nValue); virtual void SetBodyVector(lg_void* pBody, lg_dword nVecID, ML_VEC3* pVec); virtual void SetBodyFloat(lg_void* pBody, lg_dword nFloatID, lg_float fValue); virtual void SetBodyPosition(lg_void* pBody, ML_MAT* pMat); virtual lg_void* GetBodySaveInfo(lg_void* pBody, lg_dword* pSize); virtual lg_void* LoadBodySaveInfo(lg_void* pData, lg_dword nSize); private: lg_void* AddIntelligentBody(lg_void* pEnt, lp_body_info* pInfo); lg_void* AddDynamicBody(lg_void* pEnt, lp_body_info* pInfo); private: __inline static void UpdateToSrv(NxActor* pSrc, lg_srv_ent* pEnt, NxMat34* pPos); __inline static void UpdateFromSrv(NxActor* pSrc); }; #endif __LP_PHYSX2_H__ #endif<file_sep>/Misc/DBXExporter/DBXExporter/oedbx/library/dbxTree.cpp //*************************************************************************************** #define AS_OE_IMPLEMENTATION #include <oedbx/dbxTree.h> //*************************************************************************************** const int4 TreeNodeSize = 0x27c; DbxTree::DbxTree(InStream ins, int4 address, int4 values) { Address = address; Values = values; Array = new int4[Values]; if(!Array) throw DbxException("Error allocating memory !"); try { readValues(ins, 0, Address, 0, Values); } catch(const DbxException & E) { delete[] Array; throw; } } DbxTree::~DbxTree() { delete[] Array; } void DbxTree::readValues(InStream ins, int4 parent, int4 address, int4 position, int4 values) { int4 buffer[TreeNodeSize>>2], N = 0; if(position+values>Values) throw DbxException("To many values to read !"); ins.seekg(address); ins.read((char *)buffer, TreeNodeSize); if(!ins) throw DbxException("Error reading node from input stream !"); if(buffer[0]!=address) throw DbxException("Wrong object marker !"); if(buffer[3]!=parent) throw DbxException("Wrong parent !"); int1 /* id = buffer[4]&0xff, */ entries = (int1)((buffer[4] >> 8)&0xff); if(entries>0x33) throw DbxException("Wrong value for entries !"); if(buffer[2]!=0) { readValues(ins, address, buffer[2], position, buffer[5]); N += buffer[5]; } for(int1 i=0;i<entries;++i) { int4 * pos = buffer + 6 + i * 3; if(pos[0]!=0) { int4 value = position + (++N); if(value>Values) throw DbxException("To many values !"); Array[value-1] = pos[0]; } if(pos[1]!=0) { readValues(ins, address, pos[1], position+N, pos[2]); N+=pos[2]; } } if(N!=values) throw DbxException("Wrong number of values found!"); } //*************************************************************************************** int4 DbxTree::GetValue(int4 index) const { if(index<Values) return Array[index]; throw DbxException("Wrong index !"); } //*************************************************************************************** void DbxTree::ShowResults(OutStream outs) const { outs << std::endl << "tree : " << std::endl << " address : 0x" << std::hex << Address << std::endl << " values read : 0x" << std::hex << Values << std::endl; } //*************************************************************************************** <file_sep>/tools/img_lib/TexView3/TexView3.cpp // TexView3.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "TexView3.h" #include "MainFrm.h" #include "ChildFrm.h" #include "TexView3Doc.h" #include "TexView3View.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CTexView3App BEGIN_MESSAGE_MAP(CTexView3App, CWinApp) ON_COMMAND(ID_APP_ABOUT, &CTexView3App::OnAppAbout) // Standard file based document commands ON_COMMAND(ID_FILE_NEW, &CWinApp::OnFileNew) //ON_COMMAND(ID_FILE_OPEN, &CWinApp::OnFileOpen) // Standard print setup command ON_COMMAND(ID_FILE_PRINT_SETUP, &CWinApp::OnFilePrintSetup) ON_COMMAND(ID_FILE_OPEN, &CTexView3App::OnFileOpen) ON_UPDATE_COMMAND_UI(ID_FILE_NEW, &CTexView3App::OnUpdateFileNew) ON_UPDATE_COMMAND_UI(ID_FILE_SAVE, &CTexView3App::OnUpdateFileSave) ON_UPDATE_COMMAND_UI(ID_FILE_SAVE_AS, &CTexView3App::OnUpdateFileSaveAs) END_MESSAGE_MAP() // CTexView3App construction CTexView3App::CTexView3App() { // TODO: add construction code here, // Place all significant initialization in InitInstance } // The one and only CTexView3App object CTexView3App theApp; // CTexView3App initialization BOOL CTexView3App::InitInstance() { // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinApp::InitInstance(); // Initialize OLE libraries if (!AfxOleInit()) { AfxMessageBox(IDP_OLE_INIT_FAILED); return FALSE; } AfxEnableControlContainer(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need // Change the registry key under which our settings are stored // TODO: You should modify this string to be something appropriate // such as the name of your company or organization SetRegistryKey(_T("Beem Software")); LoadStdProfileSettings(5); // Load standard INI file options (including MRU) // Register the application's document templates. Document templates // serve as the connection between documents, frame windows and views CMultiDocTemplate* pDocTemplate; pDocTemplate = new CMultiDocTemplate(IDR_TexView3TYPE, RUNTIME_CLASS(CTexView3Doc), RUNTIME_CLASS(CChildFrame), // custom MDI child frame RUNTIME_CLASS(CTexView3View)); if (!pDocTemplate) return FALSE; AddDocTemplate(pDocTemplate); // create main MDI Frame window CMainFrame* pMainFrame = new CMainFrame; if (!pMainFrame || !pMainFrame->LoadFrame(IDR_MAINFRAME)) { delete pMainFrame; return FALSE; } m_pMainWnd = pMainFrame; // call DragAcceptFiles only if there's a suffix // In an MDI app, this should occur immediately after setting m_pMainWnd // Enable drag/drop open m_pMainWnd->DragAcceptFiles(); // Enable DDE Execute open EnableShellOpen(); RegisterShellFileTypes(TRUE); BOOL bUnreg=FALSE; RegisterFileType(_T(".tga"), bUnreg); RegisterFileType(_T(".bmp"), bUnreg); RegisterFileType(_T(".jpg"), bUnreg); RegisterFileType(_T(".gif"), bUnreg); RegisterFileType(_T(".png"), bUnreg); //SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL); // Parse command line for standard shell commands, DDE, file open CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); //Insure that a blank document is not created if we are not loading //something right away. if (cmdInfo.m_nShellCommand == CCommandLineInfo::FileNew) cmdInfo.m_nShellCommand = CCommandLineInfo::FileNothing; // Dispatch commands specified on the command line. Will return FALSE if // app was launched with /RegServer, /Register, /Unregserver or /Unregister. if (!ProcessShellCommand(cmdInfo)) return FALSE; // The main window has been initialized, so show and update it pMainFrame->ShowWindow(m_nCmdShow); pMainFrame->UpdateWindow(); return TRUE; } // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() public: virtual BOOL OnInitDialog(); }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) END_MESSAGE_MAP() // App command to run the dialog void CTexView3App::OnAppAbout() { CAboutDlg aboutDlg; aboutDlg.DoModal(); } // CTexView3App message handlers void CTexView3App::OnFileOpen() { LPCTSTR pszFilter = _T("TexView3 Files (*.tga;*.bmp;*.dib;*.gif;*.jpg; *.png)|*.tga;*.bmp;*.dib;*.gif;*.jpg;*.png|") _T("All files (*.*)|*.*||"); CFileDialog dlgFile(TRUE, NULL, NULL, OFN_EXPLORER|OFN_ALLOWMULTISELECT, pszFilter, AfxGetMainWnd()); if(IDOK == dlgFile.DoModal()) { POSITION ps(dlgFile.GetStartPosition()); while(ps) { OpenDocumentFile(dlgFile.GetNextPathName(ps)); } } } void CTexView3App::OnUpdateFileNew(CCmdUI *pCmdUI) { pCmdUI->Enable(FALSE); } void CTexView3App::OnUpdateFileSave(CCmdUI *pCmdUI) { pCmdUI->Enable(FALSE); } void CTexView3App::OnUpdateFileSaveAs(CCmdUI *pCmdUI) { pCmdUI->Enable(FALSE); } BOOL CAboutDlg::OnInitDialog() { #define TEXVIEW3_VERSION _T("1.01") CDialog::OnInitDialog(); this->SetDlgItemText( IDC_VERSIONTEXT, _T("Version ")TEXVIEW3_VERSION _T(" ") #ifdef UNICODE _T("(UNICODE)")); #else UNICODE _T("(ANSI)")); #endif UNICODE return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CTexView3App::RegisterFileType(LPTSTR szExt, BOOL bUnReg) { HKEY hKey=NULL; TCHAR szModPath[MAX_PATH]; GetModuleFileName(NULL, szModPath, MAX_PATH); if(szExt[0]!='.') return; RegOpenKeyEx(HKEY_CLASSES_ROOT, szExt, 0, KEY_ALL_ACCESS, &hKey); if(hKey) { //If the file type is already registered we will //add the command to open with texture viewer. CString szKey; //CString szBaseKey; CString szKeyValue; HKEY hBaseKey=NULL; #define MAX_KEY_LENGTH 1024 DWORD dwSize=MAX_KEY_LENGTH*sizeof(TCHAR); DWORD dwType=0; RegQueryValueEx(hKey, NULL, NULL, &dwType, (LPBYTE)szKey.GetBuffer(MAX_KEY_LENGTH), &dwSize); RegCloseKey(hKey); //If the image is registered as a TexView3.Document we //don't need to do anything. if(szKey.Compare(_T("TexView3.Document"))==0) return; CString szCommand; szCommand.Format(_T("TexView3"));//_T("Open with %s"), AfxGetAppName()); szKey.Format(_T("%s\\shell\\%s"), szKey, szCommand); RegCreateKeyEx(HKEY_CLASSES_ROOT, szKey, 0, NULL, 0, KEY_ALL_ACCESS, NULL, &hBaseKey, NULL); if(!hBaseKey) return; if(bUnReg) { RegDeleteKey(hBaseKey, _T("command")); RegDeleteKey(hBaseKey, _T("ddeexec\\application")); RegDeleteKey(hBaseKey, _T("ddeexec")); RegCloseKey(hBaseKey); RegDeleteKey(HKEY_CLASSES_ROOT, szKey); return; } //Register the command. RegCreateKeyEx(hBaseKey, _T("command"), 0, NULL, 0, KEY_ALL_ACCESS, NULL, &hKey, NULL); szKeyValue.Format(_T("\"%s\" \"%%1\""), szModPath); RegSetValueEx(hKey, NULL, 0, REG_SZ, (LPBYTE)szKeyValue.GetBuffer(), (DWORD)(szKeyValue.GetLength()+1)*sizeof(TCHAR)); RegCloseKey(hKey); //Register the dde open command. RegCreateKeyEx(hBaseKey, _T("ddeexec"), 0, NULL, 0, KEY_ALL_ACCESS, NULL, &hKey, NULL); szKeyValue.Format(_T("[open(\"%%1\")]"), szModPath); RegSetValueEx(hKey, NULL, 0, REG_SZ, (LPBYTE)szKeyValue.GetBuffer(), (DWORD)(szKeyValue.GetLength()+1)*sizeof(TCHAR)); RegCloseKey(hKey); /* //Register the dde app name (optional). RegCreateKeyEx(hBaseKey, _T("ddeexec\\application"), 0, NULL, 0, KEY_ALL_ACCESS, NULL, &hKey, NULL); szKeyValue.Format(_T("TexView3"), szModPath); RegSetValueEx(hKey, NULL, 0, REG_SZ, (LPBYTE)szKeyValue.GetBuffer(), (DWORD)(szKeyValue.GetLength()+1)*sizeof(TCHAR)); RegCloseKey(hKey); */ RegCloseKey(hBaseKey); } else { if(bUnReg) return; //If the file type hasn't been register we attach it //to the TexView3.Document type. RegCreateKeyEx(HKEY_CLASSES_ROOT, szExt, 0, NULL, 0, KEY_ALL_ACCESS, NULL, &hKey, NULL); CString szKeyValue=_T("TexView3.Document"); RegSetValueEx(hKey, NULL, 0, REG_SZ, (LPBYTE)szKeyValue.GetBuffer(), (szKeyValue.GetLength()+1)*sizeof(TCHAR)); RegCloseKey(hKey); } } <file_sep>/games/Legacy-Engine/Source/engine/lg_tmgr.cpp #include <d3dx9.h> #include "lg_tmgr.h" #include "lg_func.h" #include "lg_err.h" #include "lg_err_ex.h" #include "lf_sys2.h" #include "lc_sys2.h" #include "lg_cvars.h" CLTMgr* CLTMgr::s_pTMgr=LG_NULL; CLTMgr::CLTMgr(IDirect3DDevice9* pDevice, lg_dword nMaxTex): CLHashMgr(nMaxTex, LG_TEXT("TMgr")), m_pDevice(LG_NULL), m_nPool(D3DPOOL_MANAGED) { //If the texture manager already exists then we made an error somewhere. if(s_pTMgr) { throw new CLError( LG_ERR_DEFAULT, __FILE__, __LINE__, LG_TEXT("The Texture Manager can only be initialized once.")); } //Store the global manager. s_pTMgr=this; //Save a copy of the device. m_pDevice=pDevice; m_pDevice->AddRef(); //Load the default texture: //m_pDefItem=DoLoad(CV_Get(CVAR_tm_DefaultTexture)->szValue, 0); m_pItemList[0].pItem=DoLoad(CV_Get(CVAR_tm_DefaultTexture)->szValue, 0); LG_strncpy(m_pItemList[0].szName, CV_Get(CVAR_tm_DefaultTexture)->szValue, LG_MAX_PATH); if(m_pItemList[0].pItem) Err_Printf("TMgr: Default texture is \"%s\".", CV_Get(CVAR_tm_DefaultTexture)->szValue); else Err_Printf("TMgr: Could not load default texture."); Err_Printf("TMgr: Initialized with %u textures available.", m_nMaxItems); } CLTMgr::~CLTMgr() { //Clear global manager. s_pTMgr=LG_NULL; //Release all textures, we have to call UnloadItems //from the destructor here, because the CLTMgr class //will be destroyed, and we can't call DoDestroy when //the class is destroyed. UnloadItems(); //Destroy default item: DoDestroy(m_pItemList[0].pItem); //Release direct3d: LG_SafeRelease(m_pDevice); //The base class destructor will deallocate memory. } tm_tex CLTMgr::LoadTextureMem(lg_void* pData, lg_dword nSize, lg_dword nFlags) { IDirect3DTexture9* pOut=LG_NULL; //Use the cvars and flags to set up the load //If the size is 0, then the default size is taken lg_dword nTexSize=CV_Get(CVAR_tm_TextureSizeLimit)->nValue; lg_dword nMips=LG_CheckFlag(nFlags, TM_FORCENOMIP) || !CV_Get(CVAR_tm_UseMipMaps)->nValue?1:0; D3DFORMAT nFormat=CV_Get(CVAR_tm_Force16BitTextures)?D3DFMT_R5G6B5:D3DFMT_UNKNOWN; //Now attempt to load the texture... //This is just temporyary, should check flags and stuff. HRESULT nResult=D3DXCreateTextureFromFileInMemoryEx( m_pDevice, pData, nSize, nTexSize, nTexSize, nMips, 0, nFormat, m_nPool, D3DX_DEFAULT, D3DX_DEFAULT, 0, LG_NULL, LG_NULL, &pOut); if(LG_FAILED(nResult)) { Err_Printf(LG_TEXT("TMgr ERROR: Could not obtain memory texture.")); Err_Printf(LG_TEXT("TMgr: Obtained default texture.")); return HM_DEFAULT_ITEM; } else { //We need to insert the texture into the list, so the reference is //valid, since we can't really hash memory we'll just use the first //available slot. We start at 1 because 0 is default. for(lg_dword nLoc=1; nLoc<m_nMaxItems; nLoc++) { if(m_pItemList[nLoc].nHashCode==CLHashMgr::HM_EMPTY_NODE) { m_pItemList[nLoc].pItem=pOut; m_pItemList[nLoc].nHashCode=CLHashMgr::HM_MEMORY_NODE; m_pItemList[nLoc].szName[0]=0; m_pItemList[nLoc].nFlags=nFlags; Err_Printf(LG_TEXT("TMgr: Loaded memory texture.")); return nLoc+1; } } } Err_Printf(LG_TEXT("TMgr ERROR: Could not find a spot, manager full.")); return HM_DEFAULT_ITEM; } void CLTMgr::Invalidate() { //Do nothing because textures are managed. } void CLTMgr::Validate() { //Do nothing because textures are managed. } IDirect3DTexture9* CLTMgr::DoLoad(lg_path szFilename, lg_dword nFlags) { //Open the file, we open with memory access. LF_FILE3 fileTex=LF_Open(szFilename, LF_ACCESS_MEMORY|LF_ACCESS_READ, LF_OPEN_EXISTING); if(!fileTex) return LG_NULL; IDirect3DTexture9* pOut=LG_NULL; //Use the cvars and flags to set up the load //If the size is 0, then the default size is taken lg_dword nTexSize=CV_Get(CVAR_tm_TextureSizeLimit)->nValue; lg_dword nMips=LG_CheckFlag(nFlags, TM_FORCENOMIP) || !CV_Get(CVAR_tm_UseMipMaps)->nValue?1:0; D3DFORMAT nFormat=CV_Get(CVAR_tm_Force16BitTextures)?D3DFMT_R5G6B5:D3DFMT_UNKNOWN; //Now attempt to load the texture... //This is just temporyary, should check flags and stuff. HRESULT hRes=D3DXCreateTextureFromFileInMemoryEx( m_pDevice, LF_GetMemPointer(fileTex), LF_GetSize(fileTex), nTexSize, nTexSize, nMips, 0, nFormat, m_nPool, D3DX_DEFAULT, D3DX_DEFAULT, 0, LG_NULL, LG_NULL, &pOut); //Close the source file. LF_Close(fileTex); if(LG_FAILED(hRes)) { Err_Printf("TMgr ERROR: \"%s\" was not a valid texture.", szFilename); pOut=LG_NULL; } return pOut; } void CLTMgr::DoDestroy(IDirect3DTexture9* pItem) { LG_SafeRelease(pItem); } void CLTMgr::SetTexture(tm_tex texture, lg_dword nStage) { m_pDevice->SetTexture(nStage, texture?m_pItemList[texture-1].pItem:0); } tm_tex CLTMgr::TM_LoadTex(lg_path szFilename, lg_dword nFlags) { return s_pTMgr->Load(szFilename, nFlags); } tm_tex CLTMgr::TM_LoadTexMem(lg_void* pData, lg_dword nSize, lg_dword nFlags) { return s_pTMgr->LoadTextureMem(pData, nSize, nFlags); } void CLTMgr::TM_SetTexture(tm_tex texture, lg_dword nStage) { return s_pTMgr->SetTexture(texture, nStage); } #if 0 //Test manager CLTMgr::CLTMgr(IDirect3DDevice9* pDevice, lg_dword nMaxTex) { } CLTMgr::~CLTMgr() { } tm_tex CLTMgr::TM_LoadTex(lg_path szFilename, lg_dword nFlags) { return 0; } tm_tex CLTMgr::TM_LoadTexMem(lg_void *pData, lg_dword nSize, lg_dword nFlags) { return 0; } void CLTMgr::Validate() { } void CLTMgr::Invalidate() { } void CLTMgr::TM_SetTexture(tm_tex texture, lg_dword nStage) { } void CLTMgr::PrintTextures() { Err_Printf("TMgr: The test texture manager is operating."); } #endif<file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/common/lc_sys.h /* lc_sys.h - Legacy Console copyright (c) 2006, <NAME> */ #ifndef __LC_SYS_H__ #define __LC_SYS_H__ #ifdef __cplusplus extern "C"{ #endif /* __cplusplus */ /***************************************************************************************** The legacy console library, this library is object oriented, it includes a console, which basically holds lines of text, and it will also send commands typed into the console to an external function. The library also includes a cvarlist object oriented type that store and retrieves variables from a database. The console has some built in functions and if a cvarlist is attached to it, it will process those functions. The console also will store a pointer to some private data that is passed to the command function. ******************************************************************************************/ typedef void* HLCONSOLE; /* Declaration for the command function. */ typedef int ( * LPCONCOMMAND)( unsigned long nCommand, const char* szParams, HLCONSOLE hConsole, void* pExtraData); #define CONF_CVARUPDATE 0x0080000Fl /* Legacy Console Function Prototypes. */ HLCONSOLE Con_Create( LPCONCOMMAND lpfnCommandFunc, unsigned long nMaxStrLen, unsigned long nMaxEntries, unsigned long dwFlags, void* pExtraData); int Con_Delete(HLCONSOLE hConsole); int Con_SendMessage(HLCONSOLE hConsole, char* szMessage); int Con_SendErrorMsg(HLCONSOLE hConsole, char* format, ...); int Con_SendCommand(HLCONSOLE hConsole, char* szCmdLine); int Con_SetCurrent(HLCONSOLE hConsole, char* szText); int Con_EraseCurrent(HLCONSOLE hConsole); int Con_Clear(HLCONSOLE hConsole); unsigned long Con_GetNumEntries(HLCONSOLE hConsole); char* Con_GetEntry(HLCONSOLE hConsole, unsigned long nEntry, char* szOut); int Con_RegisterCmd(HLCONSOLE hConsole, char* szCmdName, unsigned long nValue); int Con_OnChar(HLCONSOLE hConsole, unsigned short cChar); int Con_AttachCVarList(HLCONSOLE hConsole, void* cvarlist); //void* Con_GetCVar(HLCONSOLE hConsole, char* name); //void* Con_GetCVarList(HLCONSOLE hConsole); /* Creation flags. */ #define CONCREATE_USEINTERNAL (0x01000001) //#define CONCREATE_USECVARLIST (0x01000002) /* Legacy Console Function Pointers. */ typedef HLCONSOLE (*LPCON_CREATE)(void*, unsigned long, unsigned long, unsigned long, void*); typedef int (*LPCON_DELETE)(HLCONSOLE); typedef int (*LPCON_SENDMESSAGE)(HLCONSOLE, char*); typedef int (*LPCON_SENDERRORMSG)(HLCONSOLE, char*, ...); typedef int (*LPCON_SENDCOMMAND)(HLCONSOLE, char*); typedef int (*LPCON_SETCURRENT)(HLCONSOLE, char*); typedef int (*LPCON_ERASECURRENT)(HLCONSOLE); typedef int (*LPCON_CLEAR)(HLCONSOLE); typedef unsigned long (*LPCON_GETNUMENTRIES)(HLCONSOLE); typedef char* (*LPCON_GETENTRY)(HLCONSOLE, unsigned long, char*); typedef int (*LPCON_REGISTERCMD)(HLCONSOLE, char*, unsigned long); typedef int (*LPCON_ONCHAR)(HLCONSOLE, unsigned short); typedef int (*LPCON_ATTACHCVARLIST)(HLCONSOLE, void*); //typedef void* (*LPCON_GETCVAR)(HLCONSOLE, char*); //typedef void* (*LPCON_GETCVARLIST)(HLCONSOLE); /* Some helper functions. */ int CCParse_GetParam( char* szParamOut, const char* szParams, unsigned long nParam); float CCParse_GetFloat( char* szParams, unsigned short wParam); signed long CCParse_GetInt( char* szParams, unsigned short wParam); int CCParse_CheckParam( const char* szParams, const char* szAttrib, int nStart); /* The types for loading teh CCParse functions. */ typedef int (*LPCCPARSE_GETPARAM)(char*, const char*, unsigned long); typedef float (*LPCCPARSE_GETFLOAT)(char*, unsigned short); typedef signed long (*LPCCPARSE_GETINT)(char*, unsigned short); typedef int (*LPCCPARSE_CHECKPARAM)(char*, char*, int); /* The following functions are to help out with the built in window console. Con_CreateDlgBox will return a handle to a window that needs to be included in the main window loop for propper processing, the defined messages will allow the user to attach the console to the dialog box. And also to force the dialog box to update. */ /* Some functions to activate the windows dialog. */ void* Con_CreateDlgBox(); /* HWND Con_CreateDlgBox(); */ typedef void* (*LPCON_CREATEDLGBOX)(); /* Definition to attach a console to the windows dialog, and to update that dialog. */ #define WM_USER_UPDATE (WM_USER+1) #define WM_USER_INSTALLCONSOLE (WM_USER+2) /***************************************************************** The following declarations and variables apply to the cvarlist object oriented thingy. ******************************************************************/ typedef void* HCVARLIST; /* The cvar structure. */ /* Note that these values should not be changed, except using the CVar_ functions, the only reason the CVar structure is visible, is so that value and stringvalue can be accessed, without having to go through the linked list every time. */ typedef struct tagLCvar{ char* name; /* The name of the cvar. */ char* string; /* The value of the cvar in string format. */ float value; /* The value of the cvar as a float. */ unsigned long flags; /* Flags that were set during creaion.*/ struct tagLCvar* next; /* pointer to the next cvar. Do not mess with this value, only let the functions manipulate it. */ }CVar, *LPCVar; HCVARLIST CVar_CreateList(void* hConsole); int CVar_DeleteList(HCVARLIST hList); CVar* CVar_Register(HCVARLIST hList, char* szName, char* szValue, unsigned long dwFlags); int CVar_Set(HCVARLIST hList, char* szName, char* szValue); int CVar_SetValue(HCVARLIST hList, char* szName, float fValue); char* CVar_Get(HCVARLIST hList, char* szName, char* szOutput); float CVar_GetValue(HCVARLIST hList, char* szName, int* bGotValue); CVar* CVar_GetCVar(HCVARLIST hList, char* szName); CVar* CVar_GetFirstCVar(HCVARLIST hList); int CVar_AddDef(HCVARLIST hList, char* szDef, float fValue); float CVar_GetDef(HCVARLIST hList, char* szDef, int* bGotDef); typedef void* (*LPCVAR_CREATELIST)(void*); typedef int (*LPCVAR_DELETELIST)(HCVARLIST); typedef int (*LPCVAR_SET)(HCVARLIST, char*, char*); typedef int (*LPCVAR_SETVALUE)(HCVARLIST, char*, float); typedef char* (*LPCVAR_GET)(HCVARLIST, char*, char*); typedef float (*LPCVAR_GETVALUE)(HCVARLIST, char*, int*); typedef CVar* (*LPCVAR_GETCVAR)(HCVARLIST, char*); typedef CVar* (*LPCVAR_GETFIRSTCVAR)(HCVARLIST); typedef int (*LPCVAR_ADDDEF)(HCVARLIST, char*, float); typedef float (*LPCVAR_GETDEF)(HCVARLIST, char*, int*); /* CVar_Register creation flags. */ #define CVAREG_UPDATE (0x00000001) #define CVAREG_SAVE (0x00000002) #define CVAREG_SETWONTCHANGE (0x00000004) #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __LC_SYS_H__ */<file_sep>/tools/GFX/GFXG7/imageDD.cpp /* main.cpp Entry point for GFXG7 Dynamic-Link Library Copyright (c) 2002, 2003 <NAME> */ /* GFXG is a libray with functions for manipulating graphics in a 2D environment. It features both a Direct3D8 and DirectDraw7 interfaces. The functions and classes provided are intended for easy implementation. GFXG was originally built for ScrollGin technology. */ /* ImageDD.cpp - the DirectDraw image class Copyright (c) 2002, 2003 <NAME> */ #include <stdio.h> #include "defines.h" #include "gfxg7.h" CImage7::CImage7(){ m_lpImage=NULL; m_hBitmap=NULL; } CImage7::~CImage7(){ } HRESULT CImage7::CreateSurface(DWORD nWidth, DWORD nHeight, LPVOID lpObject, DWORD dwTransparent){ //Make sure DirectDraw exists if(!lpObject)return E_FAIL; //if the surface already exist we clear it out ClearSurface(); //Generate surface descriptors and create surface DDSURFACEDESC2 ddsd; ZeroMemory(&ddsd, sizeof(ddsd)); ddsd.dwSize = sizeof(ddsd); ddsd.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH; ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN; ddsd.dwWidth = nWidth; ddsd.dwHeight = nHeight; //create the surface if(((LPDIRECTDRAW7)lpObject)->CreateSurface(&ddsd, &m_lpImage, NULL) != DD_OK) return E_FAIL; //Set transparent color DDCOLORKEY ddck; ddck.dwColorSpaceLowValue=ddck.dwColorSpaceHighValue=dwTransparent; m_lpImage->SetColorKey(DDCKEY_SRCBLT, &ddck); if(m_lpImage)return S_OK; else return E_FAIL; return S_OK; } HRESULT CImage7::LoadColorIntoSurface(DWORD dwColor){ //check to make sure surface exists if(!m_lpImage)return E_FAIL; DDBLTFX ddbltfx; ZeroMemory(&ddbltfx, sizeof(ddbltfx)); ddbltfx.dwSize = sizeof(ddbltfx); ddbltfx.dwFillColor = dwColor; if(SUCCEEDED(m_lpImage->Blt( NULL, NULL, NULL, DDBLT_COLORFILL, &ddbltfx ))){ return S_OK; }else return E_FAIL; } DWORD CImage7::GetWidth(){ return m_sImageData.nWidth; } DWORD CImage7::GetHeight(){ return m_sImageData.nHeight; } HRESULT CImage7::DrawPrefered(LPVOID lpBuffer, int x, int y){ //clipped image is always prefered return DrawClippedImage(lpBuffer, x, y); //return DrawImage(lpBuffer, x, y); } HRESULT CImage7::DrawClippedImage(LPVOID lpBuffer, int x, int y){ if(!lpBuffer || !m_lpImage)return E_FAIL; RECT rcSrc, rcDest; DDSURFACEDESC2 ddBufferDesc; ZeroMemory(&ddBufferDesc, sizeof(ddBufferDesc)); ddBufferDesc.dwSize=sizeof(DDSURFACEDESC2); if(FAILED(((LPDIRECTDRAWSURFACE7)lpBuffer)->GetSurfaceDesc(&ddBufferDesc)))return E_FAIL; DWORD nBufferWidth=ddBufferDesc.dwWidth; DWORD nBufferHeight=ddBufferDesc.dwHeight; //if we don't need to clip we do a regular blt if( //withing the width (x>=0) && ((m_sImageData.nWidth+x)<nBufferWidth) && //within the height (y>=0) && ((m_sImageData.nHeight+y)<nBufferHeight) )return DrawImage(lpBuffer, x, y); //if the image is off screen we do no blt if(x>(int)nBufferWidth)return S_FALSE; if(y>(int)nBufferHeight)return S_FALSE; if((x+m_sImageData.nWidth)<=0)return S_FALSE; if((y+m_sImageData.nHeight)<=0)return S_FALSE; //if it has been determined that we need to do a clipped blt lets prepare the rectangles //prepare destination rectangle if(x>=0) rcDest.left=x; else rcDest.left=0; if((x+m_sImageData.nWidth)<nBufferWidth) rcDest.right=x+m_sImageData.nWidth; else rcDest.right=nBufferWidth; if(y>=0) rcDest.top=y; else rcDest.top=0; if((y+m_sImageData.nHeight)<nBufferHeight) rcDest.bottom=y+m_sImageData.nHeight; else rcDest.bottom=nBufferHeight; //prepare src rectangle if(x>=0) rcSrc.left=0; else rcSrc.left=0-x; if((x+m_sImageData.nWidth)<nBufferWidth) rcSrc.right=m_sImageData.nWidth; else rcSrc.right=nBufferWidth-x; if(y>=0) rcSrc.top=0; else rcSrc.top=0-y; if((y+m_sImageData.nHeight)<nBufferHeight) rcSrc.bottom=m_sImageData.nHeight; else rcSrc.bottom=nBufferHeight-y; if(SUCCEEDED(((LPDIRECTDRAWSURFACE7)lpBuffer)->Blt(&rcDest, m_lpImage, &rcSrc, DDBLT_KEYSRC|DDBLT_WAIT, NULL))){ return S_OK; } return E_FAIL; } HRESULT CImage7::DrawImage(LPVOID lpBuffer, int x, int y){ if(!lpBuffer || !m_lpImage)return E_FAIL; RECT rcSrc, rcDest; rcDest.left=x; rcDest.right=x+m_sImageData.nWidth; rcDest.top=y; rcDest.bottom=y+m_sImageData.nHeight; rcSrc.top=rcSrc.left=0; rcSrc.bottom=m_sImageData.nHeight; rcSrc.right=m_sImageData.nWidth; if(SUCCEEDED(((LPDIRECTDRAWSURFACE7)lpBuffer)->Blt(&rcDest, m_lpImage, &rcSrc, DDBLT_KEYSRC|DDBLT_WAIT, NULL))){ return S_OK; } return E_FAIL; } HRESULT CImage7::Restore(){ m_lpImage->Restore(); return S_OK; } HRESULT CImage7::ReloadImageIntoSurface(){ switch(m_sImageData.nType){ case ET_BITMAP: if(SUCCEEDED(LoadBitmapInMemoryIntoSurface( m_hBitmap, m_sImageData.nWidth, m_sImageData.nHeight)))return S_OK; else return E_FAIL; break; case ET_COLOR: if(SUCCEEDED(LoadColorIntoSurface(m_sImageData.dwColor)))return S_OK; else return E_FAIL; break; default: return E_FAIL; } } HRESULT CImage7::ClearSurface(){ Release(); return S_OK; } LPDIRECTDRAWSURFACE7* CImage7::GetPointerToSurface(){ return &m_lpImage; } void CImage7::Release(){ SAFE_RELEASE(m_lpImage); DeleteObject(m_hBitmap); } HRESULT CImage7::LoadBitmapInMemoryIntoSurface( HBITMAP hBitmap, DWORD nWidth, DWORD nHeight) { HDC hdcSurface=0, hdcImage=0; m_lpImage->GetDC(&hdcSurface); hdcImage=CreateCompatibleDC(hdcSurface); SelectObject(hdcImage, hBitmap); SetMapMode(hdcImage, GetMapMode(hdcSurface)); SetStretchBltMode(hdcImage, COLORONCOLOR); StretchBlt( hdcSurface, 0, 0, nWidth, nHeight, hdcImage, 0, 0, nWidth, nHeight, SRCCOPY); DeleteDC(hdcImage); m_lpImage->ReleaseDC(hdcSurface); return S_OK; } HRESULT CImage7::CreateImageBMInMemory( LPVOID lpObject, DWORD dwTransparent, HBITMAP hBitmap, int nX, int nY, int nSrcWidth, int nSrcHeight, DWORD nWidth, DWORD nHeight, DWORD dwReverseFlags) { if(!hBitmap)return E_FAIL; if(FAILED(CreateSurface(nWidth, nHeight, (LPDIRECTDRAW7)lpObject, dwTransparent)))return E_FAIL; HDC hdcSurface=0, hdcImage=0, hdcImageDest=0; int nXFinal=nX, nYFinal=nY; int nWidthFinal=nSrcWidth, nHeightFinal=nSrcHeight; if( RV_LEFTRIGHT == (dwReverseFlags&RV_LEFTRIGHT)){ nXFinal=nX+nSrcWidth-1; nWidthFinal=-nSrcWidth; } if( RV_UPDOWN == (dwReverseFlags&RV_UPDOWN)){ nYFinal=nY+nSrcHeight-1; nHeightFinal=-nSrcHeight; } m_lpImage->GetDC(&hdcSurface); hdcImage=CreateCompatibleDC(hdcSurface); hdcImageDest=CreateCompatibleDC(hdcSurface); m_hBitmap=CreateCompatibleBitmap(hdcSurface, nWidth, nHeight); SelectObject(hdcImage, hBitmap); SelectObject(hdcImageDest, m_hBitmap); SetMapMode(hdcImage, GetMapMode(hdcSurface)); SetStretchBltMode(hdcImage, COLORONCOLOR); StretchBlt( hdcImageDest, 0, 0, nWidth, nHeight, hdcImage, nXFinal, nYFinal, nWidthFinal, nHeightFinal, SRCCOPY); DeleteDC(hdcImage); DeleteDC(hdcImageDest); m_lpImage->ReleaseDC(hdcSurface); LoadBitmapInMemoryIntoSurface(m_hBitmap, nWidth, nHeight); m_sImageData.nWidth=nWidth; m_sImageData.nHeight=nHeight; m_sImageData.nType=ET_BITMAP; return S_OK; } HRESULT CImage7::CreateImageBMA( LPVOID lpDevice, DWORD dwTransparent, char szBitmapFilename[MAX_PATH], int nX, int nY, int nSrcWidth, int nSrcHeight, DWORD nWidth, DWORD nHeight, DWORD dwReverseFlags) { HBITMAP hBitmap=0; hBitmap=(HBITMAP)LoadImageA(NULL, szBitmapFilename, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE); HRESULT hr=0; hr=CreateImageBMInMemory(lpDevice, dwTransparent, hBitmap, nX, nY, nSrcWidth, nSrcHeight, nWidth, nHeight, dwReverseFlags); DeleteObject(hBitmap); return hr; } HRESULT CImage7::CreateImageBMW( LPVOID lpDevice, DWORD dwTransparent, WCHAR szBitmapFilename[MAX_PATH], int nX, int nY, int nSrcWidth, int nSrcHeight, DWORD nWidth, DWORD nHeight, DWORD dwReverseFlags) { HBITMAP hBitmap=0; hBitmap=(HBITMAP)LoadImageW(NULL, szBitmapFilename, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE); HRESULT hr=0; hr=CreateImageBMInMemory(lpDevice, dwTransparent, hBitmap, nX, nY, nSrcWidth, nSrcHeight, nWidth, nHeight, dwReverseFlags); DeleteObject(hBitmap); return hr; } HRESULT CImage7::CreateImageColor( LPVOID lpDevice, DWORD dwTransparent, DWORD dwColor, DWORD nWidth, DWORD nHeight) { if(FAILED(CreateSurface(nWidth, nHeight, (LPDIRECTDRAW7)lpDevice, dwTransparent)))return E_FAIL; if(FAILED(LoadColorIntoSurface(dwColor)))return E_FAIL; m_sImageData.dwColor=dwColor; m_sImageData.nType=ET_COLOR; return S_OK; } <file_sep>/games/Explor2002/Source/Game/bmp.cpp #include "bmp.h" #include "defines.h" extern int g_nScreenWidth, g_nScreenHeight; CBitmapReader::CBitmapReader(){ m_hBitmap=NULL; m_nFileWidth=m_nFileHeight=0; } CBitmapReader::~CBitmapReader(){ if(m_hBitmap)DeleteObject(m_hBitmap); } BOOL CBitmapReader::draw(LPDIRECTDRAWSURFACE surface){ return draw(surface, g_nScreenWidth, g_nScreenHeight, m_nFileWidth, m_nFileHeight, 0, 0); } BOOL CBitmapReader::draw(LPDIRECTDRAWSURFACE surface, int w, int h, int x, int y){ return draw(surface, w, h, w, h, x, y); } BOOL CBitmapReader::draw(LPDIRECTDRAWSURFACE surface, int w1, int h1, int w2, int h2, int x, int y){ HDC hDCSurface, hDCBitmap; surface->GetDC(&hDCSurface); hDCBitmap=CreateCompatibleDC(hDCSurface); SetMapMode(hDCBitmap, GetMapMode(hDCSurface)); SelectObject(hDCBitmap, m_hBitmap); SetStretchBltMode(hDCSurface, COLORONCOLOR); StretchBlt(hDCSurface, 0, 0, w1, h1, hDCBitmap, x, y, w2, h2, SRCCOPY); DeleteDC(hDCBitmap); surface->ReleaseDC(hDCSurface); return TRUE; } BOOL CBitmapReader::load(char *filename){ if(m_hBitmap){DeleteObject(m_hBitmap); m_hBitmap=NULL;}; m_hBitmap=(HBITMAP)LoadImage(NULL, filename, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE|LR_CREATEDIBSECTION); if(m_hBitmap==NULL)return FALSE; BITMAP bm; GetObject(m_hBitmap, sizeof(bm), &bm); m_nFileWidth=bm.bmWidth; m_nFileHeight=bm.bmHeight; return TRUE; }<file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/lg_cmd.h #ifndef __LG_CMD_H__ #define __LG_CMD_H__ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #include <lc_sys.h> #define CONF_QUIT 0x00000010 #define CONF_VRESTART 0x00000020 #define CONF_DIR 0x00000030 #define CONF_EXTRACT 0x00000040 #define CONF_D3DCAPS 0x00000050 #define CONF_VIDMEM 0x00000060 //#define CONF_HARDVRESTART 0x00000070 #define CONF_TEXFORMATS 0x00000080 #define CONF_LOADMODEL 0x00000090 #define CONF_VERSION 0x000000A0 int LGC_RegConCmds(HLCONSOLE hConsole); int LGC_ConCommand(unsigned long nCommand, const char* szParams, HLCONSOLE hConsole, void* pExtra); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __LG_CMD_H__ */<file_sep>/games/Legacy-Engine/Scrapped/old/lw_sys.h #ifndef __LW_SYS_H__ #define __LW_SYS_H__ #include "Newton/Newton.h" #include "lf_sys2.h" #include "lw_map.h" #include "lw_skybox.h" #include "le_camera.h" #include "le_3dbase.h" #include "lv_sys.h" #include "lp_sys.h" #include "lp_newton.h" #include "lp_physx.h" class CLWorld: private CElementD3D, CElementTimer { public: static CLPhysics s_LegacyPhysics; private: friend class CLGame; friend class CLJack; CLWorldMap m_WorldMap; CLSkybox2 m_SkyBox; CLCamera m_Camera; CLBase3DEntity* m_pEntities; void SetEntityLight(CLBase3DEntity* pEnt); public: CLWorld(); ~CLWorld(); void Initialize(); lg_bool LoadMap(lf_path szFilename); lg_bool LoadSky(lf_path szFilename); lg_bool LoadLevel(lf_path szXMLFilename); CLBase3DEntity* AddEntity(CLBase3DEntity* pEnt); void RemoveEntity(CLEntity* pEnt); void RemoveAllEntities(); void ProcessEntities(); void Render(); lg_bool Validate(); void Invalidate(); }; #endif __LW_SYS_H__<file_sep>/games/Legacy-Engine/Source/ws_sys/3dwsSDK.h #ifndef __3DWSSDK_H__ #define __3DWSSDK_H__ #include <pshpack1.h> typedef char wsChar; typedef unsigned char wsByte; typedef unsigned short wsWord; typedef unsigned long wsDword; typedef signed short wsShort; typedef signed long wsLong; typedef float wsFloat; typedef char* wsString; typedef unsigned long wsName; typedef struct _wsColor3 { wsByte r, g, b; }wsColor3; typedef struct _wsVec2 { wsFloat x, y; }wsVec2; typedef struct _wsVec3 { wsFloat x, y, z; }wsVec3; typedef struct _wsVec4 { wsFloat x, y, z, w; }wsVec4; //Plugin constants #define PLUGIN_EXPORT 1 #define PLUGIN_IMPORT 2 #define PLUGIN_BRUSHCREATION 4 #define PLUGIN_MESHLOAD 8 //Brush creation parameter constants #define PLUGIN_BRUSHCREATION_SPINNER 1 #define PLUGIN_BRUSHCREATION_CHECKBOX 2 #define PLUGIN_BRUSHCREATION_COMBOBOX 3 //Map components #define PLUGIN_BRUSHES 1 #define PLUGIN_MESHES 2 #define PLUGIN_ENTITIES 4 #define PLUGIN_TERRAIN 8 #define PLUGIN_MESHREFERENCES 16 #define PLUGIN_LIGHTMAPS 32 #define PLUGIN_COPYTEXTURES 64 #define WS_FUNC __stdcall void WS_FUNC PluginClass(wsByte* pIn, wsDword nInSize, wsByte* pOut, wsDword nOutSize); void WS_FUNC PluginMeshLoad(wsByte* pIn, wsDword nInSize, wsByte* pOut, wsDword nOutSize); void WS_FUNC PluginDescription(wsByte* pIn, wsDword nInSize, wsByte* pOut, wsDword nOutSize); void WS_FUNC PluginFileExtension(wsByte* pIn, wsDword nInSize, wsByte* pOut, wsDword nOutSize); void WS_FUNC PluginExport(wsByte* pIn, wsDword nInSize, wsByte* pOut, wsDword nOutSize); void WS_FUNC PluginLabel(wsByte* pIn, wsDword nInSize, wsByte* pOut, wsDword nOutSize); typedef void (WS_FUNC * WS_PLUGIN_FUNC)(wsByte* pIn, wsDword nInSize, wsByte* pOut, wsDword nOutSize); #include <poppack.h> #endif __3DWSSDK_H__<file_sep>/Misc/DBXExporter/DBXExporter/oedbx/library/dbxFolderInfo.cpp //*************************************************************************************** #define AS_OE_IMPLEMENTATION #include <oedbx/dbxFolderInfo.h> //*************************************************************************************** const char * DbxFolderInfo::GetIndexText(int1 index) const { const char * text[MaxIndex] = { "folder index" , "index of the parent folder" , "folder name (newsgroup name)" , "dbx file name" , "id 04" , "registry key of the account" , "flags" , "messages in the folder" , "unread messages in the folder" , "index for subfolders of 'local folders'" , "local folder value" , "id 0b" , "id 0c" , "max message index on server" , "min message index on server" , "id 0f" , "max message index local" , "min message index local" , "messages to download" , "id 13" , "id 14" , "id 15" , "id 16" , "id 17" , "id 18" , "id 19" , "id 1a" , "id 1b" , "watched messages" , "id 1d" , "id 1e" , "id 1f" }; if(index<MaxIndex) return text[index]; throw DbxException("Wrong index !"); } //*************************************************************************************** IndexedInfoDataType DbxFolderInfo::GetIndexDataType(int1 index) const { IndexedInfoDataType dataType[MaxIndex] = { dtInt4 , dtInt4 , dtString,dtString,dtInt4 , dtString,dtInt4 , dtInt4 , dtInt4 , dtInt4 , dtInt4 , dtNone , dtNone , dtInt4 , dtInt4 , dtInt4 , dtInt4 , dtInt4 , dtInt4 , dtData , dtNone , dtData , dtNone , dtNone , dtNone , dtNone , dtInt4 , dtNone , dtInt4 , dtNone , dtNone , dtNone }; if(index<MaxIndex) return dataType[index]; throw DbxException("Wrong index !"); } //*************************************************************************************** <file_sep>/games/Explor2002/Source_Old/ExplorED DOS/dosexplored/MAPBOARD.H #define NUMTILES 225 #define MAXPROPNUM 10 #define FNAMELEN 13 #define TBASE tbase(x, y) typedef unsigned short int BIT; typedef struct eMapHeader { unsigned int mapType; unsigned int mapVersion; unsigned long mapFileSize; unsigned int mapReserved1; unsigned int mapReserved2; unsigned int mapWidth; unsigned int mapHeight; unsigned long mapDataSize; unsigned long mapTileDataSize; unsigned long mapPropertyDataSize; unsigned int mapNumProperty; } MAPHEADER; typedef class ExplorMap { private: BIT tiles[NUMTILES]; BIT prop[MAXPROPNUM][NUMTILES]; MAPHEADER fileHeader; unsigned short tbase(int tx, int ty); public: int saveMap(char openmap[FNAMELEN]); int resetBoard(void); int openMap(char openmap[FNAMELEN]); int boardEdit(int x, int y, unsigned int propedit, unsigned int newvalue); int boardEdit(int x, int y); char boardname[FNAMELEN]; int getTileStat(int x, int y, int propnum); int getTileStat(int x, int y); } EXPLORMAP; <file_sep>/games/Legacy-Engine/Scrapped/libs/tga_lib/tga_lib_w.c #include <windows.h> #include "tga_lib.h" /* The idea behind converting an imaged to a DDB that can be used with windows is the get necessary data and use CreateDIBitmap with specified info. */ void* TGA_CreateDIBitmap(char* szFilename, void* hdc) { HBITMAP hFinal=NULL; HTGAIMAGE hImage=NULL; LPVOID lpImageData=NULL; BITMAPINFOHEADER bmih; BITMAPINFO bmi; TGA_DESC descript; unsigned char nExtra=255; unsigned short finalwidth=0, finalheight=0; ZeroMemory(&bmih, sizeof(BITMAPINFOHEADER)); ZeroMemory(&bmi, sizeof(BITMAPINFO)); hImage=TGA_Open(szFilename); if(!hImage) return NULL; TGA_GetDesc( hImage, &descript); finalwidth=descript.Width; finalheight=descript.Height; lpImageData=malloc(finalwidth*finalheight*4);//descript.Width*descript.Height*32/8); if(!lpImageData) { TGA_Delete(hImage); return NULL; } TGA_CopyBitsStretch( hImage, TGAFILTER_LINEAR, lpImageData, TGAORIENT_BOTTOMLEFT, TGAFMT_A8R8G8B8, finalwidth, finalheight, (unsigned short)(finalwidth*4), 0xFF); TGA_Delete(hImage); bmih.biSize=sizeof(BITMAPINFOHEADER); bmih.biWidth=finalwidth; bmih.biHeight=finalheight; bmih.biPlanes=1; bmih.biBitCount=32; bmih.biCompression=BI_RGB; bmih.biSizeImage=BI_RGB; bmih.biXPelsPerMeter=0; bmih.biYPelsPerMeter=0; bmih.biClrUsed=0; bmih.biClrImportant=0; bmi.bmiHeader=bmih; hFinal=CreateDIBitmap( hdc, &bmih, CBM_INIT, lpImageData, &bmi, DIB_RGB_COLORS); free(lpImageData); return hFinal; } <file_sep>/games/Explor2002/Source_Old/ExplorED DOS/dosexplored/MOUSE.H /* mouse.h for ExplorED */ int initMouse(void); int initCursor(void); int disableCursor(void); int showMouseStats(void); union REGS mregs; <file_sep>/games/Explor2002/Source_Old/ExplorED DOS/borland/resource.h //{{NO_DEPENDENCIES}} // Microsoft Developer Studio generated include file. // Used by wxplored.rc // #define IDI_ICON1 101 #define IDI_ICON2 102 #define ICON_1 102 #define MENU_MAIN 103 #define IDR_ACCELERATOR1 104 #define CM_FILENEW 40003 #define CM_FILEOPEN 40004 #define CM_FILESAVE_AS 40006 #define CM_FILESAVE 40007 #define CM_FILEEXIT 40009 #define CM_FILEPRINT 40010 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 105 #define _APS_NEXT_COMMAND_VALUE 40011 #define _APS_NEXT_CONTROL_VALUE 1000 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif <file_sep>/tools/img_lib/img_lib2/img_lib/img_lib.c #include <stdio.h> #include <memory.h> #include <malloc.h> #include <math.h> #include "img_lib.h" #include "img_private.h" /************************ *** Public Functions. *** ************************/ HIMG IMG_FUNC IMG_OpenCallbacks(img_void* stream, IMG_CALLBACKS* lpCB) { HIMG hImage=IMG_NULL; if(!hImage) hImage=IMG_LoadPNGCallbacks(stream, lpCB); if(!hImage) hImage=IMG_LoadTGACallbacks(stream, lpCB); if(!hImage) hImage=IMG_LoadBMPCallbacks(stream, lpCB); if(!hImage) hImage=IMG_LoadGIFCallbacks(stream, lpCB); if(!hImage) hImage=IMG_LoadJPGCallbacks(stream, lpCB); lpCB->close(stream); return hImage; } HIMG IMG_FUNC IMG_OpenMemory(img_void* pData, img_dword nSize) { HIMG hImage=IMG_NULL; img_void* pFile=IMG_NULL; IMG_CALLBACKS cb; pFile=img_file_open(pData, nSize); if(!pFile) return IMG_NULL; cb.close=img_file_close; cb.read=img_file_read; cb.seek=img_file_seek; cb.tell=img_file_tell; return IMG_OpenCallbacks(pFile, &cb); } HIMG IMG_FUNC IMG_OpenA(char* szFilename) { img_dword nSize=0, nRead=0; img_void* buffer=IMG_NULL; HIMG hTemp=IMG_NULL; /* Op the file and get it's size. */ FILE* fin=IMG_NULL; fopen_s(&fin, szFilename, "rb"); if(!fin) return IMG_NULL; fseek(fin, 0, SEEK_END); nSize=ftell(fin); fseek(fin, 0, SEEK_SET); buffer=malloc(nSize); if(!buffer) { fclose(fin); return IMG_NULL; } /* Read the whole file into a buffer. */ nRead=fread(buffer, 1, nSize, fin); fclose(fin); if(nRead<nSize) { free(buffer); return IMG_NULL; } /* Call img open memory with buffer, and size as parameters to open the image. */ hTemp=IMG_OpenMemory(buffer, nSize); /* The memory must be freed, because it is not freed in IMG_OpenMemory. */ free(buffer); /* If IMG_OpenMemory failed we will be returning, the null from that function so we don't need to test here. */ return hTemp; } HIMG IMG_FUNC IMG_OpenW(img_wchar* szFilename) { img_dword nSize=0, nRead=0; img_void* buffer=IMG_NULL; HIMG hTemp=IMG_NULL; /* Op the file and get it's size. */ FILE* fin=IMG_NULL; _wfopen_s(&fin, szFilename, L"rb"); if(!fin) return IMG_NULL; fseek(fin, 0, SEEK_END); nSize=ftell(fin); fseek(fin, 0, SEEK_SET); buffer=malloc(nSize); if(!buffer) { fclose(fin); return IMG_NULL; } /* Read the whole file into a buffer. */ nRead=fread(buffer, 1, nSize, fin); fclose(fin); if(nRead<nSize) { free(buffer); return IMG_NULL; } /* Call img open memory with buffer, and size as parameters to open the image. */ hTemp=IMG_OpenMemory(buffer, nSize); /* The memory must be freed, because it is not freed in IMG_OpenMemory. */ free(buffer); /* If IMG_OpenMemory failed we will be returning, the null from that function so we don't need to test here. */ return hTemp; } img_bool IMG_FUNC IMG_Delete(HIMG hImage) { IMAGE_S* lpImage=(IMAGE_S*)hImage; if(!lpImage) return IMG_FALSE; //Delete the image data, palette, and description. IMG_SAFE_FREE(lpImage->pImage); IMG_SAFE_FREE(lpImage->pPalette); IMG_SAFE_FREE(lpImage->szDescripton); //Delete the structure. free(hImage); return IMG_TRUE; } img_bool IMG_FUNC IMG_GetPalette( HIMG hImage, void* lpDataOut) { IMAGE_S* lpImage=(IMAGE_S*)hImage; if(!lpDataOut || !lpImage->pPalette) return 0; memcpy( lpDataOut, lpImage->pPalette,//((LPTGAIMAGE)hImage)->ColorMap, lpImage->nPaletteSize);//(((LPTGAIMAGE)hImage)->Header.nCMEntrySize/8)*((LPTGAIMAGE)hImage)->Header.nNumCMEntries); return 1; } #define IMG_scale_float(value, scale) (long)(((float)value)*(scale)) #define IMG_scale_int(value, scale) (long)((((long)value)*(scale)) img_bool IMG_ChangePixelFmt( unsigned long* color, IMGFMT prevdepth, IMGFMT newdepth, img_byte extra) { unsigned long r=0, g=0, b=0, a=0; unsigned long newcolor=0x00000000l; if(!color) return 0; if(prevdepth==newdepth) return 1; if(newdepth==IMGFMT_PALETTE) return 0; switch(prevdepth) { case IMGFMT_X1R5G5B5: /* Using floating point, for the conversion proccess, is more accurate, but slower. */ a=((*color)&0x8000)>>15; r=((*color)&0x7C00)>>10; g=((*color)&0x03E0)>>5; b=((*color)&0x001F)>>0; //a*=255; a=extra; r=IMG_scale_float(r, 255.0f/31.0f); g=IMG_scale_float(g, 255.0f/31.0f); b=IMG_scale_float(b, 255.0f/31.0f); break; case IMGFMT_R5G6B5: a = extra; r = ((*color)&0xF800)>>10; g = ((*color)&0x07E0)>>5; b = ((*color)&0x001F)>>0; a = extra; r=IMG_scale_float(r, 255.0f/31.0f); g=IMG_scale_float(g, 255.0f/63.0f); b=IMG_scale_float(b, 255.0f/31.0f); case IMGFMT_A8R8G8B8: //Not 100% sure this is getting the right value. a=(char)(((*color)&0xFF000000)>>24); extra=(char)a; case IMGFMT_R8G8B8: a=extra; r=((*color)&0x00FF0000)>>16; g=((*color)&0x0000FF00)>>8; b=((*color)&0x000000FF)>>0; break; case IMGFMT_B8G8R8: a=extra; b=((*color)&0x00FF0000)>>16; g=((*color)&0x0000FF00)>>8; r=((*color)&0x000000FF)>>0; break; case IMGFMT_PALETTE: return 0; break; } switch(newdepth) { case IMGFMT_X1R5G5B5: r=IMG_scale_float(r, 31.0f/255.0f); g=IMG_scale_float(g, 31.0f/255.0f); b=IMG_scale_float(b, 31.0f/255.0f); *color=0; *color=((a>0?1:0)<<15)|(r<<10)|(g<<5)|(b<<0); break; case IMGFMT_R5G6B5: r=IMG_scale_float(r, 31.0f/255.0f); g=IMG_scale_float(g, 63.0f/255.0f); b=IMG_scale_float(b, 31.0f/255.0f); *color=0; *color=(r<<11)|(g<<5)|(b<<0); break; case IMGFMT_R8G8B8: case IMGFMT_A8R8G8B8: *color=(a<<24)|(r<<16)|(g<<8)|(b<<0); break; case IMGFMT_B8G8R8: *color=(a<<24)|(b<<16)|(g<<8)|(r<<0); break; } return 1; } int IMG_GetPixel( HIMG hImage, unsigned long* lpPix, signed short x, signed short y, IMGFMT Format, unsigned char nExtra) { IMAGE_S* lpImage=hImage; IMGORIENT nSrcOrient=lpImage->nOrient;//lpImage?TGA_IMAGE_ORIGIN(lpImage->Header.nImageDesc):0; IMGFMT nSrcFormat=0; unsigned short iHeight=0, iWidth=0; unsigned long nSource=0; unsigned long nSourceColor=0, nSourceCMEntry=0; if(!lpImage) return 0; iHeight=lpImage->nHeight;//Header.nHeight; iWidth=lpImage->nWidth;//Header.nWidth; if(x>=iWidth) x=iWidth-1; if(y>=iHeight) y=iHeight-1; if(x<0) x=0; if(y<0) y=0; switch(nSrcOrient) { case IMGORIENT_BOTTOMLEFT: nSource=iWidth*(iHeight-y-1) + x; break; case IMGORIENT_BOTTOMRIGHT: nSource=iWidth*(iHeight-1-y) + (iWidth-x-1); break; case IMGORIENT_TOPLEFT: nSource=iWidth*y + x; break; case IMGORIENT_TOPRIGHT: nSource=iWidth*y + (iWidth-x-1); break; default: return 0; } nSource*=lpImage->nBitDepth/8;//Header.nBitsPerPixel/8; memcpy(&nSourceColor, (void*)((unsigned int)lpImage->pImage+nSource), lpImage->nBitDepth/8); if(lpImage->nDataFmt==IMGFMT_PALETTE) { nSourceCMEntry=nSourceColor; nSourceColor=0; memcpy(&nSourceColor, (void*)((unsigned int)lpImage->pPalette+nSourceCMEntry*(lpImage->nPaletteBitDepth/8)), (lpImage->nPaletteBitDepth/8)); nSrcFormat=lpImage->nPaletteFmt; } else nSrcFormat=lpImage->nDataFmt; IMG_ChangePixelFmt(&nSourceColor, nSrcFormat, Format, nExtra); if(lpPix) *lpPix=nSourceColor; return 1; } img_bool IMG_GetPixelFilter( HIMG hImage, unsigned short nSampleLevel, unsigned long* lpPix, unsigned short x, unsigned short y, IMGFMT Format, unsigned char nExtra) { unsigned long lpPixels[1024]; unsigned short over=0, under=0; unsigned long i=0; unsigned long nCTR=0, nCTG=0, nCTB=0, nCTA=0; img_dword nNumPix=0; nNumPix=(img_dword)pow((double)2, (double)(nSampleLevel+1)); if( nNumPix > countof(lpPixels)) { return IMG_GetPixel( hImage, lpPix, x, y, Format, nExtra); } if(nNumPix<=1 || !lpPixels || nSampleLevel==0) { return IMG_GetPixel( hImage, lpPix, x, y, Format, nExtra); } for(under=0, i=0; under<(nNumPix/2); under++) { for(over=0; over<(nNumPix/2); over++, i++) { if(i>=nNumPix) break; lpPixels[i]=0; IMG_GetPixel(hImage, &lpPixels[i], (short)(x+over/*-nNumPix/4*/), (short)(y+under/*-nNumPix/4*/), IMGFMT_A8R8G8B8, nExtra); } } for(i=0; i<(nNumPix); i++) { nCTA+=(0xFF000000&lpPixels[i])>>24; nCTR+=(0x00FF0000&lpPixels[i])>>16; nCTG+=(0x0000FF00&lpPixels[i])>>8; nCTB+=(0x000000FF&lpPixels[i])>>0; } nCTA/=(nNumPix); nCTR/=(nNumPix); nCTG/=(nNumPix); nCTB/=(nNumPix); nCTA<<=24; nCTR<<=16; nCTG<<=8; nCTB<<=0; if(lpPix) { *lpPix=(nCTA|nCTR|nCTG|nCTB); IMG_ChangePixelFmt(lpPix, IMGFMT_A8R8G8B8, Format, nExtra); } return 1; } img_bool IMG_FUNC IMG_CopyBits( HIMG hImage, IMG_DEST_RECT* pDest, IMGFILTER Filter, IMG_RECT* prcSrc, img_byte nExtra) { IMAGE_S* lpImage=(IMAGE_S*)hImage; img_byte nDestBitDepth=0; img_long nSrcWidth=0, nSrcHeight=0; float fWidthRatio=0.0f, fHeightRatio=0.0f; img_short nFilterLevel=0; img_long x=0, y=0; img_dword nDest=0; img_dword nPix=0, nCMEntry=0; float fSrcX=0.0f, fSrcY=0.0f; IMG_RECT rcSrc; if(!lpImage) return IMG_FALSE; if(!prcSrc) { rcSrc.top=rcSrc.left=0; rcSrc.right=lpImage->nWidth; rcSrc.bottom=lpImage->nHeight; } else rcSrc=*prcSrc; //Make sure the source rectangle is valid. rcSrc.left=IMG_CLAMP(rcSrc.left, 0, lpImage->nWidth); rcSrc.right=IMG_CLAMP(rcSrc.right, 0, lpImage->nWidth); rcSrc.top=IMG_CLAMP(rcSrc.top, 0, lpImage->nHeight); rcSrc.bottom=IMG_CLAMP(rcSrc.bottom, 0, lpImage->nHeight); //Make sure the dest rectangle is valid. pDest->rcCopy.left=IMG_CLAMP(pDest->rcCopy.left, 0, (img_long)pDest->nWidth); pDest->rcCopy.right=IMG_CLAMP(pDest->rcCopy.right, 0, (img_long)pDest->nWidth); pDest->rcCopy.top=IMG_CLAMP(pDest->rcCopy.top, 0, (img_long)pDest->nHeight); pDest->rcCopy.bottom=IMG_CLAMP(pDest->rcCopy.bottom, 0, (img_long)pDest->nHeight); //We need to know the bitdepth of the destination //for copying purposes. switch(pDest->nFormat) { case IMGFMT_PALETTE: nDestBitDepth=8; break; case IMGFMT_X1R5G5B5: case IMGFMT_R5G6B5: nDestBitDepth=16; break; case IMGFMT_R8G8B8: nDestBitDepth=24; break; case IMGFMT_R8G8B8A8: case IMGFMT_A8R8G8B8: nDestBitDepth=32; break; } //If the pitch was specified as zero we are going to assume //that means that the pitch is the same as the width. if(pDest->nPitch==0) pDest->nPitch=pDest->nWidth*nDestBitDepth/8; nSrcWidth=rcSrc.right-rcSrc.left; nSrcHeight=rcSrc.bottom-rcSrc.top; //Find the width and height ratio to determine how much stretching should be done. fWidthRatio=(float)(nSrcWidth-1)/(float)(pDest->nWidth-1); fHeightRatio=(float)(nSrcHeight-1)/(float)(pDest->nHeight-1); //If we are doing linear filtering we need to find the average //ratio so we can find out how much filtering we need to do. if(Filter==IMGFILTER_LINEAR) { short nAveRatio=(short)(fWidthRatio+fHeightRatio)/2; nFilterLevel=0; while((nAveRatio/=2)>0) nFilterLevel++; } else { nFilterLevel=0; } /* For each pixel for the destination we do the following procedure:*/ for(y=pDest->rcCopy.top; y<pDest->rcCopy.bottom; y++) { for(x=pDest->rcCopy.left; x<pDest->rcCopy.right; x++) { /* We calculate where the destination pixel will go based on what the orientation is. */ switch(pDest->nOrient) { case IMGORIENT_BOTTOMLEFT: nDest=pDest->nPitch*(pDest->nHeight-(y+1))+x*(nDestBitDepth/8); break; case IMGORIENT_BOTTOMRIGHT: nDest=pDest->nPitch*(pDest->nHeight-1-y) + (pDest->nWidth-x-1)*(nDestBitDepth/8); break; case IMGORIENT_TOPLEFT: nDest=y*pDest->nPitch + x*(nDestBitDepth/8); break; case IMGORIENT_TOPRIGHT: nDest=pDest->nPitch*y + (pDest->nWidth-x-1)*(nDestBitDepth/8); break; default: return 0; } nPix=0x00000000l; /* The we calculate where the source pixel would be located.*/ fSrcX=x*fWidthRatio+rcSrc.left; fSrcY=y*fHeightRatio+rcSrc.top; /* We get that pixel (the function converts it to the format we want. The we copy it to the destination.*/ IMG_GetPixelFilter(hImage, nFilterLevel, &nPix, (short)fSrcX, (short)fSrcY, pDest->nFormat, nExtra); memcpy((void*)((unsigned int)pDest->pImage+nDest), &nPix, nDestBitDepth/8); } } return IMG_TRUE; } img_bool IMG_FUNC IMG_GetDesc( HIMG hImage, IMG_DESC* lpDescript) { IMAGE_S* lpImage=hImage; if(!lpImage || !lpDescript) return 0; lpDescript->Width=lpImage->nWidth; lpDescript->Height=lpImage->nHeight; lpDescript->Format=lpImage->nDataFmt; lpDescript->BitsPerPixel=lpImage->nBitDepth; lpDescript->NumPaletteEntries=lpImage->nPaletteEntries; lpDescript->PaletteBitDepth=lpImage->nPaletteBitDepth; lpDescript->PaletteFormat=lpImage->nPaletteFmt; return 1; } /* typedef struct _IMG_CALLBACKS{ img_int (IMG_FUNC *close)(img_void* stream); img_int (IMG_FUNC *seek)(img_void* stream, img_long offset, img_int origin); img_long (IMG_FUNC *tell)(img_void* stream); img_uint (IMG_FUNC *read)(img_void* buffer, img_uint size, img_uint count, img_void* stream); }IMG_CALLBACKS, *PIMG_CALLBACKS; */<file_sep>/games/Legacy-Engine/Scrapped/tools/Texview2/src/Texture.h // Texture.h: interface for the CTexture class. // ////////////////////////////////////////////////////////////////////// #include "img_lib.h" #if !defined(AFX_TEXTURE_H__A9B8095A_5622_48A2_83DA_06A0D7AF237E__INCLUDED_) #define AFX_TEXTURE_H__A9B8095A_5622_48A2_83DA_06A0D7AF237E__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #define BC_IMAGE (0x00000010) #define BC_ACHANNEL (0x00000020) #define BC_USEAPPBG (0x00000040) typedef struct _ARGBVALUE{ BYTE b, g, r, a; }ARGBVALUE; class CTexture { public: void GetBitmapDims(int* pWidth, int* pHeight); int m_nHeight; int m_nWidth; BOOL DrawBitmap(int x, int y, CDC* pdc); BOOL CreateCBitmap(int cx, int cy, IMGFILTER filter, CDC* pdc, DWORD Flags); BOOL Load(LPTSTR szFilename); void Unload(); CTexture(); virtual ~CTexture(); private: CBitmap m_bmImage; HIMG m_hTGAImage; }; #endif // !defined(AFX_TEXTURE_H__A9B8095A_5622_48A2_83DA_06A0D7AF237E__INCLUDED_) <file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/console/lconsole/lc_private.h #ifndef __LC_PRIVATE_H__ #define __LC_PRIVATE_H__ #include "lc_sys.h" #ifdef __cplusplus extern "C"{ #endif /* __cplusplus */ /* Internal function def values. */ #define CONF_SET 0x00800001l #define CONF_GET 0x00800002l #define CONF_LOADCFG 0x00800003l #define CONF_CLEAR 0x00800004l #define CONF_ECHO 0x00800005l #define CONF_DEFINE 0x00800006l #define CONF_CVARLIST 0x00800007l #define CONF_REGCVAR 0x00800008l #define CONF_SAVECFG 0x00800009l #define CONF_CONDUMP 0x0080000Al #define CONF_CMDLIST 0x0080000Bl /***************************************************** Definition storage, the following declarations and variables allow for the use of definitions in the cvarlist. ******************************************************/ typedef void* HLDEFS; int Defs_CheckDefName(char* szDef, char* szNoFAllow, char* szNoAllow); typedef struct tagLDef{ char* name; float value; struct tagLDef* next; }LDef, *LPLDef; typedef struct tagLDefs{ LDef* list; }LDefs, *LPLDefs; HLDEFS Defs_CreateDefs(); int Defs_DeleteDefs(HLDEFS hDefs); float Defs_Get(HLDEFS hDef, char* szName, int* bGotDef); int Defs_Add(HLDEFS hDefs, char* szDef, float fValue); int Defs_ReDef(HLDEFS hDef, char* szName, float fNewValue); /* Private types. */ typedef struct tagLCENTRY{ char* lpstrText; struct tagLCENTRY * lpNext; }LCENTRY, *LPLCENTRY; typedef struct tagLCONSOLE{ unsigned long dwNumEntries; LCENTRY * lpActiveEntry; LCENTRY * lpEntryList; LPCONCOMMAND CommandFunction; unsigned long nMaxStrLen; unsigned long nMaxEntries; int bProcessInternal; HCVARLIST cvarlist; HLDEFS commands; void* pExtraData; }LCONSOLE, *LPLCONSOLE; /* Legacy Console Private Function declarations. */ int Con_AddEntry(HLCONSOLE hConsole, char* szEntry); int Con_ClearOldestEntry(HLCONSOLE hConsole); int Con_SimpleParse(char* szCommand,char* szParams,char* szIgnore,char* szLineIn,unsigned long dwMaxLen); int Con_InternalCommands(unsigned long nCommand, const char* szParams, HLCONSOLE hConsole); unsigned long Con_CmdNameToValue(HLCONSOLE hConsole, const char* szCmdName); /* Private functions. */ int L_CheckValueName(char* szDef, char* szNoFirstAllow, char* szNoAllow); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __LC_PRIVATE_H__ */<file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/lv_init.h /* lv_init.h - Header for video initialization functions. */ #ifndef __LVINIT_H__ #define __LVINIT_H__ #include "lg_sys.h" #ifdef __cplusplus extern "C"{ #endif /*__cplusplus*/ L_bool LV_PrintPP(D3DPRESENT_PARAMETERS* pp); int LV_SetPPFromCVars( L3DGame* lpGame, D3DPRESENT_PARAMETERS* pp); L_bool LV_SetStates(L3DGame* lpGame); L_bool LV_SetFilterMode(L3DGame* lpGame, L_int nFilterMode, L_dword dwStage); L_result LV_Init(L3DGame* lpGame); L_result LV_Shutdown(L3DGame* lpGame); L_bool LV_SupportedTexFormats( HCVARLIST cvars, IDirect3D9* lpD3D, UINT nAdapterID, UINT nDeviceType, D3DFORMAT dfmt); /* Some Definitions to help make sure everything works.*/ /* These ones are for the texture filter mode. */ #define FILTER_MODE "v_TextureFilter" typedef enum _LV_TEXFILTER_MODE{ FILTER_UNKNOWN = 0, FILTER_NONE = 0, FILTER_POINT = 1, FILTER_LINEAR = 2, FILTER_BILINEAR = 2, FILTER_TRILINEAR = 3, FILTER_ANISOTROPIC = 4, FILTER_FORCE_DWORD = 0xFFFFFFFF }LV_TEXFILTER_MODE; #define FILTER_MAXANISOTROPY "v_MaxAnisotropy" #ifdef __cplusplus } #endif /*__cplusplus*/ #endif /*__LIVINIT_H__*/<file_sep>/tools/CornerBin/ReadMe.txt CornerBin (c) 2011 Beem Media Open Source ================================================================================ Officially CornernBin is as http://cornerbin.sourceforge.net. I'm including the source code here only to have an archive with the rest of the Beem Media source code. Building -------- The environment variable BEEMOUT should be set prior to building. This variable determines where the compiled data is built to. Go to advanced system settings ->environment variables and set BEEMOUT=D:\CornerBinOut (or similar). The Release build will copy the executable back to the dist directory. CornerBin uses MFC so you must install MFC alongside Visual Studio. This is included with Visual Studio 2015 Community Edition, but is not installed by default so make sure to run the Visual Studio setup utility with that option checked. (You can modify existing Visual Studio 2015 installations to install this.) <file_sep>/games/Legacy-Engine/Source/engine/lv_img2d.h #ifndef __LV_2DIMG_H__ #define __LV_2DIMG_H__ #include <d3d9.h> #include "common.h" #include "lg_tmgr.h" class CLImg2D { private: //The vertex type for the 2D image, and //the structure. #define LV2DIMGVERTEX_TYPE \ ( \ D3DFVF_XYZ| \ D3DFVF_DIFFUSE| \ D3DFVF_TEX1 \ ) typedef struct _LV2DIMGVERTEX{ float x, y, z; lg_dword Diffuse; float tu, tv; }LV2DIMGVERTEX, *LPLV2DIMGVERTEX; private: IDirect3DDevice9* m_pDevice; tm_tex m_pTexture; //Image texture. IDirect3DVertexBuffer9* m_pVB; //Vertex buffer for image. LV2DIMGVERTEX m_Vertices[4]; //Vertices for image. lg_dword m_dwWidth; //Width of image. lg_dword m_dwHeight; //Height of image. lg_bool m_bIsColor; //Color of image, if there is a color. lg_bool m_bFromTexture; //If the image is from a texture. struct _LV2DIMAGE* m_pCreate;//A pointer to the image that created this one. char m_szFilename[LG_MAX_PATH+1]; //The name of the texture for reloading. lg_dword m_dwTransparent; lg_rect m_rcSrc; public: CLImg2D(); ~CLImg2D(); lg_bool CreateFromFile( IDirect3DDevice9* lpDevice, char* szFilename, lg_rect* rcSrc, lg_dword dwWidth, lg_dword dwHeight, lg_dword dwTransparent); lg_bool CreateFromColor( IDirect3DDevice9* lpDevice, lg_dword dwWidth, lg_dword dwHeight, lg_dword dwColor); void Invalidate(); lg_bool Validate(void* pExtra); void Delete(); lg_bool Render(float x, float y); private: void CLImg2D::SetVertices( lg_rect* rcSrc, float fTexWidth, float fTexHeight, float fWidth, float fHeight); public: static lg_bool StartStopDrawing( IDirect3DDevice9* lpDevice, lg_dword ViewWidth, lg_dword ViewHeight, lg_bool bStart); }; #endif /* __LV_2DIMG_H__ */<file_sep>/games/Legacy-Engine/Source/engine/lg_mem_file.cpp #include "lg_mem_file.h" #include "lg_func.h" #include "lg_err.h" #include "lg_err_ex.h" #include <memory.h> CLMemFile::CLMemFile(lg_dword nSize) : m_pMem(LG_NULL) , m_nSize(0) , m_nPos(0) { if(nSize) Open(nSize); } CLMemFile::~CLMemFile() { Close(); } lg_dword CLMemFile::Tell()const { return m_nPos; } lg_dword CLMemFile::Size()const { return m_nSize; } lg_dword CLMemFile::Read(lg_void* pOut, const lg_dword nSize) { lg_dword nReadSize=LG_Min(nSize, m_nSize-m_nPos); memcpy(pOut, &m_pMem[m_nPos], nReadSize); m_nPos+=nReadSize; return nReadSize; } lg_dword CLMemFile::Write(const lg_void* const pIn, const lg_dword nSize) { lg_dword nWriteSize=LG_Min(nSize, m_nSize-m_nPos); memcpy(&m_pMem[m_nPos], pIn, nWriteSize); m_nPos+=nWriteSize; return nWriteSize; } void CLMemFile::Open(lg_dword nSize) { Close(); m_pMem=new lg_byte[nSize]; LG_ASSERT(m_pMem, LG_NULL); m_nPos=0; m_nSize=nSize; } void CLMemFile::Resize(lg_dword nSize) { lg_byte* pNew=new lg_byte[nSize]; LG_ASSERT(pNew, LG_NULL); memcpy(pNew, m_pMem, LG_Min(m_nSize, nSize)); LG_SafeDeleteArray(m_pMem); m_pMem=pNew; m_nSize=nSize; m_nPos=LG_Clamp(m_nPos, 0, m_nSize); } void CLMemFile::Close() { LG_SafeDeleteArray(m_pMem); m_nSize=0; m_nPos=0; } void CLMemFile::Seek(MEM_SEEK_TYPE type, lg_long distance) { lg_dword nNewPos=0; if(type==MEM_SEEK_CUR) { nNewPos+=distance; } else if(type==MEM_SEEK_BEGIN) { nNewPos=distance; } else if(type==MEM_SEEK_END) { nNewPos=m_nSize+distance; } m_nPos=LG_Clamp(nNewPos, 0, m_nSize); }<file_sep>/games/Legacy-Engine/Scrapped/UnitTests/VarTest/var_mgr.cpp #include "var_mgr.h" namespace var_sys { CVarMgr::CDefMap* CVarMgr::s_pDefMap=NULL; CVarMgr::CVarMgr(var_word nMaxVars) : m_nMaxVars(nMaxVars) , m_nNextVarToCreate(0) , m_pVarMem(NULL) { m_pVarMem = new CVar[m_nMaxVars]; s_pDefMap=&m_DefMap; //We will always register a NULL variable, and it will be returned //whenever we tried to get a variable that didn't exist. Register<var_char*>(_T("NULL"), _T("(NULL)"), CVar::F_ROM); } CVarMgr::~CVarMgr(void) { m_DefMap.clear(); m_VarMap.clear(); s_pDefMap=NULL; delete[]m_pVarMem; } bool CVarMgr::DefToValues(const var_char* def, var_float * fValue, var_long * nValue) { if(s_pDefMap && s_pDefMap->count(def)) { *fValue=(*s_pDefMap)[def].fValue; *nValue=(*s_pDefMap)[def].nValue; return true; } return false; } CVar* CVarMgr::CreateNewVar(const var_char* name) { CVar* pOut = NULL; if(m_nMaxVars>m_nNextVarToCreate) { pOut=&m_pVarMem[m_nNextVarToCreate++]; pOut->Init(name); } return pOut; } lg_var CVarMgr::Get(const var_char* name) { //If the requested variable has not been registered, the NULL //variable is returned. return m_VarMap.count(name)?*m_VarMap[name]:*m_VarMap[_T("NULL")]; } lg_var CVarMgr::operator[](const var_char* name) { return Get(name); } void CVarMgr::DebugPrintList() { for(CVarMap::iterator i = m_VarMap.begin(); i!=m_VarMap.end(); i++) { if(i->second) _tprintf(_T("%s = %s (%f)\n"), i->second->Name(), i->second->String(), i->second->Float()); else _tprintf(_T("No value at: %s\n"), i->first); } _tprintf(_T("The size of the map is: %i\n"), m_VarMap.size()); } } //namespace var_sys <file_sep>/samples/Project5/src/bcol/BSTree.java /* <NAME> CS 2420-002 bcol collection */ package bcol; public class BSTree <T extends Comparable<T>> { private BSNode m_nodeRoot; /* PRE: N/A POST: Creates a new instance of BSTree. */ public BSTree() { m_nodeRoot = null; } /* PRE: obj should be initialized. POST: obj is inserted into the search tree. */ public void insert(T obj){ //Create a new node to contain the object. BSNode nodeNew=new BSNode(obj); //If the root node is null it means we just insert the new node //into the start of the tree. if(m_nodeRoot==null){ m_nodeRoot = nodeNew; }else{ //We'll loop through the nodes, searching left or right, depending //on how the node compares, until we find the sport we're looking for //then the node is inserted. We know that we've inserted the node //when n is set to null. BSNode n = m_nodeRoot; while(n!=null){ //We perform a compareTo for every iteration. int nRes=nodeNew.compareTo(n); if(nRes<0){ //If less than we go down the left branch. if(n.m_nodeLeft==null){ //If the left node is null then we found the node //we're looking for so we need only assign the left node //to the new node, and set n to null to break out of the //search. n.m_nodeLeft=nodeNew; n=null; } else{ //If the node was not blank, we set n to the left node //to continue the search. n=n.m_nodeLeft; } }else if(nRes>0){ //if greater than we go down the right branch. if(n.m_nodeRight==null){ //See the algorithm for left node search. n.m_nodeRight=nodeNew; n=null; } else{ n=n.m_nodeRight; } }else{ //Node is already in the tree. We'll just set n to null to //break out of the loop. n=null; } } //We're done searching and the node was inserted in the propper //location. } } /* PRE: obj != null. POST: If an object is found int he tree that results in an equal comparison to the object specified (that is compareTo() reutrns 0, then that object will be removed from the tree. If the object was removed true is returned, if no matching object is found in the tree false is returned. */ public boolean remove(T obj){ SearchRes searchRes = findForDelete(obj); boolean bRemoved=false; if(searchRes==null){ bRemoved = false; }else{ if(searchRes.m_Parent==null){ //If we are deleting the root node it is a special case. //We know it is the root node because it has no parent. m_nodeRoot = deleteNode(searchRes.m_Result); }else if(searchRes.m_nResIs==RES_IS.LEFT){ //When deleting the left node we use the deleteNode method //on the result and reasign its parents node to the new tree //returned from deleteNode (see method). searchRes.m_Parent.m_nodeLeft = deleteNode(searchRes.m_Result); }else if(searchRes.m_nResIs==RES_IS.RIGHT){ //This is a similar procedure to the left node but //we asign the new tree to the right node instead of the left //one. searchRes.m_Parent.m_nodeRight = deleteNode(searchRes.m_Result); }else{ //This case should never have come up. } bRemoved = true; } return bRemoved; } /* PRE: nodeDel is a node in the tree and != null. POST: the specified node is deleted from the tree, and a new tree representing the tree that replaces the branch of the tree at nodeDel is returned. The return value should be assigned to the previous trees left or right node accordingly. (See remove method.) */ private BSNode deleteNode(BSNode nodeDel){ BSNode nodeRes = null; if(nodeDel.m_nodeLeft==null){ nodeRes = nodeDel.m_nodeRight; }else if(nodeDel.m_nodeRight==null){ nodeRes = nodeDel.m_nodeLeft; }else{ nodeRes=nodeDel; SearchRes searchRes = findLeftMost(nodeRes.m_nodeRight); nodeDel.m_object=searchRes.m_Result.m_object; if(searchRes.m_Parent != null){ //System.out.println("Deleting SUB case."); searchRes.m_Parent.m_nodeLeft = deleteNode(searchRes.m_Result); }else{ //System.out.println("Deleting STAND case!"); nodeDel.m_nodeRight = deleteNode(searchRes.m_Result); } } return nodeRes; } /* PRE: nodeStart != null, called only be deleteNode(). POST: Returns a SearchRes containing the left most node and the parent of the left most node. If nodeStart was the left most node then the m_Parent attribute of SearchRes will be null. */ private SearchRes findLeftMost(BSNode nodeStart){ SearchRes searchRes = new SearchRes(); searchRes.m_Result=nodeStart; if(searchRes.m_Result!=null){ while(searchRes.m_Result.m_nodeLeft!=null){ searchRes.m_Parent=searchRes.m_Result; searchRes.m_nResIs=RES_IS.LEFT; searchRes.m_Result=searchRes.m_Result.m_nodeLeft; } } return searchRes; } /* PRE: obj!=null. POST: If a matching object was in the tree the Object is returned, if not null is returned. */ public T find(T obj){ BSNode n = findNode(obj); return n==null?null:n.m_object; } /* PRE: obj != null POST: If a matching node is found, that node is returned. If no matching node is found null is returned. */ public BSNode findNode(T obj){ //We'll create a node to hold the obj to help //us with the compareTo process. BSNode nodeFind = new BSNode(obj); boolean bFound=false; //Now search through the tree til we find what we want. BSNode n = m_nodeRoot; while(!bFound && n!=null){ int nRes = nodeFind.compareTo(n); if(nRes < 0){ n = n.m_nodeLeft; } else if(nRes>0){ n = n.m_nodeRight; }else { bFound=true; nodeFind=n; } } //If we never found a matching node, //then we need to return null. if(!bFound) nodeFind=null; return nodeFind; } /* PRE: obj !=null POST: Returns a SearchRes if a comparable object was found in the tree. SearchRes contains the parent node, the result and wether or not the child is the left or right node. */ private SearchRes findForDelete(T obj){ SearchRes searchRes = new SearchRes(); //We'll create a node to hold the obj to help //us with the compareTo process. BSNode nodeFind = new BSNode(obj); boolean bFound=false; //Now search through the tree til we find what we want. BSNode n = m_nodeRoot; BSNode nP = null; while(!bFound && n!=null){ int nRes = nodeFind.compareTo(n); if(nRes < 0){ searchRes.m_Parent=n; searchRes.m_nResIs=RES_IS.LEFT; n = n.m_nodeLeft; } else if(nRes>0){ searchRes.m_Parent=n; searchRes.m_nResIs=RES_IS.RIGHT; n = n.m_nodeRight; }else { bFound=true; searchRes.m_Result=n; nodeFind=n; } } //If we never found a matching node, //then we need to return null. if(!bFound) searchRes=null; return searchRes; } /* PRE: N/A POST: REturns a string representation of the tree in order from least to greatest. */ public String toString() { String retString = ""; if (m_nodeRoot == null) { retString += "The list is empty\n"; } else { retString += "\nHere is the tree--------------\n"; retString += m_nodeRoot.toStringInOrder(""); //, true); retString += "This is the end of the tree---------\n"; } return retString; } /* The SearchRes class is for returning valuable information for node deletion.*/ private enum RES_IS{UNKNOWN, LEFT, RIGHT}; private class SearchRes{ private SearchRes(){ m_Parent=null; m_Result=null; m_nResIs=RES_IS.UNKNOWN; } private BSNode m_Parent; private BSNode m_Result; private RES_IS m_nResIs; } //The BSNode holds whatever object the list stores. private class BSNode implements Comparable<BSNode>{ T m_object; BSNode m_nodeLeft; BSNode m_nodeRight; /* PRE: N/A POST: Creates a new instance of BSNode */ public BSNode(){ m_nodeLeft=null; m_nodeRight=null; m_object=null; } /* PRE: N/A POST: Creates a new instance of BSNode containing the the specified object. */ public BSNode(T object){ m_nodeLeft=null; m_nodeRight=null; m_object=object; } /* PRE: n is a BSNode. POST: Returns integer value in accordance with compareTo specifications. */ public int compareTo(BSNode n){ return m_object.compareTo(n.m_object); } /* PRE: N/A POST: A string representation of the object is returned. */ public String toString(){ return m_object.toString(); } /* PRE: s is a string to be appended to. POST: Appends this node and child nodes strings together and returns the new string. Tranverses child nodes in-order. */ public String toStringInOrder(String s) { if (m_nodeLeft!=null) { s = m_nodeLeft.toStringInOrder(s); } s += m_object + "\n"; if (m_nodeRight!=null) s = m_nodeRight.toStringInOrder(s); return s; } } } <file_sep>/games/Legacy-Engine/Source/engine/lp_legacy.h /* lp_legacy.h - The basic Legacy Physics engine, not as robust as the Newton or PhysX physics engines, but a demonstration of the development process. Copyright (c) 2007 <NAME> */ #ifndef __LP_LEGACY_H__ #define __LP_LEGACY_H__ #include "lp_sys2.h" #include "lg_list.h" #include "lg_stack.h" #include "lg_list_stack.h" //#define FORCE_METHOD class CLPhysLegacy: CLPhys { //Constants: private: static const lg_dword LP_MAX_O_REGIONS=8; private: LG_CACHE_ALIGN class CLPhysBody: public CLListStack::LSItem { public: ML_MAT m_matPos; //Position of body. ML_VEC3 m_v3Thrust; ML_VEC3 m_v3Vel; ML_VEC3 m_v3Torque; ML_VEC3 m_v3AngVel; lg_float m_fMass; //Mass in KG. ML_VEC3 m_v3Center; ML_AABB m_aabbBase; //The volume of the object in meters. ML_AABB m_aabbPreMove; //The current location of the volume. ML_AABB m_aabbPostMove; //The future location of the volume. ML_AABB m_aabbMove; //The volume occupied while the body was moving. #ifdef FORCE_METHOD ML_VEC3 m_v3ClsnForces; //Forces that were applied during collsion detection: #endif //Regions that the body is occupying: lg_dword m_nNumRegions; lg_dword m_nRegions[LP_MAX_O_REGIONS]; //Additional data: lg_float m_fSpeed; //The linear speed of the object. (m/s) lg_float m_fAngSpeed; //The angular speed of the object. (rad/s) //Flags: //BITS 0-15 (Createion flags, see lp_body_info structure for mor info). //BIT 16: Awake Asleep Flag (1) Awake (0) Asleep lg_dword m_nFlags; lg_void* m_pEnt; //The entity attached to the body. //A pointer to a body that the entity is colliding with, //for inelastic collisions. lg_dword m_nColBody; public: //Constants static const lg_dword PHYS_BODY_AWAKE= 0x00010000; }; //Class to describe the map geometry: LG_CACHE_ALIGN class CLPhysHull { public: lg_dword m_nFirstFace; lg_dword m_nNumFaces; ml_aabb m_aabbHull; ml_plane* m_pFaces; }; private: lg_dword m_nMaxBodies; //The maximum number of bodies allowed. CLListStack m_AsleepBodies; //Asleep bodies CLListStack m_AwakeBodies; //Awake bodies CLListStack m_UnusedBodies; //Bodies available to be created. CLPhysBody* m_pBodyList; //List of available bodies. //Global Settings ML_VEC3 m_v3Grav;//Gravity force (Newtons). lg_float m_fDrag; //Drag coefficient. //Frame stuff: lg_float m_fTimeStep; //World geometry: //In the future it should be divided into regions: lg_dword m_nHullCount; ml_plane* m_pGeoPlaneList; CLPhysHull* m_pGeoHulls; //Some vars that are used temporarily: lg_dword m_nClsns; //Internal methods: private: __inline void ProcessAwakeBodies(); __inline void CollisionCheck(); __inline void BodyClsnCheck(CLPhysBody* pBody1, CLPhysBody* pBody2); __inline void HullClsnCheck(CLPhysBody* pBody, CLPhysHull* pHull); __inline void ApplyWorldForces(CLPhysBody* pBody); __inline static lg_dword AABBIntersectHull(const ml_aabb* pAABB, const CLPhysHull* pHull, const ml_vec3* pVel, ml_plane* pIsctPlane); /* __inline void WorldCheck(CLPhysBody* pBody); __inline void RegionCheck(CLPhysBody* pBody, lg_dword nRegion); __inline void BlockClip(CLPhysBody* pBody, LW_GEO_BLOCK_EX* pBlock); */ __inline void SetPreMoveAABB(CLPhysBody* pBody); __inline void SetPostMoveAABB(CLPhysBody* pBody); public: virtual void Init(lg_dword nMaxBodies); virtual void Shutdown(); virtual lg_void* AddBody(lg_void* pEnt, lp_body_info* pInfo); virtual void RemoveBody(lg_void* pBody); virtual void SetupWorld(lg_void* pWorldMap); virtual void SetGravity(ML_VEC3* pGrav); virtual void Simulate(lg_float fTimeStepSec); virtual void SetBodyFlag(lg_void* pBody, lg_dword nFlagID, lg_dword nValue); virtual void SetBodyVector(lg_void* pBody, lg_dword nVecID, ML_VEC3* pVec); virtual void SetBodyFloat(lg_void* pBody, lg_dword nFloatID, lg_float fValue); virtual void SetBodyPosition(lg_void* pBody, ML_MAT* pMat); virtual lg_void* GetBodySaveInfo(lg_void* pBody, lg_dword* pSize); virtual lg_void* LoadBodySaveInfo(lg_void* pData, lg_dword nSize); __inline void UpdateFromSrv(CLPhysBody* pPhysBody, lg_void* pEntSrv); __inline void UpdateToSrv(CLPhysBody* pPhysBody, lg_void* pEntSrv); }; #endif __LP_LEGACY_H__<file_sep>/games/Legacy-Engine/Scrapped/old/lv_tex.c /* lv_tex.c texture loading functions. */ #ifndef D3DX_SUPPORT #define D3DX_SUPPORT #endif //D3DX_SUPPORT #include "lv_tex.h" #ifdef D3DX_SUPPORT #include <d3dx9.h> #endif D3DX_SUPPORT #include "lg_err.h" #include "img_lib.h" #include "lf_sys2.h" #include "ML_lib.h" #include "lg_func.h" lg_bool Tex_LoadD3D( IDirect3DDevice9* lpDevice, lg_lpstr szFilename, D3DPOOL Pool, lg_dword Flags, lg_dword nSizeLimit, IDirect3DTexture9** lppTex); lg_bool Tex_CanAutoGenMipMap(IDirect3DDevice9* lpDevice, D3DFORMAT Format); //lg_bool g_bUseMipMaps=LG_TRUE; //lg_bool g_bUseHWMipMaps=LG_TRUE; //lg_bool g_MipFilter=FILTER_LINEAR; lg_bool g_nSizeLimit=0; //lg_bool g_bForce16Bit=LG_FALSE; #ifdef _DEBUG lg_bool g_bLoadOptionsSet=LG_FALSE; #endif _DEBUG lg_dword g_TexLdFlags=TEXLOAD_GENMIPMAP|TEXLOAD_HWMIPMAP|TEXLOAD_LINEARMIPFILTER; void Tex_SetLoadOptions( lg_bool bUseMipMaps, //If false all mip-mapping will be disabled. lg_bool bUseHWMips, //If true hardware mip-maps will be generated if possible. TEXFILTER_MODE MipFilter, //If the image has to be resisized at all this will be the filter applied. lg_uint nSizeLimit, //Textures will not excede this size. lg_bool bForce16Bit,//If ture all textures will be limited to 16 bits. lg_bool b16Alpha) { g_TexLdFlags=0; if(bUseMipMaps) g_TexLdFlags|=TEXLOAD_GENMIPMAP; if(bUseHWMips) g_TexLdFlags|=TEXLOAD_HWMIPMAP; if(MipFilter>=FILTER_LINEAR) g_TexLdFlags|=TEXLOAD_LINEARMIPFILTER; if(bForce16Bit) g_TexLdFlags|=TEXLOAD_FORCE16BIT; if(b16Alpha) g_TexLdFlags|=TEXLOAD_16BITALPHA; g_nSizeLimit=nSizeLimit; #ifdef _DEBUG g_bLoadOptionsSet=LG_TRUE; #endif _DEBUG } void Tex_SetLoadOptionsFlag(lg_dword Flags, lg_uint nSizeLimit) { g_TexLdFlags=Flags; g_nSizeLimit=nSizeLimit; #ifdef _DEBUG g_bLoadOptionsSet=LG_TRUE; #endif _DEBUG } lg_bool Tex_Load( IDirect3DDevice9* lpDevice, lg_lpstr szFilename, D3DPOOL Pool, lg_dword dwTransparent, lg_bool bForceNoMip, IDirect3DTexture9** lppTex) { //void* lpGame=LG_NULL;//LG_GetGame(); lg_dword nFlags=0; lg_bool (*pTexLoadCB)( IDirect3DDevice9* lpDevice, lg_lpstr szFilename, D3DPOOL Pool, lg_dword Flags, lg_dword SizeLimit, IDirect3DTexture9** lppTex)=LG_NULL; lg_bool bGenMipMap=LG_FALSE; TEXFILTER_MODE nMipFilter=FILTER_POINT; lg_dword dwSizeLimit=0; char* szExt=LG_NULL; lg_dword nLen=L_strlen(szFilename); lg_dword i=0; #ifdef _DEBUG if(!g_bLoadOptionsSet) Err_PrintfDebug("Tex_Load WARNING: Using Tex_Load before calling Tex_SetLoadOptions...\n"); #endif _DEBUG if(!lpDevice || !szFilename) { Err_Printf("Tex_Load Error: Could not open \"%s\".", szFilename); Err_Printf(" No device or no filename specified."); *lppTex=LG_NULL; return LG_FALSE; } nFlags=g_TexLdFlags; dwSizeLimit=g_nSizeLimit; /* #ifdef _DEBUG Err_PrintfDebug("Loading with the following options:\n%s%s%s%s%s\n\tSize Limit: %d", L_CHECK_FLAG(nFlags, TEXLOAD_GENMIPMAP)?"\tGENMIPMAP\n":"", L_CHECK_FLAG(nFlags, TEXLOAD_HWMIPMAP)?"\tHWMIPMAP\n":"", L_CHECK_FLAG(nFlags, TEXLOAD_LINEARMIPFILTER)?"\tLINEARMIPFILTER\n":"", L_CHECK_FLAG(nFlags, TEXLOAD_FORCE16BIT)?"\tFORCE16BIT\n":"", L_CHECK_FLAG(nFlags, TEXLOAD_16BITALPHA)?"\t16BITALPHS\n":"", g_nSizeLimit); #endif */ for(i=nLen; i>0; i--) { if(szFilename[i]=='.') { szExt=&szFilename[i+1]; break; } } #ifdef D3DX_SUPPORT if(L_strnicmp(szExt, "tga", 0) || L_strnicmp(szExt, "bmp", 0) || L_strnicmp(szExt, "dib", 0) || L_strnicmp(szExt, "jpg", 0) || L_strnicmp(szExt, "gif", 0) || L_strnicmp(szExt, "png", 0)) pTexLoadCB=Tex_LoadIMG2; else pTexLoadCB=Tex_LoadD3D; #else D3DX_SUPPORT pTexLoadCB=Tex_LoadIMG2; #endif D3DX_SUPPORT return pTexLoadCB( lpDevice, szFilename, Pool, nFlags, dwSizeLimit, lppTex); } lg_bool Tex_Load_Memory( IDirect3DDevice9* lpDevice, lg_void* pBuffer, lg_dword nSize, D3DPOOL Pool, lg_dword dwTransparent, lg_bool bForceNoMip, IDirect3DTexture9** lppTex) { //void* lpGame=LG_NULL;//LG_GetGame(); lg_dword nFlags=0; lg_bool (*pTexLoadCB)( IDirect3DDevice9* lpDevice, lg_void* pBuffer, lg_dword nSize, D3DPOOL Pool, lg_dword Flags, lg_dword SizeLimit, IDirect3DTexture9** lppTex)=LG_NULL; lg_bool bGenMipMap=LG_FALSE; TEXFILTER_MODE nMipFilter=FILTER_POINT; lg_dword dwSizeLimit=0; #ifdef _DEBUG if(!g_bLoadOptionsSet) Err_PrintfDebug("Tex_Load WARNING: Useing Tex_Load before calling Tex_SetLoadOptions...\n"); #endif _DEBUG if(!lpDevice) { Err_Printf("Tex_Load_Memory Error: Could not open texture."); Err_Printf(" No device or no filename specified."); *lppTex=LG_NULL; return LG_FALSE; } nFlags=g_TexLdFlags; dwSizeLimit=g_nSizeLimit; pTexLoadCB=Tex_LoadIMG2_Memory; return pTexLoadCB( lpDevice, pBuffer, nSize, Pool, nFlags, dwSizeLimit, lppTex); } lg_bool Tex_CanAutoGenMipMap(IDirect3DDevice9* lpDevice, D3DFORMAT Format) { D3DCAPS9 Caps; D3DDEVICE_CREATION_PARAMETERS d3ddc; D3DDISPLAYMODE d3ddm; IDirect3D9* lpD3D=LG_NULL; lg_result nResult=0; if(!lpDevice) return LG_FALSE; memset(&Caps, 0, sizeof(D3DCAPS9)); lpDevice->lpVtbl->GetDeviceCaps(lpDevice, &Caps); if(!L_CHECK_FLAG(Caps.Caps2, D3DCAPS2_CANAUTOGENMIPMAP)) return LG_FALSE; lpDevice->lpVtbl->GetDirect3D(lpDevice, &lpD3D); memset(&d3ddc, 0, sizeof(d3ddc)); lpDevice->lpVtbl->GetCreationParameters(lpDevice, &d3ddc); memset(&d3ddm, 0, sizeof(d3ddm)); nResult=lpD3D->lpVtbl->CheckDeviceFormat( lpD3D, d3ddc.AdapterOrdinal, d3ddc.DeviceType, D3DFMT_R5G6B5, D3DUSAGE_AUTOGENMIPMAP, D3DRTYPE_TEXTURE, Format); L_safe_release(lpD3D); if(LG_SUCCEEDED(nResult)) return LG_TRUE; else return LG_FALSE; } lg_bool Tex_SysToVid( IDirect3DDevice9* lpDevice, IDirect3DTexture9** lppTex, lg_dword Flags) /* lg_bool bAutoGenMipMap, D3DTEXTUREFILTERTYPE AutoGenFilter) */ { IDirect3DTexture9* lpTexSys=*lppTex; IDirect3DTexture9* lpTexVid=LG_NULL; lg_result nResult=0; D3DSURFACE_DESC sysdesc; lg_dword nLevelCount=0; if(!lpTexSys || !lpDevice) return LG_FALSE; /* Get the description of the system texture. Make sure that the source is actually in system memory. Also get the level count.*/ memset(&sysdesc, 0, sizeof(sysdesc)); nResult=IDirect3DTexture9_GetLevelDesc(lpTexSys, 0, &sysdesc); if(LG_FAILED(nResult)) return LG_FALSE; if(sysdesc.Pool!=D3DPOOL_SYSTEMMEM) return LG_FALSE; nLevelCount=IDirect3DTexture9_GetLevelCount(lpTexSys); /* Create the new texture in video memory. */ nResult=lpDevice->lpVtbl->CreateTexture( lpDevice, sysdesc.Width, sysdesc.Height, L_CHECK_FLAG(Flags, SYSTOVID_AUTOGENMIPMAP)?0:nLevelCount, L_CHECK_FLAG(Flags, SYSTOVID_AUTOGENMIPMAP)?D3DUSAGE_AUTOGENMIPMAP:0, sysdesc.Format, D3DPOOL_DEFAULT, &lpTexVid, LG_NULL); if(LG_FAILED(nResult)) { Err_Printf("Tex_Load Error: Could not open texture."); Err_PrintDX(" IDirect3DDevice9::CreateTexture", nResult); return LG_FALSE; } /* Use the device function to update the surface in video memory, with the data in system memory, then release the system memory texture, and adjust the pointer to point at the video memory texture. */ if(L_CHECK_FLAG(Flags, SYSTOVID_AUTOGENMIPMAP) && nLevelCount==1) { D3DTEXTUREFILTERTYPE nFilter=0; nFilter=L_CHECK_FLAG(Flags, SYSTOVID_LINEARMIPFILTER)?D3DTEXF_LINEAR:D3DTEXF_POINT; lpTexVid->lpVtbl->SetAutoGenFilterType(lpTexVid, nFilter); } lpTexVid->lpVtbl->AddDirtyRect(lpTexVid, LG_NULL); lpDevice->lpVtbl->UpdateTexture(lpDevice, (void*)lpTexSys, (void*)lpTexVid); lpTexSys->lpVtbl->Release(lpTexSys); *lppTex=lpTexVid; return LG_TRUE; } #ifdef D3DX_SUPPORT lg_bool Tex_LoadD3D( IDirect3DDevice9* lpDevice, lg_lpstr szFilename, D3DPOOL Pool, lg_dword Flags, lg_dword nSizeLimit, IDirect3DTexture9** lppTex) { LF_FILE3 fin=LG_NULL; lg_result nResult=0; lg_uint nMipLevels=0; lg_dword dwTexFilter=0; lg_dword dwTexFormat=0; lg_dword dwWidth=0, dwHeight=0; fin=LF_Open(szFilename, LF_ACCESS_READ|LF_ACCESS_MEMORY, LF_OPEN_EXISTING); if(!fin) { Err_Printf("Tex_Load Error: Could not create texture from \"%s\".", szFilename); Err_Printf(" Could not open source file."); return LG_FALSE; } if(L_CHECK_FLAG(Flags, TEXLOAD_GENMIPMAP)) nMipLevels=0; else nMipLevels=1; if(L_CHECK_FLAG(Flags, TEXLOAD_LINEARMIPFILTER)) dwTexFilter=D3DX_FILTER_TRIANGLE|D3DX_FILTER_DITHER; else dwTexFilter=D3DX_FILTER_POINT; if(nSizeLimit) { dwWidth=dwHeight=nSizeLimit; } else { dwWidth=dwHeight=D3DX_DEFAULT; } if(L_CHECK_FLAG(Flags, TEXLOAD_FORCE16BIT)) { if(L_CHECK_FLAG(Flags, TEXLOAD_16BITALPHA)) dwTexFormat=D3DFMT_A1R5G5B5; else dwTexFormat=D3DFMT_R5G6B5; } else { dwTexFormat=D3DFMT_UNKNOWN; } /* Because we opened the file in membuf mode, we can just pas the pFileData member, and the File Size member to create the file in memory. */ nResult=D3DXCreateTextureFromFileInMemoryEx( lpDevice, LF_GetMemPointer(fin), LF_GetSize(fin), dwWidth, dwHeight, nMipLevels, 0, dwTexFormat, Pool, dwTexFilter, dwTexFilter, 0, LG_NULL, LG_NULL, lppTex); LF_Close(fin); if(LG_FAILED(nResult)) { Err_Printf("Tex_Load Error: Could not create texture from \"%s\".", szFilename); Err_PrintDX(" D3DXCreateTextureFromFileInMemoryEx", nResult); return LG_FALSE; } return LG_TRUE; } #endif D3DX_SUPPORT typedef struct _TEX_IMG_COPY_DESC2{ lg_dword nWidth; lg_dword nHeight; IMGFMT nFormat; D3DFORMAT nD3DFormat; TEXFILTER_MODE nMipFilter; lg_bool bGenMipMap; lg_bool bUseHWMipMap; D3DPOOL nPool; lf_path szFilename; }TEX_IMG_COPY_DESC2; __inline lg_bool Tex_CopyIMGToTex( IDirect3DDevice9* lpDevice, HIMG hImage, IDirect3DTexture9** lppTex, TEX_IMG_COPY_DESC2* pDesc); int __cdecl img_close(void* stream); int __cdecl img_seek(void* stream, long offset, int origin); int __cdecl img_tell(void* stream); unsigned int __cdecl img_read(void* buffer, unsigned int size, unsigned int count, void* stream); /*************************************************************************** Tex_LoadIMG() Loads a texture into a texture interface in system memory. This is an example of how to manually load a texture into system memory. The idea behind this function is that it loads the HIMG then prepares the TEX_IMG_COPY_DESC2 structure based on the loaded texture and various paramters and cvars, then calls Tex_CopyIMGToTex using the TEX_IMG_COPY_DESC2 structure to create the texture. Note that this functions insures that all values passed to Tex_CopyIMGToTex are valid. What the different Flags parameters will do: TEXLOAD_GENMIPMAP - A mip map will be generated for the texture. TEXLOAD_HWMIPMAP - The texture will use hardware generated mip maps (if available) TEXLOAD_LINEARMIPFILTER - The device will use a linear filter to genreate mip sublevels. TEXLOAD_POINTMIPFILTER - The device will use point filterting to generate mip sublevels. TEXLOAD_FORCE16BIT - The texture will be forced to a bitdepth of 16. TEXLOAD_16BITALPHA - If the texture is being converted from 32 bit to 16 bit an alpha channel will be used for the 16 bit texture allowing the retention of some transparency. Note that 16 bit alpha channels are only 1 bit so they are either on or off, the texture loader typically converts even the remotest amount of transparency to off. Notes: The function will limit the texture to the specified size limit. It also insures that the final texture dimensions will be valid (a power of 2, square, etc) depending on the device capabilities. Note that it assumes that the final texture format will be valid so if a video card that only supports 16 bit textures is being used then when Tex_LoadIMG2 is called the TEXLOAD_FORCE16BIT flag needs to be set or the texture creation will fail. ***************************************************************************/ lg_bool Tex_LoadIMG2( IDirect3DDevice9* lpDevice, lg_lpstr szFilename, D3DPOOL Pool, lg_dword Flags, lg_dword nSizeLimit, IDirect3DTexture9** lppTex) { LF_FILE3 fin=LG_NULL; lg_bool bResult; if(!lpDevice || !szFilename) { *lppTex=LG_NULL; return LG_FALSE; } /* First thing first we open the tga file, we are using the callback function to open the file so that we can use the Legacy File system. */ /* If we can't open the file, or if the tga file can't be opened then it was probably an invalid texture. Note that TGA_OpenCallbacks will close the file for us, so we don't need to worry about closing it ourselves. */ /* We use the LF_ACCESS_MEMORY flag to insure that we can use File_GetMemPointer. */ fin=LF_Open(szFilename, LF_ACCESS_READ|LF_ACCESS_MEMORY, LF_OPEN_EXISTING); if(!fin) { Err_Printf("Tex_Load Error: Could not open \"%s\".", szFilename); Err_Printf(" Could not open source file."); *lppTex=LG_NULL; return LG_FALSE; } bResult=Tex_LoadIMG2_Memory(lpDevice, LF_GetMemPointer(fin), LF_GetSize(fin), Pool, Flags, nSizeLimit, lppTex); LF_Close(fin); return bResult; } /* Tex_CopyIMGToTex() This funciton actually creates the IDirect3DTexture9 interface, and copies the data located in hImage to the texture, it uses parameters set up in the TEX_IMG_COPY_DESC2 structure. Note that it does not check to make sure that the values in that structure are valid, as Tex_LoadIMG builds that structure and insures that it is valid. This function is only intended to be called by Tex_LoadImage and not any other function.*/ __inline lg_bool Tex_CopyIMGToTex( IDirect3DDevice9* lpDevice, HIMG hImage, IDirect3DTexture9** lppTex, TEX_IMG_COPY_DESC2* pDesc) { IDirect3DTexture9* lpTexTemp=LG_NULL; lg_dword nMipLevels=0; lg_dword nUsage=0; lg_dword i=0; lg_result nResult=0; //Find out how many mip levels need to be generated. //1 if there will be no mip map. //0 if mip levels will be generated by the video card. //variable amount if we are generating them ourselves. if(!pDesc->bGenMipMap) nMipLevels=1; else if(pDesc->bGenMipMap && pDesc->bUseHWMipMap) nMipLevels=1; else if(pDesc->bGenMipMap && !pDesc->bUseHWMipMap) { nMipLevels=0; i=LG_Min(pDesc->nWidth, pDesc->nHeight); do { nMipLevels++; }while((i/=2)>=1); } //If we are automatically generating mip maps //we specify so. nUsage=0; if(pDesc->bGenMipMap && pDesc->bUseHWMipMap && (pDesc->nPool!=D3DPOOL_DEFAULT)) { nUsage|=D3DUSAGE_AUTOGENMIPMAP; } nResult=lpDevice->lpVtbl->CreateTexture( lpDevice, pDesc->nWidth, pDesc->nHeight, nMipLevels, nUsage, pDesc->nD3DFormat, pDesc->nPool==D3DPOOL_DEFAULT?D3DPOOL_SYSTEMMEM:pDesc->nPool, &lpTexTemp, LG_NULL); if(LG_FAILED(nResult)) { *lppTex=LG_NULL; Err_Printf("Tex_Load Error: Could not open \"%s\".", pDesc->szFilename); Err_PrintDX(" IDirect3DDevice9", nResult); return LG_FALSE; } //Now for each mip level we will lock and copy the source image. nMipLevels=lpTexTemp->lpVtbl->GetLevelCount(lpTexTemp); for(i=0; i<nMipLevels; i++) { D3DLOCKED_RECT rc; D3DSURFACE_DESC sdesc; IMG_DEST_RECT rcDest; memset(&rc, 0, sizeof(rc)); memset(&sdesc, 0, sizeof(sdesc)); nResult=lpTexTemp->lpVtbl->LockRect(lpTexTemp, i, &rc, LG_NULL, 0); if(LG_FAILED(nResult)) { Err_Printf("Tex_Load Error: Could not open \"%s\".", pDesc->szFilename); Err_PrintDX(" IDirect3DTexture9::LockRect", nResult); lpTexTemp->lpVtbl->Release(lpTexTemp); return LG_FALSE; } nResult=IDirect3DTexture9_GetLevelDesc(lpTexTemp, i, &sdesc); if(LG_FAILED(nResult)) { Err_Printf("Tex_Load Error: Could not open \"%s\".", pDesc->szFilename); Err_PrintDX(" IDirect3DTexture9::GetLevelDesc", nResult); lpTexTemp->lpVtbl->UnlockRect(lpTexTemp, i); lpTexTemp->lpVtbl->Release(lpTexTemp); return LG_FALSE; } rcDest.pImage=rc.pBits; rcDest.nOrient=IMGORIENT_TOPLEFT; rcDest.nFormat=pDesc->nFormat; rcDest.nWidth=sdesc.Width; rcDest.nHeight=sdesc.Height; rcDest.nPitch=rc.Pitch; rcDest.rcCopy.left=rcDest.rcCopy.top=0; rcDest.rcCopy.right=sdesc.Width; rcDest.rcCopy.bottom=sdesc.Height; IMG_CopyBits( hImage, &rcDest, pDesc->nMipFilter>FILTER_POINT?IMGFILTER_LINEAR:IMGFILTER_POINT, LG_NULL, 0xFF); lpTexTemp->lpVtbl->UnlockRect(lpTexTemp, i); } if(pDesc->nPool==D3DPOOL_DEFAULT) { lg_dword nFlags=0; if(pDesc->nMipFilter>FILTER_POINT) nFlags|=SYSTOVID_LINEARMIPFILTER; if(pDesc->bGenMipMap && pDesc->bUseHWMipMap) { nFlags|=SYSTOVID_AUTOGENMIPMAP; } if(!Tex_SysToVid(lpDevice, &lpTexTemp, nFlags)) { Err_Printf("Tex_Load Error: Could not open \"%s\".", pDesc->szFilename); Err_Printf(" Could not move texture to video memory."); L_safe_release(lpTexTemp); return LG_FALSE; } } *lppTex=lpTexTemp; return LG_TRUE; } lg_bool Tex_LoadIMG2_Memory( IDirect3DDevice9* lpDevice, const lg_byte* pBuffer, lg_dword nBufferSize, D3DPOOL Pool, lg_dword Flags, lg_dword nSizeLimit, IDirect3DTexture9** lppTex) { TEX_IMG_COPY_DESC2 copydesc; HIMG hImage=LG_NULL; LF_FILE3 fin=LG_NULL; IMG_DESC imgdesc; D3DCAPS9 Caps; lg_void* buffer=LG_NULL; lg_bool bResult=LG_FALSE; if(!lpDevice || !pBuffer || !nBufferSize) { *lppTex=LG_NULL; return LG_FALSE; } hImage=IMG_OpenMemory((lg_pvoid)pBuffer, nBufferSize); if(!hImage) { Err_Printf("Tex_Load Error: Could not open texture at 0x%08X.", pBuffer); Err_Printf(" Could not acquire image from file."); *lppTex=LG_NULL; return LG_FALSE; } /* Next we need to get a description of the tga file, so that we can create an appropriate texture. Note that we could set the final texture format to whatever we want, but we'll try to match to original format.*/ memset(&imgdesc, 0, sizeof(imgdesc)); memset(&copydesc, 0, sizeof(copydesc)); IMG_GetDesc(hImage, &imgdesc); copydesc.nWidth=imgdesc.Width; copydesc.nHeight=imgdesc.Height; copydesc.nPool=Pool; //copydesc.dwSizeLimit=dwSizeLimit; /* If there is a size limit, we need to limit the size of the texture. */ if(nSizeLimit) { copydesc.nWidth=LG_Min(copydesc.nWidth, nSizeLimit); copydesc.nHeight=LG_Min(copydesc.nHeight, nSizeLimit); } memset(&Caps, 0, sizeof(Caps)); lpDevice->lpVtbl->GetDeviceCaps(lpDevice, &Caps); /* We need to make sure the texture is not larger than the device limits. */ copydesc.nWidth=LG_Min(copydesc.nWidth, Caps.MaxTextureWidth); copydesc.nHeight=LG_Min(copydesc.nHeight, Caps.MaxTextureHeight); /* If required (which it usually is) we need to make sure the texture is a power of 2. */ if(L_CHECK_FLAG(Caps.TextureCaps, D3DPTEXTURECAPS_POW2)) { copydesc.nWidth=ML_NextPow2(copydesc.nWidth); copydesc.nHeight=ML_NextPow2(copydesc.nHeight); } /* If required we need to make sure the texture is square.*/ if(L_CHECK_FLAG(Caps.TextureCaps, D3DPTEXTURECAPS_SQUAREONLY)) { copydesc.nWidth=copydesc.nHeight=LG_Max(copydesc.nWidth, copydesc.nHeight); } if(L_CHECK_FLAG(Flags, TEXLOAD_LINEARMIPFILTER)) copydesc.nMipFilter=FILTER_LINEAR; else copydesc.nMipFilter=FILTER_POINT; switch(imgdesc.BitsPerPixel) { default: case 16: copydesc.nD3DFormat=D3DFMT_R5G6B5; copydesc.nFormat=IMGFMT_R5G6B5; break; case 8: case 24: copydesc.nD3DFormat=D3DFMT_X8R8G8B8; copydesc.nFormat=IMGFMT_A8R8G8B8; break; case 32: copydesc.nD3DFormat=D3DFMT_A8R8G8B8; copydesc.nFormat=IMGFMT_A8R8G8B8; break; } if(L_CHECK_FLAG(Flags, TEXLOAD_FORCE16BIT))//CVar_GetValue(LG_GetGame()->m_cvars, "v_Force16BitTextures", LG_NULL)) { if(imgdesc.BitsPerPixel==32 && L_CHECK_FLAG(Flags, TEXLOAD_16BITALPHA))//(lg_bool)CVar_GetValue(LG_GetGame()->m_cvars, "v_16BitTextureAlpha", LG_NULL)) { copydesc.nD3DFormat=D3DFMT_A1R5G5B5; copydesc.nFormat=IMGFMT_X1R5G5B5; } else { copydesc.nD3DFormat=D3DFMT_R5G6B5; copydesc.nFormat=IMGFMT_R5G6B5; } } copydesc.bGenMipMap=L_CHECK_FLAG(Flags, TEXLOAD_GENMIPMAP);//bGenMipMap; copydesc.bUseHWMipMap=Tex_CanAutoGenMipMap(lpDevice, copydesc.nD3DFormat) && L_CHECK_FLAG(Flags, TEXLOAD_HWMIPMAP); //LG_strncpy(copydesc.szFilename, LG_NULL, LF_MAX_PATH); //copydesc.szFilename[0]=0; bResult=Tex_CopyIMGToTex(lpDevice, hImage, lppTex, &copydesc); IMG_Delete(hImage); hImage=LG_NULL; return bResult; } <file_sep>/games/Legacy-Engine/Scrapped/old/lm_mesh_d3d_basic.h #ifndef __LM_MESH_D3D_BASIC_H__ #define __LM_MESH_D3D_BASIC_H__ //This is an extremely basic D3D mesh for testing //purposes, it is designed to be compatible with //the Legacy Engine and not LMEdit. #include <d3d9.h> #include "lm_mesh_anim.h" #include "lg_tmgr.h" class CLMeshD3DBasic: public CLMeshAnim { private: tm_tex* m_pTex; MeshVertex* m_pTransfVB; public: virtual lg_bool Load(LMPath szFile); virtual lg_bool Save(LMPath szFile); virtual lg_void Unload(); protected: virtual MeshVertex* LockTransfVB(); virtual lg_void UnlockTransfVB(); public: CLMeshD3DBasic(): CLMeshAnim(), m_pTex(LG_NULL), m_pTransfVB(LG_NULL){}; lg_void Render(); static IDirect3DDevice9* s_pDevice; private: //The read function: static lg_uint __cdecl ReadFn(lg_void* file, lg_void* buffer, lg_uint size); }; #endif __LM_MESH_D3D_BASIC_H__<file_sep>/samples/Project5/src/bcol/BPrQueue.java /* <NAME> CS 2420-002 BPrQueue Generic Priority Queue. Objects must use comparable method. */ package bcol; public class BPrQueue <T extends Comparable> extends BQueue<T>{ /* PRE: obj!=null POST: obj will be inserted in the queue according to priority. */ public void enqueue(T obj) { m_listQ.insertInOrder(m_listQ, obj); } } <file_sep>/games/Legacy-Engine/Source/engine/lv_con.h /* lv_con.h - the graphical console. */ #ifndef __LV_CON_H__ #define __LV_CON_H__ #include "lv_img2d.h" #include "lv_font.h" #define LK_PAGEUP 1 #define LK_PAGEDOWN 2 #define LK_END 3 #define CON_KEY1 ('~') #define CON_KEY2 ('`') #define CON_KEYDX (DIK_GRAVE) class CLVCon { private: //LV2DIMAGE* m_pBackground; /* The background image. */ CLImg2D m_Background; CLFont* m_lpFont; //void* m_pFont; /* The font. */ lg_dword m_dwViewHeight; /* The view height. */ lg_dword m_dwFontHeight; //HLCONSOLE m_hConsole; /* Pointer to the console. */ IDirect3DDevice9* m_pDevice; /* The device that created teh console. */ lg_bool m_bActive; /* Whether or not the console is receiving input. */ lg_bool m_bDeactivating;/* If the console is in the process of deactivating (scrolling up).*/ float m_fPosition; /* The position of the console. */ long m_nScrollPos; /* Where the console is rendering output. */ lg_dword m_dwLastUpdate; /* The last time the console position was updated. */ lg_bool m_bCaretOn; lg_dword m_dwLastCaretChange; lg_bool m_bFullMode; lg_char m_szMessage[128]; lg_char m_szMessage2[128]; public: CLVCon(); CLVCon(IDirect3DDevice9* pDevice); ~CLVCon(); lg_bool Create( IDirect3DDevice9* pDevice); void Delete(); lg_bool Render(); lg_bool Validate(); lg_bool Invalidate(); lg_bool OnCharA(char c); void SetMessage(lg_dword nSlot, lg_char* szMessage); lg_bool IsActive(); void Toggle(); private: lg_bool UpdatePos(); static void FontStringToSize(lg_dword* pHeight, lg_dword* pWidth, lg_pstr szString); }; #endif __LV_CON_H__<file_sep>/games/Legacy-Engine/Source/common/lg_types.h #ifndef __LG_TYPES_H__ #define __LG_TYPES_H__ //Universal definitions #define LG_CACHE_ALIGN __declspec(align(4)) /*************************** Legacy Engine types. ****************************/ typedef signed int lg_int, *lg_pint; typedef unsigned int lg_uint, *lg_puint; typedef char lg_char, *lg_pchar; typedef unsigned char lg_byte, *lg_pbyte; typedef signed char lg_sbyte, *lg_psbyte; typedef signed char lg_schar, *lg_pschar; typedef char *lg_str, *lg_pstr, *lg_lpstr; typedef const char *lg_cstr, *lg_pcstr, *lg_lpcstr; typedef unsigned short lg_word, *lg_pword, lg_ushort, *lg_pushort; typedef signed short lg_short, *lg_pshort; typedef unsigned long lg_dword, *lg_pdword, lg_ulong, *lg_pulong; typedef signed long lg_long, *lg_plong; typedef float lg_float, *lg_pfloat; typedef double lg_double, *lg_pdouble; typedef long double lg_ldouble, *lg_lpdouble; typedef void lg_void, *lg_pvoid; #ifndef __cplusplus typedef unsigned short wchar_t; #endif __cplusplus typedef wchar_t lg_wchar_t, lg_wchar; typedef lg_wchar_t *lg_wstr, *lg_pwstr, *lg_lpwstr; typedef const lg_wchar_t *lg_cwstr, *lg_pcwstr, *lg_lpcwstr; typedef unsigned int lg_size_t; #ifdef UNICODE typedef lg_wchar_t lg_tchar; #else !UNICODE typedef lg_char lg_tchar; #endif UNICODE #define LG_MAX_PATH 255 typedef lg_char LG_CACHE_ALIGN lg_pathA[LG_MAX_PATH+1]; typedef lg_wchar LG_CACHE_ALIGN lg_pathW[LG_MAX_PATH+1]; #define LG_MAX_STRING 127 typedef lg_char LG_CACHE_ALIGN lg_stringA[LG_MAX_STRING+1]; typedef lg_wchar LG_CACHE_ALIGN lg_stringW[LG_MAX_STRING+1]; #ifdef UNICODE #define lg_path lg_pathW #define lg_string lg_stringW #else !UNICODE #define lg_path lg_pathA #define lg_string lg_stringA #endif UNICODE typedef struct _lg_large_integer{ lg_dword dwLowPart; lg_long dwHighPart; }lg_large_integer, *lg_plarge_integer, *lg_lplarge_integer; typedef struct _lg_rect{ lg_long left; lg_long top; lg_long right; lg_long bottom; }lg_rect, *lg_prect; typedef LG_CACHE_ALIGN int lg_bool; #define LG_TRUE (1) #define LG_FALSE (0) typedef long lg_result; #define LG_SUCCEEDED(Status) ((lg_result)(Status)>=0) #define LG_FAILED(Status) ((lg_result)(Status)<0) /****************************** Legacy Engine definitions. *******************************/ #ifdef UNICODE #define LG_TEXT(t) (L##t) #else !UNICODE #define LG_TEXT(t) (t) #endif UNICODE #ifdef __cplusplus #define LG_NULL (0) #else /* __cplusplus */ #define LG_NULL ((void*)0) #endif __cplusplus #endif __LG_TYPES_H__ <file_sep>/tools/fs_sys2/fs_err.c #include <string.h> #include <stdarg.h> #include <stdlib.h> #include <stdio.h> #include "fs_sys2.h" FS_ERR_LEVEL g_nErrLevel=ERR_LEVEL_NOTICE; void (__cdecl*g_pfnErrPrint)(fs_cstr16 szFormat)=FS_NULL; void FS_SetErrLevel(FS_ERR_LEVEL nLevel) { g_nErrLevel=nLevel; } void FS_SYS2_EXPORTS FS_SetErrPrintFn(void (__cdecl*pfn)(fs_cstr16 szFormat)) { g_pfnErrPrint=pfn; } #define FS_ERR_MAX_OUTPUT 511 void FS_ErrPrintW(fs_cstr16 szFormat, FS_ERR_LEVEL nErrLevel, ...) { fs_char16 szOutput[FS_ERR_MAX_OUTPUT+1]; va_list arglist=FS_NULL; //Don't print the message if the current error level //is greater than the error level of the message. if((nErrLevel<g_nErrLevel) || !g_pfnErrPrint) return; va_start(arglist, nErrLevel); //_vsnwprintf(szOutput, 1022, szFormat, arglist); _vsnwprintf_s(szOutput, FS_ERR_MAX_OUTPUT, FS_ERR_MAX_OUTPUT, szFormat, arglist); va_end(arglist); szOutput[wcslen(szOutput)]=0; g_pfnErrPrint(szOutput); } void FS_ErrPrintA(fs_cstr8 szFormat, FS_ERR_LEVEL nErrLevel, ...) { fs_char8 szOutput[FS_ERR_MAX_OUTPUT+1]; fs_char16 szOutputW[FS_ERR_MAX_OUTPUT+1]; va_list arglist=FS_NULL; //Don't print the message if the current error level //is greater than the error level of the message. if((nErrLevel<g_nErrLevel) || !g_pfnErrPrint) return; va_start(arglist, nErrLevel); _vsnprintf_s(szOutput, FS_ERR_MAX_OUTPUT, FS_ERR_MAX_OUTPUT, szFormat, arglist); va_end(arglist); szOutput[strlen(szOutput)]=0; mbstowcs(szOutputW, szOutput, FS_ERR_MAX_OUTPUT); g_pfnErrPrint(szOutputW); } <file_sep>/tools/GFX/readme.txt GFX Libraries ============= These are 2D drawing libraries for DirectX 7 and DirectX 8. They are not very interesting at this point. The DirectX 7 version is used to power ScrollGIN in one form or other (though now ScrollGIN also has a DirectX 11 renderer). (c) 2003 <NAME> <file_sep>/games/Legacy-Engine/Source/engine/wnd_sys/wnd_manager.cpp #include "wnd_manager.h" #include "lg_err.h" namespace wnd_sys{ CManager::CManager() { } CManager::~CManager() { } void CManager::Init() { m_TestWnd.Create(20, 20, 100, 100); m_TestWnd2.Create(50, 100, 150, 100); } void CManager::Shutdown() { } void CManager::Render() { m_TestWnd.Render(); m_TestWnd2.Render(); } } //namespace wnd_sys<file_sep>/games/Legacy-Engine/Source/ws_sys/ws_file.cpp #include "ws_file.h" #include "lg_err.h" #include <string.h> #include <stdio.h> #include <windows.h> CWSFile::CWSFile(): //Map Header. m_nVersion(0), m_nFileFlags(0), m_nNameCount(0), m_nNameOffset(0), m_nObjectCount(0), m_nObjectOffset(0), m_nMatCount(0), m_nLMCount(0), m_nLMMaxSize(0), m_nBrushCount(0), m_nFaceCount(0), m_nVisibleFaceCount(0), m_nVertexCount(0), m_nVisGroupCount(0), m_nGeoVertCount(0), m_szNames(0), m_pVertexes(0), m_pMaterials(0), m_pLMs(0), m_pVisGrps(0), m_pRasterFaces(0), m_pGeoBlocks(0), m_pGeoFaces(0), m_pLights(0) { } CWSFile::~CWSFile() { DeallocateMemory(); } lg_bool CWSFile::Load(lg_byte* pData, lg_dword nSize) { Err_Printf("Loading 3D World Studio file..."); m_File.Open(pData, nSize); try { //First check the map header to make sure it is a valid map... if((m_File.Read(&m_nVersion, 2)!=2) || (m_nVersion!=14) ) { throw("WSToLW ERROR: File is not a valid 3D World Studio Map."); } //Now read the rest of the header... m_File.Read(&m_nFileFlags, 1); m_File.Read(&m_nNameCount, 4); m_File.Read(&m_nNameOffset, 4); m_File.Read(&m_nObjectCount, 4); m_File.Read(&m_nObjectOffset, 4); Err_Printf("Flags: 0x%02X", m_nFileFlags); Err_Printf("%d names at %d", m_nNameCount, m_nNameOffset); Err_Printf("%d objects at %d", m_nObjectCount, m_nObjectOffset); GetNames(); GetCounts(); Err_Printf("Materials: %d", m_nMatCount); Err_Printf("Light Maps: %d", m_nLMCount); Err_Printf("Biggest LM: %d", m_nLMMaxSize); Err_Printf("Brushes: %d", m_nBrushCount); Err_Printf("Faces: %d", m_nFaceCount); Err_Printf("Visible Faces: %d", m_nVisibleFaceCount); Err_Printf("Vertices: %d", m_nVertexCount); Err_Printf("Polys: %d", m_nVertexCount/3); Err_Printf("Vis Groups: %d", m_nVisGroupCount); Err_Printf("Lights: %d", m_nLightCount); Err_Printf("Geo Verts: %d", m_nGeoVertCount); Err_Printf("Geo tris: %d", m_nGeoTriCount); AllocateMemory(); GetObjects(); ModifyRefsAndVertexOrder(); SortAndCompactRasterObjects(); SortAndCompactEntitys(); SortAndCompactGeoObjects(); throw("OK"); } catch(lg_char* szMessage) { Err_Printf("3D World Studio load result: %s", szMessage); if(strcmp(szMessage, "OK")==0) return LG_TRUE; } return LG_FALSE; } void CWSFile::ModifyRefsAndVertexOrder() { //Reverse the vertex orders for(lg_dword i=0; i<m_nVertexCount; i+=3) { WS_VERTEX vt=m_pVertexes[i]; m_pVertexes[i]=m_pVertexes[i+2]; m_pVertexes[i+2]=vt; } //Reverse geo vertex order for(lg_dword i=0; i<m_nGeoTriCount; i++) { ml_vec3 v3Temp; v3Temp=m_pGeoTris[i].v3Vert[0]; m_pGeoTris[i].v3Vert[0]=m_pGeoTris[i].v3Vert[2]; m_pGeoTris[i].v3Vert[2]=v3Temp; } //Change the geo block vis group references. for(lg_dword i=0; i<m_nBrushCount; i++) { for(lg_dword j=0; j<m_nVisGroupCount; j++) { if(m_pGeoBlocks[i].nVisGrp==m_pVisGrps[j].nRef) { m_pGeoBlocks[i].nVisGrp=j; break; } } } //Change references for material, lightmap, and visgroups. for(lg_dword i=0; i<m_nFaceCount; i++) { for(lg_dword j=0; j<m_nMatCount; j++) { if(m_pRasterFaces[i].nMatRef==m_pMaterials[j].nRef) { m_pRasterFaces[i].nMatRef=j; break; } } for(lg_dword j=0; j<m_nLMCount; j++) { if(m_pRasterFaces[i].nLMRef==m_pLMs[j].nRef) { m_pRasterFaces[i].nLMRef=j; break; } } for(lg_dword j=0; j<m_nVisGroupCount; j++) { if(m_pRasterFaces[i].nVisGrp==m_pVisGrps[j].nRef) { m_pRasterFaces[i].nVisGrp=j; break; } } } //Change the light references for(lg_dword i=0; i<m_nLightCount; i++) { for(lg_dword j=0; j<m_nVisGroupCount; j++) { if(m_pLights[i].nVisGrp==m_pVisGrps[j].nRef) { m_pLights[i].nVisGrp=j; break; } } } //Change the sign of the plane equation d value (nevermind) for(lg_dword i=0; i<m_nFaceCount; i++) { //m_pGeoFaces[i].plnEq.d=-m_pGeoFaces[i].plnEq.d; } } void CWSFile::SortAndCompactGeoObjects() { lg_dword nBlock=0, nVisGrp=0; WS_GEO_BLOCK* pTempBlock=new WS_GEO_BLOCK[m_nBrushCount]; if(!pTempBlock) throw("ERROR: Out of memory."); memcpy(pTempBlock, m_pGeoBlocks, sizeof(WS_GEO_BLOCK)*m_nBrushCount); for(nVisGrp=0; nVisGrp<m_nVisGroupCount; nVisGrp++) { m_pVisGrps[nVisGrp].nFirstGeoBlock=0; m_pVisGrps[nVisGrp].nGeoBlockCount=0; } nVisGrp=0; do { for(lg_dword i=0; i<m_nBrushCount; i++) { if(nBlock>=m_nBrushCount) break; if(pTempBlock[i].nVisGrp!=nVisGrp) continue; //If all the criteria are met add the block to the list. m_pGeoBlocks[nBlock]=pTempBlock[i]; nBlock++; m_pVisGrps[nVisGrp].nGeoBlockCount++; } nVisGrp++; if(nVisGrp>=m_nVisGroupCount) break; m_pVisGrps[nVisGrp].nFirstGeoBlock=nBlock; m_pVisGrps[nVisGrp].nGeoBlockCount=0; }while(nBlock<m_nBrushCount); L_safe_delete_array(pTempBlock); //Calculate region bounds. for(nVisGrp=0; nVisGrp<m_nVisGroupCount; nVisGrp++) { ML_AABB aabbTemp; aabbTemp.v3Min=m_pVertexes[m_pVisGrps[nVisGrp].nFirstVertex].v3Pos; aabbTemp.v3Max=aabbTemp.v3Min; if(nVisGrp==0) m_aabbWorld=aabbTemp; for(lg_dword i=1; i<m_pVisGrps[nVisGrp].nVertexCount; i++) { ML_AABBAddPoint(&aabbTemp, &aabbTemp, &m_pVertexes[i+m_pVisGrps[nVisGrp].nFirstVertex].v3Pos); ML_AABBAddPoint(&m_aabbWorld, &m_aabbWorld, &m_pVertexes[i+m_pVisGrps[nVisGrp].nFirstVertex].v3Pos); } m_pVisGrps[nVisGrp].aabbVisBounds=aabbTemp; } #if 0 for(lg_dword i=0; i<m_nVisGroupCount; i++) { lg_dword nStart=m_pVisGrps[i].nFirstGeoBlock; lg_dword nCount=m_pVisGrps[i].nGeoBlockCount; lg_dword nEnd=nStart+nCount; Err_Printf("Vis Group %d: %s S: %d C: %d", i, m_pVisGrps[i].szName, nStart, nCount); for(lg_dword i=nStart; i<nEnd; i++) { lg_dword nStart=m_pGeoBlocks[i].nFirstGeoFace; lg_dword nCount=m_pGeoBlocks[i].nGeoFaceCount; lg_dword nEnd=nStart+nCount; Err_Printf(" Geo Block: %d: F: %d C: %d VisGrp: %d", i, nStart, nCount, m_pGeoBlocks[i].nVisGrp); for(lg_dword i=nStart; i<nEnd; i++) { Err_Printf(" Geo Face %d: (%f, %f, %f, %f)", i, m_pGeoFaces[i].v4PlaneEq.x, m_pGeoFaces[i].v4PlaneEq.y, m_pGeoFaces[i].v4PlaneEq.z, m_pGeoFaces[i].v4PlaneEq.w); } } } #endif } void CWSFile::SortAndCompactEntitys() { lg_dword nVisGrp=0, nLight=0; //Sort the lights... WS_LIGHT* pTempLights=new WS_LIGHT[m_nLightCount]; if(!pTempLights) throw("ERROR: Out of memory."); memcpy(pTempLights, m_pLights, sizeof(WS_LIGHT)*m_nLightCount); for(nVisGrp=0; nVisGrp<m_nVisGroupCount; nVisGrp++) { m_pVisGrps[nVisGrp].nFirstLight=0; m_pVisGrps[nVisGrp].nLightCount=0; } nVisGrp=0; nLight=0; do { for(lg_dword i=0; i<m_nLightCount; i++) { if(pTempLights[i].nVisGrp!=nVisGrp) continue; if(nLight>=m_nLightCount) break; m_pLights[nLight++]=pTempLights[i]; m_pVisGrps[nVisGrp].nLightCount++; } nVisGrp++; if(nVisGrp>=m_nVisGroupCount) break; m_pVisGrps[nVisGrp].nFirstLight=nLight; m_pVisGrps[nVisGrp].nLightCount=0; }while(nLight<m_nLightCount); #if 0 for(lg_dword i=0; i<m_nLightCount; i++) { WS_LIGHT lt=m_pLights[i]; Err_Printf("===LIGHT==="); Err_Printf("Position: (%f, %f, %f)", lt.v3Pos.x, lt.v3Pos.y, lt.v3Pos.z); Err_Printf("Color: 0x%08X", lt.Color); Err_Printf("Intensity: %f", lt.fIntensity); Err_Printf("VisGrp: %u", lt.nVisGrp); } #endif L_safe_delete_array(pTempLights); } void CWSFile::SortAndCompactRasterObjects() { lg_dword nFace=0, nVisGrp=0, nMaterial=0, nLightmap=0; WS_RASTER_FACE* pTempFaces=new WS_RASTER_FACE[m_nFaceCount]; if(!pTempFaces) throw("ERROR: Out of memory."); //Store all the faces in the temporary array... memcpy(pTempFaces, m_pRasterFaces, sizeof(WS_RASTER_FACE)*m_nFaceCount); //Sort the data into the original array.. for(nVisGrp=0; nVisGrp<m_nVisGroupCount; nVisGrp++) { m_pVisGrps[nVisGrp].nFirstFace=0; m_pVisGrps[nVisGrp].nFaceCount=0; m_pVisGrps[nVisGrp].nVisibleFaceCount=0; m_pVisGrps[nVisGrp].nFirstVertex=0; m_pVisGrps[nVisGrp].nVertexCount=0; m_pVisGrps[nVisGrp].nFirstLight=0; m_pVisGrps[nVisGrp].nLightCount=0; } nVisGrp=0; do { for(lg_dword i=0; i<m_nFaceCount; i++) { if(nFace>=m_nVisibleFaceCount) break; if(!pTempFaces[i].bVisible) continue; if(pTempFaces[i].nVisGrp!=nVisGrp) continue; if(pTempFaces[i].nMatRef!=nMaterial) continue; if(pTempFaces[i].nLMRef!=nLightmap) continue; //If all the criteria are met add the face to the list. m_pRasterFaces[nFace]=pTempFaces[i]; nFace++; m_pVisGrps[nVisGrp].nFaceCount++; m_pVisGrps[nVisGrp].nVisibleFaceCount++; } if(nLightmap==0xFFFFFFFF) { nLightmap=0; nMaterial++; if(nMaterial>=m_nMatCount) { nMaterial=0; nVisGrp++; if(nVisGrp>=m_nVisGroupCount) break; m_pVisGrps[nVisGrp].nFirstFace=nFace; m_pVisGrps[nVisGrp].nFaceCount=0; m_pVisGrps[nVisGrp].nVisibleFaceCount=0; } } else nLightmap++; if((nLightmap>=m_nLMCount) && (nLightmap!=0xFFFFFFFF)) { nLightmap=0xFFFFFFFF; } }while(nFace<m_nVisibleFaceCount); for(lg_dword i=nFace; i<m_nFaceCount; i++) { memset(&m_pRasterFaces[i], 0, sizeof(WS_RASTER_FACE)); } //Now we will resort all the vertexes... //The vertexes are being sorted in the order of the faces, //that way faces that have the same texture and lightmap //can be catenated. WS_VERTEX* pTempVerts=new WS_VERTEX[m_nVertexCount]; if(!pTempVerts) { L_safe_delete_array(pTempVerts); throw("ERROR: Out of memory."); } memcpy(pTempVerts, m_pVertexes, sizeof(WS_VERTEX)*m_nVertexCount); for(lg_dword nFace=0, nVertex=0; nFace<m_nVisibleFaceCount; nFace++) { //Simply copy the faces vertexes to the destination buffer, //then set the new first vertex, and advance to the next vertex //to be written to. memcpy( &m_pVertexes[nVertex], &pTempVerts[m_pRasterFaces[nFace].nFirst], sizeof(WS_VERTEX)*m_pRasterFaces[nFace].nNumTriangles*3); m_pRasterFaces[nFace].nFirst=nVertex; nVertex+=m_pRasterFaces[nFace].nNumTriangles*3; } L_safe_delete_array(pTempVerts); //We'll now reduce the number of faces into segments (each segment will //be composed of triangles that have the same texture and lightmap). for(lg_dword nVisGrp=0; nVisGrp<m_nVisGroupCount; nVisGrp++) { lg_dword nLastMat=0, nLastLM=0; WS_RASTER_FACE* pCurFace=LG_NULL; lg_dword nStart=m_pVisGrps[nVisGrp].nFirstFace; lg_dword nEnd=m_pVisGrps[nVisGrp].nFirstFace+m_pVisGrps[nVisGrp].nFaceCount; for(lg_dword i=nStart; i<nEnd; i++) { if(!pCurFace) { pCurFace=&m_pRasterFaces[i]; nLastMat=pCurFace->nMatRef; nLastLM=pCurFace->nLMRef; continue; } if((nLastMat==m_pRasterFaces[i].nMatRef) && (nLastLM==m_pRasterFaces[i].nLMRef)) { pCurFace->nNumTriangles+=m_pRasterFaces[i].nNumTriangles; m_pRasterFaces[i].nNumTriangles=0; } else { pCurFace=&m_pRasterFaces[i]; nLastMat=pCurFace->nMatRef; nLastLM=pCurFace->nLMRef; } } } //We'll now eliminate all the empty faces... memcpy(pTempFaces, m_pRasterFaces, sizeof(WS_RASTER_FACE)*m_nVisibleFaceCount); nFace=0; for(lg_dword nVisGrp=0; nVisGrp<m_nVisGroupCount; nVisGrp++) { lg_dword nStart=m_pVisGrps[nVisGrp].nFirstFace; lg_dword nEnd=m_pVisGrps[nVisGrp].nFirstFace+m_pVisGrps[nVisGrp].nFaceCount; m_pVisGrps[nVisGrp].nFirstFace=nFace; m_pVisGrps[nVisGrp].nFaceCount=0; for(lg_dword i=nStart; i<nEnd; i++) { if(pTempFaces[i].nNumTriangles>0) { m_pRasterFaces[nFace]=pTempFaces[i]; m_pVisGrps[nVisGrp].nFaceCount++; nFace++; } } } Err_Printf("NOTICE: %d faces reduced to %d segments %0.2f%%.", m_nVisibleFaceCount, nFace, (float)nFace/(float)m_nVisibleFaceCount*100.0f); m_nVisibleFaceCount=nFace; L_safe_delete_array(pTempFaces); //We'll now setup some more information about the vis groups for(lg_dword i=0; i<m_nVisGroupCount; i++) { m_pVisGrps[i].nFirstVertex=m_pRasterFaces[m_pVisGrps[i].nFirstFace].nFirst; lg_dword nCount=0; for(lg_dword j=0; j<m_pVisGrps[i].nFaceCount; j++) { nCount+=m_pRasterFaces[m_pVisGrps[i].nFirstFace+j].nNumTriangles*3; } m_pVisGrps[i].nVertexCount=nCount; } #if 0 //For testing purposes print out the results for(lg_dword i=0; i<m_nVisGroupCount; i++) { Err_Printf( "Vis Group %d: %s (%d) FirstFace=%d FaceCount=%d VisibleFaces=%d First Vertex: %d Vertex Count: %d", i, m_pVisGrps[i].szName, m_pVisGrps[i].nRef, m_pVisGrps[i].nFirstFace, m_pVisGrps[i].nFaceCount, m_pVisGrps[i].nVisibleFaceCount, m_pVisGrps[i].nFirstVertex, m_pVisGrps[i].nVertexCount); for(lg_dword j=0; j<m_pVisGrps[i].nFaceCount; j++) { lg_dword offset=j+m_pVisGrps[i].nFirstFace; Err_Printf(" Face %d: S: %d: C: %d: Mat: %d: LM: %d: Room: %d\n", offset, m_pRasterFaces[offset].nFirst, m_pRasterFaces[offset].nNumTriangles, m_pRasterFaces[offset].nMatRef, m_pRasterFaces[offset].nLMRef, m_pRasterFaces[offset].nVisGrp); } } #endif } void CWSFile::ScaleMap(lg_float fScale) { ML_MAT matTrans; ML_MatScaling(&matTrans, fScale, fScale, fScale); ML_Vec3TransformCoord( &m_aabbWorld.v3Min, &m_aabbWorld.v3Min, &matTrans); ML_Vec3TransformCoord( &m_aabbWorld.v3Max, &m_aabbWorld.v3Max, &matTrans); ML_Vec3TransformCoordArray( (ML_VEC3*)m_pVertexes, sizeof(WS_VERTEX), (ML_VEC3*)m_pVertexes, sizeof(WS_VERTEX), &matTrans, m_nVertexCount); ML_Vec3TransformCoordArray( (ML_VEC3*)&m_pGeoBlocks[0].aabbBlock.v3Max, sizeof(WS_GEO_BLOCK), (ML_VEC3*)&m_pGeoBlocks[0].aabbBlock.v3Max, sizeof(WS_GEO_BLOCK), &matTrans, m_nBrushCount); ML_Vec3TransformCoordArray( (ML_VEC3*)&m_pGeoBlocks[0].aabbBlock.v3Min, sizeof(WS_GEO_BLOCK), (ML_VEC3*)&m_pGeoBlocks[0].aabbBlock.v3Min, sizeof(WS_GEO_BLOCK), &matTrans, m_nBrushCount); ML_Vec3TransformCoordArray( (ML_VEC3*)&m_pVisGrps[0].aabbVisBounds.v3Min, sizeof(WS_VISGROUP), (ML_VEC3*)&m_pVisGrps[0].aabbVisBounds.v3Min, sizeof(WS_VISGROUP), &matTrans, m_nVisGroupCount); ML_Vec3TransformCoordArray( (ML_VEC3*)&m_pVisGrps[0].aabbVisBounds.v3Max, sizeof(WS_VISGROUP), (ML_VEC3*)&m_pVisGrps[0].aabbVisBounds.v3Max, sizeof(WS_VISGROUP), &matTrans, m_nVisGroupCount); ML_Vec3TransformCoordArray( (ML_VEC3*)&m_pLights[0].v3Pos, sizeof(WS_LIGHT), (ML_VEC3*)&m_pLights[0].v3Pos, sizeof(WS_LIGHT), &matTrans, m_nLightCount); ML_Vec3TransformCoordArray( &m_pGeoVerts[0].v3Pos, sizeof(WS_GEO_VERT), &m_pGeoVerts[0].v3Pos, sizeof(WS_GEO_VERT), &matTrans, m_nGeoVertCount); ML_Vec3TransformCoordArray( &m_pGeoTris[0].v3Vert[0], sizeof(ML_VEC3), &m_pGeoTris[0].v3Vert[0], sizeof(ML_VEC3), &matTrans, m_nGeoTriCount*3); for(lg_dword i=0; i<m_nFaceCount; i++) { m_pGeoFaces[i].plnEq.d*=fScale; } } WS_COLOR CWSFile::StringToColor(lg_str szColor) { WS_COLOR c; c.r=atoi(szColor); for(lg_dword i=0; i<strlen(szColor); i++) { if(szColor[i]==' ') { szColor=&szColor[i+1]; break; } } c.g=atoi(szColor); for(lg_dword i=0; i<strlen(szColor); i++) { if(szColor[i]==' ') { szColor=&szColor[i+1]; break; } } c.b=atoi(szColor); return c; } lg_bool CWSFile::GetLight(WS_LIGHT* lt) { memset(lt, 0, sizeof(WS_LIGHT)); lg_bool bIsLight=LG_FALSE; lg_byte Flags; m_File.Read(&Flags, 1); m_File.Read(&lt->v3Pos, 12); lg_long nKeys; m_File.Read(&nKeys, 4); for(lg_long i=0; i<nKeys; i++) { lg_dword nKeyName; lg_dword nKeyValue; m_File.Read(&nKeyName, 4); m_File.Read(&nKeyValue, 4); if(strcmp(m_szNames[nKeyName], "classname")==0) { if( (strcmp(m_szNames[nKeyValue], "light")!=0) && (strcmp(m_szNames[nKeyValue], "spotlight")!=0) && (strcmp(m_szNames[nKeyValue], "sunlight")!=0) ) { return LG_FALSE; } else bIsLight=LG_TRUE; } else if(strcmp(m_szNames[nKeyName], "color")==0) { lt->Color=StringToColor(m_szNames[nKeyValue]); } else if(strcmp(m_szNames[nKeyName], "intensity")==0) { lt->fIntensity=(lg_float)atof(m_szNames[nKeyValue]); } /* else if(strcmp(m_szNames[nKeyName], "range")==0) { lt->nRange=atoi(m_szNames[nKeyValue]); } */ } if(!bIsLight) return LG_FALSE; //Skip the group; m_File.Seek(CWSMemFile::MEM_SEEK_CUR, 4); m_File.Read(&lt->nVisGrp, 4); return LG_TRUE; } void CWSFile::GetObjects() { // Get the materials and count the number of vertices m_File.Seek(CWSMemFile::MEM_SEEK_SET, m_nObjectOffset); lg_dword nMat=0, nVert=0, nBrush=0, nLM=0, nFace=0, nVisGrp=0; lg_dword nGeoBlock=0, nGeoFace=0, nLight=0, nGeoVert=0, nGeoTri=0; for(lg_long nObj=1; nObj<=m_nObjectCount; nObj++) { lg_dword nName; lg_long nSize; m_File.Read(&nName, 4); m_File.Read(&nSize, 4); lg_dword nBegin=m_File.Tell(); if(strcmp(m_szNames[nName], "material")==0) { if(nMat>=m_nMatCount) { m_File.Seek(CWSMemFile::MEM_SEEK_CUR, nSize); continue; } lg_byte nFlags; lg_dword nGroup; lg_dword nObject; lg_dword nExt; m_File.Read(&nFlags, 1); m_File.Read(&nGroup, 4); m_File.Read(&nObject, 4); if(nFlags&0x02) m_File.Read(&nExt, 4); const lg_char* szExt=(nFlags&0x02)?m_szNames[nExt]:"tga"; if(strcmp(m_szNames[nGroup], "textures")==0) _snprintf(m_pMaterials[nMat].szMaterial, 255, "%s/%s.%s", m_szNames[nGroup], m_szNames[nObject], szExt); else _snprintf(m_pMaterials[nMat].szMaterial, 255, "textures/%s/%s.%s", m_szNames[nGroup], m_szNames[nObject], szExt); m_pMaterials[nMat].nRef=nObj; //Err_Printf("Material %d: %s", nMat, m_pMaterials[nMat].szMaterial); nMat++; } else if(strcmp(m_szNames[nName], "entity")==0) { WS_LIGHT lt; lg_dword nStart=m_File.Tell(); if(GetLight(&lt) && (nLight<m_nLightCount)) { if(nLight>=m_nLightCount) break; //Err_Printf("===LIGHT==="); //Err_Printf("Position: (%f, %f, %f)", lt.v3Pos.x, lt.v3Pos.y, lt.v3Pos.z); //Err_Printf("Color: 0x%08X", lt.Color); //Err_Printf("Intensity: %f", lt.fIntensity); //Err_Printf("VisGrp: %u", lt.nVisGrp); m_pLights[nLight++]=lt; } /*else if(GetAIThingy()) { } */ m_File.Seek(CWSMemFile::MEM_SEEK_SET, nStart+nSize); } else if(strcmp(m_szNames[nName], "visgroup")==0) { if(nVisGrp>=m_nVisGroupCount) { m_File.Seek(CWSMemFile::MEM_SEEK_CUR, nSize); continue; } lg_dword nName; //Skip the flags m_File.Seek(CWSMemFile::MEM_SEEK_CUR, 1); m_File.Read(&nName, 4); //Skip the color m_File.Seek(CWSMemFile::MEM_SEEK_CUR, 3); m_pVisGrps[nVisGrp].nRef=nObj; strncpy(m_pVisGrps[nVisGrp].szName, m_szNames[nName], WS_MAX_NAME-1); m_pVisGrps[nVisGrp].szName[WS_MAX_NAME-1]=0; //Err_Printf("Vis Group %d: %s", nVisGrp, m_pVisGrps[nVisGrp].szName); nVisGrp++; } else if(strcmp(m_szNames[nName], "lightmap")==0) { //We'll just read the lightmap data, and do the conversion //to a tga when we write the lw file. if(nLM>=m_nLMCount) { m_File.Seek(CWSMemFile::MEM_SEEK_CUR, nSize); continue; } m_pLMs[nLM].nRef=nObj; m_pLMs[nLM].nSize=nSize; m_pLMs[nLM].pLM=m_File.GetPointer(m_File.Tell()); nLM++; } else if(strcmp(m_szNames[nName], "brush")==0) { if(nVert>=m_nVertexCount) { m_File.Seek(CWSMemFile::MEM_SEEK_CUR, nSize); continue; } lg_byte nFlags; lg_long nKeys; lg_long nGrp; lg_long nVisGrp; lg_byte nVertexCount; lg_byte nFaceCount; m_File.Read(&nFlags, 1); m_File.Read(&nKeys, 4); m_File.Seek(CWSMemFile::MEM_SEEK_CUR, nKeys*8); m_File.Read(&nGrp, 4); m_File.Read(&nVisGrp, 4); //Skip the color m_File.Seek(CWSMemFile::MEM_SEEK_CUR, 3); m_File.Read(&nVertexCount, 1); ML_VEC3* pVerts=new ML_VEC3[nVertexCount]; if(!pVerts) throw("WSToLW ERROR: Out of memory."); for(lg_byte i=0; i<nVertexCount; i++) { m_File.Read(&pVerts[i], 12); memcpy(&m_pGeoVerts[nGeoVert+i], &pVerts[i], 12); } m_File.Read(&nFaceCount, 1); //Set the geo information... m_pGeoBlocks[nGeoBlock].nFirstVertex=nGeoVert; m_pGeoBlocks[nGeoBlock].nVertexCount=nVertexCount; m_pGeoBlocks[nGeoBlock].nFirstGeoFace=nGeoFace; m_pGeoBlocks[nGeoBlock].nGeoFaceCount=0; m_pGeoBlocks[nGeoBlock].nVisGrp=nVisGrp; m_pGeoBlocks[nGeoBlock].nFirstTri=nGeoTri; m_pGeoBlocks[nGeoBlock].nNumTris=0; ML_AABBFromVec3s(&m_pGeoBlocks[nGeoBlock].aabbBlock, pVerts, nVertexCount); nGeoBlock++; nGeoVert+=nVertexCount; for(lg_byte i=0; i<nFaceCount; i++) { lg_byte nFaceFlags; ML_PLANE v4PlaneEq; lg_long nMaterial; lg_long nLightMap; m_File.Read(&nFaceFlags, 1); m_File.Read(&v4PlaneEq, 16); m_File.Seek(CWSMemFile::MEM_SEEK_CUR, 64); m_File.Read(&nMaterial, 4); //Set the geo face information (and update the current geo block). m_pGeoFaces[nGeoFace].plnEq=v4PlaneEq; nGeoFace++; m_pGeoBlocks[nGeoBlock-1].nGeoFaceCount++; if(nFaceFlags&16) m_File.Read(&nLightMap, 4); else nLightMap=0xFFFFFFFF; lg_byte nIndexCount; m_File.Read(&nIndexCount, 1); m_pGeoBlocks[nGeoBlock-1].nNumTris+=(nIndexCount-2); m_pRasterFaces[nFace].bVisible=!(nFaceFlags&0x04); m_pRasterFaces[nFace].nFirst=nVert; m_pRasterFaces[nFace].nMatRef=nMaterial; m_pRasterFaces[nFace].nLMRef=nLightMap; //Note need to change this... m_pRasterFaces[nFace].nVisGrp=nVisGrp; m_pRasterFaces[nFace].nNumTriangles=(nIndexCount-2); //m_pRasterFaces[nFace].v4PlaneEq=v4PlaneEq; //m_pRasterFaces[nFace].nOpFlags=0; nFace++; for(lg_byte i=0; i<nIndexCount; i++) { lg_byte nV; ML_VEC2 v2Tex, v2LM; m_File.Read(&nV, 1); m_pVertexes[nVert].v3Pos=pVerts[nV]; m_File.Read(&v2Tex, 8); if(nFaceFlags&16) { m_File.Read(&v2LM, 8); } else { v2LM.x=0; v2LM.y=0; } //Save triangles for raster data. if(i<3) { m_pGeoTris[nGeoTri].v3Vert[i]=pVerts[nV]; if(i==2) nGeoTri++; } else { m_pGeoTris[nGeoTri].v3Vert[0]=m_pGeoTris[nGeoTri-1].v3Vert[0]; m_pGeoTris[nGeoTri].v3Vert[1]=m_pGeoTris[nGeoTri-1].v3Vert[2]; m_pGeoTris[nGeoTri].v3Vert[2]=pVerts[nV]; nGeoTri++; } //If the face isn't visible we don't //need to save it to the raster data. if(L_CHECK_FLAG(nFaceFlags, 0x04) || (nVert>=m_nVertexCount)) continue; //The first three vertexes in a face are //the first three vertexes read, after that the //vertexes are in a fan, and therefore it is //necessary to set the first vertex to the first //vertex of the last triangle, and the second vertex //to the last vertex of the previous triangle, and //the new vertex as the new vertex. In this way a //triangle list is created. if(i<3) { m_pVertexes[nVert].v3Pos=pVerts[nV]; m_pVertexes[nVert].v2Tex=v2Tex; m_pVertexes[nVert].v2LM=v2LM; } else { m_pVertexes[nVert]=m_pVertexes[nVert-3]; m_pVertexes[nVert+1]=m_pVertexes[nVert-1]; nVert+=2; m_pVertexes[nVert].v3Pos=pVerts[nV]; m_pVertexes[nVert].v2Tex=v2Tex; m_pVertexes[nVert].v2LM=v2LM; } nVert++; } } L_safe_delete_array(pVerts); } m_File.Seek(CWSMemFile::MEM_SEEK_SET, nBegin+nSize); } Err_Printf("Got %d geo tris", nGeoTri); } void CWSFile::AllocateMemory() { //Allocate everything but the name table, //because the names have already been allocated. m_pVertexes=new WS_VERTEX[m_nVertexCount+3]; m_pMaterials=new WS_MATERIAL[m_nMatCount]; m_pLMs=new WS_LIGHTMAP[m_nLMCount]; m_pVisGrps=new WS_VISGROUP[m_nVisGroupCount]; m_pRasterFaces=new WS_RASTER_FACE[m_nFaceCount]; m_pGeoBlocks=new WS_GEO_BLOCK[m_nBrushCount]; m_pGeoFaces=new WS_GEO_FACE[m_nFaceCount]; m_pLights=new WS_LIGHT[m_nLightCount]; m_pGeoVerts=new WS_GEO_VERT[m_nGeoVertCount]; m_pGeoTris=new WS_GEO_TRI[m_nGeoTriCount]; if(!m_pGeoTris || !m_pGeoVerts || !m_pVertexes || !m_pMaterials || !m_pLMs || !m_pVisGrps || !m_pRasterFaces || !m_pGeoFaces || !m_pGeoBlocks || !m_pLights) { DeallocateMemory(); throw("CWSFile ERROR: Out of memory."); } } void CWSFile::DeallocateMemory() { L_safe_delete_array(m_szNames); L_safe_delete_array(m_pVertexes); L_safe_delete_array(m_pMaterials); L_safe_delete_array(m_pLMs); L_safe_delete_array(m_pVisGrps); L_safe_delete_array(m_pRasterFaces); L_safe_delete_array(m_pGeoFaces); L_safe_delete_array(m_pGeoBlocks); L_safe_delete_array(m_pLights); L_safe_delete_array(m_pGeoVerts); L_safe_delete_array(m_pGeoTris); } void CWSFile::GetCounts() { m_nMatCount=0; m_nLMCount=0; m_nLMMaxSize=0; m_nBrushCount=0; m_nFaceCount=0; m_nVisibleFaceCount=0; m_nVertexCount=0; m_nVisGroupCount=0; m_nLightCount=0; m_nGeoVertCount=0; m_nGeoTriCount=0; //Count all the objects for(lg_long i=1; i<=m_nObjectCount; i++) { lg_dword nName; lg_long nSize; m_File.Read(&nName, 4); m_File.Read(&nSize, 4); lg_dword nBegin=m_File.Tell(); //Err_Printf("Ojbect %d (%d): %s", i, nSize, m_szNames[nName]); if(strcmp(m_szNames[nName], "material")==0) m_nMatCount++; if(strcmp(m_szNames[nName], "visgroup")==0) m_nVisGroupCount++; if(strcmp(m_szNames[nName], "entity")==0) { //Err_Printf("===ENTITY==="); lg_byte Flags; m_File.Read(&Flags, 1); //Err_Printf("Flags: 0x%02X", Flags); //ML_VEC3 v3Pos; //m_File.Read(&v3Pos, 12); //Err_Printf("Position: (%f, %f, %f)", v3Pos.x, v3Pos.y, v3Pos.z); m_File.Seek(CWSMemFile::MEM_SEEK_CUR, 12); lg_long nKeys; m_File.Read(&nKeys, 4); for(lg_long i=0; i<nKeys; i++) { lg_dword nKeyName, nKeyValue; m_File.Read(&nKeyName, 4); m_File.Read(&nKeyValue, 4); if(strcmp(m_szNames[nKeyName], "classname")==0) { if( (strcmp(m_szNames[nKeyValue], "light")==0) || (strcmp(m_szNames[nKeyValue], "spotlight")==0) || (strcmp(m_szNames[nKeyValue], "sunlight")==0) ) { m_nLightCount++; } } //Err_Printf("%s: \"%s\"", m_szNames[nKeyName], m_szNames[nKeyValue]); } //Err_Printf("============"); } if(strcmp(m_szNames[nName], "lightmap")==0) { m_nLMCount++; m_nLMMaxSize=LG_Max(m_nLMMaxSize, (lg_dword)nSize); } if(strcmp(m_szNames[nName], "brush")==0) { m_nBrushCount++; lg_byte nFlags; lg_long nKeys; lg_byte nVertexCount; lg_byte nFaceCount; m_File.Read(&nFlags, 1); m_File.Read(&nKeys, 4); m_File.Seek(CWSMemFile::MEM_SEEK_CUR, nKeys*8); m_File.Seek(CWSMemFile::MEM_SEEK_CUR, 4+4+3); m_File.Read(&nVertexCount, 1); m_nGeoVertCount+=nVertexCount; m_File.Seek(CWSMemFile::MEM_SEEK_CUR, 12*nVertexCount); m_File.Read(&nFaceCount, 1); m_nFaceCount+=nFaceCount; //m_nGeoTriCount+=nFaceCount; for(lg_byte i=0; i<nFaceCount; i++) { lg_byte nFaceFlags; m_File.Read(&nFaceFlags, 1); m_File.Seek(CWSMemFile::MEM_SEEK_CUR, 84); if(nFaceFlags&16) m_File.Seek(CWSMemFile::MEM_SEEK_CUR, 4); lg_byte nIndexCount; m_File.Read(&nIndexCount, 1); m_nGeoTriCount+=(nIndexCount-2); if(!(nFaceFlags&0x04)) { m_nVertexCount+=3+(nIndexCount-3)*3; m_nVisibleFaceCount++; } if(nFaceFlags&16) m_File.Seek(CWSMemFile::MEM_SEEK_CUR, nIndexCount*17); else m_File.Seek(CWSMemFile::MEM_SEEK_CUR, nIndexCount*9); } } m_File.Seek(CWSMemFile::MEM_SEEK_SET, nBegin+nSize); } } void CWSFile::GetNames() { m_szNames=new lg_char*[this->m_nNameCount+1]; if(!m_szNames) throw("CWSFile ERROR: Out of memory."); m_szNames[0]=LG_NULL; lg_long nNamesFound=1; lg_byte* pData=m_File.GetPointer(m_nNameOffset); m_szNames[1]=(lg_char*)&pData[0]; for(lg_dword i=0; i<m_File.GetSize()-m_nNameOffset; i++) { if(pData[i]==0) { nNamesFound++; m_szNames[nNamesFound]=(lg_char*)&pData[i+1]; } if(nNamesFound>=m_nNameCount) return; } } #include "lf_sys2.h" #include "lw_map.h" lg_bool CWSFile::SaveAsLW(lg_char* szFilename) { LF_FILE3 fout=LF_Open(szFilename, LF_ACCESS_WRITE, LF_CREATE_ALWAYS); if(!fout) return LG_FALSE; //Calculate the whole world AABB //Now write the map... lg_word nID=LW_ID; lg_dword nVersion=LW_VERSION; lg_dword nVertexCount=m_nVertexCount; lg_dword nVertexOffset=0; lg_dword nMaterialCount=m_nMatCount; lg_dword nMaterialOffset=0; lg_dword nLMCount=m_nLMCount; lg_dword nLMOffset=0; lg_dword nLMTotalSize=0; lg_dword nFaceCount=m_nVisibleFaceCount; lg_dword nFaceOffset=0; lg_dword nRegionCount=m_nVisGroupCount; lg_dword nRegionOffset=0; lg_dword nGeoBlockCount=m_nBrushCount; lg_dword nGeoBlockOffset=0; lg_dword nGeoFaceCount=m_nFaceCount; lg_dword nGeoFaceOffset=0; lg_dword nLightCount=m_nLightCount; lg_dword nLightOffset=0; lg_dword nGeoVertOffset=0; lg_dword nGeoVertCount=m_nGeoVertCount; lg_dword nGeoTriOffset=0; lg_dword nGeoTriCount=m_nGeoTriCount; LF_Write(fout, &nID, 2); LF_Write(fout, &nVersion, 4); LF_Write(fout, &nVertexCount, 4); LF_Write(fout, &nVertexOffset, 4); LF_Write(fout, &nMaterialCount, 4); LF_Write(fout, &nMaterialOffset, 4); LF_Write(fout, &nLMCount, 4); LF_Write(fout, &nLMOffset, 4); LF_Write(fout, &nLMTotalSize, 4); LF_Write(fout, &nFaceCount, 4); LF_Write(fout, &nFaceOffset, 4); LF_Write(fout, &nRegionCount, 4); LF_Write(fout, &nRegionOffset, 4); LF_Write(fout, &nGeoBlockCount, 4); LF_Write(fout, &nGeoBlockOffset, 4); LF_Write(fout, &nGeoFaceCount, 4); LF_Write(fout, &nGeoFaceOffset, 4); LF_Write(fout, &nLightCount, 4); LF_Write(fout, &nLightOffset, 4); LF_Write(fout, &nGeoVertCount, 4); LF_Write(fout, &nGeoVertOffset, 4); LF_Write(fout, &nGeoTriCount, 4); LF_Write(fout, &nGeoTriOffset, 4); LF_Write(fout, &m_aabbWorld, 24); //We can simply write the vertexes nVertexOffset=LF_Tell(fout); for(lg_dword i=0; i<nVertexCount; i++) { LF_Write(fout, &m_pVertexes[i], 28); } //we can do the same for the materials nMaterialOffset=LF_Tell(fout); for(lg_dword i=0; i<nMaterialCount; i++) { LF_Write(fout, &m_pMaterials[i].szMaterial, WS_MAX_PATH); } //Light maps are a little more complicate, we need to convert each lightmap //to a tga file, and then write the tga file. nLMOffset=LF_Tell(fout); //Write each of the light maps for(lg_dword i=0; i<nLMCount; i++) { lg_byte* pLM=m_pLMs[i].pLM;//&pLMData[4*counts.nLightMapCount+i*counts.nLMSize]; lg_word nRes=(lg_word)ML_Pow2(pLM[1]); lg_byte nHeader[18]; lg_dword nImgDataSize=nRes*nRes*3; lg_dword nSize=18+nImgDataSize; //Start off by writing the size, then write the image data... LF_Write(fout, &nSize, 4); nLMTotalSize+=4; memset(nHeader, 0, 18); //Setup the tga header... nHeader[2]=2; *(lg_word*)(&nHeader[12])=nRes; *(lg_word*)(&nHeader[14])=nRes; nHeader[16]=24; nHeader[17]=0x20; //Write the header... LF_Write(fout, nHeader, 18); nLMTotalSize+=18; //Write the image data... LF_Write(fout, &pLM[6], nImgDataSize); nLMTotalSize+=nImgDataSize; } //We'll write only visible faces... nFaceOffset=LF_Tell(fout); for(lg_dword i=0; i<nFaceCount; i++) { LF_Write(fout, &m_pRasterFaces[i].nFirst, 4); LF_Write(fout, &m_pRasterFaces[i].nNumTriangles, 4); LF_Write(fout, &m_pRasterFaces[i].nMatRef, 4); LF_Write(fout, &m_pRasterFaces[i].nLMRef, 4); } //Write the regions... nRegionOffset=LF_Tell(fout); for(lg_dword i=0; i<nRegionCount; i++) { LF_Write(fout, &m_pVisGrps[i].szName, 32); LF_Write(fout, &m_pVisGrps[i].nFirstFace, 4); LF_Write(fout, &m_pVisGrps[i].nFaceCount, 4); LF_Write(fout, &m_pVisGrps[i].nFirstVertex, 4); LF_Write(fout, &m_pVisGrps[i].nVertexCount, 4); LF_Write(fout, &m_pVisGrps[i].nFirstGeoBlock, 4); LF_Write(fout, &m_pVisGrps[i].nGeoBlockCount, 4); LF_Write(fout, &m_pVisGrps[i].nFirstLight, 4); LF_Write(fout, &m_pVisGrps[i].nLightCount, 4); LF_Write(fout, &m_pVisGrps[i].aabbVisBounds, 24); } //Write the geo blocks... nGeoBlockOffset=LF_Tell(fout); for(lg_dword i=0; i<nGeoBlockCount; i++) { LF_Write(fout, &m_pGeoBlocks[i].nFirstVertex, 4); LF_Write(fout, &m_pGeoBlocks[i].nVertexCount, 4); LF_Write(fout, &m_pGeoBlocks[i].nFirstTri, 4); LF_Write(fout, &m_pGeoBlocks[i].nNumTris, 4); LF_Write(fout, &m_pGeoBlocks[i].nFirstGeoFace, 4); LF_Write(fout, &m_pGeoBlocks[i].nGeoFaceCount, 4); LF_Write(fout, &m_pGeoBlocks[i].aabbBlock, 24); } //Write the geo faces... nGeoFaceOffset=LF_Tell(fout); for(lg_dword i=0; i<nGeoFaceCount; i++) { LF_Write(fout, &m_pGeoFaces[i].plnEq, 16); } //Write the geo vertexes... nGeoVertOffset=LF_Tell(fout); for(lg_dword i=0; i<nGeoVertCount; i++) { LF_Write(fout, &m_pGeoVerts[i].v3Pos, 12); } //Write the lights nLightOffset=LF_Tell(fout); for(lg_dword i=0; i<nLightCount; i++) { LF_Write(fout, &m_pLights[i].v3Pos, 12); //Write the color lg_float c=m_pLights[i].Color.r/255.0f; LF_Write(fout, &c, 4); c=m_pLights[i].Color.g/255.0f; LF_Write(fout, &c, 4); c=m_pLights[i].Color.b/255.0f; LF_Write(fout, &c, 4); c=1.0f; LF_Write(fout, &c, 4); } nGeoTriOffset=LF_Tell(fout); for(lg_dword i=0; i<nGeoTriCount; i++) { LF_Write(fout, &m_pGeoTris[i], 12*3); } //Err_Printf("Light Map Size: %d", nLMTotalSize); LF_Seek(fout, LF_SEEK_BEGIN, 10); LF_Write(fout, &nVertexOffset, 4); LF_Seek(fout, LF_SEEK_CURRENT, 4); LF_Write(fout, &nMaterialOffset, 4); LF_Seek(fout, LF_SEEK_CURRENT, 4); LF_Write(fout, &nLMOffset, 4); LF_Write(fout, &nLMTotalSize, 4); LF_Seek(fout, LF_SEEK_CURRENT, 4); LF_Write(fout, &nFaceOffset, 4); LF_Seek(fout, LF_SEEK_CURRENT, 4); LF_Write(fout, &nRegionOffset, 4); LF_Seek(fout, LF_SEEK_CURRENT, 4); LF_Write(fout, &nGeoBlockOffset, 4); LF_Seek(fout, LF_SEEK_CURRENT, 4); LF_Write(fout, &nGeoFaceOffset, 4); LF_Seek(fout, LF_SEEK_CURRENT, 4); LF_Write(fout, &nLightOffset, 4); LF_Seek(fout, LF_SEEK_CURRENT, 4); LF_Write(fout, &nGeoVertOffset, 4); LF_Seek(fout, LF_SEEK_CURRENT, 4); LF_Write(fout, &nGeoTriOffset, 4); LF_Close(fout); return LG_TRUE; }<file_sep>/tools/GFX/GFXG7/GFXG7.h /* GFXGin.h - header for GFXG7 Dynamic-Link Library Copyright (c) 2002, 2003 <NAME> */ #ifndef __GFXG7_H__ #define __GFXG7_H__ #include <ddraw.h> #include <windows.h> #ifdef __cplusplus extern "C"{ #endif /* __cplusplus */ #define GFXG7_EXPORTS typedef struct tagSAVEDPARAMETERS{ DWORD dwWidth; DWORD dwHeight; DWORD dwColorDepth; DWORD dwTransparentColor; HWND hWnd; RECT rcWindow; BOOL bWindowed; }SAVEDPARAMETERS; typedef enum tagIMAGETYPE{ ET_BITMAP=0, ET_COLOR }IMAGETYPE; typedef struct tagIMAGEDATA3{ IMAGETYPE nType; //type of image bitmap or color DWORD nWidth; //width of image DWORD nHeight; //height of image DWORD dwColor; //color of image }IMAGEDATA3; #define RV_LEFTRIGHT 0x01000000l #define RV_UPDOWN 0x02000000l #define CImage CImage7 #ifdef UNICODE #define CreateImageBM CreateImageBMW #else //unicode #define CreateImageBM CreateImageBMA #endif //unicode GFXG7_EXPORTS HRESULT InitDirectDraw( LPDIRECTDRAW7 *lppDDraw, LPDIRECTDRAWSURFACE7 *lppPrimary, LPDIRECTDRAWSURFACE7 *lppBack, HWND hwnd, BOOL bWindowed, DWORD dwWidth, DWORD dwHeight, DWORD dwBitDepth, RECT *rcWindow, DWORD *dwTransparentColor); GFXG7_EXPORTS HRESULT InitDirectDrawEx( LPDIRECTDRAW7 * lppDDraw, LPDIRECTDRAWSURFACE7 * lppPrimary, LPDIRECTDRAWSURFACE7 * lppBack, SAVEDPARAMETERS * pSavedParams); GFXG7_EXPORTS HRESULT InitFullScreenDirectDraw( LPDIRECTDRAW7 *lppDDraw, LPDIRECTDRAWSURFACE7 *lppBackBuffer, LPDIRECTDRAWSURFACE7 *lppPrimary, HWND hWnd, DWORD dwWidth, DWORD dwHeight, DWORD dwBitDepth, RECT *rcWindow, DWORD *nTransparentColor); GFXG7_EXPORTS HRESULT InitWindowedDirectDraw( LPDIRECTDRAW7 *lppDDraw, LPDIRECTDRAWSURFACE7 *lppBackBuffer, LPDIRECTDRAWSURFACE7 *lppPrimary, HWND hWnd, DWORD dwWidth, DWORD dwHeight, RECT * rcWindow, DWORD * lpTransparentColor); GFXG7_EXPORTS void SetSavedParameters( SAVEDPARAMETERS * pSavedParams, DWORD dwWidth, DWORD dwHeight, DWORD dwColorDepth, DWORD dwTransparentColor, HWND hWnd, RECT * rcWindow, BOOL bWindowed); GFXG7_EXPORTS DWORD WindowsColorToDirectDraw( COLORREF rgb, LPDIRECTDRAWSURFACE7 surface); GFXG7_EXPORTS HRESULT UpdateBounds( BOOL bWindowed, HWND hWnd, RECT * rcWindow); GFXG7_EXPORTS HRESULT AdjustWindowSize( HWND hWnd, DWORD nWidth, DWORD nHeight, BOOL bWindowed, HMENU hMenu); GFXG7_EXPORTS HRESULT PageFlip( LPDIRECTDRAWSURFACE7 lpPrimary, LPDIRECTDRAWSURFACE7 lpBackBuffer, BOOL bWindowed, RECT * rcWindow, HRESULT ( * Restore)()); #ifdef __cplusplus class GFXG7_EXPORTS CImage7{ private: LPDIRECTDRAWSURFACE7 m_lpImage; //Surface for image HBITMAP m_hBitmap; //Bitmap compatible version of image IMAGEDATA3 m_sImageData; //data about image HRESULT CreateSurface(DWORD nWidth, DWORD nHeight, LPVOID lpObject, DWORD dwTransparent); //create surface for image HRESULT LoadBitmapInMemoryIntoSurface( HBITMAP hBitmap, DWORD nWidth, DWORD nHeight); //loads an hbitmap into m_lpImage, both should have same dimensions HRESULT LoadColorIntoSurface(DWORD dwColor); //loads color into surface public: CImage7(); //constructor ~CImage7(); //destructor DWORD GetWidth(); //Get Image Width DWORD GetHeight(); //Get Image Height HRESULT Restore(); //restore images surface HRESULT ReloadImageIntoSurface(); //reloads image into surface (for after a restore) HRESULT ClearSurface(); //clears the surface to write new image to void Release(); //releases the surface LPDIRECTDRAWSURFACE7* GetPointerToSurface(); HRESULT CreateImageBMA( LPVOID lpDevice, DWORD dwTransparent, char szFilename[MAX_PATH], int nX, int nY, int nSrcWidth, int nSrcHeight, DWORD nWidth, DWORD nHeight, DWORD dwReverseFlags); //creates and image in the surface from a bitmap file HRESULT CreateImageBMW( LPVOID lpDevice, DWORD dwTransparent, WCHAR szFilename[MAX_PATH], int nX, int nY, int nSrcWidth, int nSrcHeight, DWORD nWidth, DWORD nHeight, DWORD dwReverseFlags); //creates and image in the surface from a bitmap file HRESULT CreateImageBMInMemory( LPVOID lpObject, DWORD dwTransparent, HBITMAP hBitmap, int nX, int nY, int nSrcWidth, int nSrcHeight, DWORD nWidth, DWORD nHeight, DWORD dwReverseFlags); HRESULT CreateImageColor( LPVOID lpDevice, DWORD dwTransparent, DWORD dwColor, DWORD nWidth, DWORD nHeight); //creates image from color //The following draws (and clips if necessary an image) the surface being blted to does //not require a clipper for clipping to take place HRESULT DrawClippedImage( LPVOID lpBuffer, int x, int y); HRESULT DrawImage( LPVOID lpBuffer, int x, int y); //draws image at specified coords to specified buffer HRESULT DrawPrefered( LPVOID lpBuffer, int x, int y); //clips if in windowed mode }; #endif /* __cplusplus */ #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __GFXG7_H__ */<file_sep>/games/Legacy-Engine/Source/engine/lw_server.h #ifndef __LW_SERVER_H__ #define __LW_SERVER_H__ #include "lw_entity.h" #include "lw_ai.h" #include "lt_sys.h" #include "lw_map.h" #include "lv_sys.h" #include "lp_sys2.h" #include "lw_net.h" class CLWorldSrv{ friend class CLWorldClnt; //Internal structures: private: //Data stored about the clients. struct ClntData{ lg_string szName; lg_dword nClntID; CLNT_CONNECT_TYPE nType; lg_dword nClntEnt; //The entity of most interest to the client. CLListStack m_CmdList; }; struct EntTemplate { lg_srv_ent Ent; lp_body_info BdyInfo; }; //Constants: private: static const lg_dword LSRV_MAX_CLIENTS=8; static const lg_dword LSRV_MAX_CMDS=1024; //Flags: private: //Server is running: static const lg_dword LSRV_FLAG_RUNNING=0x00000001; //Server is running, but it is paused: static const lg_dword LSRV_FLAG_PAUSED=0x00000002; private: //static const lg_dword MAX_ENTS=10000; //10,000 is about 14MB. lg_str m_szName; //The name of the server. //Clients connected to the server: lg_dword m_nNumClnts; lg_dword m_nClntRefs[LSRV_MAX_CLIENTS]; ClntData m_Clients[LSRV_MAX_CLIENTS]; ClntData m_AllClients; //Network commands: CLWCmdItem* m_pCmdList; CLListStack m_UnusedCmds; lg_path m_szSkyboxFile; //The path of the skybox mesh (to be sent to clients) lg_path m_szSkyboxSkinFile; //The path of the skin for the skybox (to be sent to clients) //Entity management variables. lg_dword m_nMaxEnts; //The maximum number of entities available. LEntitySrv* m_pEntList; //The list of all entities (used or unused). LEntList m_EntsBlank; //The list of unused entities. LEntList m_EntsInt; //The list of intelligent entities. LEntList m_EntsInert; //The list of inert (unintelligent) entities. //The physics engine. CLPhys* m_pPhys; CLTimer m_Timer; //The timer. CLMap m_Map; //The map. //The AI manager: CLWAIMgr m_AIMgr; lg_dword m_nFlags; //See above for what the flags mean. static const lg_dword m_nEntKillListSize=10; lg_dword m_nEntKillList[m_nEntKillListSize]; lg_dword m_nEntKillCount; private: lg_bool InitEnts(); lg_void DestroyEnts(); //Entity templates: lg_dword m_nNumTemplateEnts; EntTemplate* m_pTemplateEnt; lg_void LoadEntTemplate(lg_cstr szTemplateScript); lg_void UnloadEntTemplate(); lg_bool SetupEntityFromScript(lg_srv_ent* pEnt, lp_body_info* pBdyInfo, lg_cstr szScript); lg_void SetupEntFromTemplate(lg_srv_ent* pEnt, lp_body_info* pBdyInfo, const lg_dword nTemplate); protected: lg_void AddClient(const ClntData* pData); lg_bool AcceptLocalConnect(lg_dword* pPCEnt, lg_dword* pID, lg_cstr szName); lg_void Broadcast(); lg_void Receive(); public: CLWorldSrv(); ~CLWorldSrv(); lg_void Init(); lg_void Shutdown(); lg_bool IsRunning(){return LG_CheckFlag(m_nFlags, LSRV_FLAG_RUNNING);} lg_void ProcessServer(); __inline lg_void ProcessEntFuncs(LEntitySrv* pEnt); //lg_void CreateTestEnts(); lg_dword AddEntity(lf_path szObjScript, ML_MAT* matPos); lg_dword AddEntity(lg_dword nTemplate, ml_mat* matPos); lg_void RemoveEnt(const lg_dword nID); lg_void LoadMap(lg_str szMapFile); lg_void LoadLevel(lg_str szLevelScriptFile); lg_void ClearEnts(); //Debugging functions: lg_void PrintEntInfo(); /* PRE: N/A POST: If the server was runing it get's paused. */ lg_void Pause(); /* PRE: N/A POST: If the server was paused, it will resume. */ lg_void Resume(); /* PRE: N/A POST: Togles the pause status. */ lg_void TogglePause(); }; #endif __LW_SERVER_H__<file_sep>/samples/D3DDemo/code/MD3Base/MD3WeaponMesh.cpp #define D3D_MD3 #include <d3dx9.h> #include <stdio.h> #include "defines.h" #include "functions.h" #include "md3.h" CMD3WeaponMesh::CMD3WeaponMesh() { m_lpFlashTex=NULL; m_lpWeaponTex=NULL; m_lpBarrelTex=NULL; m_bBarrel=FALSE; m_nTagWeapon=m_nTagBarrel=m_nTagFlash=0; m_bLoaded=FALSE; } CMD3WeaponMesh::~CMD3WeaponMesh() { Clear(); } HRESULT CMD3WeaponMesh::Clear() { DWORD i=0, j=0; LONG lNumMesh=0; if(!m_bLoaded) return S_FALSE; m_TexDB.ClearDB(); //Delete the weapon. m_meshWeapon.GetNumMeshes(&lNumMesh); for(i=0; i<(DWORD)lNumMesh; i++){ SAFE_RELEASE(m_lpWeaponTex[i]); } SAFE_FREE(m_lpWeaponTex); m_meshWeapon.ClearMD3(); //Delete the barrel. if(m_bBarrel){ m_meshBarrel.GetNumMeshes(&lNumMesh); for(i=0; i<(DWORD)lNumMesh; i++){ SAFE_RELEASE(m_lpBarrelTex[i]); } SAFE_FREE(m_lpBarrelTex); m_meshBarrel.ClearMD3(); } //Delete the flash. m_meshFlash.GetNumMeshes(&lNumMesh); for(i=0; i<(DWORD)lNumMesh; i++){ SAFE_RELEASE(m_lpFlashTex[i]); } SAFE_FREE(m_lpFlashTex); m_meshFlash.ClearMD3(); //Delete the hand. m_meshHand.ClearMD3(); m_bLoaded=FALSE; m_bBarrel=FALSE; m_nTagWeapon=m_nTagBarrel=m_nTagFlash=0; SAFE_RELEASE(m_lpDevice); return S_OK; } HRESULT CMD3WeaponMesh::Load(LPDIRECT3DDEVICE9 lpDevice, char szDir[], MD3DETAIL nDetail) { char szPath[MAX_PATH]; char szWeaponName[MAX_QPATH]; char szWeaponPath[MAX_PATH]; char szBarrelPath[MAX_PATH]; char szFlashPath[MAX_PATH]; char szHandPath[MAX_PATH]; char szDetailLevel[3]; char szShaderName[MAX_QPATH]; char szTexName[MAX_PATH]; LONG lNumMesh=0; DWORD i=0; DWORD dwLen=0; HRESULT hr=0; Clear(); m_lpDevice=lpDevice; m_lpDevice->AddRef(); //Get the weapon's name. strcpy(szPath, szDir); dwLen=strlen(szPath); if(szPath[dwLen-1]!='\\'){ szPath[dwLen]='\\'; szPath[dwLen+1]=0; } strcpy(szWeaponName, szPath); dwLen=strlen(szWeaponName); szWeaponName[dwLen-1]=0; RemoveDirectoryFromStringA(szWeaponName, szWeaponName); //Prepare each of the path names. //Set the detail level. if(nDetail==DETAIL_LOW) strcpy(szDetailLevel, "_2"); else if(nDetail==DETAIL_MEDIUM) strcpy(szDetailLevel, "_1"); else strcpy(szDetailLevel, ""); //The weapon path. sprintf(szWeaponPath, "%s%s%s.md3", szPath, szWeaponName, szDetailLevel); //The barrel path. sprintf(szBarrelPath, "%s%s_barrel%s.md3", szPath, szWeaponName, szDetailLevel); //The flash path. sprintf(szFlashPath, "%s%s_flash.md3", szPath, szWeaponName); //The hand path. sprintf(szHandPath, "%s%s_hand.md3", szPath, szWeaponName); //Attempt to load the weapon mesh. hr=m_meshWeapon.LoadMD3A(szWeaponPath, NULL, lpDevice, D3DPOOL_DEFAULT); if(FAILED(hr)){ if(nDetail!=DETAIL_HIGH) { SAFE_RELEASE(m_lpDevice); return Load(lpDevice, szDir, DETAIL_HIGH); } SAFE_RELEASE(m_lpDevice); return E_FAIL; } //Load the hand and flash meshes. hr=m_meshHand.LoadMD3A(szHandPath, NULL, lpDevice, D3DPOOL_DEFAULT); hr|=m_meshFlash.LoadMD3A(szFlashPath, NULL, lpDevice, D3DPOOL_DEFAULT); if(FAILED(hr)){ m_meshHand.ClearMD3(); m_meshFlash.ClearMD3(); m_meshWeapon.ClearMD3(); SAFE_RELEASE(m_lpDevice); return E_FAIL; } //Load the barrel, if success then we set barrel to true. hr=m_meshBarrel.LoadMD3A(szBarrelPath, NULL, lpDevice, D3DPOOL_DEFAULT); if(SUCCEEDED(hr)){ m_bBarrel=TRUE; } //Load the textures. m_meshWeapon.GetNumMeshes(&lNumMesh); m_lpWeaponTex=(LPDIRECT3DTEXTURE9*)malloc(lNumMesh*sizeof(LPDIRECT3DTEXTURE9)); if(m_lpWeaponTex==NULL){ m_meshHand.ClearMD3(); m_meshFlash.ClearMD3(); m_meshWeapon.ClearMD3(); m_meshBarrel.ClearMD3(); SAFE_RELEASE(m_lpDevice); return E_FAIL; } if(m_bBarrel){ m_meshBarrel.GetNumMeshes(&lNumMesh); m_lpBarrelTex=(LPDIRECT3DTEXTURE9*)malloc(lNumMesh*sizeof(LPDIRECT3DTEXTURE9)); if(m_lpBarrelTex==NULL){ SAFE_DELETE_ARRAY(m_lpWeaponTex); m_meshHand.ClearMD3(); m_meshFlash.ClearMD3(); m_meshWeapon.ClearMD3(); m_meshBarrel.ClearMD3(); SAFE_RELEASE(m_lpDevice); return E_FAIL; } } m_meshFlash.GetNumMeshes(&lNumMesh); m_lpFlashTex=(LPDIRECT3DTEXTURE9*)malloc(lNumMesh*sizeof(LPDIRECT3DTEXTURE9)); if(m_lpFlashTex==NULL){ SAFE_DELETE_ARRAY(m_lpWeaponTex); if(m_bBarrel){ SAFE_DELETE_ARRAY(m_lpBarrelTex); } m_meshHand.ClearMD3(); m_meshFlash.ClearMD3(); m_meshWeapon.ClearMD3(); m_meshBarrel.ClearMD3(); SAFE_RELEASE(m_lpDevice); return E_FAIL; } //Get the weapon textures. m_meshWeapon.GetNumMeshes(&lNumMesh); for(i=0; i<(DWORD)lNumMesh; i++){ m_meshWeapon.GetShader(i+1, 1, szShaderName, NULL); RemoveDirectoryFromStringA(szShaderName, szShaderName); sprintf(szTexName, "%s%s", szPath, szShaderName); if(SUCCEEDED(TextureExtension(szTexName))){ m_TexDB.GetTexture(szTexName, &m_lpWeaponTex[i]); }else{ m_lpWeaponTex[i]=NULL; } } //Get the barrel textures if it exists. if(m_bBarrel){ m_meshBarrel.GetNumMeshes(&lNumMesh); for(i=0; i<(DWORD)lNumMesh; i++){ m_meshBarrel.GetShader(i+1, 1, szShaderName, NULL); RemoveDirectoryFromStringA(szShaderName, szShaderName); sprintf(szTexName, "%s%s", szPath, szShaderName); if(SUCCEEDED(TextureExtension(szTexName))){ m_TexDB.GetTexture(szTexName, &m_lpBarrelTex[i]); }else{ m_lpBarrelTex[i]=NULL; } } } //Get the flash textures. m_meshFlash.GetNumMeshes(&lNumMesh); for(i=0; i<(DWORD)lNumMesh; i++){ m_meshFlash.GetShader(i+1, 1, szShaderName, NULL); RemoveDirectoryFromStringA(szShaderName, szShaderName); sprintf(szTexName, "%s%s", szPath, szShaderName); if(SUCCEEDED(TextureExtension(szTexName))){ m_TexDB.GetTexture(szTexName, &m_lpFlashTex[i]); }else{ m_lpFlashTex[i]=NULL; } } //Get the tags. GetLink(&m_meshWeapon, "tag_weapon", &m_nTagWeapon); GetLink(&m_meshWeapon, "tag_barrel", &m_nTagBarrel); GetLink(&m_meshWeapon, "tag_flash", &m_nTagFlash); m_bLoaded=TRUE; return S_OK; } HRESULT CMD3WeaponMesh::TextureExtension(char szShader[MAX_PATH]) { DWORD dwLen=0, i=0, j=0; char szTemp[MAX_PATH]; HRESULT hr=0; //First attempt to load the name provided. hr=m_TexDB.AddTexture(m_lpDevice, szShader); if(SUCCEEDED(hr)){ RemoveDirectoryFromStringA(szShader, szShader); return S_OK; } dwLen=strlen(szShader); for(i=0, j=0; i<dwLen; i++, j++){ if(szShader[i]=='.'){ szTemp[j]=szShader[i]; szTemp[j+1]=0; break; } szTemp[j]=szShader[i]; } //Attempt to replace the extension till we successfully load. strcpy(szShader, szTemp); strcpy(szTemp, szShader); strcat(szTemp, "JPG"); hr=m_TexDB.AddTexture(m_lpDevice, szTemp); if(SUCCEEDED(hr)){ strcpy(szShader, szTemp); RemoveDirectoryFromStringA(szShader, szShader); return S_OK; } strcpy(szTemp, szShader); strcat(szTemp, "BMP"); hr=m_TexDB.AddTexture(m_lpDevice, szTemp); if(SUCCEEDED(hr)){ strcpy(szShader, szTemp); RemoveDirectoryFromStringA(szShader, szShader); return S_OK; } strcpy(szTemp, szShader); strcat(szTemp, "PNG"); hr=m_TexDB.AddTexture(m_lpDevice, szTemp); if(SUCCEEDED(hr)){ strcpy(szShader, szTemp); RemoveDirectoryFromStringA(szShader, szShader); return S_OK; } strcpy(szTemp, szShader); strcat(szTemp, "DIB"); hr=m_TexDB.AddTexture(m_lpDevice, szTemp); if(SUCCEEDED(hr)){ strcpy(szShader, szTemp); RemoveDirectoryFromStringA(szShader, szShader); return S_OK; } strcpy(szTemp, szShader); strcat(szTemp, "DDS"); hr=m_TexDB.AddTexture(m_lpDevice, szTemp); if(SUCCEEDED(hr)){ strcpy(szShader, szTemp); RemoveDirectoryFromStringA(szShader, szShader); return S_OK; } strcpy(szTemp, szShader); strcat(szTemp, "TGA"); hr=m_TexDB.AddTexture(m_lpDevice, szTemp); if(SUCCEEDED(hr)){ strcpy(szShader, szTemp); RemoveDirectoryFromStringA(szShader, szShader); return S_OK; } return E_FAIL; } HRESULT CMD3WeaponMesh::GetLink(CMD3Mesh * lpFirst, char szTagName[], WORD * lpTagRef) { LONG i=0; LONG lNumTags=0; char szTemp[MAX_QPATH]; lpFirst->GetNumTags(&lNumTags); for(i=1; i<=lNumTags; i++){ lpFirst->GetTagName(i, szTemp); if(_strnicmp(szTemp, szTagName, strlen(szTagName))==0){ *lpTagRef=(WORD)i; return S_OK; } } return E_FAIL; } HRESULT CMD3WeaponMesh::Invalidate() { if(!m_bLoaded) return S_FALSE; m_meshFlash.Invalidate(); m_meshHand.Invalidate(); m_meshWeapon.Invalidate(); if(m_bBarrel){ m_meshBarrel.Invalidate(); } return S_OK; } HRESULT CMD3WeaponMesh::Validate() { if(!m_bLoaded) return S_FALSE; m_meshFlash.Validate(); m_meshHand.Validate(); m_meshWeapon.Validate(); if(m_bBarrel){ m_meshBarrel.Validate(); } return S_OK; } HRESULT CMD3WeaponMesh::Render(BOOL bFlash, const D3DMATRIX& SavedWorldMatrix) { DWORD i=0, j=0; LONG lNumMesh=0; D3DXMATRIX WorldMatrix, Translation, Orientation, Temp; if(!m_bLoaded) return S_FALSE; D3DXMatrixIdentity(&WorldMatrix); D3DXMatrixIdentity(&Orientation); D3DXMatrixRotationX(&Translation, 1.5f*D3DX_PI); Orientation*=Translation; D3DXMatrixRotationY(&Translation, 0.5f*D3DX_PI); Orientation*=Translation; Orientation*=SavedWorldMatrix; WorldMatrix*=Orientation; m_lpDevice->SetTransform(D3DTS_WORLD, &WorldMatrix); //Render the weapon first. Temp=WorldMatrix; m_meshWeapon.GetTagTranslation(m_nTagWeapon, 0.0f, 0, 0, &Translation); WorldMatrix=Translation*WorldMatrix; m_lpDevice->SetTransform(D3DTS_WORLD, &WorldMatrix); m_meshWeapon.GetNumMeshes(&lNumMesh); for(i=0; i<(DWORD)lNumMesh; i++){ m_meshWeapon.RenderWithTexture( m_lpWeaponTex[i], i+1, 0.0f, 0, 0, 0); } WorldMatrix=Temp; //Render the barrel if there is one. if(m_bBarrel){ Temp=WorldMatrix; m_meshWeapon.GetTagTranslation(m_nTagBarrel, 0.0f, 0, 0, &Translation); WorldMatrix=Translation*WorldMatrix; m_lpDevice->SetTransform(D3DTS_WORLD, &WorldMatrix); m_meshBarrel.GetNumMeshes(&lNumMesh); for(i=0; i<(DWORD)lNumMesh; i++){ m_meshBarrel.RenderWithTexture( m_lpBarrelTex[i], i+1, 0.0f, 0, 0, 0); } WorldMatrix=Temp; } if(bFlash){ Temp=WorldMatrix; m_meshWeapon.GetTagTranslation(m_nTagFlash, 0.0f, 0, 0, &Translation); WorldMatrix=Translation*WorldMatrix; m_lpDevice->SetTransform(D3DTS_WORLD, &WorldMatrix); m_meshFlash.GetNumMeshes(&lNumMesh); ////////////////////////////////////////// //NOTICE: Should enable alpha blending./// ////////////////////////////////////////// for(i=0; i<(DWORD)lNumMesh; i++){ m_meshFlash.RenderWithTexture( m_lpFlashTex[i], i+1, 0.0f, 0, 0, MD3TEXRENDER_NOCULL); } //Should restore alpha blending values. WorldMatrix=Temp; } m_lpDevice->SetTransform(D3DTS_WORLD, &SavedWorldMatrix); return S_OK; }<file_sep>/Misc/GamepadToKey/GamepadToKey/GamepadToKey.cpp // GamepadToKey.cpp : Defines the entry point for the application. // #include "GPTKXInputHandler.h" #include <windows.h> #include "resource.h" #define MAX_LOADSTRING 100 static HINSTANCE g_Inst = nullptr; static bool g_bKeeyLooping = true; // Forward declarations of functions included in this code module: LRESULT CALLBACK GamepadToKey_WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK GamepadToKey_About(HWND, UINT, WPARAM, LPARAM); static void GampeadToKey_Handler( DWORD Key , UINT Msg , void* Extra ) { if( false ) //Key == 'Z' ) { g_bKeeyLooping = false; } UINT ScanCode = MapVirtualKeyExW( Key , MAPVK_VK_TO_VSC_EX , 0 ); struct gptkKeyLParam { int Repeat:16; int ScanCode:8; int IsExtended:1; int Reserved:4; int ContextCode:1; int PreviousState:1; int TransitionState:1; }; union gptkKeyLParamConverter { LPARAM lParam; gptkKeyLParam AsStruct; }; gptkKeyLParamConverter lParam; lParam.lParam = 0; lParam.AsStruct.Repeat = 1; lParam.AsStruct.IsExtended = 0; lParam.AsStruct.PreviousState = ( Msg == WM_KEYUP ) ? 1 : 0; lParam.AsStruct.TransitionState = (Msg == WM_KEYUP ) ? 1 : 0; lParam.AsStruct.ScanCode = ScanCode; HWND hFocusedWindow = GetForegroundWindow(); WCHAR FocusedWindowName[256]; GetWindowTextW( hFocusedWindow , FocusedWindowName , 256 ); SendMessageW( hFocusedWindow , Msg , Key , lParam.lParam ); } int APIENTRY wWinMain( _In_ HINSTANCE hInstance , _In_opt_ HINSTANCE hPrevInstance ,_In_ LPWSTR lpCmdLine , _In_ int nCmdShow ) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); WCHAR szTitle[MAX_LOADSTRING]; // The title bar text WCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name GPTKXInputHandler_Init(); while( g_bKeeyLooping ) { GPTKXInputHandler_Update( 0.f , GampeadToKey_Handler , nullptr ); } GPTKXInputHandler_Deinit(); auto DoRegisterClass = [&szTitle,&szWindowClass](HINSTANCE hInstance) -> ATOM { WNDCLASSEXW wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = GamepadToKey_WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_GAMEPADTOKEY)); wcex.hCursor = LoadCursor(nullptr, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_GAMEPADTOKEY); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassExW(&wcex); }; auto InitInstance =[&szWindowClass,&szTitle](HINSTANCE hInstance, int nCmdShow) -> BOOL { g_Inst = hInstance; HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; }; // Initialize global strings LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadStringW(hInstance, IDC_GAMEPADTOKEY, szWindowClass, MAX_LOADSTRING); DoRegisterClass( hInstance ); // Perform application initialization: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_GAMEPADTOKEY)); MSG msg; // Main message loop: while (GetMessage(&msg, nullptr, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int) msg.wParam; } LRESULT CALLBACK GamepadToKey_WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_COMMAND: { int wmId = LOWORD(wParam); // Parse the menu selections: switch (wmId) { case IDM_ABOUT: DialogBox(g_Inst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, GamepadToKey_About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProcW(hWnd, message, wParam, lParam); } } break; case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hWnd, &ps); // TODO: Add any drawing code that uses hdc here... EndPaint(hWnd, &ps); } break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProcW(hWnd, message, wParam, lParam); } return 0; } INT_PTR CALLBACK GamepadToKey_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; } <file_sep>/games/Legacy-Engine/Source/lm_sys/lm_skel.h #ifndef __LM_SKEL_H__ #define __LM_SKEL_H__ #include "lm_base.h" class CLSkel2: public CLMBase { friend class CLMeshAnim; //Constants & Flags: public: static const lg_dword LM_SKEL_ID=0x4C4B534C; static const lg_dword LM_SKEL_VER=105; //Privately used structures: public: struct SkelJoint{ LMName szName; //32 LMName szParent; //32 lg_dword nParent; // 4 lg_float fPos[3]; //12 lg_float fRot[3]; //12 //Relevant size: 92 //The following info is not currently //stored in the file format: ML_MAT matLocal; ML_MAT matFinal; lg_dword nJointRef; static const lg_dword SKEL_JOINT_SIZE_IN_FILE=92; }; struct SkelJointPos{ lg_float fPos[3]; lg_float fRot[3]; }; struct SkelAnim{ LMName szName; //Animation name. lg_dword nFirstFrame; //First frame of anim. lg_dword nNumFrames; //Number of frams in the anim. lg_dword nLoopingFrames; //Number of frames to loop (unused, may get dropped). lg_float fRate; //Recommended rate of animation. lg_dword nFlags; //flags for the animation. static const lg_dword ANIM_FLAG_DEFAULT=0x00000000; static const lg_dword ANIM_FLAG_LOOPBACK=0x00000001; //Means loop forward then backward. }; //The CLFrame class, stores information about the frames. class SkelFrame { public: lg_dword m_nNumJoints; SkelJointPos* LocalPos; ML_AABB aabbBox; ML_MAT* Local; ML_MAT* Final; public: SkelFrame(); SkelFrame(lg_dword nNumJoints); ~SkelFrame(); lg_bool Initialize(lg_dword nNumJoints); lg_dword GetNumJoints(); const ML_MAT* GetFinalMat(lg_dword nJoint); const ML_MAT* GetLocalMat(lg_dword nJoint); lg_bool SetFinalMat(lg_dword nJoint, ML_MAT* pM); lg_bool SetLocalMat(lg_dword nJoint, ML_MAT* pM); lg_bool SetLocalMat(lg_dword nJoint, float* position, float* rotation); }; public: friend class CLMAnim; public: CLSkel2(); ~CLSkel2(); virtual lg_bool Load(LMPath szFile)=0; virtual lg_bool Save(LMPath szFile)=0; virtual lg_void Unload(); lg_bool CalcExData(); lg_dword GetNumFrames(); lg_dword GetNumJoints(); lg_dword GetNumKeyFrames(); lg_dword GetNumAnims(); lg_dword GetParentBoneRef(lg_dword nBone); ML_MAT* GenerateJointTransform(ML_MAT* pOut, lg_dword nJoint, lg_dword nFrame1, lg_dword nFrame2, float t); ML_MAT* GenerateJointTransform(ML_MAT* pOut, lg_dword nJoint, lg_dword nFrame1, lg_dword nFrame2, float t, CLSkel2* pSkel2); ML_AABB* GenerateAABB(ML_AABB* pOut, lg_dword nFrame1, lg_dword nFrame2, lg_float t); const ML_MAT* GetBaseTransform(lg_dword nJoint); lg_dword GetFrameFromTime(lg_dword nAnim, lg_float fTime, lg_float* pFrameTime, lg_dword* pFrame2); const SkelAnim* GetAnim(lg_dword n); lg_bool IsLoaded(); const ml_aabb* GetMinsAndMaxes(ml_aabb* pBounds); protected: lg_bool AllocateMemory(); void DeallocateMemory(); lg_bool Serialize( lg_void* file, ReadWriteFn read_or_write, RW_MODE mode); protected: lg_dword m_nID; lg_dword m_nVersion; LMName m_szSkelName; lg_dword m_nNumJoints; lg_dword m_nNumKeyFrames; lg_dword m_nNumAnims; SkelJoint* m_pBaseSkeleton; SkelFrame* m_pFrames; SkelAnim* m_pAnims; public: static ML_MAT* EulerToMatrix(ML_MAT* pOut, float* pEuler); }; #endif __LM_SKEL_H__<file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/lv_tex.h /* lv_tex.h - Header for texture loading functions. */ #ifndef __LV_TEX_H__ #define __LV_TEX_H__ #include "common.h" #include <d3d9.h> #include "lv_init.h" #ifdef __cplusplus extern "C"{ #endif /*__cplusplus*/ L_bool Tex_Load( IDirect3DDevice9* lpDevice, L_lpstr szFilename, D3DPOOL Pool, L_dword dwTransparent, L_bool bForceNoMip, IDirect3DTexture9** lppTex); #define TEXLOAD_GENMIPMAP 0x00000001 #define TEXLOAD_HWMIPMAP 0x00000002 #define TEXLOAD_LINEARMIPFILTER 0x00000004 #define TEXLOAD_POINTMIPFILTER 0x00000000 #define TEXLOAD_FORCE16BIT 0x00000010 #define TEXLOAD_16BITALPHA 0x00000020 L_bool Tex_LoadIMG2( IDirect3DDevice9* lpDevice, L_lpstr szFilename, D3DPOOL Pool, L_dword Flags, L_dword SizeLimit, IDirect3DTexture9** lppTex); #define SYSTOVID_AUTOGENMIPMAP 0x00000001 #define SYSTOVID_POINTMIPFILTER 0x00000000 #define SYSTOVID_LINEARMIPFILTER 0x00000002 L_bool Tex_SysToVid( IDirect3DDevice9* lpDevice, IDirect3DTexture9** lppTex, L_dword Flags); L_bool Tex_CanAutoGenMipMap(IDirect3DDevice9* lpDevice, D3DFORMAT Format); #ifdef __cplusplus } #endif /*__cplusplus*/ #endif /*__LV_TEX_H__*/<file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/lg_math/lg_math.h /* lm_math.h - Header for the mathmetical functions for Legacy 3D game engine. Copyright (c) 2006, <NAME>. */ #ifndef __LM_MATH_H__ #define __LM_MATH_H__ #include "common.h" #ifdef __cplusplus extern "C"{ #endif __cplusplus /************************************* Structures for the math functions. *************************************/ typedef struct _L_matrix{ float _11, _12, _13, _14; float _21, _22, _23, _24; float _31, _32, _33, _34; float _41, _42, _43, _44; }L_matrix, L_mat; typedef struct _L_vector2{ float x; float y; }L_vector2, L_vec2; typedef struct _L_vector3{ float x; float y; float z; }L_vector3, L_vec3; typedef struct _L_vector4{ float x; float y; float z; float w; }L_vector4, L_vec4; /*********************** L_vector2 functions. ***********************/ /*********************** L_vector3 functions. ***********************/ L_vector3* __cdecl L_vec3add(L_vector3* pOut, const L_vector3* pV1, const L_vector3* pV2); L_vector3* __cdecl L_vec3cross(L_vector3* pOut, const L_vector3* pV1, const L_vector3* pV2); float __cdecl L_vec3dot(const L_vector3* pV1, const L_vector3* pV2); float __cdecl L_vec3length(const L_vector3* pV); #define L_vec3magnitude L_vec3length L_vector3* __cdecl L_vec3normalize(L_vector3* pOut, const L_vector3* pV); L_vector3* __cdecl L_vec3scale(L_vector3* pOut, const L_vector3* pV, float s); L_vector3* __cdecl L_vec3subtract(L_vector3* pOut, const L_vector3* pV1, const L_vector3* pV2); //L_vector4* __cdecl L_vec3transform(L_vector4* pOut, const L_vector3* pV, const L_matrix* pM); //L_vector3* __cdecl L_vec3transformcoord(L_vector3* pOut, const L_vector3* pV, const L_matrix* pM); //L_vector3* __cdecl L_vec3transformnormal(L_vector3* pOut, const L_vector3* pV, const L_matrix* pM); float __cdecl L_vec3distance(const L_vector3* PV1, const L_vector3* pV2); float __cdecl L_vec3distance_C(const L_vector3* pV1, const L_vector3* pV2); /*********************** L_vector4 functions. ***********************/ /******************** Matrix functions. ********************/ L_matrix* __cdecl L_matident(L_matrix* pOut); /* Create an identity matrix. */ L_matrix* __cdecl L_matmultiply(L_matrix* pOut, const L_matrix* pM1, const L_matrix* pM2); /* Multiply (pM1 X pM2). */ L_matrix* __cdecl L_matmultiply_C(L_matrix* pOut, const L_matrix* pM1, const L_matrix* pM2); /* Same as above. */ /****************** Misc functions. ******************/ L_dword __cdecl L_nextpow2(const L_dword n); /* Find the next highest power of 2. */ L_dword __cdecl L_nextpow2_C(const L_dword n); /* C Version. */ L_dword __cdecl L_pow2(const L_byte n); /* Find (2^n). */ #ifdef __cplusplus } #endif __cplusplus #endif /*__LM_MATH_H__*/<file_sep>/tools/CornerBin/CornerBin/CornerBin.h // CornerBin.h : main header file for the CornerBin application // #pragma once #ifndef __AFXWIN_H__ #error "include 'stdafx.h' before including this file for PCH" #endif #include "resource.h" // main symbols #include "cbsettings.h" #include "cbtrayicon.h" // CCornerBinApp: // See CornerBin.cpp for the implementation of this class // class CCornerBinApp : public CWinApp { public: CCornerBinApp(); // Overrides public: virtual BOOL InitInstance(); virtual int ExitInstance(); // Implementation public: afx_msg void OnAppAbout(); DECLARE_MESSAGE_MAP() afx_msg void OnOpenSettings(); afx_msg void OnOpenRB(); afx_msg void OnEmptyRB(); private: CCBSettings m_Settings; CCBTrayIcon m_CBTrayIcon; public: void OnDblClkTrayIcon(void); void OnTimerUpdate(void); void OpenSettingsDlg(void); private: // This mutex keeps track if the application is running, so that two copies are not run simoltaneously. HANDLE m_hMutex; }; extern CCornerBinApp theApp; <file_sep>/games/Legacy-Engine/Source/lm_sys/lm_mesh.h #ifndef __LM_MESH_H__ #define __LM_MESH_H__ #include "lm_base.h" class CLMesh2: public CLMBase { friend class CLSkin; //Internally used constants: public: static const lg_dword LM_MESH_ID=0x48534D4C;//(*(lg_dword*)"LMSH"); static const lg_dword LM_MESH_VER=(122);//Final version will be 200. //Internally used classes and structs: public: //MeshVertex is the type of vertexes that make up //the mesh. It is designed to be direct3D compatible //but should be OpenGL compatible as well. struct MeshVertex{ lg_float x, y, z; //Vertex Coordinates. lg_float nx, ny, nz; //Vertex Normals. lg_float tu, tv; //Texture Coordinates. }; //SubMesh is a smaller mesh within the entire mesh, //submeshes are used for different parts of the mesh //that use different materials, typically you want as //few as possible, because they are rendered separately. struct SubMesh{ LMName szName; //Name of the submesh. lg_dword nFirstIndex; //Index of the first vertex in the mesh. lg_dword nNumTri; //Number of triangles in the mesh. lg_dword nMtrIndex; //Index of the mesh's material. }; //MeshMtr is the structure that stores information about //the texture, not that this is only default information //as typically a mesh gets it's texture from a skin. struct MeshMtr{ LMName szName; //Name of the material. LMPath szFile; //Filename of material (relative to the mesh); }; //The actual model format: //The model format in the file is pretty much exactly //as it is seen here, the header is first, followed by //the data (the size of which can be calculated using //the information in the header). protected: //File Format Start: lg_dword m_nID; lg_dword m_nVer; LMName m_szMeshName; lg_dword m_nNumVerts; lg_dword m_nNumTris; lg_dword m_nNumSubMesh; lg_dword m_nNumMtrs; lg_dword m_nNumBones; MeshVertex* m_pVerts; lg_word* m_pIndexes; //Should be sized 3*m_nNumTriangles*sizeof(lg_word) in size; lg_dword* m_pVertBoneList; LMName* m_pBoneNameList; SubMesh* m_pSubMesh; MeshMtr* m_pMtrs; ml_aabb m_AABB; //The bounding box for the static mesh (note that skeletal bounding boxes are used for animated objects). //File Format End. //Additional information that is stored: lg_byte* m_pMem; //The memory allocation chunk. LMPath m_szModelPath; //Stores the model path information. public: CLMesh2(); ~CLMesh2(); public: virtual lg_bool Load(LMPath szFile)=0; virtual lg_bool Save(LMPath szFile)=0; virtual lg_void Unload(); protected: lg_bool AllocateMemory(); lg_void DeallocateMemory(); virtual lg_bool Serialize( lg_void* file, ReadWriteFn read_or_write, RW_MODE mode); }; #endif __LM_MESH_H__<file_sep>/tools/fs_sys2/readme.txt fs_sys2 - A video game file system. This was originally developed for the Legacy engine. It is currently used by Beem Media for the Emergence Engine (which is closed source at this time). This source code doesn't include any project as it's meant to be directly linked to the project being used. (c) 2016 Beem Media<file_sep>/games/Legacy-Engine/Scrapped/old/lv_test.h #ifndef __LV_TEST_H__ #define __LV_TEST_H__ #include <d3d9.h> #include "common.h" #include "lg_meshmgr.h" #include "lv_img2d.h" #include "le_test.h" #include "le_camera.h" #include "lv_skybox.h" #include "lw_map.h" class CLVTObj { private: IDirect3DDevice9* m_pDevice; CLImg2D m_Img; CLCamera m_Camera; CLSkybox2 m_SkyBox; CLWorldMap m_World; lg_dword m_nNumEnts; CLBase3DEntity* m_pEnts[3]; public: CLVTObj():m_pDevice(LG_NULL){} void Init(IDirect3DDevice9* pDevice, void* pGame); void UnInit(); void Render(); void ValidateInvalidate(lg_bool bValidate); //void ValidateTestWall(); void RenderMeshes(); //void RenderTestWall(); }; #endif __LV_TEST_H__<file_sep>/games/Explor2002/Source_Old/ExplorED DOS/borland/Wxplored.h /* wxplored.h - Header for WinExplorED */ BOOL RegisterWindowClass(void); LRESULT MainWindowProc(HWND hWnd, unsigned msg, WORD wParam, LONG lParam); void MainWindowPaint(HWND hWnd, HDC hDc); BOOL MainCommandProc(HWND hMainWnd, WORD wCommand, WORD wNotify, HWND hControl); int GetOpenFileName(HWND hWnd, char *filename); int GetSaveFileName(HWND hWnd, char *filename);<file_sep>/games/Legacy-Engine/Source/engine/lp_sys2.h /* lp_phys2.h - Physics egine base class. Copyright (c) 2007 <NAME> */ #ifndef __LP_SYS2_H__ #define __LP_SYS2_H__ #include "common.h" #include "ML_lib.h" /* This is just a list of supposedly available physics engines. */ typedef enum _PHYS_ENGINE{ PHYS_ENGINE_NULL=0, PHYS_ENGINE_LEGACY, PHYS_ENGINE_NEWTON, #if 0 PHYS_ENGINE_PHYSX #endif }PHYS_ENGINE; typedef enum _PHYS_SHAPE{ PHYS_SHAPE_UNKNOWN=0, PHYS_SHAPE_BOX, PHYS_SHAPE_CAPSULE, PHYS_SHAPE_SPHERE, PHYS_SHAPE_CYLINDER }PHYS_SHAPE; typedef struct _lp_body_info{ ML_MAT m_matPos; ML_AABB m_aabbBody; lg_float m_fMass; lg_float m_fMassCenter[3]; lg_float m_fShapeOffset[3]; PHYS_SHAPE m_nShape; //Flags gotten from the AI routine. lg_dword m_nAIPhysFlags; }lp_body_info; class CLPhys{ //Some Global variables: protected: static const ML_VEC3 s_v3StdFace[3]; //Standard face vectors (see declaration). static const ML_VEC3 s_v3Zero; //Zero vector //Methods that need to be overriddent: public: virtual void Init(lg_dword nMaxBodies)=0; virtual void Shutdown()=0; virtual lg_void* AddBody(lg_void* pEnt, lp_body_info* pInfo)=0; virtual void RemoveBody(lg_void* pBody)=0; virtual void SetupWorld(lg_void* pWorldMap)=0; virtual void SetGravity(ML_VEC3* pGrav)=0; virtual void Simulate(lg_float fTimeStepSec)=0; virtual void SetBodyFlag(lg_void* pBody, lg_dword nFlagID, lg_dword nValue)=0; virtual void SetBodyVector(lg_void* pBody, lg_dword nVecID, ML_VEC3* pVec)=0; virtual void SetBodyFloat(lg_void* pBody, lg_dword nFloatID, lg_float fValue)=0; virtual void SetBodyPosition(lg_void* pBody, ML_MAT* pMat)=0; virtual lg_void* GetBodySaveInfo(lg_void* pBody, lg_dword* pSize)=0; virtual lg_void* LoadBodySaveInfo(lg_void* pData, lg_dword nSize)=0; }; #endif __LP_SYS2_H__<file_sep>/games/Legacy-Engine/Source/engine/lw_ai.cpp #include "lw_ai.h" #include <string.h> #include "lg_err.h" // Hack #include "../game/test_game_main.cpp" #include "../game/lw_ai_test.cpp" CLWAIMgr::CLWAIMgr() : m_hDllFile(LG_NULL) { } CLWAIMgr::~CLWAIMgr() { #if 0 if(m_hDllFile) { FreeLibrary(m_hDllFile); m_hDllFile=LG_NULL; } #endif } void CLWAIMgr::LoadAI(lg_path szFilename) { CloseAI(); Err_Printf("= AI script: %s. =", szFilename); Err_IncTab(); #if 0 m_hDllFile=LoadLibraryEx(szFilename, LG_NULL, 0); if(!m_hDllFile) { Err_Printf("Could not load the specified game file."); CloseAI(); } //Setup all the methods: LWAI_OBTAIN_FUNC(Game_Init); LWAI_OBTAIN_FUNC(Game_ObtainAI); LWAI_OBTAIN_FUNC(Game_UpdateGlobals); #endif Game_Init = TestGame_Game_Init; Game_ObtainAI = TestGame_Game_ObtainAI; Game_UpdateGlobals = TestGame_Game_UpdateGlobals; Game_Init(); Err_DecTab(); Err_Printf("="); } void CLWAIMgr::CloseAI() { #if 0 if(m_hDllFile) { FreeLibrary(m_hDllFile); m_hDllFile=LG_NULL; } #endif Game_ObtainAI=DEF_Game_ObtainAI; } void CLWAIMgr::SetGlobals(const GAME_AI_GLOBALS* pGlobals) { Game_UpdateGlobals(pGlobals); } CLWAIBase* CLWAIMgr::GetAI(lg_cstr szName) { CLWAIBase* pOut=Game_ObtainAI(szName); if(!pOut) pOut=&s_DefaultAI; return pOut; } CLWAIDefault CLWAIMgr::s_DefaultAI; void GAME_FUNC CLWAIMgr::DEF_Game_Init() { } void GAME_FUNC CLWAIMgr::DEF_Game_UpdateGlobals(const GAME_AI_GLOBALS* pIn) { } CLWAIBase* GAME_FUNC CLWAIMgr::DEF_Game_ObtainAI(lg_cstr szName) { return &s_DefaultAI; } /*************************** *** The Default AI class *** ***************************/ void CLWAIDefault::Init(LEntitySrv *pEnt) { } void CLWAIDefault::PrePhys(LEntitySrv *pEnt) { } void CLWAIDefault::PostPhys(LEntitySrv *pEnt) { } lg_dword CLWAIDefault::PhysFlags() { return 0; }<file_sep>/games/Legacy-Engine/Scrapped/libs/ML_lib2008April/ML_lib.h /* ML_lib.h - Header LM_lib math library. Copyright (c) 2006, <NAME>. With code by: <NAME>, 2005 (<EMAIL>) Under LGPL License */ #ifndef __ML_LIB_H__ #define __ML_LIB_H__ #ifdef __cplusplus extern "C"{ #endif __cplusplus #ifdef ML_LIB_BYTEPACK #include <pshpack1.h> #endif ML_LIB_BYTEPACK /* Some types that we will use.*/ typedef unsigned char ml_byte; typedef signed char ml_sbyte; typedef unsigned short ml_word; typedef signed short ml_short; typedef unsigned long ml_dword; typedef signed long ml_long; typedef int ml_bool; typedef unsigned int ml_uint; typedef signed int ml_int; typedef void ml_void; typedef float ml_float; /* A few definitions. */ #define ML_TRUE (1) #define ML_FALSE (0) #define MLG_Max(v1, v2) ((v1)>(v2))?(v1):(v2) #define MLG_Min(v1, v2) ((v1)<(v2))?(v1):(v2) #define MLG_Clamp(v1, min, max) ( (v1)>(max)?(max):(v1)<(min)?(min):(v1) ) #define ML_FUNC __cdecl /**************************************** Some constants for the math library. ****************************************/ #define ML_PI ((float)3.141592654f) #define ML_2PI ((float)3.141592654f*2.0f) #define ML_HALFPI ((float)3.141592654f*0.5f) /************************************* Structures for the math functions. *************************************/ typedef struct _ML_MATRIX{ float _11, _12, _13, _14; float _21, _22, _23, _24; float _31, _32, _33, _34; float _41, _42, _43, _44; }ML_MATRIX, ML_MAT; typedef struct _ML_QUATERNION{ float x, y, z, w; }ML_QUATERNION, ML_QUAT; typedef struct _ML_VECTOR2{ float x, y; }ML_VECTOR2, ML_VEC2; typedef struct _ML_VECTOR3{ float x, y, z; }ML_VECTOR3, ML_VEC3; typedef struct _ML_VECTOR4{ float x, y, z, w; }LML_VECTOR4, ML_VEC4; typedef struct _ML_PLANE{ float a, b, c, d; }ML_PLANE; typedef struct _ML_AABB{ ML_VEC3 v3Min; ML_VEC3 v3Max; }ML_AABB; /*********************** ML_vector2 functions. ***********************/ /*********************** ML_VEC3 functions. ***********************/ ML_VEC3* ML_FUNC ML_Vec3Add(ML_VEC3* pOut, const ML_VEC3* pV1, const ML_VEC3* pV2); ML_VEC3* ML_FUNC ML_Vec3Cross(ML_VEC3* pOut, const ML_VEC3* pV1, const ML_VEC3* pV2); float ML_FUNC ML_Vec3Dot(const ML_VEC3* pV1, const ML_VEC3* pV2); float ML_FUNC ML_Vec3Length(const ML_VEC3* pV); float ML_FUNC ML_Vec3LengthSq(const ML_VEC3* pV); #define ML_Vec3Magnitude ML_Vec3Magnitude ML_VEC3* ML_FUNC ML_Vec3Normalize(ML_VEC3* pOut, const ML_VEC3* pV); ML_VEC3* ML_FUNC ML_Vec3Scale(ML_VEC3* pOut, const ML_VEC3* pV, float s); ML_VEC3* ML_FUNC ML_Vec3Subtract(ML_VEC3* pOut, const ML_VEC3* pV1, const ML_VEC3* pV2); ML_VEC4* ML_FUNC ML_Vec3Transform(ML_VEC4* pOut, const ML_VEC3* pV, const ML_MAT* pM); ML_VEC4* ML_FUNC ML_Vec3TransformArray( ML_VEC4* pOut, ml_uint nOutStride, const ML_VEC3* pV, ml_uint nInStride, const ML_MAT* pM, ml_uint nNum); ML_VEC3* ML_FUNC ML_Vec3TransformCoord(ML_VEC3* pOut, const ML_VEC3* pV, const ML_MAT* pM); ML_VEC3* ML_FUNC ML_Vec3TransformCoordArray( ML_VEC3* pOut, ml_uint nOutStride, const ML_VEC3* pV, ml_uint nInStride, const ML_MAT* pM, ml_uint nNum); ML_VEC3* ML_FUNC ML_Vec3TransformNormal(ML_VEC3* pOut, const ML_VEC3* pV, const ML_MAT* pM); ML_VEC3* ML_FUNC ML_Vec3TransformNormalArray( ML_VEC3* pOut, ml_uint nOutStride, const ML_VEC3* pV, ml_uint nInStride, const ML_MAT* pM, ml_uint nNum); float ML_FUNC ML_Vec3Distance(const ML_VEC3* pV1, const ML_VEC3* pV2); /*********************** ML_vector4 functions. ***********************/ /********************** ML_PLANE functions **********************/ ml_float ML_FUNC ML_PlaneDotCoord(const ML_PLANE* pPlane, const ML_VEC3* pV); ML_PLANE* ML_FUNC ML_PlaneScale(ML_PLANE* pOut, const ML_PLANE* pPlane, ml_float s); /******************** Matrix functions. ********************/ ML_MAT* ML_FUNC ML_MatIdentity(ML_MAT* pOut); ML_MAT* ML_FUNC ML_MatMultiply(ML_MAT* pOut, const ML_MAT* pM1, const ML_MAT* pM2); ML_MAT* ML_FUNC ML_MatRotationX(ML_MAT* pOut, float fAngle); ML_MAT* ML_FUNC ML_MatRotationY(ML_MAT* pOut, float fAngle); ML_MAT* ML_FUNC ML_MatRotationZ(ML_MAT* pOut, float fAngle); ML_MAT* ML_FUNC ML_MatRotationAxis(ML_MAT* pOut, const ML_VEC3* pAxis, float fAngle); ML_MAT* ML_FUNC ML_MatRotationYawPitchRoll(ML_MAT* pOut, float Yaw, float Pitch, float Roll); ML_MAT* ML_FUNC ML_MatScaling(ML_MAT* pOut, float sx, float sy, float sz); ML_MAT* ML_FUNC ML_MatPerspectiveFovLH(ML_MAT* pOut, float fovy, float Aspect, float zn, float zf); ML_MAT* ML_FUNC ML_MatLookAtLH(ML_MAT* pOut, const ML_VEC3* pEye, const ML_VEC3* pAt, const ML_VEC3* pUp); ML_MAT* ML_FUNC ML_MatRotationQuat(ML_MAT* pOut, const ML_QUAT* pQ); ML_MAT* ML_FUNC ML_MatSlerp(ML_MAT* pOut, ML_MAT* pM1, ML_MAT* pM2, float t); float ML_FUNC ML_MatDeterminant(ML_MAT* pM); ML_MAT* ML_FUNC ML_MatInverse(ML_MAT* pOut, float* pDet, ML_MAT* pM); ML_MAT* ML_FUNC ML_MatInverse_SSE(ML_MAT* pOut, float* pDet, ML_MAT* pM); /************************* Quaternion functions. *************************/ ML_QUAT* ML_FUNC ML_QuatRotationMat(ML_QUAT* pOut, const ML_MAT* pM); ML_QUAT* ML_FUNC ML_QuatSlerp(ML_QUAT* pOut, const ML_QUAT* pQ1, const ML_QUAT* pQ2, float t); /******************* AABB functions. *******************/ typedef enum _ML_AABB_CORNER{ ML_AABB_BLF=0x00, /* Botton Left Front */ ML_AABB_BRF=0x01, /* Bottom Right Front */ ML_AABB_TLF=0x02, /* Top Left Front */ ML_AABB_TRF=0x03, /* Top Right Front */ ML_AABB_BLB=0x04, /* Bottom Left Back */ ML_AABB_BRB=0x05, /* Bottom Right Back */ ML_AABB_TLB=0x06, /* Top Left Back */ ML_AABB_TRB=0x07 /* Top Right Back */ }ML_AABB_CORNER; ML_VEC3* ML_FUNC ML_AABBCorner(ML_VEC3* pV, const ML_AABB* pAABB, const ML_AABB_CORNER ref); ML_AABB* ML_FUNC ML_AABBTransform(ML_AABB* pOut, const ML_AABB* pAABB, const ML_MAT* pM); ML_AABB* ML_FUNC ML_AABBFromVec3s(ML_AABB* pOut, const ML_VEC3* pVList, const ml_dword nNumVecs); ml_bool ML_FUNC ML_AABBIntersect(const ML_AABB* pBox1, const ML_AABB* pBox2, ML_AABB* pIntersect); float ML_FUNC ML_AABBIntersectMoving(const ML_AABB* pBoxMove, const ML_AABB* pBoxStat, const ML_VEC3* pVel); ML_AABB* ML_FUNC ML_AABBCatenate(ML_AABB* pOut, const ML_AABB* pBox1, const ML_AABB* pBox2); ML_AABB* ML_FUNC ML_AABBAddPoint(ML_AABB* pOut, const ML_AABB* pBox, const ML_VEC3* pVec); #define ML_INTERSECT_ONPOS 0x00000000 #define ML_INTERSECT_ONNEG 0x00000001 #define ML_INTERSECT_CUR 0x00000002 #define ML_INTERSECT_HITPOS 0x00000003 #define ML_INTERSECT_HITNEG 0x00000004 ml_bool ML_FUNC ML_AABBIntersectBlock(ML_AABB* pAABB, ML_PLANE* pPlanes, ml_dword nPlaneCount); ml_dword ML_FUNC ML_AABBIntersectPlane(const ML_AABB* pAABB, const ML_PLANE* pPlane); ml_float ML_FUNC ML_AABBIntersectPlaneVel(const ML_AABB* pAABB, const ML_PLANE* pPlane, const ML_VEC3* pVel); ml_dword ML_FUNC ML_AABBIntersectPlaneVelType(const ML_AABB* pAABB, const ML_PLANE* pPlane, const ML_VEC3* pVel, ml_float* pTime); ML_PLANE* ML_FUNC ML_AABBToPlanes(ML_PLANE* pOut, ML_AABB* pAABB); /******************************** Instruction Set Determination ********************************/ /****************** Misc functions. ******************/ ml_dword ML_FUNC ML_NextPow2(const ml_dword n); // Find the next highest power of 2. ml_dword ML_FUNC ML_Pow2(const ml_byte n); // Find (2^n). float ML_FUNC ML_sqrtf(const float f); float ML_FUNC ML_cosf(const float f); float ML_FUNC ML_sinf(const float f); float ML_FUNC ML_tanf(const float f); float ML_FUNC ML_acosf(const float f); float ML_FUNC ML_asinf(const float f); float ML_FUNC ML_sincosf(const float f, float *cos); ml_long ML_FUNC ML_absl(ml_long l); ml_float ML_FUNC ML_absf(ml_float f); /****************************** Instruction set functions. ******************************/ typedef enum _ML_INSTR{ ML_INSTR_F= 0x00000000, ML_INSTR_MMX= 0x00000001, ML_INSTR_SSE= 0x00000002, ML_INSTR_SSE2= 0x00000003, ML_INSTR_SSE3= 0x00000004, ML_INSTR_AMDMMX=0x00000005, ML_INSTR_3DNOW= 0x00000006, ML_INSTR_3DNOW2=0x00000007 }ML_INSTR; ml_bool ML_SetSIMDSupport(ML_INSTR nInstr); ML_INSTR ML_FUNC ML_SetBestSIMDSupport(); #ifdef ML_LIB_BYTEPACK #include <poppack.h> #endif ML_LIB_BYTEPACK #ifdef __cplusplus } #endif __cplusplus #endif /*__ML_LIB_H__*/<file_sep>/games/Legacy-Engine/Source/engine/lg_sys_init.cpp #include <stdio.h> #include "lg_cmd.h" #include "lg_sys.h" #include "lg_err.h" #include "lf_sys2.h" #include "lg_cvars.h" #include "lg_err_ex.h" #include "lg_malloc.h" #include "lg_func.h" #include "../lc_sys2/lc_sys2.h" /********************************************************************* LG_GameInit() Initializes various game things, including the console, cvarlist, graphics, and audio. *********************************************************************/ lg_bool CLGame::LG_GameInit(lg_pstr szGameDir, HWND hwnd) { lg_long nResult=0; /* Attach the window to the game. */ m_hwnd=hwnd; /******************************** Initialzie the math library ********************************/ ML_Init(ML_INSTR_BEST); /************************** Initialize the console. *************************/ /* Create the console, if we fail to create the console, the who program isn't going to function correctly. Pretty much the only reason the console wouldn't start is if the user was out of memory, which means the program wouldn't work anyway. We also need the cvarlist to get created for the game to work.*/ if(!LC_Init()) throw CLError(LG_ERR_DEFAULT, __FILE__, __LINE__, "LG: Could not initialize conosle."); LC_SetCommandFunc(LCG_ConCommand, this); Err_Printf("=== Initializing Legacy Game ==="); Err_IncTab(); Err_PrintVersion(); //Err_Printf("Created console at 0x%08X.", s_console); /************************* Initialzie the timer. *************************/ Err_Printf("Initializing timer..."); s_Timer.Initialize(); /******************************* Initialze the file system. ******************************/ /* We need to set the directory to the game data directory. By default this is [legacy3ddirectory]\base, but we want to make it so that the user can change this to run custom games for example*/ Err_Printf("Initializing File System..."); FS_Initialize(1024*5, LG_Malloc, LG_Free); LF_SetErrLevel(ERR_LEVEL_NOTICE); LF_SetErrPrintFn((LF_ERR_CALLBACK)Err_FSCallback); //Mount the base file system. FS_MountBase(szGameDir); //The mounted path /dbase represents the "default" base, //any mods should be mounted to /gbase for "game" base. //#define DBASE_PATH "base" #define DBASE_PATH "baseuncmp" FS_Mount(DBASE_PATH, "/dbase", MOUNT_FILE_OVERWRITE|MOUNT_MOUNT_SUBDIRS); //Expand all the lpk files in the default directory. //In theory we could search for all lpk files, but this //way it insures that lpk files get mounted in the correct //order, note that higher numbered lpks //will overwrite any files with the same name in lower numbered //lpks. for(lg_word i=0; i<99; i++) { lf_path szPakFile; sprintf(szPakFile, "/dbase/pak%u.lpk", i); if(!FS_MountLPK(szPakFile, MOUNT_FILE_OVERWRITELPKONLY)) break; } /************************** Create the cvarlist. **************************/ /* We create the cvarlist, attach it to the console, so the console can use the built in functions with it we register all the commands for the console, and we register all the cvars for teh game, and then we set the cvars by attempting to load config.cfg as well as autoexec.cfg. Note that any cvars that will be saved will be written to config.cfg, any cvars that the user wants to manipulate and save that aren't saved should be written in autoexec.cfg (for example v_VideoHint is not saved, but if the user wanted to set this variable to true, he should put SET v_VideoHint "TRUE" in the autoexec.cfg file.*/ /* Register the console commands for Legacy 3D. */ LGC_RegConCmds(); /* Register the cvars for the game. */ LG_RegisterCVars(); /* Now load all the presets. */ //Should load these from the main game base... LC_SendCommand("loadcfg \"/dbase/config.cfg\""); LC_SendCommand("loadcfg \"/dbase/autoexec.cfg\""); /************************* Initialize the video. **************************/ Err_Printf("Calling LV_Init..."); if(!m_Video.Init(m_hwnd)) { Err_Printf("LV_Init failed with result 0x%08X.", nResult); LC_SendCommand("condump \"/dbase/debug.txt\""); /*Destroy everything we've created so far. */ //CVar_DeleteList(s_cvars); //s_cvars=LG_NULL; LC_Shutdown(); //s_console=LG_NULL; m_nGameState=LGSTATE_SHUTDOWN; return LG_FALSE; } else Err_Printf("LV_Init succeeded."); #if 0 Err_Printf("Initializing texture manager..."); //Should get maximum textures from a cvar. m_pTMgr=new CLTMgr(s_pDevice, CV_Get(CVAR_lg_MaxTex)->nValue); m_pFxMgr=new CLFxMgr(s_pDevice, CV_Get(CVAR_lg_MaxFx)->nValue); m_pMtrMgr=new CLMtrMgr(CV_Get(CVAR_lg_MaxMtr)->nValue); #endif InitMgrs(s_pDevice); /******** Initialize Game Windowing System *********/ Err_Printf("=== Initialzing Windowing System ==="); m_WndMgr.Init(); Err_Printf("===================================="); //Once the video is initialized, we can initalize the graphical console. Err_Printf("Initializing console graphical interface..."); if(!m_VCon.Create(s_pDevice)) { //If the creation of the graphical console fails, the game can still run, //but any calls to m_VCon methods will not do anything. Err_Printf("Graphical console creation failed, feature not available."); } /************************* Initialize the sound. **************************/ Err_Printf("=== Audio System Initialization ==="); Err_Printf("Calling LS_Init..."); if(!m_SndMgr.LS_Init()) { /* If the sound isn't initialized we just display an error message, as the game can still run without sound. */ Err_Printf("LS_Init failed with, audio not available."); } else Err_Printf("LS_Init succeeded."); Err_Printf("==================================="); #if 0 //Begin initializing game structures. Err_Printf("Initializing the mesh & skeleton manager..."); m_pMMgr=new CLMMgr(s_pDevice, CV_Get(CVAR_lg_MaxMeshes)->nValue, CV_Get(CVAR_lg_MaxSkels)->nValue); #endif /*********************** Initialize input. ***********************/ Err_Printf("Calling LI_Init..."); lg_dword nFlags=0; if(CV_Get(CVAR_li_ExclusiveKB)->nValue) nFlags|=LINPUT_EXCLUSIVEKB; if(CV_Get(CVAR_li_ExclusiveMouse)->nValue) nFlags|=LINPUT_EXCLUSIVEMOUSE; if(CV_Get(CVAR_li_DisableWinKey)->nValue) nFlags|=LINPUT_DISABLEWINKEY; if(CV_Get(CVAR_li_MouseSmoothing)->nValue) nFlags|=LINPUT_SMOOTHMOUSE; if(!m_Input.LI_Init(m_hwnd, nFlags, CON_KEYDX)) { Err_Printf("LI_Init failed, input not available."); } else Err_Printf("LI_Init succeeded"); /***************************** Initialize the game world ******************************/ Err_Printf("=== Initializing Game World ==="); Err_IncTab(); m_WorldSrv.Init(); m_WorldCln.Init(&m_Input); #if 1 /* Some test stuff */ //m_WorldSrv.LoadLevel("/dbase/scripts/levels/very_simple.xml"); m_WorldSrv.LoadLevel("/dbase/scripts/levels/primitive_test.xml"); m_WorldCln.ConnectLocal(&m_WorldSrv); //m_WorldSrv.RemoveEnt(9999); lg_str szTestSound="InTown.ogg"; LC_SendCommandf("MUSIC_START \"%s\"", szTestSound); #elif 0 m_WorldSrv.LoadMap("/dbase/maps/lame_level.3dw"); m_WorldCln.ConnectLocal(&m_WorldSrv); #endif Err_DecTab(); Err_Printf("==============================="); m_nGameState=LGSTATE_RUNNING; Err_DecTab(); Err_Printf("================================"); return LG_TRUE; } /*************************************************************** LG_GameShutdown() Shuts down and deletes everything created in LG_GameInit(). ***************************************************************/ void CLGame::LG_GameShutdown() { IDirect3D9* lpD3D=NULL; lg_int nResult=0; lg_ulong nNumLeft=0; lg_bool bDump=LG_FALSE; Err_Printf("Shutting down Legacy Engine."); Err_Printf("Shutting down the world..."); m_WorldCln.Disconnect(); m_WorldCln.Shutdown(); m_WorldSrv.Shutdown(); ShutdownMgrs(); Err_Printf("Shutting down input system..."); m_Input.LI_Shutdown(); Err_Printf("=== Audio System Shutdown ==="); Err_Printf("Calling LS_Shutdown..."); m_SndMgr.LS_Shutdown(); Err_Printf("============================="); /********************************* Raster object uninitalization. *********************************/ Err_Printf("Destroying graphic console..."); m_VCon.Delete(); s_pDevice->SetTexture(0, LG_NULL); s_pDevice->SetTexture(1, LG_NULL); Err_Printf("Destorying windowing system..."); m_WndMgr.Shutdown(); Err_Printf("Shutting down video processing..."); m_Video.Shutdown(); /* Dump the console, it should probably be determined by a cvar if the console should get dumped or not, but for now we always dump it. */ bDump=CV_Get(CVAR_lg_DumpDebugData)->nValue; /* Save the cvars that want to be saved. */ LC_SendCommand("savecfg \"/dbase/config.cfg\""); Err_Printf("Destroying console, goodbye!"); if(bDump) LC_SendCommand("condump \"/dbase/debug.txt\""); /* Destroy the file system. Any open files should be closed before this is called. Note that this must be done after the console is dump so that the data can be written.*/ Err_Printf("Shutting down the file system..."); FS_Shutdown(); LC_Shutdown(); /* Make sure there is no pointer in the error reporting. */ m_nGameState=LGSTATE_SHUTDOWN; } <file_sep>/tools/GFX/GFXG8/Direct3DImage.cpp #include <d3dx8.h> #include "GFXG8.h" CImage8::CImage8() { m_dwWidth=0; m_dwHeight=0; m_lpImage=NULL; } CImage8::~CImage8() { Release(); } DWORD CImage8::GetWidth() { return m_dwWidth; } DWORD CImage8::GetHeight() { return m_dwHeight; } HRESULT CImage8::CreateSurface( LPVOID lpDevice, D3DFORMAT Format, DWORD dwWidth, DWORD dwHeight) { if(lpDevice) return ((LPDIRECT3DDEVICE8)lpDevice)->CreateImageSurface( dwWidth, dwHeight, Format, &m_lpImage); else return E_FAIL; } HRESULT CImage8::LoadBitmapIntoSurfaceA( char szBitmapFileName[], DWORD x, DWORD y, DWORD nSrcWidth, DWORD nSrcHeight, DWORD nWidth, DWORD nHeight) { RECT rcSrc; //Prepare the source rectangle. rcSrc.top=y; rcSrc.bottom=y+nSrcHeight; rcSrc.left=x; rcSrc.right=x+nSrcWidth; return D3DXLoadSurfaceFromFileA( m_lpImage, NULL, NULL, szBitmapFileName, &rcSrc, D3DX_DEFAULT, 0xFF000000L, NULL); } HRESULT CImage8::LoadBitmapIntoSurfaceW( WCHAR szBitmapFileName[], DWORD x, DWORD y, DWORD nSrcWidth, DWORD nSrcHeight, DWORD nWidth, DWORD nHeight) { RECT rcSrc; //Prepare the source rectangle. rcSrc.top=y; rcSrc.bottom=y+nSrcHeight; rcSrc.left=x; rcSrc.right=x+nSrcWidth; return D3DXLoadSurfaceFromFileW( m_lpImage, NULL, NULL, szBitmapFileName, &rcSrc, D3DX_DEFAULT, 0xFF000000L, NULL); } HRESULT CImage8::CreateImageBMA( char szBitmapFilename[], LPVOID lpDevice, D3DFORMAT Format, DWORD x, DWORD y, DWORD nSrcWidth, DWORD nSrcHeight, DWORD nWidth, DWORD nHeight) { if(FAILED(CreateSurface(lpDevice, Format, nWidth, nHeight))){ return E_FAIL; } if(FAILED(LoadBitmapIntoSurfaceA( szBitmapFilename, x, y, nSrcWidth, nSrcHeight, nWidth, nHeight))) { return E_FAIL; } m_dwWidth=nWidth; m_dwHeight=nHeight; return S_OK; } HRESULT CImage8::CreateImageBMW( WCHAR szBitmapFilename[], LPVOID lpDevice, D3DFORMAT Format, DWORD x, DWORD y, DWORD nSrcWidth, DWORD nSrcHeight, DWORD nWidth, DWORD nHeight) { if(FAILED(CreateSurface(lpDevice, Format, nWidth, nHeight))){ return E_FAIL; } if(FAILED(LoadBitmapIntoSurfaceW( szBitmapFilename, x, y, nSrcWidth, nSrcHeight, nWidth, nHeight))) { return E_FAIL; } m_dwWidth=nWidth; m_dwHeight=nHeight; return S_OK; } void CImage8::ClearSurface() { m_dwWidth=0; m_dwHeight=0; Release(); } void CImage8::Release() { if(m_lpImage){ m_lpImage->Release(); m_lpImage=NULL; } } HRESULT CImage8::DrawImage( LPVOID lpDevice, LPVOID lpBuffer, int x, int y) { RECT rcSrc; POINT pDest; //Prepare the source rectangle. rcSrc.top=rcSrc.left=0; rcSrc.bottom=m_dwHeight; rcSrc.right=m_dwWidth; //Prepare the destianion point. pDest.x=x; pDest.y=y; return CopySurfaceToSurface( (LPDIRECT3DDEVICE8)lpDevice, &rcSrc, m_lpImage, &pDest, (LPDIRECT3DSURFACE8)lpBuffer, TRUE, 0x00FF00FF); //return ((LPDIRECT3DDEVICE8)lpDevice)->CopyRects( // m_lpImage, // &rcSrc, // 1, // ((LPDIRECT3DSURFACE8)lpBuffer), // &pDest); } HRESULT CImage8::DrawClippedImage( LPVOID lpDevice, LPVOID lpBuffer, int x, int y) { if(!lpBuffer || !m_lpImage || !lpDevice)return E_FAIL; RECT rcSrc; POINT psDest; //we get a description for the buffer D3DSURFACE_DESC d3dsDesc; ((LPDIRECT3DSURFACE8)lpBuffer)->GetDesc(&d3dsDesc); //store buffer dimensions int nBufferWidth=d3dsDesc.Width; int nBufferHeight=d3dsDesc.Height; //if we don't need to clip we do a regular blt if( //withing the width (x>=0) && ((int)(m_dwWidth+x)<nBufferWidth) && //within the height (y>=0) && ((int)(m_dwHeight+y)<nBufferHeight) )return DrawImage(lpDevice, lpBuffer, x, y); //if the image is off screen we do no blt if(x>nBufferWidth)return S_FALSE; if(y>nBufferHeight)return S_FALSE; if((x+m_dwWidth)<=0)return S_FALSE; if((y+m_dwHeight)<=0)return S_FALSE; //if it has been determined that we need to do a clipped blt lets prepare the rectangles //prepare destination rectangle (with D3D we only determine x, y value if(x>=0) psDest.x=x; else psDest.x=0; if(y>=0) psDest.y=y; else psDest.y=0; //prepare src rectangle this algorithm is appropriate for the matter. if(x>=0) rcSrc.left=0; else rcSrc.left=0-x; if((int)(x+m_dwWidth)<nBufferWidth) rcSrc.right=m_dwWidth; else rcSrc.right=nBufferWidth-x; if(y>=0) rcSrc.top=0; else rcSrc.top=0-y; if((int)(y+m_dwHeight)<nBufferHeight) rcSrc.bottom=m_dwHeight; else rcSrc.bottom=nBufferHeight-y; //Copy the rects. return CopySurfaceToSurface( (LPDIRECT3DDEVICE8)lpDevice, &rcSrc, m_lpImage, &psDest, (LPDIRECT3DSURFACE8)lpBuffer, TRUE, 0x00FF00FF); } <file_sep>/games/Legacy-Engine/Source/engine/lw_client.cpp #include "lw_client.h" #include "lg_err.h" #include "lx_sys.h" #include "lg_func.h" #include "lc_sys2.h" #include "ld_sys.h" CLWorldClnt::CLWorldClnt(): m_Map(), m_nConnectType(CLNT_CONNECT_DISC), m_pEntList(LG_NULL), m_bRunning(LG_FALSE) { } CLWorldClnt::~CLWorldClnt() { //Technically we don't want to shut down here, but //just in case. //Shutdown(); } void CLWorldClnt::Init(CLInput* pInput) { Err_Printf("===Initializing Legacy World Client==="); Err_IncTab(); m_pInput=pInput; Err_DecTab(); Err_Printf("======================================"); } void CLWorldClnt::Shutdown() { Err_Printf("===Destroying Legacy World Client==="); Disconnect(); Err_Printf("===================================="); } lg_void CLWorldClnt::Broadcast() { } lg_void CLWorldClnt::Receive() { switch(m_nConnectType) { case CLNT_CONNECT_LOCAL: { //Interpret commands for the client: CLListStack* pCmds=&m_pSrvLocal->m_Clients[m_pSrvLocal->m_nClntRefs[this->m_nIDOnSrv]].m_CmdList; while(!pCmds->IsEmpty()) { CLWCmdItem* pCmd=(CLWCmdItem*)pCmds->Pop(); ProcessSrvCmd(pCmd); m_pSrvLocal->m_UnusedCmds.Push(pCmd); } break; } case CLNT_CONNECT_TCP: break; case CLNT_CONNECT_UDP: break; default: case CLNT_CONNECT_DISC: break; } } lg_void CLWorldClnt::ProcessSrvCmd(const CLWCmdItem* pCmd) { switch(pCmd->Command) { case STCC_ENT_DESTROY: STCC_ENT_DESTROY_INFO* pInfo=(STCC_ENT_DESTROY_INFO*)pCmd->Params; RemoveEnt(pInfo->nEntID); break; } } lg_void CLWorldClnt::RemoveEnt(const lg_dword nUEID) { DeleteRasterInfo(m_pEntList[nUEID].m_pRasterInfo); m_pEntList[nUEID].m_pRasterInfo=LG_NULL; m_EntsAll.Remove(&m_pEntList[nUEID]); } lg_void CLWorldClnt::Update() { if(m_nConnectType==CLNT_CONNECT_DISC) return; Receive(); for(LEntityClnt* pEnt = (LEntityClnt*)m_EntsAll.m_pFirst; pEnt; pEnt=(LEntityClnt*)pEnt->m_pNext) { pEnt->m_matPos=m_pSrvLocal->m_pEntList[pEnt->m_nUEID].m_matPos; pEnt->m_aabbBody=m_pSrvLocal->m_pEntList[pEnt->m_nUEID].m_aabbBody; pEnt->m_nAnimFlags1=m_pSrvLocal->m_pEntList[pEnt->m_nUEID].m_nAnimFlags1; pEnt->m_nAnimFlags2=m_pSrvLocal->m_pEntList[pEnt->m_nUEID].m_nAnimFlags2; pEnt->m_v3Vel=m_pSrvLocal->m_pEntList[pEnt->m_nUEID].m_v3Vel; memcpy(pEnt->m_v3Look, m_pSrvLocal->m_pEntList[pEnt->m_nUEID].m_v3Look, sizeof(ML_VEC3)*3); LEntRasterInfo* pRInfo=(LEntRasterInfo*)pEnt->m_pRasterInfo; pRInfo->m_MeshTree.SetAnimation(pEnt->m_nAnimFlags1); pRInfo->m_MeshTree.SetAnimation(pEnt->m_nAnimFlags2); } #if 1 LEntityClnt* pEnt=&m_pEntList[m_nPCEnt]; Err_MsgPrintf( "Ent %d: Pos: (%.3f, %.3f, %.3f) Vel: (%.3f, %.3f, %.3f)", pEnt->m_nUEID, pEnt->m_matPos._41, pEnt->m_matPos._42, pEnt->m_matPos._43, pEnt->m_v3Vel.x, pEnt->m_v3Vel.y, pEnt->m_v3Vel.z); #endif //Send information back to the server for the temp entity: This is only for testing, //in the future it will be sent in the appropriate method. LEntitySrv* pPCEnt=&m_pSrvLocal->m_pEntList[m_nPCEnt]; pPCEnt->m_nCmdsActive=m_pInput->m_nCmdsActive[0]; pPCEnt->m_nCmdsPressed=m_pInput->m_nCmdsPressed[0]; pPCEnt->m_fAxis[0]=m_pInput->m_fAxis[0]; pPCEnt->m_fAxis[1]=m_pInput->m_fAxis[1]; } lg_void CLWorldClnt::SetCamera(ML_MAT* pMat) { static ml_vec3 v3Eye, v3At, v3Up, v3Temp; static ml_mat matTemp; if(m_nConnectType==CLNT_CONNECT_DISC) return; LEntityClnt* pEnt=&m_pEntList[m_nPCEnt]; LEntRasterInfo* pRInfo=(LEntRasterInfo*)pEnt->m_pRasterInfo; pRInfo->m_MeshTree.GetAttachTransform(&matTemp, 1); ML_MatMultiply(&matTemp, &matTemp, &pEnt->m_matPos); v3Eye=*(ml_vec3*)&matTemp._41; ML_Vec3Add(&v3At, &pEnt->m_v3Look[0], &v3Eye); v3Up=*(ml_vec3*)&pEnt->m_v3Look[1]; #define FIRST_PERSON 0 #if !FIRST_PERSON ML_Vec3Subtract(&v3Temp, &v3At, &v3Eye); ML_Vec3Scale(&v3Temp, &v3Temp, 3.0f); ML_Vec3Subtract(&v3Eye, &v3At, &v3Temp); #endif !FIRST_PERSON ML_MatLookAtLH( pMat, &v3Eye, &v3At, &v3Up); #if 0 //ML_MAT matTemp; ML_VEC3 v3Look[4]; //Copy the position: memcpy(&v3Look[0], &pEnt->m_matPos._41, sizeof(v3Look[0])); v3Look[0].y+=1.0f; //Calculate the Look At (Just Translate it): ML_Vec3Add(&v3Look[1], &pEnt->m_v3Look[0], &v3Look[0]); //Copy in the up vector: memcpy(&v3Look[2], &pEnt->m_v3Look[1], sizeof(v3Look[2])); //If we want the camera away from the object we scale a bit: ML_Vec3Subtract(&v3Look[3], &v3Look[1], &v3Look[0]); ML_Vec3Scale(&v3Look[3], &v3Look[3], 5.0f); ML_Vec3Subtract(&v3Look[0], &v3Look[1], &v3Look[3]); ML_MatLookAtLH( pMat, &v3Look[0], //Eye &v3Look[1], //At &v3Look[2]); //Up #endif #if 0 v3Look[0].x=3.0f; v3Look[0].y=1.0f; v3Look[0].z=-1.0f; v3Look[1].x=0.0f; v3Look[1].y=1.0f; v3Look[1].z=-1.0f; v3Look[2].x=0.0f; v3Look[2].y=1.0f; v3Look[2].z=0.0f; ML_MatLookAtLH( pMat, &v3Look[0], //Eye &v3Look[1], //At &v3Look[2]); //Up #endif } /* PRE: IDirect3DDevice9::BeginScene() must be called. POST: All elements of the scene are rasterized. This includes the map and visible entities. */ lg_void CLWorldClnt::Render() { if(m_nConnectType==CLNT_CONNECT_DISC) return; /* #define TESTLIGHT #ifdef TESTLIGHT D3DLIGHT9 Light={ D3DLIGHT_DIRECTIONAL, //Type {1.0f, 1.0f, 1.0f, 0.0f},//Diffuse {0.0f, 0.0f, 0.0f, 0.0f},//Specular {0.75f, 0.5f, 0.25f, 0.0f},//Ambient {0.0f, 0.0f, 0.0f},//Position {-1.0f, -1.0f, 0.0f},//Direction 0.0f,//Range 0.0f,//Falloff 0.0f,//Attenuation0 0.0f,//Attenuation1 0.0f,//Attenuation2 0.0f,//Theta 0.0f};//Phi s_pDevice->SetLight(0, &Light); s_pDevice->LightEnable(0, TRUE); D3DMATERIAL9 mtrl; memset( &mtrl, 0, sizeof(mtrl) ); mtrl.Diffuse.r = mtrl.Ambient.r = 1.0f; mtrl.Diffuse.g = mtrl.Ambient.g = 1.0f; mtrl.Diffuse.b = mtrl.Ambient.b = 1.0f; mtrl.Diffuse.a = mtrl.Ambient.a = 1.0f; s_pDevice->SetMaterial(&mtrl); #else s_pDevice->SetRenderState(D3DRS_LIGHTING, LG_FALSE); #endif */ D3DXMATRIX matT; SetCamera((ML_MAT*)&matT); ML_MatIdentity((ML_MAT*)&matT); ML_MatPerspectiveFovLH((ML_MAT*)&matT, D3DX_PI*0.25f, 4.0f/3.0f, 0.1f, 100.0f); //matT._11=2.0f/1.0f; //matT._22=2.0f/1.0f; s_pDevice->SetTransform(D3DTS_PROJECTION, &matT); /* ML_VEC3 v3Pos={0.0f, 0.0f, 0.0f}; ML_VEC3 v3LookAt; ML_Vec3Subtract(&v3LookAt, &m_v3LookAt, &m_v3Pos); ML_MatLookAtLH( &m_matView, &v3Pos, &v3LookAt, &m_v3Up); */ matT._41=matT._42=matT._43=0; s_pDevice->SetTransform(D3DTS_VIEW, &matT); CLMeshLG::LM_SetSkyboxRenderStates(); m_Skybox.Render(); //s_pDevice->SetTransform(D3DTS_VIEW, (D3DMATRIX*)&m_matView); SetCamera((ML_MAT*)&matT); s_pDevice->SetTransform(D3DTS_VIEW, &matT); /* D3DVIEWPORT9 vp; D3DVIEWPORT9 vpOld; s_pDevice->GetViewport(&vpOld); vp.X=0; vp.Y=300; vp.Width=400; vp.Height=300; vp.MinZ=0.0f; vp.MaxZ=1.0f; s_pDevice->SetViewport(&vp); */ m_Map.Render(); /* vp.X=400; vp.Y=300; vp.Width=400; vp.Height=300; vp.MinZ=0.0f; vp.MaxZ=1.0f; s_pDevice->SetViewport(&vp); */ CLMeshLG::LM_SetRenderStates(); //Technically we should only render visible entities. for(LEntityClnt* pEnt = (LEntityClnt*)m_EntsAll.m_pFirst; pEnt; pEnt=(LEntityClnt*)pEnt->m_pNext) { LEntRasterInfo* pRInfo=(LEntRasterInfo*)pEnt->m_pRasterInfo; D3DXMATRIX matTemp=*(D3DXMATRIX*)&m_pSrvLocal->m_pEntList[pEnt->m_nUEID].m_matPos; pRInfo->m_MeshTree.Update(m_pSrvLocal->m_Timer.GetFElapsed()); pRInfo->m_MeshTree.Render((ML_MAT*)&matTemp); #if 0 //_DEBUG LD_DrawAABB(s_pDevice, &pEnt->m_aabbBody, 0xFF00FF00); #endif _DEBUG } #if 0 // _DEBUG lg_dword nDebugFlags=0; //LG_SetFlag(nDebugFlags, m_Map.MAPDEBUG_HULLTRI); LG_SetFlag(nDebugFlags, m_Map.MAPDEBUG_HULLAABB); LG_SetFlag(nDebugFlags, m_Map.MAPDEBUG_WORLDAABB); m_Map.RenderAABBs(nDebugFlags); #endif _DEBUG //s_pDevice->SetViewport(&vpOld); } /* PRE: pSrv is the local server. POST: The client is connected to the server, and ready for updating. If a connection could not be esablished then an error message is printed. */ lg_void CLWorldClnt::ConnectLocal(CLWorldSrv* pSrv) { Disconnect(); if(!pSrv->IsRunning()) { Err_Printf("LEGACY CLIENT: Can't connect to the specified server."); return; } Err_Printf("Connecting to \"%s\" ...", pSrv->m_szName); Err_Printf("Initializing Entity List..."); m_nMaxEnts=pSrv->m_nMaxEnts; Err_Printf("Allocating memory for %u entities...", m_nMaxEnts); m_pEntList=new LEntityClnt[m_nMaxEnts]; if(!m_pEntList) return; Err_Printf("%u bytes allocated (%uMB).", m_nMaxEnts*sizeof(LEntityClnt), m_nMaxEnts*sizeof(LEntityClnt)/1048576); //Assign UEIDs for(lg_dword i=0; i<m_nMaxEnts; i++) { m_pEntList[i].m_pRasterInfo=LG_NULL; m_pEntList[i].m_nUEID=i; } //Establish the connection, and obtain the pc entitiy. if(!pSrv->AcceptLocalConnect(&m_nPCEnt, &m_nIDOnSrv, "Default Client")) Disconnect(); //Go ahead and create entities for the ones that exist. //Note that in the server intelligent entities are separated //from inert ones, but in the client it doesn't matter //so all entities are stored in the same list. (In the //future, however, they may be dived into lists based //on their region, fut faster rasterization. m_EntsAll.Clear(); //We need to initially duplicate all inert entities... for(LEntitySrv* pEnt=(LEntitySrv*)pSrv->m_EntsInert.m_pFirst; pEnt; pEnt=(LEntitySrv*)pEnt->m_pNext) { LEntityClnt* pEntCli = &m_pEntList[pEnt->m_nUEID]; UpdateEntSrvToCli(pEntCli, pEnt); m_EntsAll.Push(pEntCli); } //And all intelligent entities... for(LEntitySrv* pEnt=(LEntitySrv*)pSrv->m_EntsInt.m_pFirst; pEnt; pEnt=(LEntitySrv*)pEnt->m_pNext) { LEntityClnt* pEntCli = &m_pEntList[pEnt->m_nUEID]; UpdateEntSrvToCli(pEntCli, pEnt); m_EntsAll.Push(pEntCli); } m_pSrvLocal=pSrv; m_Map.Init(s_pDevice, &pSrv->m_Map); m_Skybox.Load(pSrv->m_szSkyboxFile, pSrv->m_szSkyboxSkinFile); //m_Map.Validate(); m_nConnectType=CLNT_CONNECT_LOCAL; } lg_void CLWorldClnt::Disconnect() { Err_Printf("Disconnecting..."); m_Skybox.Unload(); m_Map.UnInit(); m_nConnectType=CLNT_CONNECT_DISC; ClearEntities(); LG_SafeDeleteArray(m_pEntList); } lg_void CLWorldClnt::ClearEntities() { for(LEntityClnt* pEnt=(LEntityClnt*)m_EntsAll.m_pFirst; pEnt; pEnt=(LEntityClnt*)pEnt->m_pNext) { DeleteRasterInfo(pEnt->m_pRasterInfo); pEnt->m_pRasterInfo=LG_NULL; } m_EntsAll.Clear(); } lg_void CLWorldClnt::Validate() { m_Map.Validate(); } lg_void CLWorldClnt::Invalidate() { m_Map.Invalidate(); } /* UpdateEntSrvToCli PRE: pDest and pSrc should have the same UEID. POST: All client relative data is copied from pSrc to pDest. This method is primarily for local connections only, and not network. */ lg_void CLWorldClnt::UpdateEntSrvToCli(LEntityClnt* pDest, const LEntitySrv* pSrc) { //pDest->m_nUEID= pSrc->m_nUEID; pDest->m_matPos= pSrc->m_matPos; pDest->m_nFlags1= pSrc->m_nFlags1; pDest->m_nFlags2= pSrc->m_nFlags2; pDest->m_nMode1= pSrc->m_nMode1; pDest->m_nMode2= pSrc->m_nMode2; pDest->m_nNumRegions= pSrc->m_nNumRegions; memcpy(pDest->m_nRegions, pSrc->m_nRegions, sizeof(pDest->m_nRegions)); pDest->m_v3AngVel= pSrc->m_v3AngVel; pDest->m_v3Thrust= pSrc->m_v3Thrust; pDest->m_v3Vel= pSrc->m_v3Vel; pDest->m_aabbBody= pSrc->m_aabbBody; pDest->m_nAnimFlags1= pSrc->m_nAnimFlags1; pDest->m_nAnimFlags2= pSrc->m_nAnimFlags2; memcpy(pDest->m_v3Look, pSrc->m_v3Look, sizeof(ML_VEC3)*3); //Create the raster info, hopefully not done here in the future //as new is called several times for this. pDest->m_pRasterInfo=CreateRasterInfo(pSrc->m_szObjScript); //DeleteRasterInfo(pDest->m_pRasterInfo); } lg_void* CLWorldClnt::CreateRasterInfo(const lg_path szObjScript) { lx_object* pObj=LX_LoadObject(szObjScript); if(!pObj) return LG_NULL; LEntRasterInfo* pRasterInfo = new LEntRasterInfo; //pRasterInfo->m_fScale=pObj->fScale; pRasterInfo->m_MeshTree.Load(pObj->szModelFile); pRasterInfo->m_MeshTree.SetAnimation(0, 0, 0, 2.0f, 0.0f); LX_DestroyObject(pObj); return pRasterInfo; } lg_void CLWorldClnt::DeleteRasterInfo(lg_void* pInfo) { if(!pInfo) return; LEntRasterInfo* pRasterInfo=(LEntRasterInfo*)pInfo; //LM_DeleteMeshNodes(pRasterInfo->m_pMeshNodes); //LG_SafeDeleteArray(pRasterInfo->m_pSkels); pRasterInfo->m_MeshTree.Unload(); LG_SafeDelete(pRasterInfo); } <file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/console/lconsole/lc_cmd.c #include <stdio.h> #include <malloc.h> #include "lc_sys.h" #include "lc_private.h" #include "common.h" #include <windows.h> #define CVAR_CHECK_EXIT {if(lpConsole->cvarlist==NULL){Con_SendMessage(hConsole, "No lcvarlist loaded!");break;}} /* Con_InternalCommands attempts to process internal commands. */ /* As of right now this is the only function that uses the very max, setting, but I do want to eliminate it from this. */ int Con_InternalCommands(unsigned long nCommand, const char* szParams, HLCONSOLE hConsole) { LPLCONSOLE lpConsole=hConsole; /* unsigned long nCommand=0; */ char* szString1=NULL; char* szString2=NULL; char* szString3=NULL; int nResult=0; if(lpConsole==NULL) return 0; /* nCommand=Con_CmdNameToValue(hConsole, szCommand); */ if(nCommand==0) return 0; /* Go ahead, and allocate three strings for the use of these functions. */ szString1=malloc(lpConsole->nMaxStrLen+1); szString2=malloc(lpConsole->nMaxStrLen+1); szString3=malloc(lpConsole->nMaxStrLen+1); if(!szString1 || !szString2 || !szString3) { L_safe_free(szString1); L_safe_free(szString2); L_safe_free(szString3); Con_SendMessage(hConsole, "Could not allocate memory for temp strings."); return 1; } /* We'll set the nResult to 1, but then if nothing gets processed, the default switch with change it to a zero, which means we didn't process a message. */ nResult=1; switch(nCommand) { case CONF_ECHO: { char* szEcho=szString1; CCParse_GetParam(szEcho, szParams, 1); Con_SendMessage(hConsole, szEcho); break; } case CONF_CLEAR: { Con_Clear(hConsole); break; } case CONF_CMDLIST: { LDefs* defs=lpConsole->commands; LDef* def=NULL; char* szLimit=szString1; L_dword dwLen=0; if(!defs) { Con_SendMessage(hConsole, "Could not obtain list of commands."); break; } CCParse_GetParam(szLimit, szParams, 1); /* If there is a parameter, it is to limit the listed commands to the ones starting with the specified string. */ dwLen=L_strlen(szLimit); Con_SendMessage(hConsole, "Registered commands:"); for(def=defs->list; def; def=def->next) { if(dwLen) if(!L_strnicmp(szLimit, def->name, dwLen)) continue; Con_SendErrorMsg(hConsole, " %s", def->name); } break; } case CONF_CONDUMP: { LCENTRY* entry=NULL; FILE* fout=NULL; char* szFilename=szString1; L_dword i=0, j=0; CCParse_GetParam(szFilename, szParams, 1); if(L_strlen(szFilename)<1) { Con_SendMessage(hConsole, "Usage: CONDUMP filename$"); break; } Con_SendErrorMsg(hConsole, "Dumping console to \"%s\".", szFilename); fout=fopen(szFilename, "w"); if(!fout) { Con_SendErrorMsg(hConsole, "Could not open \"%s\" for saving.", szFilename); break; } /* We stop at entry 2, because that contains the lines that are printed by this function and the command line, which we don't want to print. */ for(i=lpConsole->dwNumEntries; i>2; i--) { fprintf(fout, "%s\n", Con_GetEntry(hConsole, i, NULL)); } fclose(fout); Con_SendMessage(hConsole, "Finished dumping console."); break; } case CONF_REGCVAR: { char* szCVarName=szString1; char* szCVarValue=szString2; char* szUpdate=szString3; unsigned long dwCreateFlags=0x00000000l; CVAR_CHECK_EXIT CCParse_GetParam(szCVarName, szParams, 1); CCParse_GetParam(szCVarValue, szParams, 2); /* Make sure that we at least have two parameters for the value and name. */ if( (L_strlen(szCVarName)<1) || (L_strlen(szCVarValue)<1) ) { Con_SendMessage(hConsole, "Usage: REGCVAR name$ value$ [UPDATE] [NOSAVE]"); break; } //CCParse_GetParam(szUpdate, szParams, 3); dwCreateFlags=CVAREG_SAVE; /* If the update value is set to true then, we update. */ if(CCParse_CheckParam(szParams, "UPDATE", 3)) dwCreateFlags=dwCreateFlags|CVAREG_UPDATE; //CCParse_GetParam(szUpdate, szParams, 4); if(CCParse_CheckParam(szParams, "NOSAVE", 3)) dwCreateFlags=dwCreateFlags^CVAREG_SAVE; CVar_Register(lpConsole->cvarlist, szCVarName, szCVarValue, dwCreateFlags); break; } case CONF_SET: { /* Changes a cvars value. */ char* cvarname=szString1; char* newvalue=szString2; CVar* cvar=NULL; CVAR_CHECK_EXIT CCParse_GetParam(cvarname, szParams, 1); CCParse_GetParam(newvalue, szParams, 2); if((L_strlen(cvarname)<1) || (L_strlen(newvalue)<1)) { Con_SendMessage(hConsole, "Usage: SET name$ newvalue$"); break; } cvar=CVar_GetCVar(lpConsole->cvarlist, cvarname); if(!cvar) { Con_SendErrorMsg( hConsole, "Could not set \"%s\", no such cvar!", cvarname); break; } if(L_CHECK_FLAG(cvar->flags, CVAREG_SETWONTCHANGE)) { Con_SendErrorMsg(hConsole, "Cannot change \"%s\" permission denied by app.", cvarname); break; } if(CVar_Set(lpConsole->cvarlist, cvarname, newvalue)) { if(cvar) { Con_SendErrorMsg( hConsole, " %s = \"%s\", %.0f", cvarname, newvalue, cvar->value); if(L_CHECK_FLAG(cvar->flags, CVAREG_UPDATE)) { sprintf(szString1, "cvarupdate \"%s\"", cvar->name); Con_SendCommand(hConsole, szString1); } } else Con_SendErrorMsg( hConsole, "Could not check to see if \"%s\" was successfully set.", cvarname); } break; } case CONF_GET: { /* Retrieves a cvar. */ char* szCVarName=szString1; char* lpValue=NULL; CVar* value=NULL; CVAR_CHECK_EXIT CCParse_GetParam(szCVarName, szParams, 1); if(L_strlen(szCVarName)<1) { Con_SendMessage(hConsole, "Usage: GET name$ [FP]"); break; } value=CVar_GetCVar(lpConsole->cvarlist, szCVarName); if(value) { if(CCParse_CheckParam(szParams, "FP", 2)) Con_SendErrorMsg(hConsole, " %s = \"%s\", %f", value->name, value->string, value->value); else Con_SendErrorMsg(hConsole, " %s = \"%s\", %.0f", value->name, value->string, value->value); } else Con_SendErrorMsg(hConsole, "Cannot get \"%s\", no such cvar!", szCVarName); break; } case CONF_DEFINE: { char* szDef=szString1; char* szValue=szString2; CVAR_CHECK_EXIT CCParse_GetParam(szDef, szParams, 1); CCParse_GetParam(szValue, szParams, 2); if( (L_strlen(szDef)<1) || (L_strlen(szValue)<1)) { Con_SendMessage(hConsole, "Usage: DEFINE name$ value%"); break; } if(CVar_AddDef(lpConsole->cvarlist, szDef, L_atof(szValue))) Con_SendErrorMsg(lpConsole, "Defined \"%s\" as %f", szDef, L_atof(szValue)); else Con_SendErrorMsg(hConsole, "Couldn't define \"%s\", possible bad name, or already defined.", szDef); break; } case CONF_CVARLIST: { CVar* cvarlist=NULL; char* szLimit=szString1; L_dword dwLen=0; CVAR_CHECK_EXIT Con_SendMessage(hConsole, "Registered cvars:"); cvarlist=CVar_GetFirstCVar(lpConsole->cvarlist); CCParse_GetParam(szLimit, szParams, 1); /* We can limit the number of cvars displayed, by putting a parameter with the first leters we want. */ dwLen=L_strlen(szLimit); for(cvarlist=CVar_GetFirstCVar(lpConsole->cvarlist); cvarlist; cvarlist=cvarlist->next) { if(dwLen) if(!L_strnicmp(szLimit, cvarlist->name, dwLen)) continue; Con_SendErrorMsg(hConsole, " %s = \"%s\", %.0f", cvarlist->name, cvarlist->string, cvarlist->value); } break; } case CONF_SAVECFG: { char* szFilename=szString1; char* szAppend=szString2; FILE* fout=NULL; HCVARLIST cvarlist=NULL; CVar* cvar=NULL; HLCONSOLE tempconsole=NULL; L_dword i=0, j=0; L_bool bAppend=L_false, bAll=L_false; CVAR_CHECK_EXIT CCParse_GetParam(szFilename, szParams, 1); if(L_strlen(szFilename)<1) { Con_SendMessage(hConsole, "Usage: SAVECFG filename$ [APPEND] [ALL]"); break; } //CCParse_GetParam(szAppend, szParams, 2); if(CCParse_CheckParam(szParams, "APPEND", 2)) bAppend=L_true; if(CCParse_CheckParam(szParams, "ALL", 2)) bAll=L_true; Con_SendErrorMsg(hConsole, "Saving cvars as \"%s\"...", szFilename); cvarlist=lpConsole->cvarlist; if(!cvarlist) { Con_SendErrorMsg(hConsole, "Could not get cvarlist.", szFilename); break; } /* We need to reverse the order of the outputed text, the easyest way to do this is to use a def file to referse the order of the string. The reason we do this is so the cvars will be saved in the order they were created.*/ tempconsole=Con_Create(NULL, lpConsole->nMaxStrLen, lpConsole->nMaxEntries, 0, NULL); if(tempconsole==NULL) { Con_SendMessage(hConsole, "Could not open temp console for dumping."); break; } for(cvar=CVar_GetFirstCVar(cvarlist), i=0; cvar; cvar=cvar->next) { if(L_CHECK_FLAG(cvar->flags, CVAREG_SAVE) || bAll) { Con_SendErrorMsg(tempconsole, "set \"%s\" \"%s\"", cvar->name, cvar->string); i++; } } fout=fopen(szFilename, bAppend?"r+":"w"); if(!fout) { Con_Delete(tempconsole); Con_SendErrorMsg(hConsole, "Could not open \"%s\" for saving.", szFilename); break; } fseek(fout, 0, SEEK_END); for(j=0; j<i; j++) { fprintf(fout, "%s\n", Con_GetEntry(tempconsole, j+2, NULL)); } fclose(fout); Con_Delete(tempconsole); Con_SendMessage(hConsole, "Finished saving cvars."); break; } case CONF_LOADCFG: { char* szFilename=szString1; char* szLine=szString2; FILE* fin=NULL; unsigned long nLen=0, i=0; CVAR_CHECK_EXIT CCParse_GetParam(szFilename, szParams, 1); if(L_strlen(szFilename)<1) { Con_SendMessage(hConsole, "Usage: LOADCFG filename$"); break; } fin=fopen(szFilename, "r"); if(fin==NULL) { Con_SendErrorMsg(hConsole, "Could not open \"%s\" for processing!", szFilename); break; } Con_SendErrorMsg(hConsole, "Processing \"%s\"...", szFilename); while(!feof(fin)) { if(fgets(szLine, lpConsole->nMaxStrLen-1, fin)==NULL) continue; /* Ignore strings, that have nothing in them, and ignore strings that are just return carriages. */ nLen=L_strlen(szLine); if(nLen<1) continue; if((szLine[0]=='\r') || (szLine[0]=='\n')) continue; /* Check to see for comments, and remove them. */ for(i=0; i<=nLen; i++) { if((szLine[i]=='/')&&(szLine[i+1]=='/')) { szLine[i]=0; break; } if(szLine[i]=='\r' || szLine[i]=='\n') { szLine[i]=0; break; } } if(szLine[0]==0) continue; Con_SendCommand(hConsole, szLine); } fclose(fin); Con_SendErrorMsg(hConsole, "Finished processing \"%s\".", szFilename); break; } default: L_safe_free(szString1); L_safe_free(szString2); L_safe_free(szString3); nResult=0; } L_safe_free(szString1); L_safe_free(szString2); L_safe_free(szString3); return nResult; } <file_sep>/games/Legacy-Engine/Scrapped/UnitTests/VarTest/var_types.h #pragma once #include <tchar.h> namespace var_sys{ typedef float var_float; typedef signed long var_long; typedef unsigned long var_word; const var_word VAR_STR_LEN=127; typedef TCHAR var_char; typedef var_char var_string[VAR_STR_LEN+1]; } //namespace var_sys <file_sep>/games/Legacy-Engine/Source/engine/ls_stream.cpp #include "ls_stream.h" #include "lg_err.h" #include "ls_sys.h" #include "lg_malloc.h" /* lg_dword CLSndStream::m_nLastUpdate; ALuint CLSndStream::m_Buffers[2]; ALuint CLSndStream::m_Source; ALenum CLSndStream::m_nFormat; CLSndFile CLSndStream::m_cSndFile;*/ lg_bool CLSndStream::CheckError() { ALenum nError=alGetError(); if(nError==AL_NO_ERROR) return LG_FALSE; Err_Printf("Sound Stream ERROR %u: %s", nError, "ERROR MESSAGE GOES HERE"); return LG_TRUE; } CLSndStream::CLSndStream(): m_bOpen(LG_FALSE), m_pTempBuffer(LG_NULL), m_bLoop(LG_FALSE), m_bPlaying(LG_FALSE), m_bPaused(LG_TRUE) { } CLSndStream::~CLSndStream() { Close(); } void CLSndStream::SetVolume(lg_int nVolume) { if(!m_bOpen) return; nVolume=LG_Clamp(nVolume, 0, 100); alSourcef(m_Source, AL_GAIN, nVolume/100.0f); } lg_bool CLSndStream::Load(lg_str szPath) { Close(); Err_Printf("Loading \"%s\" as a streaming sound...", szPath); if(!m_cSndFile.Open(szPath)) { Err_Printf(" ERROR: Could not open sound file!", szPath); return LG_FALSE; } m_nFormat=CLSndMgr::GetALFormat(m_cSndFile.GetNumChannels(), m_cSndFile.GetBitsPerSample()); if(m_nFormat==-1) { Err_Printf(" ERROR: Sound is not a supported audio format."); m_cSndFile.Close(); return LG_FALSE; } //Setup the temp buffer... m_nTempBufferSize=m_cSndFile.GetBitsPerSample()*m_cSndFile.GetSamplesPerSecond()/8; m_pTempBuffer=LG_Malloc(m_nTempBufferSize); if(!m_pTempBuffer) { Err_Printf(" ERROR: Could not allocate memory for temp buffer."); m_cSndFile.Close(); return LG_FALSE; } CheckError(); alGenBuffers(2, m_Buffers); if(CheckError()) { Err_Printf(" ERROR: Could not create buffers."); m_cSndFile.Close(); LG_Free(m_pTempBuffer); return LG_FALSE; } alGenSources(1, &m_Source); if(CheckError()) { Err_Printf(" ERROR: Could not create source."); alDeleteBuffers(2, m_Buffers); m_cSndFile.Close(); LG_Free(m_pTempBuffer); return LG_FALSE; } /* Set source properties for background music, may want this changeable, in case an object is giving a dialog or something. */ alSource3f(m_Source, AL_POSITION, 0.0f, 0.0f, 0.0f); alSource3f(m_Source, AL_VELOCITY, 0.0f, 0.0f, 0.0f); alSource3f(m_Source, AL_DIRECTION, 0.0f, 0.0f, 0.0f); alSourcef(m_Source, AL_ROLLOFF_FACTOR, 0.0f); alSourcei(m_Source, AL_SOURCE_RELATIVE, AL_TRUE); m_bOpen=LG_TRUE; m_bPlaying=LG_FALSE; m_bLoop=LG_FALSE; SetVolume(100); return LG_TRUE; } void CLSndStream::Close() { if(!m_bOpen) return; LG_Free(m_pTempBuffer); m_pTempBuffer=LG_NULL; CheckError(); alDeleteSources(1, &m_Source); CheckError(); alDeleteBuffers(2, m_Buffers); CheckError(); m_cSndFile.Close(); m_bOpen=LG_FALSE; m_bPlaying=LG_FALSE; m_bPaused=LG_FALSE; m_bLoop=LG_FALSE; } lg_bool CLSndStream::UpdateBuffer(ALuint buffer) { if(!m_bPlaying) return LG_FALSE; lg_dword nRead=0; while(nRead<m_nTempBufferSize) { nRead+=m_cSndFile.Read((lg_byte*)m_pTempBuffer+nRead, m_nTempBufferSize-nRead); if(m_cSndFile.IsEOF()) { if(m_bLoop) { m_cSndFile.Reset(); continue; } break; } } alBufferData(buffer, m_nFormat, m_pTempBuffer, nRead, m_cSndFile.GetSamplesPerSecond()); CheckError(); return nRead==m_nTempBufferSize?LG_TRUE:LG_FALSE; } void CLSndStream::Play(lg_bool bLoop) { if(!m_bOpen) return; m_bLoop=bLoop; if(m_bPlaying) { if(m_bPaused) { alSourcePlay(m_Source); m_bPaused=LG_FALSE; } return; } m_bPlaying=LG_TRUE; m_bPaused=LG_FALSE; if(!UpdateBuffer(m_Buffers[0]) || !UpdateBuffer(m_Buffers[1])) { m_bPlaying=LG_FALSE; return; } alSourceQueueBuffers(m_Source, 2, m_Buffers); alSourcePlay(m_Source); } void CLSndStream::Stop() { if(!m_bOpen) return; alSourceStop(m_Source); alSourceUnqueueBuffers(m_Source, 2, m_Buffers); m_cSndFile.Reset(); m_bPlaying=LG_FALSE; m_bPaused=LG_FALSE; } void CLSndStream::Pause() { if(!m_bOpen) return; alSourcePause(m_Source); m_bPaused=LG_TRUE; } void CLSndStream::Update() { if(!m_bPlaying || m_bPaused || !m_bOpen) return; ALint nProcessed; alGetSourcei(m_Source, AL_BUFFERS_PROCESSED, &nProcessed); while(nProcessed--) { ALuint buffer; alSourceUnqueueBuffers(m_Source, 1, &buffer); CheckError(); lg_bool bResult=UpdateBuffer(buffer); alSourceQueueBuffers(m_Source, 1, &buffer); CheckError(); if(!bResult) { m_bPlaying=LG_FALSE; break; } } ALint nState; alGetSourcei(m_Source, AL_SOURCE_STATE, &nState); if(nState!=AL_PLAYING) alSourcePlay(m_Source); } <file_sep>/tools/CornerBin/CornerBin/DlgSettings.cpp // DlgSettings.cpp : implementation file // #include "stdafx.h" #include "CornerBin.h" #include "DlgSettings.h" #include "afxdialogex.h" #include "IconDlg/IconDlg.h" // CDlgSettings dialog IMPLEMENT_DYNAMIC(CDlgSettings, CDialogEx) CDlgSettings::CDlgSettings(CWnd* pParent, CCBSettings* pSettings) : CDialogEx(CDlgSettings::IDD, pParent) , m_pSettings(NULL) { m_pSettings = pSettings; } CDlgSettings::~CDlgSettings() { } void CDlgSettings::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); CCBSettings::SSettings Settings; m_pSettings->GetSettings(&Settings); ::DDX_Text(pDX, IDC_TXTEICON, Settings.m_strEmptyIcon); ::DDX_Text(pDX, IDC_TXTFICON, Settings.m_strFullIcon); ::DDX_Text(pDX, IDC_TXTTOOLTIP, Settings.m_strToolTip); ::DDX_Check(pDX, IDC_CHKEMPTYPROMPT, (int&)Settings.m_bEmptyPrompt); ::DDX_Check(pDX, IDC_CHKDBLCLKRB, (int&)Settings.m_bOpenRBOnDblClk); //::DDX_Check(pDX, IDC_CHKSTARTWITHWINDOWS, (int&)bStartWithWindows); ::DDX_Check(pDX, IDC_CHKSIMPLEMENU, (int&)Settings.m_bSimpleMenu); m_pSettings->SetSettings(&Settings); //Decide what to do with the start with windows button. if(pDX->m_bSaveAndValidate) { SetStartWithWindows(IsDlgButtonChecked(IDC_CHKSTARTWITHWINDOWS)); } else { this->CheckDlgButton(IDC_CHKSTARTWITHWINDOWS, this->IsStartWithWindowsSet()); } } BEGIN_MESSAGE_MAP(CDlgSettings, CDialogEx) ON_BN_CLICKED(IDC_BTNBROWSEE, &CDlgSettings::OnBnClickedBtnbrowsee) ON_BN_CLICKED(IDC_BTNBROWSEF, &CDlgSettings::OnBnClickedBtnbrowsef) ON_BN_CLICKED(IDC_BTNSYSEMPTY, &CDlgSettings::OnBnClickedBtnsysempty) ON_BN_CLICKED(IDC_BTNSYSFULL, &CDlgSettings::OnBnClickedBtnsysfull) ON_WM_CREATE() ON_BN_CLICKED(IDC_BTNDEFS, &CDlgSettings::OnBnClickedBtndefs) END_MESSAGE_MAP() // CDlgSettings message handlers void CDlgSettings::OnBnClickedBtnbrowsee() { BrowseForIcon(IDC_TXTEICON); } void CDlgSettings::BrowseForIcon(int nCtrlID) { CIconDialog dlg(this); CString strFile, strResID; CString strText; this->GetDlgItemText(nCtrlID, strText); int n = 0; strFile = strText.Tokenize(_T("|"), n); if(-1 == n) { strResID = _T(""); } else { strResID = strText.Tokenize(_T("|"), n); } dlg.SetIcon(strFile, _ttol(strResID)); if (dlg.DoModal() == IDOK) { dlg.GetIcon(strFile, n); //Form the new string. strText.Format(_T("%s|%d"), strFile, n); this->SetDlgItemText(nCtrlID, strText); } } void CDlgSettings::OnBnClickedBtnbrowsef() { BrowseForIcon(IDC_TXTFICON); } void CDlgSettings::OnBnClickedBtnsysempty() { // HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\CLSID\{645FF040-5081-101B-9F08-00AA002F954E}\DefaultIcon CRegKey Key; Key.Open(HKEY_CURRENT_USER, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\CLSID\\{645FF040-5081-101B-9F08-00AA002F954E}\\DefaultIcon")); ULONG nChars = 1023; TCHAR strTemp[1024] = { 0 }; Key.QueryStringValue(_T("empty"), strTemp, &nChars); CString strIcon(strTemp); int n = strIcon.Find(_T(",")); if(-1 != n) { strIcon.SetAt(n, '|'); //strIcon.Delete(n+1); } this->SetDlgItemText(IDC_TXTEICON, strIcon); Key.Close(); } void CDlgSettings::OnBnClickedBtnsysfull() { // HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\CLSID\{645FF040-5081-101B-9F08-00AA002F954E}\DefaultIcon CRegKey Key; Key.Open(HKEY_CURRENT_USER, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\CLSID\\{645FF040-5081-101B-9F08-00AA002F954E}\\DefaultIcon")); ULONG nChars = 1023; TCHAR strTemp[1024] = { 0 }; Key.QueryStringValue(_T("full"), strTemp, &nChars); CString strIcon(strTemp); int n = strIcon.Find(_T(",")); if(-1 != n) { strIcon.SetAt(n, '|'); //strIcon.Delete(n+1); } this->SetDlgItemText(IDC_TXTFICON, strIcon); Key.Close(); } void CDlgSettings::SetStartWithWindows(BOOL bStartWith) { //MessageBox(_T("Here!")); //We add the startup registry entry, or remove it, as soon as this button is clicked. CRegKey Key; Key.Open(HKEY_CURRENT_USER, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Run")); if(bStartWith) { //Add the startup key. //We need to get the path: CString strExec; ::AfxGetModuleFileName(NULL, strExec); strExec.Insert(0, '"'); strExec.Append(_T("\"")); Key.SetStringValue(_T("CornerBin"), strExec); } else { Key.DeleteValue(_T("CornerBin")); } Key.Close(); } BOOL CDlgSettings::IsStartWithWindowsSet(void) { //Just need to check to see if the key exists. CRegKey Key; Key.Open(HKEY_CURRENT_USER, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Run")); BOOL bRes = ERROR_SUCCESS == Key.QueryValue(_T("CornerBin"), NULL, NULL, NULL); Key.Close(); return bRes; } void CDlgSettings::OnBnClickedBtndefs() { this->CheckDlgButton(IDC_CHKEMPTYPROMPT, 1); this->CheckDlgButton(IDC_CHKDBLCLKRB, 1); this->CheckDlgButton(IDC_CHKSTARTWITHWINDOWS, 0); this->CheckDlgButton(IDC_CHKSIMPLEMENU, 0); this->SetDlgItemText(IDC_TXTEICON, _T("")); this->SetDlgItemText(IDC_TXTFICON, _T("")); this->SetDlgItemText(IDC_TXTTOOLTIP, _T("Recycle Bin")); } <file_sep>/games/Legacy-Engine/Source/engine/lg_mmgr.h /* lg_mmgr.h - The Legacy Game Mesh Manager is responsible for loading meshes, allowing objects to get meshes to use, cleaning up the meshes, etc, meshes should always be loaded using the game's instance of this class, though meshes themselves can be used however an object sees fit to use it. CLMMgr uses a hash table meshes and skeletons. The manager also has validate and invalidate calls to validate and invalidate the Direct3D components, for this reason the objects that use the meshes don't need to worry about validatation at all, if because of the mesh manager a mesh is not valid if an in game object tries to render it, nothing will get rendered, but the game will not crash. Copyright (c) 2008 <NAME> */ /* Usage: Only one instance of CLMMgr should be declared, and that should be in the actual game class. From there any other classes that need meshes may use the static member functions to load them, but all management of meshes (validating, invalidating, unloading) should be taken care of in the game class. Creating a CLMMgr is all done in the constructor, so the desired values must be specified at that time. Direct3D should be initialized first if we need rendering (in the case of a dedicated server we won't need rendering, so null can be passed). We also need to know the max number of meshes that we need, as well as skeletons. These values could be stored in cvars for instance. See the declaration of the class for further instructions. Notes: The meshes and skeletons are stored in a hash table. The hash table is set up so that if a duplicate hash is detected, it will go to the next available slot. The manager also keeps track of how many objects share the same hash, and so we are able to speed up the search as to whether or not a mesh is even in the manager. For this reason if we load the number of meshes that are available it is possible that the object might be stored quite far away from the actual hash location (in fact it might wrap all the way around the the furthest location available), so it is probably a good idea to have more meshes available than are actually needed (skeletons too). Also the manager is designed for only one instance to be created, if a second instance is created an exception will be thrown. */ #ifndef __LG_MMGR_H__ #define __LG_MMGR_H__ #include "lg_types.h" #include "lm_mesh_lg.h" #include "lm_skel_lg.h" #include "lg_hash_mgr.h" #include "lg_list_stack.h" LG_CACHE_ALIGN struct MeshItem: public CLListStack::LSItem { CLMeshLG Mesh; }; LG_CACHE_ALIGN class CLMeshMgr: public CLHashMgr<MeshItem> { private: MeshItem* m_pMeshMem; CLListStack m_stkMeshes; public: CLMeshMgr(IDirect3DDevice9* pDevice, lg_dword nMaxMeshes); ~CLMeshMgr(); private: virtual MeshItem* DoLoad(lg_path szFilename, lg_dword nFlags); virtual void DoDestroy(MeshItem* pItem); public: CLMeshLG* GetInterface(hm_item mesh); void Validate(); void Invalidate(); }; LG_CACHE_ALIGN struct SkelItem: public CLListStack::LSItem { CLSkelLG Skel; }; LG_CACHE_ALIGN class CLSkelMgr: public CLHashMgr<SkelItem> { private: SkelItem* m_pSkelMem; CLListStack m_stkSkels; public: CLSkelMgr(lg_dword nMaxSkels); ~CLSkelMgr(); private: virtual SkelItem* DoLoad(lg_path szFilename, lg_dword nFlags); virtual void DoDestroy(SkelItem* pItem); public: CLSkelLG* GetInterface(hm_item skel); }; class CLMMgr { //friend class CLGlobalMethods; public: //Flags for loading: const static lg_dword MM_RETAIN=0x00000001; const static lg_dword MM_NOD3D= 0x00000002; //Flags for unloading: const static lg_dword MM_FORCE_UNLOAD=0x00000002; private: CLMeshMgr m_MeshMgr; CLSkelMgr m_SkelMgr; public: /* Constructor PRE: If we want to render a valide Direct3D Device must be passed. Also we need to declare, upon construction, the maximum number of meshes and skeletons that we can load. Additionally since Meshes use Direct3D resources such as textures, things like the Texture Manager must be initialized before the initialization of this manager. POST: The isntance is created. */ CLMMgr(IDirect3DDevice9* pDevice, lg_dword nMaxMesh, lg_dword nMaxSkel); /* PRE: N/A. POST: Destroys everything, unloads all meshes and skels, and deallocates all memory associated. Note that after the manager is destroyed, any attempt to use a CLMeshLG or CLSkelLG obtained from it will cause memory access violations. */ ~CLMMgr(); /* PRE: Use flags to specify how the mesh should be loaded, CLMMgr::MM_RETAIN means that upon a call to UnloadMeshes the mesh will survive (this is useful for meshes that will always be used such as weapons, main characters, etc.). CLMMgr::MM_NOD3D means that the mesh will be loaded, but it will not be renderable. This is useful for physics engine loading, not that if later on the same mesh is loaded (or in other words retrieved) without the MM_NOD3D flag, it will be made renderable, at that time. So when the server is initialized calling MM_NOD3D, the meshes will not be renderable, but when the client calls the method without the flag, the mesh will then be renderable. POST: If szFilename is a valid mesh file, the mesh will be returned, if not LG_NULL is returned. Note that if the mesh was previously loaded, the mesh will only be obtained a second copy will not be loaded. */ CLMeshLG* LoadMesh(lg_path szFilename, lg_dword nFlags); /* PRE: Same as for meshes, but works on skeletons, and the MM_NOD3D flag would have no effect as skeletons are not renderable in the actual game anyway. POST: Same as for meshes. */ CLSkelLG* LoadSkel(lg_path szFilename, lg_dword nFlags); /* PRE: N/A POST: Unloades all meshes, except for those loaded with the MM_RETIAN flag, unless CLMMgr::MM_FORCE_UNLOAD is specifed, in which case all meshes are unloaded. NOTES: Most likely to be called in between map loads. */ void UnloadMeshes(lg_dword nFlags); /* PRE: N/A POST: Same as for meshes. NOTES: Same as for meshes. */ void UnloadSkels(lg_dword nFlags); /* PRE: InvalidateMeshes should have been called, otherwise we are simply wasting processor power. POST: Validates the Direct3D components of all meshes. */ void ValidateMeshes(); /* PRE: The Direct3D device needs to be reset. POST: Invalidates the Direct3D components of all meshes. Useful for resetting the video device. */ void InvalidateMeshes(); //Debug Functions: /* PRE: N/A POST: Prints information about all the meshes loaded, output is sent to the console. The output is for debugging only, so some of the information may appear to be gibberish. */ void PrintMeshes(); /* PRE: N/A POST: Same as above, but for skels. */ void PrintSkels(); private: //The static mesh manager is so that meshes can be loaded //on demand without having access to the extablished mesh //manager within the game class. static CLMMgr* s_pMMgr; //Only one instance of this is created during the constructor. public: /* PRE: The CLMMgr must be initialized. POST: If the specified mesh is available it is loaded, see the public member LoadMesh for more details. */ static CLMeshLG* MM_LoadMesh(lg_path szFilename, lg_dword nFlags); /* PRE: The CLMMgr must be initialized. POST: If the specifed skel is available it is loaded, see the public member LoadSkel for more details. */ static CLSkelLG* MM_LoadSkel(lg_path szFilename, lg_dword nFlags); }; #endif __LG_MMGR_H__<file_sep>/tools/img_lib/dist/img_lib.h /* img_lib.h - The Image Loader library. Copyright (c) 2006 <NAME>*/ #ifndef __IMG_LIB_H__ #define __IMG_LIB_H__ #include "img_lib_types.h" /* Insure that if a c++ app is calling the img_lib functions that it knows they were written in C. This is for VC++ and is not ANSI C.*/ #ifdef __cplusplus extern "C"{ #endif /*__cplusplus*/ /********************************* The img_lib public functions. *********************************/ HIMG IMG_FUNC IMG_OpenMemory(img_void* pData, img_dword nSize); HIMG IMG_FUNC IMG_OpenA(img_char* szFilename); HIMG IMG_FUNC IMG_OpenW(img_wchar* szFilename); img_bool IMG_FUNC IMG_Delete(HIMG hImage); #ifdef _UNICODE #define IMG_Open IMG_OpenW #else #define IMG_Open IMG_OpenA #endif img_bool IMG_FUNC IMG_GetDesc( HIMG hImage, IMG_DESC* lpDescript); img_bool IMG_FUNC IMG_CopyBits( HIMG hImage, IMG_DEST_RECT* pDest, IMGFILTER Filter, IMG_RECT* rcSrc, img_byte nExtra); img_bool IMG_FUNC IMG_GetPalette( HIMG hImage, img_void* lpDataOut); /* Terminate the extern "C" (see above).*/ #ifdef __cplusplus } #endif /*__cplusplus*/ #endif /*__IMG_LIB_H__*/<file_sep>/games/Explor2002/Source_Old/ExplorED DOS/dosexplored/EXPLORED.CPP /* ExplorEd: A DOS Based map editor for explor type maps. Copyright(C) 2001, Beem Software Author: <NAME> Start Date January 12, 2001 */ /* Log: January 12, 2001 I've created a GUI and I'm pretty satisfied. I'm having troubles dealing with sprites and moving them from one function to another. Using the arrow keys is really crappy. If you press a capitol of the corresponding letter it reads it as the up arrow. My next goal will be to write a program similar to my QBasic Moveen program once I have completed that I may continue to develop this one. January 13, 2001 I perfected the location of the placement of the cursor. Now it needs an input consistent with a x, y format. The cursor now moves fine except that it leaves behind a lot of funny pixel formations. What needs to be done now is design sprites for different tiles and then impliment them by placing them on the map when certain buttons are pressed. January 14, 2001 Now if you press 'T' it places a tile sprite on the screen it doesn't it will need to activate the fact that there is a tile at that location for the save feature. I'm facing many issues with the buffered memory. I've perfected the binary writing but now the cursor disapears for an unexplained reason. My goodness I think it's working! I believe open works correctly it just doesn't re-display the tileset. It now opens the tileset fine, but the cursor doesn't work quite right. The file commands are really screwy. Save seems to work fine. The rest of them create visual errors. July 21, 2001 Removed the necessity for the temb.buf file which cleared up a lot of the memory issues. But still a lot of memory issues remain. If you only edit the first map loaded and then us SaveAs you can make multiple maps. NewMap and LoadMap cause a lot of errors. Probably need to redo the graphicsloading to fix that. OpenMap will load the screen correctly but after that the cursor gets very screwed up. <no longer keeping track of dates> BoardEdit has been slighly altered for greater effect. Updated to map type 2. 0's instead of 1's. Changed tiles to 'D' 's and 'W' 's for Door and Wall correspondingly. Improved the algorithm for mapping out the board when initial map load happens. This improved some of the memory issues. Fixed a damn good portion of the memory issues. I'm not even sure if any are left. Have expiramented quite a bit. Updated to map type 3 it took a damn bit of a long time but I am so fucking satisfied now. There are a lot of bugs it will take time to fix them. Most bugs are fixed. I know memory issues exist when saving. Need to make it so alternate tile properties may be altered besides 1 and 2. To do that need to make it so you can change the size of fileHeader.mapNumProperty. Wrote a new function that takes input. It is used to take input for property and for new map names, as well as save as. Works pretty damn good. Greatly increased the LoadMap function now scrolls down when more than 23 maps are present. It supports a maximum number of maps described by a definition in openmap.h. Preforming a Save causes memory issues. One thing to implement. If escape is pressed while in the LoadMap menu the program should return to the previous map, as it was right before the LoadMap was called. Right now it will return to the previous map, but in the state it was in when it was last saved. I'd also like to implement a screenshot feature. Now supports mouse, the mouse doesn't actually do anything yet though. October 18, 2001 I have implemented the EXPLORMAP class which contains all the variables of an explor type map, as well as the functions to load an explormap into memory, save an explor map on the disk, and edit and explor map. Mapboard.cpp and mapboard.h contain this class and work independently of any other programs. Just include #include "mapboard.h" in the file that uses the EXPLORMAP class and include the mapboard.cpp as part of the project. With this new class it should be much easier to port the code to windows. The code in now C++ rather than C language. I also separated the source into 3 parts. One for the defintion of the CASTLEMAP class: mapboard.cpp. Another for the openfile process: openfile.cpp. And finally the main program; explored.cpp. I also implemented overlaoding functions for the input for easier usage. */ /* About Explor Map Type 3: Explor Maps are read in the following manner: The first bytes are the fileheader described by the typedef MAPHEADER. Directly after the map data is the tile data. Each tile is an unsigned int which represents the type of tile (see below). Directly after the tile type is the property data. They are unsigned ints as well. There may be as many properties as you wish per tile. Tile types: 0: Nothing - Means nothing is there 10: Wall - Regular wall represented by 'W' on the display 20: Door - A Door represented by 'D' on the display Possible Future Tile tipes: xx: Invisible Wall - Wall you cannot see but cannot pass through xx: Visible Emptiness - You see a wall but can pass through Property values: The property values can be incremented by 1 and 2 on the keyboard. They have not been assigned to any specific functions yet. But may either in explor source code or ExplorSCRIPT. */ /******************************************************************* The following definitions are to change certain things about the source. ********************************************************************/ #define SHOWMOUSE //#define DEBUG //Included Files #include <conio.h> #include <string.h> #include <ctype.h> #include "explored.h" #include "mapboard.h" #include "openmap.h" #include "mouse.h" //Definitions /* Type Definitions */ typedef unsigned short int BIT; /* Enumerated Items */ const enum eboard {TILE, PROP}; const enum etile {PUT, ERASE}; /* Global Variables */ static void far *ptr[4]; void far *tile[4]; int xloc = 1, yloc=1; int firstime = 0; int firstime1 = 0; char filename[13]; EXPLORMAP explormap; int main(int argc, char *argv[]) { // char *filename; Initialize(); // if(argv[1] != NULL){ // filename = argv[1]; // }else{ strcpy(filename, "default.map"); // } GetSprite(tile); GetCur(ptr); LoadDisp(); PutCur(ptr, xloc, yloc, NULL, NULL); OpenMap(filename); dtext("ExplorED Started"); DispTileStats(); initMouse(); #ifdef SHOWMOUSE initCursor(); #endif while(GetKey() != 1){ DispTileStats(); } closegraph(); return 0; } /* int takeInput(char theoutput[80], char type[]); writes input out to the screen and copies it to char array defined by theoutput. Type must be specified as "INT" or "STRING" If the type is "INT" the function returns and unsigned short int. Valid characters that can be entered: for "STRING" a-z, A-Z, and '.' for "INT" 0-9 */ unsigned int takeInput(void) { int value; int position = 0; char bufstring[1]; char theoutput[80]; char keystroke; setfillstyle(SOLID_FILL, BLACK); bar(200, 400, 600, 410); do{ keystroke = getch(); switch(keystroke) { case 27: return 301; case 13: position = 80; break; case 8: //Hitting backspace if(position > 0){ //setfillstyle(SOLID_FILL, WHITE); bar(202+(position-1)*8, 400, 202+position*8, 410); position--; theoutput[position] = NULL; } break; default: if(((48<=keystroke)&&(keystroke<=59))){ sprintf(bufstring, "%c", keystroke); theoutput[position] = keystroke; outtextxy(202+position*8, 402, bufstring); position++; } } }while(position < 80); setfillstyle(SOLID_FILL, 6); bar(200, 400, 600, 410); setfillstyle(SOLID_FILL, BLACK); return atoi(theoutput); } int takeInput(char theoutput[80]) { int keystroke; int position = 0; char bufstring[1]; setfillstyle(SOLID_FILL, BLACK); bar(200, 400, 600, 410); do{ keystroke = getch(); switch(keystroke) { case 27://hitting escape return 301; case 13://Hitting enter position = 80; break; case 8://Hitting Backspace if(position > 0){ //setfillstyle(SOLID_FILL, WHITE); bar(202+(position-1)*8, 400, 202+position*8, 410); position--; theoutput[position] = NULL; } break; default: if(((97<=keystroke)&&(keystroke<=122)) || ((65<=keystroke)&&(keystroke<=90)) || (keystroke==46)){ sprintf(bufstring, "%c", keystroke); theoutput[position] = keystroke; outtextxy(202+position*8, 402, bufstring); position++; } break; } }while(position < 80); setfillstyle(SOLID_FILL, 6); bar(200, 400, 600, 410); setfillstyle(SOLID_FILL, BLACK); return 0; } /* int quiting(int c); process for quiting. returns 1 if program should quit int c can really be just about anything */ int quiting(int c) { dtext("Are you sure you want to quit Y/n"); while(c != 'Y' || c != 'y' || c != 'n' || c != 'N' || c != 27){ c = getch(); if(c == 'Y' || c == 'y' || c == 27){ dtext("Quiting: Do You want to save Y/n"); c = getch(); if (c == 'Y' || c == 'y') explormap.saveMap(filename); else ; return 1; } else if(c == 'N' || c == 'n'){ dtext(""); break; } } } void putWall(int wswitch) { switch (wswitch){ case PUT: setcolor(BROWN); settextstyle(0, 0, 2); outtextxy(xloc*25+xloc+6, yloc*20+yloc+5, "W"); settextstyle(0, 0, 0); setcolor(WHITE); break; case ERASE: setcolor(BLACK); settextstyle(0, 0, 2); outtextxy(xloc*25+xloc+6, yloc*20+yloc+5, "W"); setcolor(WHITE); settextstyle(0, 0, 0); break; default: dtext("Error 511: wsitch not valid"); break; } } void putDoor(int dswitch) { switch (dswitch){ case PUT: setcolor(GREEN); settextstyle(0, 0, 2); outtextxy(xloc*25+xloc+6, yloc*20+yloc+5, "D"); settextstyle(0, 0, 0); setcolor(WHITE); break; case ERASE: setcolor(BLACK); settextstyle(0, 0, 2); outtextxy(xloc*25+xloc+6, yloc*20+yloc+5, "D"); setcolor(WHITE); settextstyle(0, 0, 0); break; default: dtext("Error 512: dswitch not valid"); break; } } void DispTileStats(void) { //Need to change EXPLORMAP class to make these work. char whatToDisp[100]; setfillstyle(SOLID_FILL, BLACK); sprintf(whatToDisp, "(T)ile State: %i", explormap.getTileStat(xloc, yloc)); bar(440, 50, 600, 56); outtextxy(440, 50, whatToDisp); sprintf(whatToDisp, "Property One: %i", explormap.getTileStat(xloc, yloc, 0)); bar(440, 60, 600, 66); outtextxy(440, 60, whatToDisp); sprintf(whatToDisp, "Property Two: %i", explormap.getTileStat(xloc, yloc, 1)); bar(440, 70, 600, 76); outtextxy(440, 70, whatToDisp); sprintf(whatToDisp, "X Location: %i", xloc); bar(440, 100, 600, 106); outtextxy(440, 100, whatToDisp); sprintf(whatToDisp, "Y Location: %i", yloc); bar(440, 110, 600, 116); outtextxy(440, 110, whatToDisp); } void SaveMap(char openmap[FNAMELEN]) { if (openmap == NULL){ dtext("Save Map as what:"); takeInput(openmap); } strcpy(filename, openmap); explormap.saveMap(openmap); dtext("Saved"); } /* void dtext(char *string); This function outputs a string into the text window. Returns no value. */ void dtext(char *string) { setcolor(BLACK); setfillstyle(SOLID_FILL, BLACK); bar(200, 380, 600, 390); setcolor(WHITE); outtextxy(202, 382, string); } /* void NewMap(void); This function show clear the current board and replace it with nothing and allow the user to rename the current map. It doesn't work right, yet. */ void NewMap(void) { int i; int j; dtext("Name the new map:"); takeInput(filename); clearviewport(); // Initialize(); GetCur(ptr); //GetSprite(tile); LoadDisp(); explormap.resetBoard(); xloc = 1; yloc = 1; PutCur(ptr, xloc, yloc, NULL, NULL); firstime = 0; } /* void OpenMap(char openmap[13]); This function clears the current map then either: a) if and argument is included: attempts to open the file b) runs the LoadMap function then displays the new map on the screen. Should be programmed later to return a certain value if it failed currently returns nothing. */ void OpenMap(char openmap[13]) { int i; int j; clearviewport(); clrscr(); closegraph(); if(openmap == NULL){ LoadMap(filename); }else{ strcpy(filename, openmap); } Initialize(); explormap.openMap(filename); /* To fix the memory issues all we fucking had to do was re-get the images used for the sprites */ GetCur(ptr); // This Fixed all the memory issues //GetSprite(tile); LoadDisp(); //The following code displays what the map looks like in the viewport. for(i=1;i<16;i++){ for(j=1;j<16;j++){ xloc = j; yloc = i; switch(explormap.getTileStat(xloc, yloc)){ case 10: putWall(PUT); break; case 20: putDoor(PUT); break; default: break; } } } xloc = 1; yloc = 1; // firstime1 = 0; #ifdef SHOWMOUSE initCursor(); #endif PutCur(ptr, xloc, yloc, NULL, NULL); } /* void BoardEdit(int x, int y, int stat); this edits the current x, y position on the board according to the value of stat given. */ void BoardEdit(int x, int y, int stat, unsigned int propedit) { // int tileselect[4] = {0, 10, 20, 30}; char buffer[80]; int newpropvalue; if(stat == TILE){ switch(explormap.boardEdit(x, y)){ case 10: putWall(PUT); dtext("Wall Placed"); break; case 20: putWall(ERASE); //Puts door image down putDoor(PUT); dtext("Wall Erased, Door Placed"); break; case 0: putDoor(ERASE); dtext("Door Erased"); break; default: dtext("Error 201: Tile incorrectly marked, defaulting to zero"); break; } // Edit Property[propedit] }else if(stat == PROP){ dtext("Enter the property value"); newpropvalue = takeInput(); explormap.boardEdit(x, y, propedit, newpropvalue); } } /* void GetSprite(void far *buf1[4]); This program gets the sprite for TILE and stores it in memory. Needs to be fixed. */ void GetSprite(void far *buf1[4]) { unsigned size; int block1; int i; size = imagesize(11, 11, 36, 32); for(block1=0;block1<=3;block1++){ if((buf1[block1] = farmalloc(size)) == NULL){ closegraph(); printf("Error: not enough heap space in GetSprite %i", i); exit(1); } } for(block1=0;block1<=3;block1++){ setfillstyle(SOLID_FILL, BROWN); bar(12, 12, 35, 31); for(i=0;i<=5; i++){ line((12+i*5-1), 12, (12+i*5-1), 31); } for(i=0; i<=2; i++){ line(11, 10*i+11, 16, 10*i+11); line(21, 10*i+11, 25, 10*i+11); line(31, 10*i+11, 35, 10*i+11); } for(i=0; i<=1; i++){ line(16, 10*i+16, 21, 10*i+16); line(26, 10*i+16, 31, 10*i+16); } getimage(11, 11, 36, 32, buf1[block1]); clearviewport(); } } /* void PutSprite(void far *buf1[4], int x, inty); This function puts the TILE sprite at the given explormap location */ void PutSprite(void far *buf1[4], int x, int y) { int block1; if(firstime != 1){ for(block1=0;block1<=3;block1++){ putimage(x*25+x+1, (y*20+y), buf1[block1], OR_PUT); farfree(buf1[block1]); } firstime=1; }else{ for(block1=0;block1<=3;block1++){ putimage(x*25+x+1, (y*20+y), buf1[block1], XOR_PUT); // farfree(buf1[block1]); } } } /* void PutCur(void far *buf[4], int x, int y, int oldx, int oldy); Put the cursor image at the new location as well as clears the old position needs some repairing. */ void PutCur(void far *buf[4], int x, int y, int oldx, int oldy) { int block; if(oldx == NULL && oldy == NULL && firstime1 == 0){ for (block=0; block<=3; block++) { putimage(x*25+x-2, (y*20+y-2), buf[block], OR_PUT); farfree(buf[block]); firstime1 = 1; } }else if(oldx == NULL & oldy == NULL){ for (block=0; block<=3; block++) { putimage(x*25+x-2, (y*20+y-2), buf[block], OR_PUT); farfree(buf[block]); } }else{ for (block=0; block<=3; block++){ putimage(oldx*25+oldx-2,(oldy*20+oldy-2), buf[block], XOR_PUT); // farfree(buf[block]); } for (block=0; block<=3; block++) { putimage(x*25+x-2, (y*20+y-2), buf[block], XOR_PUT); // farfree(buf[block]); } } } /* void GetCur(void far *buf[4]) Gets the image used for the cursor and stores it in memory. Needs some fixing. */ void GetCur(void far *buf[4]) { unsigned size; int block; size = imagesize(9, 9, 39, 34); for(block=0;block<=3;block++){ if((buf[block] = farmalloc(size)) == NULL){ closegraph(); printf("Error: not enough heap space in GetCur %i", block); exit(1); } // setcolor(GREEN); rectangle(10, 10, 38, 33); rectangle(9, 9, 39, 34); // setcolor(WHITE); getimage(9, 9, 39, 34, buf[block]); } setcolor(BLACK); rectangle(10, 10, 38, 33); rectangle(9, 9, 39, 34); setcolor(WHITE); // farfree(buf[block]); clearviewport(); } /* void LoadDisp(void); Loads the constant viewport. */ void LoadDisp(void) { // int c; // int x; // int y; int i; setcolor(WHITE); rectangle(0, 479, 639, 350); setfillstyle(SOLID_FILL, 22); floodfill(1, 351, WHITE); rectangle(2, 364, 637, 352); setfillstyle(SOLID_FILL, LIGHTGRAY); floodfill(3, 363, WHITE); setcolor(BLACK); outtextxy(6, 355, "ExplorEd: Copyright 2001, Beem Software by <NAME>"); setcolor(RED); outtextxy(5, 354, "ExplorEd: Copyright 2001, Beem Software by <NAME>"); setcolor(WHITE); outtextxy(5, 370, "(N)ew"); outtextxy(5, 379, "(O)pen"); outtextxy(5, 388, "(S)ave"); outtextxy(5, 397, "Save (A)s"); outtextxy(5, 406, "P(r)int"); setcolor(WHITE); for(i=1; i<MAPWIDTH+2; i++){ line(i+25*i, 21, i+25*i, 314+21); line(26, i+20*i, 390+26, i+20*i); } } /* int GetKey(void); The bulk of the program takes input and acts accordingly. Returns 0 if programs should continue. Or a 1 if program should terminate. */ void Initialize() { int xasp, yasp; int GraphDriver; int GraphMode; int ErrorCode; GraphDriver = DETECT; /* Request auto-detection */ initgraph(&GraphDriver,&GraphMode,""); ErrorCode = graphresult(); /* Read result of initialization*/ if( ErrorCode != grOk ){ /* Error occured during init */ printf(" Graphics System Error: %s\n", grapherrormsg(ErrorCode)); exit(1); } } int disableCursor(void) { mregs.x.ax = 2; int86(0x33, &mregs, &mregs); } int initCursor(void) { mregs.x.ax = 1; int86(0x33, &mregs, &mregs); return 0; } int initMouse(void) { mregs.x.ax = 0; int86(0x33, &mregs, &mregs); if(!mregs.x.ax) return 1; return 0; } int GetKey(void) { int c; while(!kbhit()){ mregs.x.ax=3; int86(0x33, &mregs, &mregs); if(mregs.x.bx>0){ gotoxy(1,1); // printf("Button Pressed is %i", mregs.x.bx); dtext("Button pressed"); continue; }else{ //dtext(""); continue; } } c = getch(); c = toupper(c); switch (c){ case UP: dtext("Up"); if(yloc > 1){ yloc--; PutCur(ptr, xloc, yloc, xloc, yloc+1); } break; case DOWN: dtext("Down"); if(yloc < 15){ yloc++; PutCur(ptr, xloc, yloc, xloc, yloc-1); } break; case LEFT: dtext( "Left"); if(xloc > 1){ xloc--; PutCur(ptr, xloc, yloc, xloc+1, yloc); } break; case RIGHT: dtext( "Right"); if(xloc < 15){ xloc++; PutCur(ptr, xloc, yloc, xloc-1, yloc); } break; case 'S': dtext( "Saving..."); SaveMap(filename); break; case 'N': dtext( "Generating Map"); NewMap(); break; case 'O': dtext( "Opening"); OpenMap(NULL); break; case 'A': dtext("Saving As..."); SaveMap(NULL); break; case 'R': dtext( "Print: Not Implemented"); break; case ('F'): //Special currently displays filename dtext(filename); break; case '1': BoardEdit(xloc, yloc, PROP, 0); break; case '2': BoardEdit(xloc, yloc, PROP, 1); break; case 27: // if(quiting(c) == 1) return quiting(c); break; case 'T': BoardEdit(xloc, yloc, TILE, NULL); break; default: dtext( "Command Not Recognized"); break; } return 0; } <file_sep>/games/Legacy-Engine/Source/engine/lg_elements.cpp //lg_elements.cpp Copyright (c) 2007 <NAME> //This is more or less where all the global elements //of the legacy engine are stored... //However instead of simply accessing the globabls by //using an extern a class that uses a global needs //to inhererit the element as a child class, //so if a class needs to use the IDirect3DDevice9 interface //then that class needs to inherit CElementD3D, and if a //class needs to use the global timer then that class //needs to inherit CElementTimer, etc... //The actual declarations for these class are in the header file //directly above the elements. #include "lv_sys.h" IDirect3D9* CElementD3D::s_pD3D=0; IDirect3DDevice9* CElementD3D::s_pDevice=0; IDirect3DSurface9* CElementD3D::s_pBackSurface=0; lg_uint CElementD3D::s_nAdapterID=0; D3DDEVTYPE CElementD3D::s_nDeviceType=D3DDEVTYPE_HAL; D3DFORMAT CElementD3D::s_nBackBufferFormat=D3DFMT_UNKNOWN; lg_dword CElementD3D::s_nDisplayWidth=0; lg_dword CElementD3D::s_nDisplayHeight=0; #include "lt_sys.h" CLTimer CElementTimer::s_Timer; #include "li_sys.h" CLICommand* CElementInput::s_pCmds=0; CLAxis* CElementInput::s_pAxis=0; <file_sep>/tools/PodSyncPrep/src/podsyncp/resources/SettingsBox.properties m_btnOkay.text=Apply onBtnOkay.Action.text= onBtnOkay.Action.shortDescription= jLabel1.text=Working Directory m_txtWorkingDir.text=./ m_cboxDate.text=Use date in filename m_btnBrowse.text=Browse... onBtnBrowse.Action.text= onBtnBrowse.Action.shortDescription= Form.title=Settings m_btnCancel.text=Cancel onBtnCancel.Action.shortDescription= onBtnCancel.Action.text= <file_sep>/games/Explor2002/Source/Game/DirectMidi.h // DirectMidi.h: interface for the CDirectMidi class. //Copyright <NAME>, 2000 //Last updated October 12, 2000 #if !defined(AFX_DIRECTMIDI_H) #define AFX_DIRECTMIDI_H #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include <windows.h> #include <dmusici.h> class CDirectMidi{ //DirectMusic MIDI class private: BOOL m_bInitialized; //TRUE if initialized correctly IDirectMusicPerformance* m_pPerf; //performance IDirectMusicLoader* m_pLoader; //loader IDirectMusicSegment* m_pMIDIseg; //midi segment IDirectMusicSegmentState* m_pSegState; //segment state BOOL CreatePerformance(void); //create performance BOOL CreateLoader(void); //create MIDI loader BOOL LoadMIDISegment(char* wszMidiFileName); //create segment public: CDirectMidi(); //constructor virtual ~CDirectMidi(); //destructor void Load(char* filename); //load MIDI from file void Play(); //play loaded MIDI void Stop(); //stop playing MIDI BOOL IsPlaying(); //TRUE if playing void Toggle(); //toggle stop/play }; #endif // !defined(AFX_DIRECTMIDI_H) <file_sep>/games/Legacy-Engine/Scrapped/old/lw_wstolw.cpp #include "lw_sys.h" #include "lg_err.h" #include <stdio.h> typedef struct _WSToLW_COUNTS{ lg_dword nMaterialCount; lg_dword nLightMapCount; lg_dword nLMSize; lg_dword nBrushCount; lg_dword nFaceCount; lg_dword nVisibleFaceCount; lg_dword nTotalVertexCount; lg_dword nVisGroupCount; }WSToLW_COUNTS; typedef struct _WS_MATERIAL{ LW_MATERIAL szMaterial; lg_dword nReference; }WS_MATERIAL; typedef struct _WS_VISGROUP{ LW_NAME szName; lg_dword nRef; lg_dword nFirstFace; lg_dword nFaceCount; lg_dword nVisibleFaceCount; lg_dword nFirstVertex; lg_dword nVertexCount; }WS_VISGROUP; typedef struct _WS_RASTER_FACE{ lg_bool bVisible; lg_dword nFirst; lg_dword nNumTriangles; lg_dword nMatRef; lg_dword nLMRef; lg_dword nRoom; ML_VEC4 v4PlaneEq; lg_dword nOpFlags; }WS_RASTER_FACE; #define WS_RASTER_FACE_COPIED 0x00000001 void WSToLW_SortData(WS_RASTER_FACE* pFaces, WS_VISGROUP* pVisGrp, LW_VERTEX* pVerts, WSToLW_COUNTS* pCounts); void WSToLW_GetNameTable(lg_char** szNames, lg_byte* pData, lg_dword nSize, lg_long nNumNames); void WSToLW_GetCounts(LF_FILE3 file, WSToLW_COUNTS* pCounts, lg_char** szNames, lg_long nObjectCount); lg_bool WSToLW(lf_path szFilenameIn, lf_path szFilenameOut) { //Map Header. lg_word nVersion; lg_byte nFlags; lg_long nNameCount; lg_long nNameOffset; lg_long nObjectCount; lg_long nObjectOffset; LF_FILE3 fileMap=LG_NULL; lg_char** szNames=LG_NULL; WS_MATERIAL* pMaterials=LG_NULL; LW_VERTEX* pVertexes=LG_NULL; lg_byte* pLMData=LG_NULL; WS_RASTER_FACE* pFaces=LG_NULL; WS_VISGROUP* pVisGroups=LG_NULL; lg_byte* pData; try { fileMap=LF_Open(szFilenameIn, LF_ACCESS_READ|LF_ACCESS_MEMORY, LF_OPEN_EXISTING); if(!fileMap) { throw("WSToLW ERROR: Could not open file."); } //First check the map header to make sure it is a valid map... if((LF_Read(fileMap, &nVersion, 2)!=2) || (nVersion!=14) ) { throw("WSToLW ERROR: File is not a valid 3D World Studio Map."); } pData=(lg_byte*)LF_GetMemPointer(fileMap); //Now read the rest of the header... LF_Read(fileMap, &nFlags, 1); LF_Read(fileMap, &nNameCount, 4); LF_Read(fileMap, &nNameOffset, 4); LF_Read(fileMap, &nObjectCount, 4); LF_Read(fileMap, &nObjectOffset, 4); //Now read the name table... szNames=new lg_char*[nNameCount+1]; if(!szNames) { throw("WSToLW ERROR: Out of memory."); } WSToLW_GetNameTable(szNames, &pData[nNameOffset], LF_GetSize(fileMap)-nNameOffset, nNameCount); /* for(lg_dword i=0; i<=nNameCount; i++) { Err_Printf("Name %d: %s", i, szNames[i]); } */ //Get all the object counts... WSToLW_COUNTS counts; LF_Seek(fileMap, LF_SEEK_BEGIN, nObjectOffset); WSToLW_GetCounts(fileMap, &counts, szNames, nObjectCount); #if 1 Err_Printf("Materials: %d", counts.nMaterialCount); Err_Printf("Light Maps: %d", counts.nLightMapCount); Err_Printf("Biggest LM: %d", counts.nLMSize); Err_Printf("Brushes: %d", counts.nBrushCount); Err_Printf("Faces: %d", counts.nFaceCount); Err_Printf("Visible Faces: %d", counts.nVisibleFaceCount); Err_Printf("Vertices: %d", counts.nTotalVertexCount); Err_Printf("Polys: %d", counts.nTotalVertexCount/3); Err_Printf("Vis Groups: %d", counts.nVisGroupCount); #endif //Get all the objects. pMaterials=new WS_MATERIAL[counts.nMaterialCount]; pVertexes=new LW_VERTEX[counts.nTotalVertexCount+3]; //Add room for 3 more vertexes for processing. pLMData=new lg_byte[counts.nLightMapCount*(counts.nLMSize+4)]; pVisGroups=new WS_VISGROUP[counts.nVisGroupCount]; pFaces=new WS_RASTER_FACE[counts.nFaceCount]; if(!pMaterials || !pVertexes || !pLMData || !pFaces) throw("WSToLW ERROR: Out of memory."); // Get the materials and count the number of vertices LF_Seek(fileMap, LF_SEEK_BEGIN, nObjectOffset); for(lg_dword i=1, nMat=0, nVert=0, nBrush=0, nLM=0, nFace=0, nVisGrp=0; i<=nObjectCount; i++) { lg_dword nName; lg_long nSize; LF_Read(fileMap, &nName, 4); LF_Read(fileMap, &nSize, 4); if(strcmp(szNames[nName], "material")==0) { if(nMat>=counts.nMaterialCount) { LF_Seek(fileMap, LF_SEEK_CURRENT, nSize); continue; } lg_byte nFlags; lg_dword nGroup; lg_dword nObject; lg_dword nExt; LF_Read(fileMap, &nFlags, 1); LF_Read(fileMap, &nGroup, 4); LF_Read(fileMap, &nObject, 4); if(nFlags&0x02) LF_Read(fileMap, &nExt, 4); if(strcmp(szNames[nGroup], "textures")==0) _snprintf(pMaterials[nMat].szMaterial, 255, "%s/%s.%s", szNames[nGroup], szNames[nObject], (nFlags&0x02)?szNames[nExt]:"tga"); else _snprintf(pMaterials[nMat].szMaterial, 255, "textures/%s/%s.%s", szNames[nGroup], szNames[nObject], (nFlags&0x02)?szNames[nExt]:"tga"); pMaterials[nMat].nReference=i; nMat++; } else if(strcmp(szNames[nName], "visgroup")==0) { if(nVisGrp>=counts.nVisGroupCount) { LF_Seek(fileMap, LF_SEEK_CURRENT, nSize); continue; } lg_dword nName; //Skip the flags LF_Seek(fileMap, LF_SEEK_CURRENT, 1); LF_Read(fileMap, &nName, 4); //Skip the color LF_Seek(fileMap, LF_SEEK_CURRENT, 3); pVisGroups[nVisGrp].nRef=i; strncpy(pVisGroups[nVisGrp].szName, szNames[nName], LW_MAX_NAME-1); pVisGroups[nVisGrp].szName[LW_MAX_NAME-1]=0; nVisGrp++; } else if(strcmp(szNames[nName], "lightmap")==0) { //We'll just read the lightmap data, and do the conversion //to a tga when we write the lw file. lg_dword* pRef=(lg_dword*)&pLMData[4*nLM]; lg_byte* pLM=&pLMData[4*counts.nLightMapCount+nLM*counts.nLMSize]; if(nLM>=counts.nLightMapCount) { LF_Seek(fileMap, LF_SEEK_CURRENT, nSize); continue; } *pRef=i; LF_Read(fileMap, pLM, nSize); nLM++; } else if(strcmp(szNames[nName], "brush")==0) { if(nVert>=counts.nTotalVertexCount) { LF_Seek(fileMap, LF_SEEK_CURRENT, nSize); continue; } lg_dword nBegin=LF_Tell(fileMap); lg_byte nFlags; lg_long nKeys; lg_long nGrp; lg_long nVisGrp; lg_byte nVertexCount; lg_byte nFaceCount; LF_Read(fileMap, &nFlags, 1); LF_Read(fileMap, &nKeys, 4); LF_Seek(fileMap, LF_SEEK_CURRENT, nKeys*8); LF_Read(fileMap, &nGrp, 4); LF_Read(fileMap, &nVisGrp, 4); //Skip the color LF_Seek(fileMap, LF_SEEK_CURRENT, 3); LF_Read(fileMap, &nVertexCount, 1); ML_VEC3* pVerts=new ML_VEC3[nVertexCount]; if(!pVerts) throw("WSToLW ERROR: Out of memory."); for(lg_byte i=0; i<nVertexCount; i++) { LF_Read(fileMap, &pVerts[i], 12); } LF_Read(fileMap, &nFaceCount, 1); for(lg_byte i=0; i<nFaceCount; i++) { lf_byte nFaceFlags; ML_VEC4 v4PlaneEq; lg_long nMaterial; lg_long nLightMap; LF_Read(fileMap, &nFaceFlags, 1); LF_Read(fileMap, &v4PlaneEq, 16); LF_Seek(fileMap, LF_SEEK_CURRENT, 64); LF_Read(fileMap, &nMaterial, 4); if(nFaceFlags&16) LF_Read(fileMap, &nLightMap, 4); else nLightMap=0xFFFFFFFF; lf_byte nIndexCount; LF_Read(fileMap, &nIndexCount, 1); pFaces[nFace].bVisible=!(nFaceFlags&0x04); pFaces[nFace].nFirst=nVert; pFaces[nFace].nMatRef=nMaterial; pFaces[nFace].nLMRef=nLightMap; //Note need to change this... pFaces[nFace].nRoom=nVisGrp; pFaces[nFace].nNumTriangles=(nIndexCount-2); pFaces[nFace].v4PlaneEq=v4PlaneEq; pFaces[nFace].nOpFlags=0; nFace++; for(lg_byte i=0; i<nIndexCount; i++) { lg_byte nV; ML_VEC2 v2Tex, v2LM; LF_Read(fileMap, &nV, 1); pVertexes[nVert].v3Pos=pVerts[nV]; LF_Read(fileMap, &v2Tex, 8); if(nFaceFlags&16) { LF_Read(fileMap, &v2LM, 8); } else { v2LM.x=0; v2LM.y=0; } //If the face isn't visible we don't //need to save it to the raster data. if(L_CHECK_FLAG(nFaceFlags, 0x04) || (nVert>=counts.nTotalVertexCount)) continue; //The first three vertexes in a face are //the first three vertexes read, after that the //vertexes are in a fan, and therefore it is //necessary to set the first vertex to the first //vertex of the last triangle, and the second vertex //to the last vertex of the previous triangle, and //the new vertex as the new vertex. In this way a //triangle list is created. if(i<3) { pVertexes[nVert].v3Pos=pVerts[nV]; pVertexes[nVert].v2Tex=v2Tex; pVertexes[nVert].v2LM=v2LM; } else { pVertexes[nVert]=pVertexes[nVert-3]; pVertexes[nVert+1]=pVertexes[nVert-1]; nVert+=2; pVertexes[nVert].v3Pos=pVerts[nV]; pVertexes[nVert].v2Tex=v2Tex; pVertexes[nVert].v2LM=v2LM; } nVert++; } } L_safe_delete_array(pVerts); LF_Seek(fileMap, LF_SEEK_BEGIN, nBegin+nSize); } else { LF_Seek(fileMap, LF_SEEK_CURRENT, nSize); } } //Reverse the vertex orders for(lg_dword i=0; i<counts.nTotalVertexCount; i+=3) { LW_VERTEX vt=pVertexes[i]; pVertexes[i]=pVertexes[i+2]; pVertexes[i+2]=vt; } //Change references for material, lightmap, and visgroups. for(lg_dword i=0; i<counts.nFaceCount; i++) { for(lg_dword j=0; j<counts.nMaterialCount; j++) { if(pFaces[i].nMatRef==pMaterials[j].nReference) { pFaces[i].nMatRef=j; break; } } for(lg_dword j=0; j<counts.nLightMapCount; j++) { lg_dword* pLMRef=(lg_dword*)&pLMData[j*4]; if(pFaces[i].nLMRef==*pLMRef) { pFaces[i].nLMRef=j; break; } } for(lg_dword j=0; j<counts.nVisGroupCount; j++) { if(pFaces[i].nRoom==pVisGroups[j].nRef) { pFaces[i].nRoom=j; break; } } } //We are going to restructure the vertexes, so that all //faces that share the same texture in a room will be part //of the same segment. WSToLW_SortData(pFaces, pVisGroups, pVertexes, &counts); //Now write the map... lg_word nID=LW_ID; lg_dword nVersion=LW_VERSION; lg_dword nVertexCount=counts.nTotalVertexCount; lg_dword nVertexOffset=0; lg_dword nMaterialCount=counts.nMaterialCount; lg_dword nMaterialOffset=0; lg_dword nLMCount=counts.nLightMapCount; lg_dword nLMOffset=0; lg_dword nLMTotalSize=0; //This is just temporary, later faces will be organized according to room. lg_dword nFaceCount=counts.nVisibleFaceCount; lg_dword nFaceOffset=0; lg_dword nRegionCount=counts.nVisGroupCount; lg_dword nRegionOffset=0; LF_FILE3 fout=LF_Open(szFilenameOut, LF_ACCESS_WRITE, LF_CREATE_ALWAYS); if(!fout) throw("WSToLW ERROR: Could not open output file."); LF_Write(fout, &nID, 2); LF_Write(fout, &nVersion, 4); LF_Write(fout, &nVertexCount, 4); LF_Write(fout, &nVertexOffset, 4); LF_Write(fout, &nMaterialCount, 4); LF_Write(fout, &nMaterialOffset, 4); LF_Write(fout, &nLMCount, 4); LF_Write(fout, &nLMOffset, 4); LF_Write(fout, &nLMTotalSize, 4); LF_Write(fout, &nFaceCount, 4); LF_Write(fout, &nFaceOffset, 4); LF_Write(fout, &nRegionCount, 4); LF_Write(fout, &nRegionOffset, 4); //We can simply write the vertexes nVertexOffset=LF_Tell(fout); for(lg_dword i=0; i<nVertexCount; i++) { LF_Write(fout, &pVertexes[i], 28); } //we can do the same for the materials nMaterialOffset=LF_Tell(fout); for(lg_dword i=0; i<nMaterialCount; i++) { LF_Write(fout, &pMaterials[i].szMaterial, 256); } //Light maps are a little more complicate, we need to convert each lightmap //to a tga file, and then write the tga file. nLMOffset=LF_Tell(fout); //Write each of the light maps for(lg_dword i=0; i<nLMCount; i++) { lg_byte* pLM=&pLMData[4*counts.nLightMapCount+i*counts.nLMSize]; lg_word nRes=ML_Pow2(pLM[1]); lg_byte nHeader[18]; lg_dword nImgDataSize=nRes*nRes*3; lg_dword nSize=18+nImgDataSize; //Start off by writing the size, then write the image data... LF_Write(fout, &nSize, 4); nLMTotalSize+=4; memset(nHeader, 0, 18); //Setup the tga header... nHeader[2]=2; *(lg_word*)(&nHeader[12])=nRes; *(lg_word*)(&nHeader[14])=nRes; nHeader[16]=24; nHeader[17]=0x20; //Write the header... LF_Write(fout, nHeader, 18); nLMTotalSize+=18; //Write the image data... LF_Write(fout, &pLM[6], nImgDataSize); nLMTotalSize+=nImgDataSize; } //We'll write only visible faces... nFaceOffset=LF_Tell(fout); for(lg_dword i=0; i<nFaceCount; i++) { LF_Write(fout, &pFaces[i].nFirst, 4); LF_Write(fout, &pFaces[i].nNumTriangles, 4); LF_Write(fout, &pFaces[i].nMatRef, 4); LF_Write(fout, &pFaces[i].nLMRef, 4); } //Write the regions... nRegionOffset=LF_Tell(fout); for(lg_dword i=0; i<nRegionCount; i++) { LF_Write(fout, &pVisGroups[i].szName, 32); LF_Write(fout, &pVisGroups[i].nFirstFace, 4); LF_Write(fout, &pVisGroups[i].nFaceCount, 4); LF_Write(fout, &pVisGroups[i].nFirstVertex, 4); LF_Write(fout, &pVisGroups[i].nVertexCount, 4); } //Err_Printf("Light Map Size: %d", nLMTotalSize); LF_Seek(fout, LF_SEEK_BEGIN, 10); LF_Write(fout, &nVertexOffset, 4); LF_Seek(fout, LF_SEEK_CURRENT, 4); LF_Write(fout, &nMaterialOffset, 4); LF_Seek(fout, LF_SEEK_CURRENT, 4); LF_Write(fout, &nLMOffset, 4); LF_Write(fout, &nLMTotalSize, 4); LF_Seek(fout, LF_SEEK_CURRENT, 4); LF_Write(fout, &nFaceOffset, 4); LF_Seek(fout, LF_SEEK_CURRENT, 4); LF_Write(fout, &nRegionOffset, 4); LF_Close(fout); throw("OK"); } //try catch(lg_cstr szError) { Err_Printf("Map Conversion Result: %s", szError); if(fileMap)LF_Close(fileMap); L_safe_delete_array(szNames); L_safe_delete_array(pMaterials); L_safe_delete_array(pVertexes); L_safe_delete_array(pLMData); L_safe_delete_array(pFaces); L_safe_delete_array(pVisGroups); if(strcmp(szError, "OK")==0) return LG_TRUE; else return LG_FALSE; } } void WSToLW_SortData(WS_RASTER_FACE* pFaces, WS_VISGROUP* pVisGrps, LW_VERTEX* pVerts, WSToLW_COUNTS* pCounts) { lg_dword nFace=0, nVisGrp=0, nMaterial=0, nLightmap=0; WS_RASTER_FACE* pTempFaces=new WS_RASTER_FACE[pCounts->nFaceCount]; if(!pTempFaces) return; //Store all the faces in the temporary array... memcpy(pTempFaces, pFaces, sizeof(WS_RASTER_FACE)*pCounts->nFaceCount); //Sort the data into the original array.. for(nVisGrp=0; nVisGrp<pCounts->nVisGroupCount; nVisGrp++) { pVisGrps[nVisGrp].nFirstFace=nFace; pVisGrps[nVisGrp].nFaceCount=0; pVisGrps[nVisGrp].nVisibleFaceCount=0; pVisGrps[nVisGrp].nFirstVertex=0; pVisGrps[nVisGrp].nVertexCount=0; } nVisGrp=0; do { for(lg_dword i=0; i<pCounts->nFaceCount; i++) { if(nFace>=pCounts->nVisibleFaceCount) break; if(!pTempFaces[i].bVisible) continue; if(pTempFaces[i].nRoom!=nVisGrp) continue; if(pTempFaces[i].nMatRef!=nMaterial) continue; if(pTempFaces[i].nLMRef!=nLightmap) continue; //If all the criteria are met add the face to the list. pFaces[nFace]=pTempFaces[i]; nFace++; pVisGrps[nVisGrp].nFaceCount++; pVisGrps[nVisGrp].nVisibleFaceCount++; } if(nLightmap==0xFFFFFFFF) { nLightmap=0; nMaterial++; if(nMaterial>=pCounts->nMaterialCount) { nMaterial=0; nVisGrp++; if(nVisGrp>=pCounts->nVisGroupCount) break; pVisGrps[nVisGrp].nFirstFace=nFace; pVisGrps[nVisGrp].nFaceCount=0; pVisGrps[nVisGrp].nVisibleFaceCount=0; } } else nLightmap++; if((nLightmap>=pCounts->nLightMapCount) && (nLightmap!=0xFFFFFFFF)) { nLightmap=0xFFFFFFFF; } }while(nFace<pCounts->nVisibleFaceCount); for(lg_dword i=nFace; i<pCounts->nFaceCount; i++) { memset(&pFaces[i], 0, sizeof(WS_RASTER_FACE)); } //Now we will resort all the vertexes... //The vertexes are being sorted in the order of the faces, //that way faces that have the same texture and lightmap //can be catenated. LW_VERTEX* pTempVerts=new LW_VERTEX[pCounts->nTotalVertexCount]; if(!pTempVerts) return; memcpy(pTempVerts, pVerts, sizeof(LW_VERTEX)*pCounts->nTotalVertexCount); for(lg_dword nFace=0, nVertex=0; nFace<pCounts->nVisibleFaceCount; nFace++) { //Simply copy the faces vertexes to the destination buffer, //then set the new first vertex, and advance to the next vertex //to be written to. memcpy( &pVerts[nVertex], &pTempVerts[pFaces[nFace].nFirst], sizeof(LW_VERTEX)*pFaces[nFace].nNumTriangles*3); pFaces[nFace].nFirst=nVertex; nVertex+=pFaces[nFace].nNumTriangles*3; } L_safe_delete_array(pTempVerts); //We'll now reduce the number of faces into segments (each segment will //be composed of triangles that have the same texture and lightmap). for(lg_dword nVisGrp=0; nVisGrp<pCounts->nVisGroupCount; nVisGrp++) { lg_dword nLastMat=0, nLastLM=0; WS_RASTER_FACE* pCurFace=LG_NULL; lg_dword nStart=pVisGrps[nVisGrp].nFirstFace; lg_dword nEnd=pVisGrps[nVisGrp].nFirstFace+pVisGrps[nVisGrp].nFaceCount; for(lg_dword i=nStart; i<nEnd; i++) { if(!pCurFace) { pCurFace=&pFaces[i]; nLastMat=pCurFace->nMatRef; nLastLM=pCurFace->nLMRef; continue; } if((nLastMat==pFaces[i].nMatRef) && (nLastLM==pFaces[i].nLMRef)) { pCurFace->nNumTriangles+=pFaces[i].nNumTriangles; pFaces[i].nNumTriangles=0; } else { pCurFace=&pFaces[i]; nLastMat=pCurFace->nMatRef; nLastLM=pCurFace->nLMRef; } } } //We'll now eliminate all the empty faces... memcpy(pTempFaces, pFaces, sizeof(WS_RASTER_FACE)*pCounts->nVisibleFaceCount); nFace=0; for(lg_dword nVisGrp=0; nVisGrp<pCounts->nVisGroupCount; nVisGrp++) { lg_dword nStart=pVisGrps[nVisGrp].nFirstFace; lg_dword nEnd=pVisGrps[nVisGrp].nFirstFace+pVisGrps[nVisGrp].nFaceCount; pVisGrps[nVisGrp].nFirstFace=nFace; pVisGrps[nVisGrp].nFaceCount=0; for(lg_dword i=nStart; i<nEnd; i++) { if(pTempFaces[i].nNumTriangles>0) { pFaces[nFace]=pTempFaces[i]; pVisGrps[nVisGrp].nFaceCount++; nFace++; } } } Err_Printf("NOTICE: %d faces reduced to %d segments %0.2f%%.", pCounts->nVisibleFaceCount, nFace, (float)nFace/(float)pCounts->nVisibleFaceCount*100.0f); pCounts->nVisibleFaceCount=nFace; L_safe_delete_array(pTempFaces); //We'll now setup some more information about the vis groups for(lg_dword i=0; i<pCounts->nVisGroupCount; i++) { pVisGrps[i].nFirstVertex=pFaces[pVisGrps[i].nFirstFace].nFirst; lg_dword nCount=0; for(lg_dword j=0; j<pVisGrps[i].nFaceCount; j++) { nCount+=pFaces[pVisGrps[i].nFirstFace+j].nNumTriangles*3; } pVisGrps[i].nVertexCount=nCount; } //For testing purposes print out the results for(lg_dword i=0; i<pCounts->nVisGroupCount; i++) { Err_Printf( "Vis Group %d: %s (%d) FirstFace=%d FaceCount=%d VisibleFaces=%d First Vertex: %d Vertex Count: %d", i, pVisGrps[i].szName, pVisGrps[i].nRef, pVisGrps[i].nFirstFace, pVisGrps[i].nFaceCount, pVisGrps[i].nVisibleFaceCount, pVisGrps[i].nFirstVertex, pVisGrps[i].nVertexCount); for(lg_dword j=0; j<pVisGrps[i].nFaceCount; j++) { lg_dword offset=j+pVisGrps[i].nFirstFace; Err_Printf(" Face %d: S: %d: C: %d: Mat: %d: LM: %d: Room: %d\n", offset, pFaces[offset].nFirst, pFaces[offset].nNumTriangles, pFaces[offset].nMatRef, pFaces[offset].nLMRef, pFaces[offset].nRoom); } } } void WSToLW_GetCounts(LF_FILE3 file, WSToLW_COUNTS* pCounts, lg_char** szNames, lg_long nObjectCount) { WSToLW_COUNTS counts; memset(&counts, 0, sizeof(counts)); //Count all the objects for(lg_dword i=1; i<=nObjectCount; i++) { lg_dword nName; lg_long nSize; LF_Read(file, &nName, 4); LF_Read(file, &nSize, 4); //Err_Printf("Ojbect %d (%d): %s", i, nSize, szNames[nName]); if(strcmp(szNames[nName], "material")==0) counts.nMaterialCount++; if(strcmp(szNames[nName], "visgroup")==0) counts.nVisGroupCount++; if(strcmp(szNames[nName], "lightmap")==0) { counts.nLightMapCount++; counts.nLMSize=LG_Max(counts.nLMSize, nSize); } if(strcmp(szNames[nName], "brush")==0) { counts.nBrushCount++; lg_dword nBegin=LF_Tell(file); lg_byte nFlags; lg_long nKeys; lg_byte nVertexCount; lg_byte nFaceCount; LF_Read(file, &nFlags, 1); LF_Read(file, &nKeys, 4); LF_Seek(file, LF_SEEK_CURRENT, nKeys*8); LF_Seek(file, LF_SEEK_CURRENT, 4+4+3); LF_Read(file, &nVertexCount, 1); LF_Seek(file, LF_SEEK_CURRENT, 12*nVertexCount); LF_Read(file, &nFaceCount, 1); counts.nFaceCount+=nFaceCount; for(lg_byte i=0; i<nFaceCount; i++) { lf_byte nFaceFlags; LF_Read(file, &nFaceFlags, 1); LF_Seek(file, LF_SEEK_CURRENT, 84); if(nFaceFlags&16) LF_Seek(file, LF_SEEK_CURRENT, 4); lf_byte nIndexCount; LF_Read(file, &nIndexCount, 1); if(!(nFaceFlags&0x04)) { counts.nTotalVertexCount+=3+(nIndexCount-3)*3; counts.nVisibleFaceCount++; } if(nFaceFlags&16) LF_Seek(file, LF_SEEK_CURRENT, nIndexCount*17); else LF_Seek(file, LF_SEEK_CURRENT, nIndexCount*9); } LF_Seek(file, LF_SEEK_BEGIN, nBegin); } LF_Seek(file, LF_SEEK_CURRENT, nSize); } *pCounts=counts; } void WSToLW_GetNameTable(lg_char** szNames, lg_byte* pData, lg_dword nSize, lg_long nNumNames) { lg_long nNamesFound=1; szNames[0]=LG_NULL; szNames[1]=(lg_char*)&pData[0]; for(lg_dword i=0; i<nSize; i++) { if(pData[i]==0) { nNamesFound++; szNames[nNamesFound]=(lg_char*)&pData[i+1]; } if(nNamesFound>=nNumNames) return; } } <file_sep>/tools/fs_sys2/fs_internal.h #include "fs_sys2.h" #if defined( __cplusplus ) extern "C" { #endif void* FS_Malloc(fs_size_t size, LF_ALLOC_REASON reason, const fs_char8*const type, const fs_char8*const file, const fs_uint line); void FS_Free(void* p, LF_ALLOC_REASON reason); /* Path name parsing functions. */ fs_str8 FS_GetDirFromPathA(fs_str8 szDir, fs_cstr8 szFullPath); fs_str16 FS_GetDirFromPathW(fs_str16 szDir, fs_cstr16 szFullPath); void FS_FixCaseA(fs_pathA szOut, fs_cstr8 szFullPath); void FS_FixCaseW(fs_pathW szOut, fs_cstr16 szFullPath); void FS_ErrPrintW(fs_cstr16 szFormat, FS_ERR_LEVEL nErrLevel, ...); void FS_ErrPrintA(fs_cstr8 szFormat, FS_ERR_LEVEL nErrLevel, ...); #if defined( __cplusplus ) } //extern "C" #endif #if defined( __cplusplus ) class IFsMemObj { public: void* operator new(fs_size_t Size); void operator delete(void*); }; #endif <file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/lm_sys.h #ifndef __LM_SYS_H__ #define __LM_SYS_H__ #include <common.h> #include <d3dx9.h> #define LMESH_ID (*(L_dword*)"L3DM") #define LMESH_VERSION (116) //Final version will be 200. #define LMESH_MAX_NAME_LENGTH (32) #define LMESH_MAX_PATH (64) //The Structures: #pragma pack(1) typedef struct _LMESH_VERTEX{ float x, y, z; //Vertex Coordinates. float nx, ny, nz; //Vertex Normals. float tu, tv; //Texture Coordinates. }LMESH_VERTEX, *PLMESH_VERTEX; #define LMESH_VERTEX_FORMAT (D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX1) typedef struct _LMESH_SET{ char szName[LMESH_MAX_NAME_LENGTH]; //Name of the mesh. L_dword nFirstVertex; //Index of the first vertex in the mesh. L_dword nNumTriangles; //Number of triangles in the mesh. L_dword nMaterialIndex; //Index of the mesh material. }LMESH_SET, *PLMESH_SET; typedef struct _LMESH_MATERIAL{ char szMaterialName[LMESH_MAX_NAME_LENGTH]; char szTexture[LMESH_MAX_PATH]; }LMESH_MATERIAL, *PLMESH_MATERIAL; typedef struct _LMESH_BONE_LOCATION{ float xr, yr, zr; //x, y, and z rotation. float xp, yp, zp; //x, y, and z position. }LMESH_BONE_LOCATION; typedef struct _LMESH_JOINT{ char szName[LMESH_MAX_NAME_LENGTH]; char szParentBone[LMESH_MAX_NAME_LENGTH]; L_dword nParentBone; float position[3]; float rotation[3]; }LMESH_JOINT; typedef struct _LMESH_JOINTEX: public LMESH_JOINT{ D3DXMATRIX Local; D3DXMATRIX Final; L_dword nJointRef; }LMESH_JOINTEX; typedef struct _LMESH_JOINTPOS{ float position[3]; float rotation[3]; }LMESH_JOINTPOS; typedef struct _LMESH_JOINTPOSEX: public LMESH_JOINTPOS{ D3DXMATRIX Local; D3DXMATRIX Final; }LMESH_JOINTPOSEX; typedef struct _LMESH_KEYFRAME{ LMESH_JOINTPOSEX* pJointPos; }LMESH_KEYFRAME; //The Format: typedef struct _LMESH_CALLBACKS{ int (__cdecl *close)(void* stream); int (__cdecl *seek)(void* stream, long offset, int origin); int (__cdecl *tell)(void* stream); unsigned int (__cdecl *read)(void* buffer, unsigned int size, unsigned int count, void* stream); }LMESH_CALLBACKS, *PLMESH_CALLBACKS; #pragma pack() D3DXMATRIX* LM_EulerToMatrix(D3DXMATRIX* pOut, float* pEuler); #define LSKEL_ID (*(L_dword*)"LSKL") #define LSKEL_VERSION 101 class CLegacyMesh; class CLegacySkeleton{ public: friend class CLegacyMeshD3D; CLegacySkeleton(); ~CLegacySkeleton(); L_bool Load(void* file, LMESH_CALLBACKS* pcb); L_bool CalcExData(); L_bool Save(char* szFilename, L_bool bAppend); L_bool Unload(); L_dword GetNumFrames(); protected: L_bool AllocateMemory(); void DeallocateMemory(); protected: L_dword m_nID; L_dword m_nVersion; L_dword m_nNumJoints; L_dword m_nNumKeyFrames; LMESH_JOINTEX* m_pBaseSkeleton; LMESH_KEYFRAME* m_pKeyFrames; L_dword m_nTotalSize; L_bool m_bLoaded; }; class CLegacyMesh{ public: CLegacyMesh(); virtual ~CLegacyMesh(); L_bool Load(void* file, LMESH_CALLBACKS* pcb, char* szModelPath); L_bool Save(L_lpstr szFilename); virtual L_bool Unload(); L_dword GetNumFrames(); protected: protected: L_dword m_ID; L_dword m_nVersion; L_dword m_nNumVertices; L_dword m_nNumMeshes; L_dword m_nNumMaterials; LMESH_VERTEX* m_pVertices; L_dword* m_pVertexBoneList; LMESH_SET* m_pMeshes; LMESH_MATERIAL* m_pMaterials; CLegacySkeleton m_cSkel; L_bool m_bLoaded; private: }; #endif //__SM_SYS_H__<file_sep>/tools/Countdown/README.md Countdown ========= Usage: Eidt countdown.inf with the date you want to countdown to or from. countdown.ini should have three lines. Here is an example. Trunky Countdown 2/3/2006 ur The first line is the title that shows up at the top. The second line is the date. Christmas is a good choice. The third line is the position on the desktop where it shows up. This can be ur for upper right. ul for upper left. ll lr Quit frankly this program is useless, as I'm sure there are better alternatives.<file_sep>/games/Legacy-Engine/Source/engine/lp_sys2.cpp #include "lp_sys2.h" //At, Up, and Right standard vectors. const ML_VEC3 CLPhys::s_v3StdFace[3]= {{0.0f, 0.0f, 1.0f}, {0.0f, 1.0f, 0.0f}, {1.0f, 0.0f, 0.0f}}; const ML_VEC3 CLPhys::s_v3Zero={0.0f, 0.0f, 0.0f};<file_sep>/games/Explor2002/Dist/Art/Readme.txt This is the art for explor. Tiles are organized into sets. A set is one 280x160 bitmap. The first tile in the set should occupy a 160x160 space starting at 0,0. The second tile should occupy a 40x160 space starting at 200, 0. The third tile should occupy a 40x160 space staring at 240, 0. I currently have two available sets. set0001.bmp - Default walls set0002.bmp - default doors<file_sep>/games/Legacy-Engine/Source/LMEdit/DlgSaveAs.h #pragma once // CDlgSaveAs dialog class CDlgSaveAs : public CDialog { DECLARE_DYNAMIC(CDlgSaveAs) public: CDlgSaveAs(CWnd* pParent = NULL); // standard constructor CDlgSaveAs(LPCTSTR szMesh, LPCTSTR szSkel, CWnd* pParent = NULL); virtual ~CDlgSaveAs(); // Dialog Data enum { IDD = IDD_SAVEAS }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support DECLARE_MESSAGE_MAP() public: CString m_szMeshFile; CString m_szSkelFile; public: afx_msg void OnBnClickedBrowsemesh(); public: afx_msg void OnBnClickedBrowseskel(); public: virtual BOOL OnInitDialog(); }; <file_sep>/tools/GFX/GFXG8/GFXG8.h /* GFXG8.h - Header for GraFiX enGine DirectX 8; Copyright (c) 2003, <NAME>. */ #include <d3d8.h> #include <windows.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #define GFXG8_EXPORTS GFXG8_EXPORTS HRESULT InitD3D( HWND hwndTarget, DWORD dwWidth, DWORD dwHeight, BOOL bWindowed, D3DFORMAT Format, LPDIRECT3D8 lpD3D, LPDIRECT3DDEVICE8 * lpDevice, D3DPRESENT_PARAMETERS * lpSavedPP, LPDIRECT3DSURFACE8 * lpBackBuffer); /* ValidateDevice validates the device and restores backbuffer. It also calls a RestoreGraphics function if one is specified. */ typedef BOOL ( * POOLFN)(); GFXG8_EXPORTS BOOL ValidateDevice( LPDIRECT3DDEVICE8 * lppDevice, LPDIRECT3DSURFACE8 * lppBackSurface, D3DPRESENT_PARAMETERS d3dpp, POOLFN fpReleasePool, POOLFN fpRestorePool); GFXG8_EXPORTS BOOL CorrectWindowSize( HWND hWnd, DWORD nWidth, DWORD nHeight, BOOL bWindowed, HMENU hMenu); GFXG8_EXPORTS HRESULT CopySurfaceToSurface( LPDIRECT3DDEVICE8 lpDevice, RECT * lpSourceRect, LPDIRECT3DSURFACE8 lpSourceSurf, POINT * lpDestPoint, LPDIRECT3DSURFACE8 lpDestSurf, BOOL bTransparent, D3DCOLOR ColorKey); GFXG8_EXPORTS HRESULT CopySurfaceToSurface32( RECT * lpSourceRect, LPDIRECT3DSURFACE8 lpSourceSurf, POINT * lpDestPoint, LPDIRECT3DSURFACE8 lpDestSurf, BOOL bTransparent, D3DCOLOR ColorKey); GFXG8_EXPORTS HRESULT CopySurfaceToSurface16( RECT * lpSourceRect, LPDIRECT3DSURFACE8 lpSourceSurf, POINT * lpDestPoint, LPDIRECT3DSURFACE8 lpDestSurf, BOOL bTransparent, D3DCOLOR ColorKey); #ifdef __cplusplus #ifdef UNICODE #define CreateImageBM CreateImageBMW #else /* UNICODE */ #define CreateImageBM CreateImageBMA #endif #define CImage CImage8 class GFXG8_EXPORTS CImage8 { protected: LPDIRECT3DSURFACE8 m_lpImage; DWORD m_dwWidth; DWORD m_dwHeight; HRESULT CreateSurface( LPVOID lpDevice, D3DFORMAT Format, DWORD dwWidth, DWORD dwHeight); HRESULT LoadBitmapIntoSurfaceA( char szBitmapFileName[], DWORD x, DWORD y, DWORD nSrcWidth, DWORD nSrcHeight, DWORD nWidth, DWORD nHeight); HRESULT LoadBitmapIntoSurfaceW( WCHAR szBitmapFileName[], DWORD x, DWORD y, DWORD nSrcWidth, DWORD nSrcHeight, DWORD nWidth, DWORD nHeight); public: CImage8(); ~CImage8(); void ClearSurface(); HRESULT CreateImageBMA( char szBitmapFilename[], LPVOID lpDevice, D3DFORMAT Format, DWORD x, DWORD y, DWORD nSrcWidth, DWORD nSrcHeight, DWORD nWidth, DWORD nHeight); HRESULT CreateImageBMW( WCHAR szBitmapFilename[], LPVOID lpDevice, D3DFORMAT Format, DWORD x, DWORD y, DWORD nSrcWidth, DWORD nSrcHeight, DWORD nWidth, DWORD nHeight); HRESULT DrawClippedImage( LPVOID lpDevice, LPVOID lpBuffer, int x, int y); HRESULT DrawImage( LPVOID lpDevice, LPVOID lpBuffer, int x, int y); void Release(); DWORD GetWidth(); DWORD GetHeight(); }; #endif /* __cplusplus */ #ifdef __cplusplus } #endif /* __cplusplus */<file_sep>/games/Legacy-Engine/Source/engine/lx_level.cpp #include "lx_sys.h" #include "lg_stack.h" #include "lg_err.h" #include "lg_xml.h" #include "lg_malloc.h" #include "lg_func.h" #include <string.h> typedef enum _LX_LEVEL_MODE{ LEVEL_MODE_NONE=0, LEVEL_MODE_UNKNOWN, LEVEL_MODE_LEVEL, LEVEL_MODE_MAP, LEVEL_MODE_SKYBOX, LEVEL_MODE_SKYBOX_SKIN, LEVEL_MODE_MUSIC, LEVEL_MODE_OBJECTS, LEVEL_MODE_OBJECT, LEVEL_MODE_ACTORS, LEVEL_MODE_ACTOR }LX_LEVEL_MODE; typedef struct _lx_level_data{ lx_level* pLevel; lg_dword nCurObj; lg_dword nCurActor; CLStack<LX_LEVEL_MODE> stkMode; }lx_level_data; void LX_LevelStart(void* userData, const XML_Char* name, const XML_Char** atts); void LX_LevelEnd(void* userData, const XML_Char* name); void LX_LevelCharData(void* userData, const XML_Char*s, int len); lx_level* LX_LoadLevel(const lg_path szXMLFile) { Err_Printf("LX_LoadLevel: Reading \"%s\"...", szXMLFile); LF_FILE3 fileScript=LF_Open(szXMLFile, LF_ACCESS_READ|LF_ACCESS_MEMORY, LF_OPEN_EXISTING); if(!fileScript) { Err_Printf("LX_LoadLevel ERROR: Could not open \"%s\" for parsing.", szXMLFile); return LG_NULL; } //We need a new instance of the output data lx_level* pOut = (lx_level*)LG_Malloc(sizeof(lx_level)); memset(pOut, 0, sizeof(lx_level)); XML_Parser parser = XML_ParserCreate_LG(LG_NULL); if(!parser) { Err_Printf("LX_LoadLevel ERROR: Could not create XML parser. (%s)", szXMLFile); LF_Close(fileScript); return LG_NULL; } //Setup parsing. lx_level_data data; data.stkMode.Push(LEVEL_MODE_NONE); data.pLevel=pOut; XML_ParserReset(parser, LG_NULL); XML_SetUserData(parser, &data); XML_SetElementHandler(parser, LX_LevelStart, LX_LevelEnd); XML_SetCharacterDataHandler(parser, LX_LevelCharData); //Do parsing. if(!XML_Parse(parser, (const char*)LF_GetMemPointer(fileScript), LF_GetSize(fileScript), LG_TRUE)) { Err_Printf("LX_LoadObject ERROR: Pares error at line %d: \"%s\".", XML_GetCurrentLineNumber(parser), XML_ErrorString(XML_GetErrorCode(parser))); LX_DestroyLevel(pOut); LF_Close(fileScript); XML_ParserFree(parser); return LG_NULL; } XML_ParserFree(parser); LF_Close(fileScript); return pOut; } lg_void LX_DestroyLevel(lx_level* pLevel) { if(!pLevel) return; LG_SafeFree(pLevel->pObjs); LG_SafeFree(pLevel->pActors); LG_SafeFree(pLevel); } /* PRE: Accepts a name for the mode. POST: Returns the numerical value for the mode. */ LX_LEVEL_MODE LX_LevelNameToMode(const XML_Char* name) { LX_LEVEL_MODE nMode=LEVEL_MODE_UNKNOWN; if(stricmp(name, "level")==0) nMode=LEVEL_MODE_LEVEL; else if(stricmp(name, "map")==0) nMode=LEVEL_MODE_MAP; else if(stricmp(name, "skybox")==0) nMode=LEVEL_MODE_SKYBOX; else if(stricmp(name, "skybox_skin")==0) nMode=LEVEL_MODE_SKYBOX_SKIN; else if(stricmp(name, "music")==0) nMode=LEVEL_MODE_MUSIC; else if(stricmp(name, "objects")==0) nMode=LEVEL_MODE_OBJECTS; else if(stricmp(name, "object")==0) nMode=LEVEL_MODE_OBJECT; else if(stricmp(name, "actors")==0) nMode=LEVEL_MODE_ACTORS; else if(stricmp(name, "actor")==0) nMode=LEVEL_MODE_ACTOR; return nMode; } void LX_LevelStart(void* userData, const XML_Char* name, const XML_Char** atts) { lx_level_data* pData=(lx_level_data*)userData; LX_LEVEL_MODE nMode=LX_LevelNameToMode(name); //We'll always push the mode onto the stack even it was invalid //that way when the values get popped off the stack they //will always match. pData->stkMode.Push(nMode); //If the mode was NONE or UNKNWOWN there is nothing to do. if(nMode==LEVEL_MODE_UNKNOWN || nMode==LEVEL_MODE_NONE) { Err_Printf("LX_Level Parse ERROR: Invalid tag (%s).", name); } else if(nMode==LEVEL_MODE_MAP) { pData->pLevel->szMapFile[0]=0; } else if(nMode==LEVEL_MODE_SKYBOX) { pData->pLevel->szSkyBoxFile[0]=0; } else if(nMode==LEVEL_MODE_SKYBOX_SKIN) { pData->pLevel->szSkyBoxSkin[0]=0; } else if(nMode==LEVEL_MODE_MUSIC) { pData->pLevel->szMusicFile[0]=0; } else if(nMode==LEVEL_MODE_OBJECTS) { for(lg_dword i=0; atts[i]; i+=2) { if(stricmp(atts[i], "object_count")==0) { pData->pLevel->nObjCount=atoi(atts[i+1]); } } //Should allocate memory for objects here: //Free the data in case there is more than one call to the object tag. LG_SafeFree(pData->pLevel->pObjs); pData->pLevel->pObjs=(lx_level_object*)LG_Malloc(sizeof(lx_level_object)*pData->pLevel->nObjCount); pData->nCurObj=0; } else if(nMode==LEVEL_MODE_ACTORS) { for(lg_dword i=0; atts[i]; i+=2) { if(stricmp(atts[i], "actor_count")==0) { pData->pLevel->nActorCount=atoi(atts[i+1]); } } //Should allocate memory: LG_SafeFree(pData->pLevel->pActors); pData->pLevel->pActors=(lx_level_object*)LG_Malloc(sizeof(lx_level_object)*pData->pLevel->nActorCount); pData->nCurActor=0; } else if(nMode==LEVEL_MODE_OBJECT || nMode==LEVEL_MODE_ACTOR) { //Err_Printf("%d/%d ACTORS.", pData->nCurActor, pData->pLevel->nActorCount); //Err_Printf("%d/%d OBJECTS.", pData->nCurObj, pData->pLevel->nObjCount); //We can use the same code for actors and objects because //the both have the same parameters (script and position). lg_path szScript; lg_float fPos[3]; for(lg_dword i=0; atts[i]; i+=2) { if(stricmp(atts[i], "script")==0) { LG_strncpy(szScript, atts[i+1], LG_MAX_PATH); } else if(stricmp(atts[i], "position")==0) { lg_string szTemp; LG_strncpy(szTemp, atts[i+1], LG_MAX_STRING); lg_char* szTok=strtok(szTemp, ", "); lg_dword nPos=0; while(szTok && nPos<3) { fPos[nPos++]=(lg_float)atof(szTok); szTok=strtok(LG_NULL, ", "); } } } //Err_Printf("(%f, %f, %f)", fPos[0], fPos[1], fPos[2]); //Now copy the obtained data to the propper position. lx_level_object* pObj=LG_NULL; if(nMode==LEVEL_MODE_OBJECT && (pData->nCurObj<pData->pLevel->nObjCount)) { pObj=&pData->pLevel->pObjs[pData->nCurObj++]; } else if(pData->nCurActor<pData->pLevel->nActorCount) { pObj=&pData->pLevel->pActors[pData->nCurActor++]; } //Copy the data. if(pObj) { LG_strncpy(pObj->szObjFile, szScript, LG_MAX_PATH); memcpy(pObj->fPosition, fPos, sizeof(fPos)); } else { Err_Printf("LX_Level Parse ERROR: There are either more actors or objects present than specified."); } } } void LX_LevelEnd(void* userData, const XML_Char* name) { lx_level_data* pData=(lx_level_data*)userData; LX_LEVEL_MODE nMode=LX_LevelNameToMode(name); LX_LEVEL_MODE nPrevMode=pData->stkMode.Pop(); if(nPrevMode!=nMode){ Err_Printf("LX_Level Parse ERROR: Starting tage did not match end tage."); } } void LX_LevelCharData(void* userData, const XML_Char* s, int len) { lx_level_data* pData = (lx_level_data*)userData; LX_LEVEL_MODE nMode = pData->stkMode.Peek(); lg_bool bRead=LG_FALSE; lg_char* szFile=LG_NULL; if(nMode==LEVEL_MODE_MAP) { szFile=&pData->pLevel->szMapFile[0]; bRead=LG_TRUE; } else if(nMode==LEVEL_MODE_SKYBOX) { szFile=&pData->pLevel->szSkyBoxFile[0]; bRead=LG_TRUE; } else if(nMode==LEVEL_MODE_SKYBOX_SKIN) { szFile=&pData->pLevel->szSkyBoxSkin[0]; bRead=LG_TRUE; } else if(nMode==LEVEL_MODE_MUSIC) { szFile=&pData->pLevel->szMusicFile[0]; bRead=LG_TRUE; } if(bRead) { lg_path szTemp; strncpy(szTemp, s, len); szTemp[len]=0; //Take off any return carriages. while(szTemp[len-1]=='\n' || szTemp[len-1]=='\r') { szTemp[--len]=0; } //Attach the remainder of the string to teh level. strncat(szFile, szTemp, LG_MAX_PATH-strlen(szFile)); szFile[LG_MAX_PATH]=0; } } #if 0 void LX_ObjectEnd(void* userData, const XML_Char* name) { lx_obj_data* pData = (lx_obj_data*)userData; LX_OBJ_MODE nMode=LX_ObjectNameToMode(name); LX_OBJ_MODE nPrevMode=pData->stkMode.Pop(); if(nPrevMode!=nMode){ Err_Printf("LX_Object Parse ERROR: Starting tag did not match end tag."); } } void LX_ObjectCharData(void* userData, const XML_Char*s, int len) { lx_obj_data* pData = (lx_obj_data*)userData; lg_char* szText=(lg_char*)LG_Malloc((len+1)*sizeof(lg_char)); memcpy(szText, s, len+1); szText[len]=0; if(pData->stkMode.Peek()==OBJ_MODE_MODE) { #if 0 Err_Printf(szText); #endif } LG_Free(szText); } #endif<file_sep>/games/Legacy-Engine/Scrapped/old/lg_init.c /************************************************************ File: lg_init.c Copyright (c) 2006, <NAME> Purpose: Functions for initializing the Legacy 3D game. ************************************************************/ #include "common.h" #include <d3d9.h> #include <stdio.h> #include "lg_cmd.h" #include "lg_init.h" #include <lc_sys.h> #include "lv_init.h" #include "lg_sys.h" #include <lf_sys.h> #include "ls_init.h" #include "ML_lib.h" extern L3DGame* g_game; /*************************************************************************************** LG_RegisterCVars() Register the cvars that the game will use, we set some default values for all of them. The cvarlist should report any errors in registering to the console, so we don't test it out ourselves. If we need to save a cvar we can. All cvars should be registered in this function. The user can register cvars on the fly using the regcvar console command, but this is discouraged. ***************************************************************************************/ void LG_RegisterCVars(L3DGame* lpGame, HCVARLIST cvarlist) { /* We'll register the built in definitions. The user can define definitions on the fly with define, which is dangerous because the define function will redefine values. */ #define CVAR_DEF(a, b) CVar_AddDef(cvarlist, #a, (float)b) //Definitions, users should not change these. CVAR_DEF(TRUE, 1); CVAR_DEF(FALSE, 0); CVAR_DEF(ADAPTER_DEFAULT, D3DADAPTER_DEFAULT); //typedef enum _D3DDEVTYPE CVAR_DEF(HAL, D3DDEVTYPE_HAL); CVAR_DEF(REF, D3DDEVTYPE_REF); CVAR_DEF(SW, D3DDEVTYPE_SW); //Vertex processing methods. CVAR_DEF(SOFTWAREVP, D3DCREATE_SOFTWARE_VERTEXPROCESSING); CVAR_DEF(HARDWAREVP, D3DCREATE_HARDWARE_VERTEXPROCESSING); CVAR_DEF(MIXEDVP, D3DCREATE_MIXED_VERTEXPROCESSING); //typdef enum _D3DFORMAT //Back buffer formats. CVAR_DEF(FMT_UNKNOWN, D3DFMT_UNKNOWN); CVAR_DEF(FMT_A8R8G8B8, D3DFMT_A8R8G8B8); CVAR_DEF(FMT_X8R8G8B8, D3DFMT_X8R8G8B8); CVAR_DEF(FMT_R5G6B5, D3DFMT_R5G6B5); CVAR_DEF(FMT_X1R5G5B5, D3DFMT_X1R5G5B5); CVAR_DEF(FMT_A1R5G5B5, D3DFMT_A1R5G5B5); CVAR_DEF(FMT_A2R10G10B10, D3DFMT_A2R10G10B10); //Depth buffer formats. CVAR_DEF(FMT_D16_LOCKABLE, D3DFMT_D16_LOCKABLE); CVAR_DEF(FMT_D32, D3DFMT_D32); CVAR_DEF(FMT_D15S1, D3DFMT_D15S1); CVAR_DEF(FMT_D24S8, D3DFMT_D24S8); CVAR_DEF(FMT_D24X8, D3DFMT_D24X8); CVAR_DEF(FMT_D24X4S4, D3DFMT_D24X4S4); CVAR_DEF(FMT_D16, D3DFMT_D16); CVAR_DEF(FMT_D32F_LOCKABLE, D3DFMT_D32F_LOCKABLE); CVAR_DEF(FMT_D24FS8, D3DFMT_D24FS8); //typedef enum _CVAR_DEF(D3DMULTISAMPLE_TYPE /* CVAR_DEF(D3DMULTISAMPLE_NONE, 0); CVAR_DEF(D3DMULTISAMPLE_NONMASKABLE, 1); CVAR_DEF(D3DMULTISAMPLE_2_SAMPLES, 2); CVAR_DEF(D3DMULTISAMPLE_3_SAMPLES, 3); CVAR_DEF(D3DMULTISAMPLE_4_SAMPLES, 4); CVAR_DEF(D3DMULTISAMPLE_5_SAMPLES, 5); CVAR_DEF(D3DMULTISAMPLE_6_SAMPLES, 6); CVAR_DEF(D3DMULTISAMPLE_7_SAMPLES, 7); CVAR_DEF(D3DMULTISAMPLE_8_SAMPLES, 8); CVAR_DEF(D3DMULTISAMPLE_9_SAMPLES, 9); CVAR_DEF(D3DMULTISAMPLE_10_SAMPLES,10); CVAR_DEF(D3DMULTISAMPLE_11_SAMPLES,11); CVAR_DEF(D3DMULTISAMPLE_12_SAMPLES,12); CVAR_DEF(D3DMULTISAMPLE_13_SAMPLES,13); CVAR_DEF(D3DMULTISAMPLE_14_SAMPLES,14); CVAR_DEF(D3DMULTISAMPLE_15_SAMPLES,15); CVAR_DEF(D3DMULTISAMPLE_16_SAMPLES,16); */ //typedef enum _D3DSWAPEFFECT CVAR_DEF(SWAP_DISCARD, D3DSWAPEFFECT_DISCARD); CVAR_DEF(SWAP_FLIP, D3DSWAPEFFECT_FLIP); CVAR_DEF(SWAP_COPY, D3DSWAPEFFECT_COPY); //PresentationIntervals /* CVAR_DEF(D3DPRESENT_INTERVAL_DEFAULT, 0); CVAR_DEF(D3DPRESENT_INTERVAL_ONE, 1); CVAR_DEF(D3DPRESENT_INTERVAL_TWO, 2); CVAR_DEF(D3DPRESENT_INTERVAL_THREE, 3); CVAR_DEF(D3DPRESENT_INTERVAL_FOUR, 4); CVAR_DEF(D3DPRESENT_INTERVAL_IMMEDIATE, -1); */ /* Register the definitions for the texture filter mode. */ CVar_AddDef(cvarlist, "POINT", (float)FILTER_POINT); CVar_AddDef(cvarlist, "LINEAR", (float)FILTER_LINEAR); CVar_AddDef(cvarlist, "BILINEAR", (float)FILTER_BILINEAR); CVar_AddDef(cvarlist, "TRILINEAR", (float)FILTER_TRILINEAR); CVar_AddDef(cvarlist, "ANISOTROPIC", (float)FILTER_ANISOTROPIC); /* To register a cvar: cvar=REGISTER_CVAR("cvar name", "cvar default value", flags) */ /* Which would be the same as REGCVAR "cvarname" "cvarvalue" [NOSAVE] [UPDATE]*/ /******************************************** Direct3D cvars, stuff that controls D3D. *********************************************/ //D3D Initialization stuff. CVar_Register(cvarlist, "v_AdapterID", "ADAPTER_DEFAULT", CVAREG_SAVE); CVar_Register(cvarlist, "v_DeviceType", "HAL", 0); CVar_Register(cvarlist, "v_VertexProc", "SOFTWAREVP", CVAREG_SAVE); CVar_Register(cvarlist, "v_FPU_Preserve", "FALSE", 0); CVar_Register(cvarlist, "v_MultiThread", "FALSE", 0); CVar_Register(cvarlist, "v_PureDevice", "FALSE", 0); CVar_Register(cvarlist, "v_DisableDriverManagement", "FALSE", 0); CVar_Register(cvarlist, "v_AdapterGroupDevice", "FALSE", 0); CVar_Register(cvarlist, "v_Managed", "FALSE", 0); //D3DPRESENT_PARAMETERS CVar_Register(cvarlist, "v_Width", "640", CVAREG_SAVE); CVar_Register(cvarlist, "v_Height", "480", CVAREG_SAVE); CVar_Register(cvarlist, "v_BitDepth", "16", CVAREG_SAVE); CVar_Register(cvarlist, "v_ScreenBuffers", "1", CVAREG_SAVE); CVar_Register(cvarlist, "v_FSAAQuality", "0", CVAREG_SAVE); CVar_Register(cvarlist, "v_SwapEffect", "SWAP_DISCARD", 0); CVar_Register(cvarlist, "v_Windowed", "FALSE", CVAREG_SAVE); CVar_Register(cvarlist, "v_EnableAutoDepthStencil", "TRUE", 0); CVar_Register(cvarlist, "v_AutoDepthStencilFormat", "FMT_D16", 0); //v_D3DPP_Flags: CVar_Register(cvarlist, "v_LockableBackBuffer", "FALSE", 0); CVar_Register(cvarlist, "v_DiscardDepthStencil", "FALSE", 0); CVar_Register(cvarlist, "v_DeviceClip", "FALSE", 0); CVar_Register(cvarlist, "v_VideoHint", "FALSE", 0); //More D3DPRESENT_PARAMETERS CVar_Register(cvarlist, "v_RefreshRate", "0", CVAREG_SAVE); CVar_Register(cvarlist, "v_EnableVSync", "FALSE", CVAREG_SAVE); //Sampler CVars, the sampler cvars have the update attribute, so we will //see the results immediately. CVar_Register(cvarlist, FILTER_MODE, "BILINEAR", CVAREG_SAVE|CVAREG_UPDATE); CVar_Register(cvarlist, FILTER_MAXANISOTROPY, "1", CVAREG_SAVE|CVAREG_UPDATE); //Texture loading related cvars. CVar_Register(cvarlist, "v_UseMipMaps", "TRUE", CVAREG_SAVE); CVar_Register(cvarlist, "v_HWMipMaps", "TRUE", CVAREG_SAVE); CVar_Register(cvarlist, "v_MipGenFilter", "LINEAR", CVAREG_SAVE); CVar_Register(cvarlist, "v_TextureSizeLimit", "0", CVAREG_SAVE); CVar_Register(cvarlist, "v_Force16BitTextures", "FALSE", CVAREG_SAVE); //v_32BitTextrueAlpha and v_16BitTextureAlpha are used to store information //as to whethere or not alpha textures are supported, these cvars shouldn't //be changed by the user, only by the application. CVar_Register(cvarlist, "v_32BitTextureAlpha", "TRUE", CVAREG_SETWONTCHANGE); CVar_Register(cvarlist, "v_16BitTextureAlpha", "TRUE", CVAREG_SETWONTCHANGE); //Should have a cvar to determine which pool textures are loaded into. //Debug cvars CVar_Register(cvarlist, "v_DebugWireframe", "FALSE", CVAREG_UPDATE); /****************************************** Sound cvars, stuff that controls audio. *******************************************/ CVar_Register(cvarlist, "s_Channels", "2", CVAREG_SAVE); CVar_Register(cvarlist, "s_Frequency", "22050", CVAREG_SAVE); CVar_Register(cvarlist, "s_BitsPerSample", "16", CVAREG_SAVE); /************************************ Game cvars, stuff about the game. *************************************/ /* The path to the console background, note that this can only be changed by the user by modifying the cvar in the console and calling vrestart or setting a different path in the autoexec.cfg file. Same is true for the font.*/ CVar_Register(cvarlist, "lc_UseLegacyFont", "FALSE", CVAREG_SAVE); CVar_Register(cvarlist, "lc_BG", "console\\conbg.tga", 0); CVar_Register(cvarlist, "lc_Font", "fixedsys", 0); CVar_Register(cvarlist, "lc_FontColor", "0xFFFF00", 0); CVar_Register(cvarlist, "lc_LegacyFont", "font\\lfontsm.tga", 0); CVar_Register(cvarlist, "lc_LegacyFontSizeInFile", "15X8", 0); //Format is (H)X(W) CVar_Register(cvarlist, "lc_FontSize", "16X0", 0); //Format is (H)X(W) lpGame->l_ShouldQuit=CVar_Register(cvarlist, "l_ShouldQuit", "FALSE", CVAREG_UPDATE); lpGame->l_AverageFPS=CVar_Register(cvarlist, "l_AverageFPS", "0", CVAREG_SETWONTCHANGE); CVar_Register(cvarlist, "l_DumpDebugData", "FALSE", CVAREG_SAVE); return; } /********************************************************************* LG_GameInit() Initializes various game things, including the console, cvarlist, graphics, and audio. *********************************************************************/ L3DGame* LG_GameInit(char* szGameDir, HWND hwnd) { L3DGame* lpNewGame=NULL; L_long nResult=0; /* Allocate memory for the game, and clear it all out. */ lpNewGame=malloc(sizeof(L3DGame)); if(!lpNewGame) return L_null; memset(lpNewGame, 0, sizeof(L3DGame)); /* Attach the window to the game. */ lpNewGame->m_hwnd=hwnd; /************************** Initialize the console. *************************/ /* Create the console, if we fail to create the console, the who program isn't going to function correctly. Pretty much the only reason the console wouldn't start is if the user was out of memory, which means the program wouldn't work anyway. We also need the cvarlist to get created for the game to work.*/ lpNewGame->m_Console=Con_Create( LGC_ConCommand, 512, 2048, CONCREATE_USEINTERNAL, lpNewGame); /* Set the global pointer to the game. */ g_game=lpNewGame; /* If the console fails, we can't do anything else with the app. */ if(!lpNewGame->m_Console) { free(lpNewGame); return L_null; } /* Attach the console to the error reporting. Which means we can just call Err_Printf to send a message to the console, as opposed to calling the Con_SendErrorMsg(*console, ...) function. */ Err_InitReporting(lpNewGame->m_Console); Err_PrintVersion(); Err_Printf("Created console at 0x%08X.", lpNewGame->m_Console); /******************************* Initialze the file system. ******************************/ /* We need to set the directory to the game data directory. By default this is [legacy3ddirectory]\base, but we want to make it so that the user can change this to run custom games for example*/ Err_Printf("Calling LF_Init..."); LF_Init(szGameDir, 0);//LFINIT_CHECKARCHIVESFIRST); Err_Printf(LF_GetLastError()); /* Keep adding pak files incrementally til we can't find one. In theory we could use _findfirst and _findnext to find all the pack files in the directory, but that wouldn't gaurantee what order they got put in. */ { unsigned short i=0; char szPakFile[10]; for(i=0; i<99; i++) { sprintf(szPakFile, "pak%.2i.lpk", i); if(LF_AddArchive(szPakFile)) { Err_Printf(LF_GetLastError());//"Added %s to seach path.", szPakFile); } else break; } } /************************** Create the cvarlist. **************************/ /* We create the cvarlist, attach it to the console, so the console can use the built in functions with it we register all the commands for the console, and we register all the cvars for teh game, and then we set the cvars by attempting to load config.cfg as well as autoexec.cfg. Note that any cvars that will be saved will be written to config.cfg, any cvars that the user wants to manipulate and save that aren't saved should be written in autoexec.cfg (for example v_VideoHint is not saved, but if the user wanted to set this variable to true, he should put SET v_VideoHint "TRUE" in the autoexec.cfg file.*/ lpNewGame->m_cvars=CVar_CreateList(lpNewGame->m_Console); if(lpNewGame->m_cvars==NULL) { Err_Printf("Failed to initialze cvars."); Con_SendCommand(lpNewGame->m_Console, "condump \"debug.txt\""); Con_Delete(lpNewGame->m_Console); lpNewGame->m_Console=L_null; free(lpNewGame); return L_null; } Err_Printf("Created cvars at 0x%08X.", lpNewGame->m_cvars); Con_AttachCVarList(lpNewGame->m_Console, lpNewGame->m_cvars); /* Register the console commands for Legacy 3D. */ LGC_RegConCmds(lpNewGame->m_Console); /* Register the cvars for the game. */ LG_RegisterCVars(lpNewGame, lpNewGame->m_cvars); /* Now load all the presets. */ Con_SendCommand(lpNewGame->m_Console, "loadcfg \"config.cfg\""); Con_SendCommand(lpNewGame->m_Console, "loadcfg \"autoexec.cfg\""); /************************* Initialize the video. **************************/ Err_Printf("Calling LV_Init..."); nResult=LV_Init(lpNewGame); if(L_failed(nResult)) { Err_Printf("LV_Init failed with result 0x%08X.", nResult); Con_SendCommand(lpNewGame->m_Console, "condump \"debug.txt\""); /*Destroy everything we've created so far. */ CVar_DeleteList(lpNewGame->m_cvars); lpNewGame->m_cvars=NULL; Con_Delete(lpNewGame->m_Console); lpNewGame->m_Console=NULL; free(lpNewGame); return L_null; } else Err_Printf("LV_Init succeeded."); /************************* Initialize the sound. **************************/ Err_Printf("Calling LS_Init..."); nResult=LS_Init(lpNewGame); if(L_failed(nResult)) { /* If the sound isn't initialized we just display an error message, as the game can still run without sound. */ Err_Printf("LS_Init failed with result 0x%08X, audio not available.", nResult); } else Err_Printf("LS_Init succeeded."); /* Some test stuff. */ return lpNewGame; } /*************************************************************** LG_GameShutdown() Shuts down and deletes everything created in LG_GameInit(). ***************************************************************/ L_bool LG_GameShutdown(L3DGame* lpGame) { IDirect3D9* lpD3D=NULL; L_int nResult=0; L_ulong nNumLeft=0; L_bool bDump=L_false; if(!lpGame) return L_false; Err_Printf("Shutting down Legacy Engine."); Err_Printf("Calling LS_Shutdown..."); nResult=LS_Shutdown(lpGame); Err_Printf("LS_Shutdown resulted with 0x%08X.", nResult); Err_Printf("Calling LV_Shutdown..."); nResult=LV_Shutdown(lpGame); Err_Printf("LV_Shutdown resulted with 0x%08X.", nResult); /* Dump the console, it should probably be determined by a cvar if the console should get dumped or not, but for now we always dump it. */ bDump=(int)CVar_GetValue(lpGame->m_cvars, "l_DumpDebugData", L_null); /* Save the cvars that want to be saved. */ Con_SendCommand(lpGame->m_Console, "savecfg \"config.cfg\""); Err_Printf("Destroying cvarlist."); CVar_DeleteList(lpGame->m_cvars); lpGame->m_cvars=L_null; /* Destroy the file system. Any open files should be closed before this is called. */ LF_Shutdown(); Err_Printf("Destroying console, goodbye!"); if(bDump) Con_SendCommand( lpGame->m_Console, "condump \"debug.txt\""); Con_Delete(lpGame->m_Console); lpGame->m_Console=L_null; /* Make sure there is no pointer in the error reporting. */ Err_InitReporting(L_null); free(lpGame); return L_true; }<file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/lv_tex_img_lib.c #include <common.h> #include <d3d9.h> #include <lf_sys.h> #include "lv_tex.h" #include <img_lib.h> #include "lg_err.h" #include "lv_init.h" #include "lm_math.h" typedef struct _TEX_IMG_COPY_DESC2{ L_dword nWidth; L_dword nHeight; IMGFMT nFormat; D3DFORMAT nD3DFormat; LV_TEXFILTER_MODE nMipFilter; L_bool bGenMipMap; L_bool bUseHWMipMap; D3DPOOL nPool; char szFilename[MAX_F_PATH]; }TEX_IMG_COPY_DESC2; __inline L_bool Tex_CopyIMGToTex( IDirect3DDevice9* lpDevice, HIMG hImage, IDirect3DTexture9** lppTex, TEX_IMG_COPY_DESC2* pDesc); int __cdecl img_close(void* stream); int __cdecl img_seek(void* stream, long offset, int origin); int __cdecl img_tell(void* stream); unsigned int __cdecl img_read(void* buffer, unsigned int size, unsigned int count, void* stream); /*************************************************************************** Tex_LoadIMG() Loads a texture into a texture interface in system memory. This is an example of how to manually load a texture into system memory. The idea behind this function is that it loads the HIMG then prepares the TEX_IMG_COPY_DESC2 structure based on the loaded texture and various paramters and cvars, then calls Tex_CopyIMGToTex using the TEX_IMG_COPY_DESC2 structure to create the texture. Note that this functions insures that all values passed to Tex_CopyIMGToTex are valid. What the different Flags parameters will do: TEXLOAD_GENMIPMAP - A mip map will be generated for the texture. TEXLOAD_HWMIPMAP - The texture will use hardware generated mip maps (if available) TEXLOAD_LINEARMIPFILTER - The device will use a linear filter to genreate mip sublevels. TEXLOAD_POINTMIPFILTER - The device will use point filterting to generate mip sublevels. TEXLOAD_FORCE16BIT - The texture will be forced to a bitdepth of 16. TEXLOAD_16BITALPHA - If the texture is being converted from 32 bit to 16 bit an alpha channel will be used for the 16 bit texture allowing the retention of some transparency. Note that 16 bit alpha channels are only 1 bit so they are either on or off, the texture loader typically converts even the remotest amount of transparency to off. Notes: The function will limit the texture to the specified size limit. It also insures that the final texture dimensions will be valid (a power of 2, square, etc) depending on the device capabilities. Note that it assumes that the final texture format will be valid so if a video card that only supports 16 bit textures is being used then when Tex_LoadIMG2 is called the TEXLOAD_FORCE16BIT flag needs to be set or the texture creation will fail. ***************************************************************************/ L_bool Tex_LoadIMG2( IDirect3DDevice9* lpDevice, L_lpstr szFilename, D3DPOOL Pool, L_dword Flags, L_dword nSizeLimit, IDirect3DTexture9** lppTex) { TEX_IMG_COPY_DESC2 copydesc; HIMG hImage=L_null; IMG_CALLBACKS cb; LF_FILE2 fin=L_null; IMG_DESC imgdesc; D3DCAPS9 Caps; L_bool bResult=L_false; if(!lpDevice || !szFilename) return L_false; /* First thing first we open the tga file, we are using the callback function to open the file so that we can use the Legacy File system. */ cb.close=img_close; cb.read=img_read; cb.seek=img_seek; cb.tell=img_tell; /* If we can't open the file, or if the tga file can't be opened then it was probably an invalid texture. Note that TGA_OpenCallbacks will close the file for us, so we don't need to worry about closing it ourselves. */ fin=File_Open(szFilename, 0, LF_ACCESS_READ, LFCREATE_OPEN_EXISTING); if(!fin) { Err_Printf("Tex_Load Error: Could not open \"%s\".", szFilename); Err_Printf(" Could not open source file."); return L_false; } hImage=IMG_OpenCallbacks(fin, &cb); if(!hImage) { Err_Printf("Tex_Load Error: Could not open \"%s\".", szFilename); Err_Printf(" Could not acquire Truevision Targa from file."); return L_false; } /* Next we need to get a description of the tga file, so that we can create an appropriate texture. Note that we could set the final texture format to whatever we want, but we'll try to match to original format.*/ memset(&imgdesc, 0, sizeof(imgdesc)); memset(&copydesc, 0, sizeof(copydesc)); IMG_GetDesc(hImage, &imgdesc); copydesc.nWidth=imgdesc.Width; copydesc.nHeight=imgdesc.Height; copydesc.nPool=Pool; //copydesc.dwSizeLimit=dwSizeLimit; /* If there is a size limit, we need to limit the size of the texture. */ if(nSizeLimit) { copydesc.nWidth=L_min(copydesc.nWidth, nSizeLimit); copydesc.nHeight=L_min(copydesc.nHeight, nSizeLimit); } memset(&Caps, 0, sizeof(Caps)); lpDevice->lpVtbl->GetDeviceCaps(lpDevice, &Caps); /* We need to make sure the texture is not larger than the device limits. */ copydesc.nWidth=L_min(copydesc.nWidth, Caps.MaxTextureWidth); copydesc.nHeight=L_min(copydesc.nHeight, Caps.MaxTextureHeight); /* If required (which it usually is) we need to make sure the texture is a power of 2. */ if(L_CHECK_FLAG(Caps.TextureCaps, D3DPTEXTURECAPS_POW2)) { copydesc.nWidth=L_nextpow2(copydesc.nWidth); copydesc.nHeight=L_nextpow2(copydesc.nHeight); } /* If required we need to make sure the texture is square.*/ if(L_CHECK_FLAG(Caps.TextureCaps, D3DPTEXTURECAPS_SQUAREONLY)) { copydesc.nWidth=copydesc.nHeight=L_max(copydesc.nWidth, copydesc.nHeight); } if(L_CHECK_FLAG(Flags, TEXLOAD_LINEARMIPFILTER)) copydesc.nMipFilter=FILTER_LINEAR; else copydesc.nMipFilter=FILTER_POINT; switch(imgdesc.BitsPerPixel) { default: case 16: copydesc.nD3DFormat=D3DFMT_R5G6B5; copydesc.nFormat=IMGFMT_R5G6B5; break; case 8: case 24: copydesc.nD3DFormat=D3DFMT_X8R8G8B8; copydesc.nFormat=IMGFMT_A8R8G8B8; break; case 32: copydesc.nD3DFormat=D3DFMT_A8R8G8B8; copydesc.nFormat=IMGFMT_A8R8G8B8; break; } if(L_CHECK_FLAG(Flags, TEXLOAD_FORCE16BIT))//CVar_GetValue(LG_GetGame()->m_cvars, "v_Force16BitTextures", L_null)) { if(imgdesc.BitsPerPixel==32 && L_CHECK_FLAG(Flags, TEXLOAD_16BITALPHA))//(L_bool)CVar_GetValue(LG_GetGame()->m_cvars, "v_16BitTextureAlpha", L_null)) { copydesc.nD3DFormat=D3DFMT_A1R5G5B5; copydesc.nFormat=IMGFMT_X1R5G5B5; } else { copydesc.nD3DFormat=D3DFMT_R5G6B5; copydesc.nFormat=IMGFMT_R5G6B5; } } copydesc.bGenMipMap=L_CHECK_FLAG(Flags, TEXLOAD_GENMIPMAP);//bGenMipMap; copydesc.bUseHWMipMap=Tex_CanAutoGenMipMap(lpDevice, copydesc.nD3DFormat) && L_CHECK_FLAG(Flags, TEXLOAD_HWMIPMAP); L_strncpy(copydesc.szFilename, szFilename, MAX_F_PATH); bResult=Tex_CopyIMGToTex(lpDevice, hImage, lppTex, &copydesc); IMG_Delete(hImage); hImage=L_null; return bResult; } /* Tex_CopyIMGToTex() This funciton actually creates the IDirect3DTexture9 interface, and copies the data located in hImage to the texture, it uses parameters set up in the TEX_IMG_COPY_DESC2 structure. Note that it does not check to make sure that the values in that structure are valid, as Tex_LoadIMG builds that structure and insures that it is valid. This function is only intended to be called by Tex_LoadImage and not any other function.*/ __inline L_bool Tex_CopyIMGToTex( IDirect3DDevice9* lpDevice, HIMG hImage, IDirect3DTexture9** lppTex, TEX_IMG_COPY_DESC2* pDesc) { IDirect3DTexture9* lpTexTemp=L_null; L_dword nMipLevels=0; L_dword nUsage=0; L_dword i=0; L_result nResult=0; //Find out how many mip levels need to be generated. //1 if there will be no mip map. //0 if mip levels will be generated by the video card. //variable amount if we are generating them ourselves. if(!pDesc->bGenMipMap) nMipLevels=1; else if(pDesc->bGenMipMap && pDesc->bUseHWMipMap) nMipLevels=1; else if(pDesc->bGenMipMap && !pDesc->bUseHWMipMap) { nMipLevels=0; i=L_min(pDesc->nWidth, pDesc->nHeight); do { nMipLevels++; }while((i/=2)>=1); } //If we are automatically generating mip maps //we specify so. nUsage=0; if(pDesc->bGenMipMap && pDesc->bUseHWMipMap && (pDesc->nPool!=D3DPOOL_DEFAULT)) { nUsage|=D3DUSAGE_AUTOGENMIPMAP; } nResult=lpDevice->lpVtbl->CreateTexture( lpDevice, pDesc->nWidth, pDesc->nHeight, nMipLevels, nUsage, pDesc->nD3DFormat, pDesc->nPool==D3DPOOL_DEFAULT?D3DPOOL_SYSTEMMEM:pDesc->nPool, &lpTexTemp, L_null); if(L_failed(nResult)) { *lppTex=L_null; Err_Printf("Tex_Load Error: Could not open \"%s\".", pDesc->szFilename); Err_PrintDX(" IDirect3DDevice9", nResult); return L_false; } //Now for each mip level we will lock and copy the source image. nMipLevels=lpTexTemp->lpVtbl->GetLevelCount(lpTexTemp); for(i=0; i<nMipLevels; i++) { D3DLOCKED_RECT rc; D3DSURFACE_DESC sdesc; IMG_DEST_RECT rcDest; memset(&rc, 0, sizeof(rc)); memset(&sdesc, 0, sizeof(sdesc)); nResult=lpTexTemp->lpVtbl->LockRect(lpTexTemp, i, &rc, L_null, 0); if(L_failed(nResult)) { Err_Printf("Tex_Load Error: Could not open \"%s\".", pDesc->szFilename); Err_PrintDX(" IDirect3DTexture9::LockRect", nResult); lpTexTemp->lpVtbl->Release(lpTexTemp); return L_false; } nResult=IDirect3DTexture9_GetLevelDesc(lpTexTemp, i, &sdesc); if(L_failed(nResult)) { Err_Printf("Tex_Load Error: Could not open \"%s\".", pDesc->szFilename); Err_PrintDX(" IDirect3DTexture9::GetLevelDesc", nResult); lpTexTemp->lpVtbl->UnlockRect(lpTexTemp, i); lpTexTemp->lpVtbl->Release(lpTexTemp); return L_false; } rcDest.pImage=rc.pBits; rcDest.nOrient=IMGORIENT_TOPLEFT; rcDest.nFormat=pDesc->nFormat; rcDest.nWidth=sdesc.Width; rcDest.nHeight=sdesc.Height; rcDest.nPitch=rc.Pitch; rcDest.rcCopy.left=rcDest.rcCopy.top=0; rcDest.rcCopy.right=sdesc.Width; rcDest.rcCopy.bottom=sdesc.Height; IMG_CopyBits( hImage, &rcDest, pDesc->nMipFilter>FILTER_POINT?IMGFILTER_LINEAR:IMGFILTER_POINT, L_null, 0xFF); lpTexTemp->lpVtbl->UnlockRect(lpTexTemp, i); } if(pDesc->nPool==D3DPOOL_DEFAULT) { L_dword nFlags=0; if(pDesc->nMipFilter>FILTER_POINT) nFlags|=SYSTOVID_LINEARMIPFILTER; if(pDesc->bGenMipMap && pDesc->bUseHWMipMap) { nFlags|=SYSTOVID_AUTOGENMIPMAP; } if(!Tex_SysToVid(lpDevice, &lpTexTemp, nFlags)) { Err_Printf("Tex_Load Error: Could not open \"%s\".", pDesc->szFilename); Err_Printf(" Could not move texture to video memory."); L_safe_release(lpTexTemp); return L_false; } } *lppTex=lpTexTemp; return L_true; } /********************************************* Callback functions for reading tga file. *********************************************/ int __cdecl img_close(void* stream) { return File_Close(stream); } int __cdecl img_seek(void* stream, long offset, int origin) { return File_Seek(stream, offset, origin); } int __cdecl img_tell(void* stream) { return File_Tell(stream); } unsigned int __cdecl img_read(void* buffer, unsigned int size, unsigned int count, void* stream) { return File_Read(stream, size*count, buffer); }<file_sep>/games/Legacy-Engine/Source/engine/lw_map.h //lw_sys.h - The Legacy World (map) system. //Copyright (c) 2007 <NAME> #ifndef __LW_MAP_H__ #define __LW_MAP_H__ #include <d3d9.h> #include "lf_sys2.h" #include "ML_lib.h" #include "lg_tmgr.h" #include "common.h" #define LW_ID (*(lg_word*)"LW") #define LW_VERSION (1) #define LW_MAX_NAME (32) #define LW_MAX_PATH (256) typedef lg_char LW_MATERIAL[LW_MAX_PATH]; typedef lg_char LW_NAME[LW_MAX_NAME]; typedef struct _LW_VERTEX{ ML_VEC3 v3Pos; ML_VEC2 v2Tex; ML_VEC2 v2LM; }LW_VERTEX; #define LW_VERTEX_TYPE (D3DFVF_XYZ|D3DFVF_TEX2) typedef struct _LW_RASTER_SEGMENT{ lg_dword nFirst; lg_dword nTriCount; lg_dword nMaterialRef; lg_dword nLMRef; }LW_RASTER_SEGMENT; typedef ML_PLANE LW_GEO_FACE; typedef ML_VEC3 LW_GEO_VERTEX; typedef ML_VEC3 LW_GEO_TRI[3]; typedef struct _LW_GEO_BLOCK{ lg_dword nFirstVertex; lg_dword nVertexCount; lg_dword nFirstTri; lg_dword nTriCount; lg_dword nFirstFace; lg_dword nFaceCount; ML_AABB aabbBlock; }LW_GEO_BLOCK; typedef struct _LW_GEO_BLOCK_EX: public _LW_GEO_BLOCK{ LW_GEO_FACE* pFaces; LW_GEO_VERTEX* pVerts; LW_GEO_TRI* pTris; }LW_GEO_BLOCK_EX; typedef struct _LW_REGION{ LW_NAME szName; lg_dword nFirstRasterSeg; lg_dword nRasterSegCount; lg_dword nFirstVertex; lg_dword nVertexCount; lg_dword nFirstGeoBlock; lg_dword nGeoBlockCount; lg_dword nFirstLight; lg_dword nLightcount; ML_AABB aabbAreaBounds; }LW_REGION; typedef struct _LW_COLORVALUE{ lg_float r, g, b, a; }LW_COLORVALUE; typedef struct _LW_LIGHT{ ML_VEC3 v3Pos; LW_COLORVALUE Color; }LW_LIGHT; typedef struct _LW_REGION_EX: public _LW_REGION{ LW_RASTER_SEGMENT* pRasterSegs; LW_GEO_BLOCK_EX* pGeoBlocks; LW_LIGHT* pLights; }LW_REGION_EX; class CLMap{ public: lg_bool m_bLoaded; lf_path m_szMapPath; lg_word m_nID; lg_dword m_nVersion; lg_dword m_nVertexCount; lg_dword m_nVertexOffset; lg_dword m_nMaterialCount; lg_dword m_nMaterialOffset; lg_dword m_nLMCount; lg_dword m_nLMOffset; lg_dword m_nLMTotalSize; lg_dword m_nSegmentCount; lg_dword m_nSegmentOffset; lg_dword m_nRegionCount; lg_dword m_nRegionOffset; lg_dword m_nGeoBlockCount; lg_dword m_nGeoBlockOffset; lg_dword m_nGeoFaceCount; lg_dword m_nGeoFaceOffset; lg_dword m_nLightCount; lg_dword m_nLightOffset; lg_dword m_nGeoVertCount; lg_dword m_nGeoVertOffset; lg_dword m_nGeoTriCount; lg_dword m_nGeoTriOffset; //Map data ML_AABB m_aabbMapBounds; LW_VERTEX* m_pVertexes; LW_MATERIAL* m_pMaterials; lg_byte* m_pLMData; lg_byte** m_pLMs; LW_RASTER_SEGMENT* m_pSegments; LW_REGION_EX* m_pRegions; LW_GEO_BLOCK_EX* m_pGeoBlocks; LW_GEO_FACE* m_pGeoFaces; LW_LIGHT* m_pLights; LW_GEO_VERTEX* m_pGeoVerts; LW_GEO_TRI* m_pGeoTris; //The memory lump lg_byte* m_pMem; private: lg_bool AllocateMemory(); void DeallocateMemory(); public: CLMap(); ~CLMap(); lg_bool LoadFromWS(lf_path szFilename); lg_bool Load(lf_path szFilename); lg_bool LoadReal(lf_path szFilename); void Unload(); lg_bool IsLoaded(); const lg_str GetMapPath(); lg_dword CheckRegions(const ML_AABB* pAABB, lg_dword* pRegions, lg_dword nMaxRegions); }; class CLMapD3D { public: static const lg_dword MAPDEBUG_HULLAABB=0x00000001; static const lg_dword MAPDEBUG_HULLTRI=0x00000002; static const lg_dword MAPDEBUG_WORLDAABB=0x00000004; private: //The actual map. CLMap* m_pMap; //Direct3D interfaces. IDirect3DDevice9* m_pDevice; tm_tex* m_pTextures; tm_tex* m_pLMTextures; IDirect3DVertexBuffer9* m_pVB; //Data lump. lg_byte* m_pMem; lg_bool m_bIsValid; public: CLMapD3D(); ~CLMapD3D(); void Init(IDirect3DDevice9* pDevice, CLMap* pMap); void UnInit(); void Render(); void RenderAABBs(lg_dword nFlags); void Validate(); void Invalidate(); }; #if 0 class CLWorldMap: public CLMap { friend class CLEntity; friend class CLWorld; friend class CLJack; friend class CLPhysBody; friend class CElementNewton; friend class CElementPhysX; private: lg_bool m_bD3DValid; //Direct3D Interfaces IDirect3DDevice9* m_pDevice; tm_tex* m_pTextures; tm_tex* m_pLMTextures; IDirect3DVertexBuffer9* m_pVB; public: CLWorldMap(); ~CLWorldMap(); void Render(); lg_bool Validate(); void Invalidate(); lg_bool LoadFromWS(lf_path szFilename, IDirect3DDevice9* pDevice); lg_bool Load(lf_path szFilename, IDirect3DDevice9* pDevice); void Unload(); }; #endif #endif __LW_MAP_H__<file_sep>/games/Legacy-Engine/Scrapped/old/lv_test.cpp /* lv_test.c - Some test stuff. */ #include "common.h" #include "lv_test.h" #include <d3d9.h> #include <d3dx9.h> #include "lv_tex.h" #include "lg_err.h" //#include <lf_sys.h> #include "lm_d3d.h" #include "ML_lib.h" #include "lg_meshmgr.h" #include "lv_img2d.h" #include "lg_sys.h" void CLVTObj::Init(IDirect3DDevice9* pDevice, void* pGame) { m_Camera.SetDevice(pDevice); CLGame* pGame1=(CLGame*)pGame; m_pDevice=pDevice; m_pDevice->AddRef(); m_Img.CreateFromFile(m_pDevice,"/dbase/textures/misc/test_face.tga", LG_NULL, 128, 128, 0x00000000); ML_VEC3 v3Pos={2.0f, 0.0f, -2.0f}; this->m_pEnts[0]=new CLJack(); m_pEnts[0]->Initialize(pGame, &v3Pos); //m_Player.Initialize(pGame, &v3Pos); v3Pos.x=20.0f; v3Pos.z=1.2f; v3Pos.y=0.1f; m_pEnts[1]=new CLMonaEnt(); m_pEnts[1]->Initialize(pGame, &v3Pos); //m_Mona.Initialize(pGame, &v3Pos); v3Pos.x=-10.0f; v3Pos.z=0.0f; m_pEnts[2]=new CLBarrelEnt(); m_pEnts[2]->Initialize(pGame, &v3Pos); //m_Barrel.Initialize(pGame, &v3Pos); ML_VEC3 offset={0.0f, 1.5f, 0.0f}; //ML_VEC3 offset={0.0f, 1.5f*30.0f, 0.0f}; //m_Camera.AttachToObject(&m_Player, CLCamera::CLCAMERA_ATTACH_FOLLOW, &offset, 2.0f); m_Camera.AttachToObject( m_pEnts[0], CLCamera::CLCAMERA_ATTACH_FOLLOW, //CLCamera::CLCAMERA_ATTACH_EYE, &offset, 2.0f);//*30.0f); m_nNumEnts=3; ValidateInvalidate(LG_TRUE); //m_SkyBox.Initialize(m_pDevice); //m_SkyBox.Load("textures\\set 16\\samp%d.bmp", LG_TRUE); m_SkyBox.Load("/dbase/meshes/skybox/skybox.lmsh"); //lg_char szMap[]="/dbase/maps/solids_test.3dw"; //lg_char szMap[]="/dbase/maps/tri_test.3dw"; //lg_char szMap[]="/dbase/maps/thing.3dw"; lg_char szMap[]="/dbase/maps/room_test.3dw"; //lg_char szMap[]="/dbase/maps/block.3dw"; //lg_char szMap[]="/dbase/maps/house.3dw"; //lg_char szMap[]="/dbase/maps/simple_example.3dw"; m_World.LoadFromWS(szMap, m_pDevice); } void CLVTObj::Render() { lg_result nResult=0; if(!m_pDevice) return; /* D3DVIEWPORT9 vp, oldvp; vp.X=10; vp.Y=10; vp.Width=640; vp.Height=480; vp.MinZ=0.0f; vp.MaxZ=1.0f; m_pDevice->GetViewport(&oldvp); m_pDevice->SetViewport(&vp); */ //First things first is to process all the entitie's AI (processing //AI doesn't move the object, but it generates a proposoed movement //vector stored int m_v3Vel. lg_dword i, j; for(i=0; i<m_nNumEnts; i++) { m_pEnts[i]->ProcessAI(); m_pEnts[i]->WorldCollision(&m_World); } //Now check to see if the proposed movements will cause any collisions //to occur. for(i=0; i<m_nNumEnts; i++) { for(j=0; j<m_nNumEnts; j++) { //Don't bother checking with itself. if(i==j) continue; if(m_pEnts[i]->Collision(m_pEnts[j])) { ;//j=0; } } } for(i=0; i<m_nNumEnts; i++) m_pEnts[i]->Update(); //The camera should be the last thing updated. m_Camera.Update(); //The camera should be the first thing rendered. m_Camera.RenderForSkybox(); CLSkybox2::SetSkyboxRenderMode(m_pDevice); m_SkyBox.Render(); m_Camera.Render(); //The level should be the second thing rendered. m_pDevice->SetRenderState(D3DRS_ZENABLE, TRUE); m_pDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE); //RenderTestWall(); m_pDevice->SetRenderState(D3DRS_LIGHTING, FALSE); //m_Map.Render(); m_World.Render(); //Then all the entities should be rendered //note that in the call to Update for //each entity they should be flagged whether or //not they are visible (in a room that is visible) //and in the call to render they should be checked //to see if they are in the view frustrum. CLMeshD3D::SetLMeshRenderStates(m_pDevice); m_pDevice->SetRenderState(D3DRS_LIGHTING, TRUE); for(i=0; i<m_nNumEnts; i++) m_pEnts[i]->Render(); //Any 2D stuff should be rendered last, the 2d drawing //code is not very good right now. CLImg2D::StartStopDrawing(m_pDevice, 640, 480, LG_TRUE); m_Img.Render(10, 10); CLImg2D::StartStopDrawing(m_pDevice, 640, 480, LG_FALSE); //m_pDevice->SetViewport(&oldvp); } void CLVTObj::UnInit() { for(lg_dword i=0; i<m_nNumEnts; i++) delete m_pEnts[i]; m_Img.Delete(); m_SkyBox.Unload(); m_World.Unload(); ValidateInvalidate(LG_FALSE); m_pDevice->Release(); m_pDevice=NULL; } void CLVTObj::ValidateInvalidate(lg_bool bValidate) { if(bValidate) { m_Img.Validate(LG_NULL); m_World.Validate(); } else { m_Img.Invalidate(); m_World.Invalidate(); } } <file_sep>/samples/D3DDemo/readme.txt D3DDemo (c) 2003 <NAME> =========================== This was written as a learning exercise for Direct3D. It actually started as Direct3D 8, but was upgraded to Direct3D 9 (and that is the only version that exists today). It in itself is not very interesting, and it's not even useful since DirectX 9 is obsolete (and this used the fixed function pipeline on top of that). It does feature MD3 file support (the Quake 3 Arena file forma) fairly robustly (but again fixed function pipeline so no shader support). Which is probably the most interesting thing about it. It really exists only for novelty at this point, and doesn't even represent my capabilities as a game programmer. Being that it is over 13 years old. <file_sep>/Misc/DBXExporter/DBXExporter/oedbx/library/oedbx/dbxConditions.h //*************************************************************************************** #ifndef dbxConditionsH #define dbxConditionsH //*************************************************************************************** #include <oedbx/dbxCommon.h> //*************************************************************************************** class AS_EXPORT DbxConditions { public : DbxConditions(InStream ins, int4 address); ~DbxConditions(); const char * GetText() const { return Text; } void ShowResults(OutStream outs) const; private : void init(); void readConditions(InStream ins); //data int4 Address, Length; char * Text; }; //*********************************************** #endif dbxConditionsH <file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/lv_test.cpp /* lv_test.c - Some test stuff. */ #include "common.h" #include "lv_test.h" #include <d3d9.h> #include "lv_tex.h" #include "lg_err.h" #include <lf_sys.h> #include "lm_d3d.h" typedef struct _LVTVERTEX{ float x, y, z; L_dword diffuse; float tu, tv; float tcu, tcv; }LVTVERTEX; CLegacyMeshD3D g_Mesh; #define LVTVERTEX_TYPE (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX2) //int LVT_ValidateInvalidate(LVT_OBJ* lpObj, IDirect3DDevice9* lpDevice, L_bool bValidate); void LVT_LoadModel(char* szFilename) { g_Mesh.Create(szFilename, LG_GetGame()->v.m_lpDevice); } LVT_OBJ* LVT_CreateTest(IDirect3DDevice9* lpDevice) { LVT_OBJ* lpObj=L_null; lpObj=(LVT_OBJ*)malloc(sizeof(LVT_OBJ)); if(!lpObj) return 0; //Stuff for the test model. g_Mesh.Create("Models\\maxpayne\\payne_walk.l3dm", lpDevice); if(!LVT_ValidateInvalidate(lpObj, lpDevice, L_true)) { free(lpObj); return 0; } return lpObj; } int LVT_ValidateInvalidate(LVT_OBJ* lpObj, IDirect3DDevice9* lpDevice, L_bool bValidate) { if(bValidate) { // Stuff for the test wall. LVTVERTEX lpVerts[600]; int x=0, y=0, i=0; L_result nResult=0; void* lpBuffer=L_null; //Code for test wall. if(!Tex_Load( lpDevice, "textures\\graybrick.tga", D3DPOOL_DEFAULT, 0x00000000, L_false, &lpObj->lpTex)) { return 0; } if(!Tex_Load(lpDevice, "test\\spotdown01lm.tga", D3DPOOL_DEFAULT, 0x00000000, L_false, &lpObj->lpLM)) { L_safe_release(lpObj->lpTex); return 0; } for(x=0, i=0; x<10; x++) { for(y=0; y<10; y++, i+=6) { L_bool bExtY=L_false; L_bool bExtX=L_false; float fTop=0.0f; float fBottom=1.0f; float fLeft=0.0f; float fRight=1.0f; if(!(x%2)) { fLeft=0.0f; fRight=0.5f; } else { fLeft=0.5f; fRight=1.0f; } if(!(y%2)) { fTop=0.0f; fBottom=0.5f; } else { fTop=0.5f; fBottom=1.0f; } lpVerts[i].x=x*10.0f-50.0f; lpVerts[i].z=0.0f; lpVerts[i].y=y*10.0f-50.0f; lpVerts[i].diffuse=0xFFFFFFFF; lpVerts[i].tu=0.0f; lpVerts[i].tv=1.0f; lpVerts[i].tcu=fLeft; lpVerts[i].tcv=fBottom; lpVerts[i+1].x=x*10.0f+10.0f-50.0f; lpVerts[i+1].z=0.0f; lpVerts[i+1].y=y*10.0f+10.0f-50.0f; lpVerts[i+1].diffuse=0xFFFFFFFF; lpVerts[i+1].tu=1.0f; lpVerts[i+1].tv=0.0f; lpVerts[i+1].tcu=fRight; lpVerts[i+1].tcv=fTop;; lpVerts[i+2].x=x*10.0f+10.0f-50.0f; lpVerts[i+2].z=0.0f; lpVerts[i+2].y=y*10.0f-50.0f; lpVerts[i+2].diffuse=0xFFFFFFFF; lpVerts[i+2].tu=1.0f; lpVerts[i+2].tv=1.0f; lpVerts[i+2].tcu=fRight; lpVerts[i+2].tcv=fBottom; memcpy(&lpVerts[i+3], &lpVerts[i+1], sizeof(lpVerts[0])); memcpy(&lpVerts[i+4], &lpVerts[i], sizeof(lpVerts[0])); lpVerts[i+5].x=x*10.0f-50.0f; lpVerts[i+5].z=0.0f; lpVerts[i+5].y=y*10.0f+10.0f-50.0f; lpVerts[i+5].diffuse=0x00FFFFFF; lpVerts[i+5].tu=0.0f; lpVerts[i+5].tv=0.0f; lpVerts[i+5].tcu=fLeft; lpVerts[i+5].tcv=fTop; } } nResult=IDirect3DDevice9_CreateVertexBuffer( lpDevice, sizeof(LVTVERTEX)*600, 0, LVTVERTEX_TYPE, D3DPOOL_MANAGED, &lpObj->lpVB, L_null); if(L_failed(nResult)) { Err_PrintDX("IDirect3DDevice9::CreateVertexBuffer", nResult); L_safe_release(lpObj->lpLM); L_safe_release(lpObj->lpTex);; return 0; } nResult=IDirect3DVertexBuffer9_Lock(lpObj->lpVB, 0, sizeof(LVTVERTEX)*600, &lpBuffer, 0); if(lpBuffer) memcpy(lpBuffer, &lpVerts, sizeof(LVTVERTEX)*600); IDirect3DVertexBuffer9_Unlock(lpObj->lpVB); //The mesh stuff. g_Mesh.Validate(); return 1; } else { g_Mesh.Invalidate(); L_safe_release(lpObj->lpLM); L_safe_release(lpObj->lpTex); L_safe_release(lpObj->lpVB); return 1; } return 1; } void LVT_Render(LVT_OBJ* lpObj, IDirect3DDevice9* lpDevice) { L_result nResult=0; if(!lpObj) return; //Test render the model. /* IDirect3DDevice9_SetFVF(lpDevice, L3DMVERTEX_TYPE); IDirect3DDevice9_SetStreamSource(lpDevice,0,lpObj->l3dmTest.lpVB,0,sizeof(L3DMVERTEX)); IDirect3DDevice9_SetTexture(lpDevice,0,lpObj->l3dmTest.lpSkin); //For the model rendering we set it to alpha blend based on the texture, //in this way say we wanted a holographic model we could use a partially //transparent texture. */ IDirect3DDevice9_SetRenderState(lpDevice, D3DRS_ALPHABLENDENABLE, TRUE); IDirect3DDevice9_SetRenderState(lpDevice, D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); IDirect3DDevice9_SetRenderState(lpDevice, D3DRS_DESTBLEND, D3DBLEND_ZERO); //IDirect3DDevice9_DrawPrimitive(lpDevice,D3DPT_TRIANGLELIST, 0, lpObj->l3dmTest.dwTriangleCount); L_dword i=0; { static L_dword frame1=1, frame2=2; static L_dword time=timeGetTime(); static float fMSPerFrame=30.0f; if((timeGetTime()-time)>fMSPerFrame) { frame1++; frame2++; //frame2=frame1+1; time=timeGetTime(); //We set the frames to 2 for the max //payne model because the first frame //is the same as the last. frame2=frame1+1; if(frame1==g_Mesh.GetNumFrames()) { frame2=1; } else if(frame1>g_Mesh.GetNumFrames()) { frame1=1; frame2=frame1+1; } } g_Mesh.PrepareFrame( frame1, frame2, (float)(timeGetTime()-time)/fMSPerFrame); g_Mesh.SetupSkeleton(frame1, frame2, (float)(timeGetTime()-time)/fMSPerFrame); } D3DXMATRIX matTrans; D3DXMatrixIdentity(&matTrans); matTrans._43=250.0f; matTrans._43=2.5f; matTrans._42=-0.9f; lpDevice->SetTransform(D3DTS_VIEW, &matTrans); D3DXMatrixRotationY(&matTrans, timeGetTime()/3000.0f); lpDevice->SetTransform(D3DTS_WORLD, &matTrans); g_Mesh.Render(); g_Mesh.RenderSkeleton(); IDirect3DDevice9_SetFVF(lpDevice, LVTVERTEX_TYPE); IDirect3DDevice9_SetStreamSource(lpDevice,0,lpObj->lpVB,0,sizeof(LVTVERTEX)); //#define RENDERTESTWALL #ifdef RENDERTESTWALL D3DXMatrixIdentity(&matTrans); matTrans._43=50.0f; matTrans._42=0.0f; lpDevice->SetTransform(D3DTS_VIEW, &matTrans); lpDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); #define MULTIPASS #ifdef MULTIPASS IDirect3DDevice9_SetTexture(lpDevice,0,lpObj->lpTex); IDirect3DDevice9_SetRenderState(lpDevice, D3DRS_ALPHABLENDENABLE, FALSE); nResult=IDirect3DDevice9_DrawPrimitive(lpDevice,D3DPT_TRIANGLELIST, 0, 200); IDirect3DDevice9_SetRenderState(lpDevice, D3DRS_ALPHABLENDENABLE, TRUE); IDirect3DDevice9_SetTexture(lpDevice,0,lpObj->lpLM); IDirect3DDevice9_SetTextureStageState(lpDevice, 0, D3DTSS_TEXCOORDINDEX, 1); IDirect3DDevice9_SetRenderState(lpDevice, D3DRS_SRCBLEND, D3DBLEND_ZERO); IDirect3DDevice9_SetRenderState(lpDevice, D3DRS_DESTBLEND, D3DBLEND_SRCCOLOR); nResult=IDirect3DDevice9_DrawPrimitive(lpDevice,D3DPT_TRIANGLELIST, 0, 200); IDirect3DDevice9_SetTextureStageState(lpDevice, 0, D3DTSS_TEXCOORDINDEX, 0); #else lpDevice->lpVtbl->SetTexture(lpDevice,0,lpObj->lpTex); lpDevice->lpVtbl->SetTexture(lpDevice,1,lpObj->lpLM); lpDevice->lpVtbl->SetTextureStageState(lpDevice, 0, D3DTSS_TEXCOORDINDEX, 0); lpDevice->lpVtbl->SetTextureStageState(lpDevice, 0, D3DTSS_COLORARG1, D3DTA_TEXTURE); lpDevice->lpVtbl->SetTextureStageState(lpDevice, 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1); lpDevice->lpVtbl->SetTextureStageState(lpDevice, 1, D3DTSS_TEXCOORDINDEX, 1); lpDevice->lpVtbl->SetTextureStageState(lpDevice, 1, D3DTSS_COLORARG1, D3DTA_TEXTURE); lpDevice->lpVtbl->SetTextureStageState(lpDevice, 1, D3DTSS_COLORARG2, D3DTA_CURRENT); lpDevice->lpVtbl->SetTextureStageState(lpDevice, 1, D3DTSS_COLOROP, D3DTOP_MODULATE); nResult=lpDevice->lpVtbl->DrawPrimitive(lpDevice,D3DPT_TRIANGLELIST, 0, 200); lpDevice->lpVtbl->SetTexture(lpDevice, 1, L_null); #endif #endif //A little test. if(0) { POINT p={20,20}; IDirect3DSurface9* lpSurface=L_null, *lpBackBuffer=L_null; IDirect3DTexture9_GetSurfaceLevel(lpObj->lpTex, 0, &lpSurface); IDirect3DDevice9_SetRenderState(lpDevice, D3DRS_ALPHABLENDENABLE, TRUE); IDirect3DDevice9_SetRenderState(lpDevice, D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); IDirect3DDevice9_SetRenderState(lpDevice, D3DRS_DESTBLEND, D3DBLEND_ZERO); IDirect3DDevice9_GetBackBuffer(lpDevice, 0, 0, D3DBACKBUFFER_TYPE_MONO, &lpBackBuffer); IDirect3DDevice9_StretchRect(lpDevice, lpSurface, L_null, lpBackBuffer, L_null, D3DTEXF_POINT); L_safe_release(lpBackBuffer); L_safe_release(lpSurface); } return; } int LVT_Delete(LVT_OBJ* lpObj) { if(!lpObj) return 0; LVT_ValidateInvalidate(lpObj, L_null, L_false); g_Mesh.Unload(); free(lpObj); return 1; } <file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/ModelExporter/msL3DM.cpp //Milkshape Exporter for the Legacy3D Model Formal (L3DM). #include <windows.h> #include "msLib\\msPlugIn.h" #include "lm_ms.h" #include "msLib\\msLib.h" #pragma comment(lib, "msLib\\lib6\\msModelLib.lib") #pragma comment(lib, "d3dx9.lib") // ---------------------------------------------------------------------------------------------- class CLegacy3DExp:public cMsPlugIn { private: public: CLegacy3DExp(){} virtual ~CLegacy3DExp(){}; int GetType(){return cMsPlugIn::eTypeExport/*|cMsPlugIn::eNormalsAndTexCoordsPerTriangleVertex*/;} const char* GetTitle(){return "Legacy 3D Format";} int Execute(msModel* pModel); }; int CLegacy3DExp::Execute(msModel* pModel) { //Get a filename to export our data to. char szFile[MAX_PATH]; szFile[0]=0; OPENFILENAME sf; memset(&sf, 0, sizeof(OPENFILENAME)); sf.lStructSize=sizeof(OPENFILENAME); sf.lpstrFilter="Legacy 3D Model Format (L3DM)\0*l3dm\0All Files\0*.*\0"; sf.lpstrFile=szFile; sf.nMaxFile=MAX_PATH; sf.lpstrTitle="Legacy 3D Model Exporter"; sf.lpstrDefExt="l3dm"; if(!GetSaveFileName(&sf)) return -1; //All we need to to is load the mesh //from the milkshape model then call //the save function. CLegacyMeshMS Mesh(pModel); Mesh.Save(szFile); CLegacySkelMS Skel(pModel); Skel.Save(szFile, L_true); msModel_Destroy(pModel); MessageBox( NULL, "Legacy 3D Model Exported", "Legacy 3D Model Exporter", MB_OK|MB_ICONINFORMATION); return 0; } //Our export function so milkshape can perform //the operations. cMsPlugIn *CreatePlugIn() { return new CLegacy3DExp; } <file_sep>/samples/D3DDemo/code/GFX3D9/D3DInit.c /* D3DInit.c - Initialization Functions for GFX3D9 Copyright (c) 2003, <NAME> */ #include <d3d9.h> #include <math.h> #include <windowsx.h> #include "GFX3D9.h" BOOL SetViewPort( LPDIRECT3DDEVICE9 lpDevice, DWORD dwWidth, DWORD dwHeight) { D3DVIEWPORT9 VP; ZeroMemory(&VP, sizeof(D3DVIEWPORT9)); VP.X = 0; VP.Y = 0; VP.Width = dwWidth; VP.Height = dwHeight; VP.MinZ = 0.0f; VP.MaxZ = 1.0f; lpDevice->lpVtbl->SetViewport(lpDevice, &VP); return TRUE; } BOOL SetProjectionMatrix( LPDIRECT3DDEVICE9 lpDevice, DWORD dwWidth, DWORD dwHeight, FLOAT zn, FLOAT zf) { FLOAT FOV=0.0f; FLOAT h=0.0f, w=0.0f; D3DMATRIX PM; ZeroMemory(&PM, sizeof(D3DMATRIX)); if(!lpDevice) return FALSE; FOV = 3.141592654f / 4; h=(FLOAT)((DOUBLE)1.0f/tan(FOV/2)); w=h/((FLOAT)dwWidth/(FLOAT)dwHeight); /* Create the projections matrix. */ PM._11=w; PM._12=0; PM._13=0; PM._14=0; PM._21=0; PM._22=h; PM._23=0; PM._24=0; PM._31=0; PM._32=0; PM._33=zf/(zf-zn); PM._34=1; PM._41=0; PM._42=0; PM._43=((-zn)*zf)/(zf-zn); PM._44=0; if(SUCCEEDED(lpDevice->lpVtbl->SetTransform(lpDevice, D3DTS_PROJECTION, &PM))) return TRUE; else return FALSE; } GFX3D9_EXPORTS BOOL SetTextureFilter( LPDIRECT3DDEVICE9 lpDevice, DWORD Stage, D3DFILTER FilterMode) { D3DCAPS9 Caps; if(!lpDevice)return FALSE; if(FAILED(IDirect3DDevice9_GetDeviceCaps(lpDevice, &Caps))) return FALSE; switch(FilterMode) { case D3DFILTER_POINT: IDirect3DDevice9_SetSamplerState(lpDevice, Stage, D3DSAMP_MAGFILTER, D3DTEXF_POINT); IDirect3DDevice9_SetSamplerState(lpDevice, Stage, D3DSAMP_MINFILTER, D3DTEXF_POINT); IDirect3DDevice9_SetSamplerState(lpDevice, Stage, D3DSAMP_MIPFILTER, D3DTEXF_NONE); break; case D3DFILTER_BILINEAR: IDirect3DDevice9_SetSamplerState(lpDevice, Stage, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); IDirect3DDevice9_SetSamplerState(lpDevice, Stage, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); IDirect3DDevice9_SetSamplerState(lpDevice, Stage, D3DSAMP_MIPFILTER, D3DTEXF_NONE); break; case D3DFILTER_TRILINEAR: IDirect3DDevice9_SetSamplerState(lpDevice, Stage, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); IDirect3DDevice9_SetSamplerState(lpDevice, Stage, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); IDirect3DDevice9_SetSamplerState(lpDevice, Stage, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR); break; case D3DFILTER_ANISOTROPIC: if((Caps.DevCaps&D3DPRASTERCAPS_ANISOTROPY) == D3DPRASTERCAPS_ANISOTROPY){ IDirect3DDevice9_SetSamplerState(lpDevice, Stage, D3DSAMP_MAGFILTER, D3DTEXF_ANISOTROPIC); IDirect3DDevice9_SetSamplerState(lpDevice, Stage, D3DSAMP_MINFILTER, D3DTEXF_ANISOTROPIC); IDirect3DDevice9_SetSamplerState(lpDevice, Stage, D3DSAMP_MIPFILTER, D3DTEXF_ANISOTROPIC); IDirect3DDevice9_SetSamplerState(lpDevice, Stage, D3DSAMP_MAXANISOTROPY, Caps.MaxAnisotropy); }else return FALSE; break; default: return FALSE; }; return TRUE; } BOOL ScreenSwitch( DWORD dwWidth, DWORD dwHeight, BOOL bWindowed, D3DFORMAT FullScreenFormat, BOOL bVsync, LPDIRECT3DDEVICE9 lpDevice, LPDIRECT3DSURFACE9 * lppBackSurface, D3DPRESENT_PARAMETERS * lpSavedParams, POOLFN fpReleasePool, POOLFN fpRestorePool) { return TRUE; } BOOL ValidateDevice( LPDIRECT3DDEVICE9 * lppDevice, LPDIRECT3DSURFACE9 * lppBackSurface, D3DPRESENT_PARAMETERS d3dpp, POOLFN fpReleasePool, POOLFN fpRestorePool) { HRESULT hr=0; BOOL bWasBackSurface=FALSE; if(lppBackSurface) bWasBackSurface=TRUE; if(!(lppDevice))return FALSE; if(FAILED(hr=IDirect3DDevice9_TestCooperativeLevel((*lppDevice)))){ if(hr == D3DERR_DEVICELOST)return TRUE; if(hr == D3DERR_DEVICENOTRESET){ if(bWasBackSurface){ if( *lppBackSurface ){ IDirect3DSurface9_Release((*lppBackSurface)); *lppBackSurface=NULL; } } if(fpReleasePool) fpReleasePool(); if(FAILED(IDirect3DDevice9_Reset((*lppDevice), &d3dpp))){ return FALSE; } if(bWasBackSurface){ if(FAILED(IDirect3DDevice9_GetBackBuffer( (*lppDevice), 0, 0, D3DBACKBUFFER_TYPE_MONO, (lppBackSurface) )))return FALSE; } IDirect3DDevice9_Clear( (*lppDevice), 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0, 0, 200), 1.0f, 0); if(fpRestorePool) fpRestorePool(); } } return TRUE; } BOOL CorrectWindowSize( HWND hWnd, DWORD nWidth, DWORD nHeight, BOOL bWindowed, HMENU hMenu){ if(bWindowed){ /* Make sure window styles are correct */ RECT rcWork; RECT rc; DWORD dwStyle; if(hMenu) SetMenu(hWnd, hMenu); dwStyle=GetWindowStyle(hWnd); dwStyle &= ~WS_POPUP; dwStyle |= WS_SYSMENU|WS_OVERLAPPED|WS_CAPTION | WS_DLGFRAME | WS_MINIMIZEBOX; SetWindowLong(hWnd, GWL_STYLE, dwStyle); SetRect(&rc, 0, 0, nWidth, nHeight); AdjustWindowRectEx(&rc, GetWindowStyle(hWnd), GetMenu(hWnd)!=NULL, GetWindowExStyle(hWnd)); SetWindowPos( hWnd, NULL, 0, 0, rc.right-rc.left, rc.bottom-rc.top, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE ); SetWindowPos( hWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE ); /* Make sure our window does not hang outside of the work area */ SystemParametersInfo( SPI_GETWORKAREA, 0, &rcWork, 0 ); GetWindowRect( hWnd, &rc ); if( rc.left < rcWork.left ) rc.left = rcWork.left; if( rc.top < rcWork.top ) rc.top = rcWork.top; SetWindowPos( hWnd, NULL, rc.left, rc.top, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE ); return TRUE; }else return TRUE; } BOOL InitD3D( HWND hWndTarget, DWORD dwWidth, DWORD dwHeight, BOOL bWindowed, BOOL bVsync, D3DFORMAT d3dfFullScreenFormat, LPDIRECT3D9 lppD3D, LPDIRECT3DDEVICE9 * lppDevice, LPDIRECT3DSURFACE9 * lppBackSurface, D3DPRESENT_PARAMETERS * d3dSavedParams) { D3DPRESENT_PARAMETERS d3dpp; D3DDISPLAYMODE d3ddm; ZeroMemory(&d3ddm, sizeof(d3ddm)); ZeroMemory(&d3dpp, sizeof(d3dpp)); if( !(lppD3D) )return FALSE; if( (*lppDevice) ){ IDirect3DDevice9_Release((*lppDevice)); (*lppDevice)=NULL; } d3dpp.BackBufferWidth = dwWidth; d3dpp.BackBufferHeight = dwHeight; d3dpp.BackBufferFormat = bWindowed ? D3DFMT_UNKNOWN : d3dfFullScreenFormat; d3dpp.BackBufferCount = 1; d3dpp.MultiSampleType = D3DMULTISAMPLE_NONE; d3dpp.MultiSampleQuality=0; /* If vsync */ d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; d3dpp.hDeviceWindow=hWndTarget; d3dpp.Windowed = bWindowed; d3dpp.EnableAutoDepthStencil=TRUE; d3dpp.AutoDepthStencilFormat = D3DFMT_D16; d3dpp.FullScreen_RefreshRateInHz=D3DPRESENT_RATE_DEFAULT; d3dpp.PresentationInterval = (bVsync ? (bWindowed ? 0 : D3DPRESENT_INTERVAL_ONE) : (bWindowed ? 0 : D3DPRESENT_INTERVAL_IMMEDIATE) ); d3dpp.Flags = 0;//D3DPRESENTFLAG_LOCKABLE_BACKBUFFER; if(FAILED(IDirect3D9_CreateDevice( (lppD3D), D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWndTarget, D3DCREATE_SOFTWARE_VERTEXPROCESSING, /* Should be able to specify these flags. */ &d3dpp, lppDevice)))return FALSE; memcpy(d3dSavedParams, &d3dpp, sizeof(D3DPRESENT_PARAMETERS)); /* if(lppBackSurface){ if(FAILED(IDirect3DDevice9_GetBackBuffer((*lppDevice), 0, 0, D3DBACKBUFFER_TYPE_MONO, lppBackSurface))){ return FALSE; } } */ return TRUE; }<file_sep>/games/Explor2002/Source/Game/main.cpp #include <windows.h> #include <ddraw.h> #include <stdio.h> #include "defines.h" #include "ddsetup.h" #include "resource.h" #include "gmapboard.h" #include "bmp.h" #include "tiles.h" #include "tilemgr.h" #include "player.h" #include "directmidi.h" #pragma comment(lib, "../DXLIB/dxguid.lib") #pragma comment(lib, "../DXLIB/ddraw.lib") //#define TEST_RENDERING1 #ifdef TEST_RENDERING1 int global_test_number=0; #endif //Function Prototype long CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); BOOL LoadImages(); BOOL keyboard_handler(WPARAM keystroke); void ShutDownDirectDraw(); void ReleaseSurfaces(); BOOL ProcessFrame(); BOOL ComposeFrame(); BOOL PageFlip(); BOOL RestoreSurfaces(); BOOL InitImages(); BOOL GetImages(); BOOL StartLevel(char *mapname, int x, int y, Direction Face, char *musicfile); //Global variables HWND g_hwnd; DWORD g_dwTransparentColor; int g_nScreenWidth=SCREEN_WIDTH; int g_nScreenHeight=SCREEN_HEIGHT; int g_nColorDepth=COLOR_DEPTH; LPDIRECTDRAW lpDirectDrawObject=NULL; LPDIRECTDRAWSURFACE lpPrimary=NULL; LPDIRECTDRAWSURFACE lpSecondary=NULL; LPDIRECTDRAWSURFACE lpBackground=NULL; BOOL ActiveApp; CGameMap g_cGameBoard; CPlayerObject g_cPlayer(1, 1, NORTH); CDirectMidi MusicPlayer; CBitmapReader background; CBitmapReader defaultImageSet; CBitmapReader defaultDoorSet; CTileSet g_cTileSets[NUM_TILE_SETS]; HWND hWnd; int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { MSG msg; hWnd=CreateDefaultWindow("Explor", hInstance); if(!hWnd)return FALSE; g_hwnd=hWnd; ShowWindow(hWnd, nShowCmd); SetFocus(hWnd); ShowCursor(FALSE); BOOL ok=InitDirectDraw(hWnd); if(ok)ok=InitImages(); if(!ok){ DestroyWindow(hWnd); return FALSE; } StartLevel("maps\\default.map", 2, 2, SOUTH, "music\\mmcannon.mid"); //StartLevel("maps\\tunnel.map", 2, 2, SOUTH, "music\\bl_btear.mid"); while(TRUE) if(PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)){ if(!GetMessage(&msg, NULL, 0, 0))return msg.wParam; TranslateMessage(&msg); DispatchMessage(&msg); } else if(ActiveApp)ProcessFrame(); else WaitMessage(); return 0; } BOOL StartLevel(char *mapname, int x, int y, Direction Face, char *musicfile){ g_cGameBoard.openMap(mapname); g_cPlayer.SetFace(Face); if((x<=g_cGameBoard.getMapWidth()&&x>0)&&((y<=g_cGameBoard.getMapHeight()&&y>0))) g_cPlayer.SetLocation(x, y); else g_cPlayer.SetLocation(1, 1); g_cGameBoard.SetTileType(20, DOOR); if(musicfile!=NULL){ if(GetFileAttributes(musicfile)){ MusicPlayer.Load(musicfile); MusicPlayer.Play(); } } return TRUE; } /* void PutText(char* text,LPDIRECTDRAWSURFACE surface){ HDC hdc; if(SUCCEEDED(surface->GetDC(&hdc))){ RECT rect; rect.left=10; rect.right=g_nScreenWidth-10; rect.top=10; rect.bottom=g_nScreenHeight-10; DrawText(hdc,text,-1,&rect,0); surface->ReleaseDC(hdc); } } */ BOOL RenderTFrontTile(int index, CTileSet *set){ switch (index){ case 0://Nothing this is the tile behind the player break; case 1: set->draw(lpSecondary, 3, 80, 240); break; case 2: set->draw(lpSecondary, 0, 320, 240); set->draw(lpSecondary, 3, 80, 240); set->draw(lpSecondary, 7, 640-80, 240); break; case 3: set->draw(lpSecondary, 7, 640-80, 240); break; case 4: set->draw(lpSecondary, 11, 0, 240); break; case 5: set->draw(lpSecondary, 0, 0, 240); set->draw(lpSecondary, 4, 200, 240); break; case 6: set->draw(lpSecondary, 0, 320, 240); break; case 7: set->draw(lpSecondary, 8, 640-200, 240); set->draw(lpSecondary, 0, 640, 240); break; case 8: set->draw(lpSecondary, 14, 640, 240); break; case 9: set->draw(lpSecondary, 17, 20, 240); break; case 10: set->draw(lpSecondary, 12, 140, 240); set->draw(lpSecondary, 1, 0, 240); break; case 11: set->draw(lpSecondary, 1, 160, 240); set->draw(lpSecondary, 5, 260, 240); break; case 12: set->draw(lpSecondary, 1, 320, 240); break; case 13: set->draw(lpSecondary, 9, 640-260, 240); set->draw(lpSecondary, 1, 640-160, 240); break; case 14: set->draw(lpSecondary, 15, 640-140, 240); set->draw(lpSecondary, 1, 640, 240); break; case 15: set->draw(lpSecondary, 19, 640-20, 240); break; case 16: set->draw(lpSecondary, 21, 110, 240); set->draw(lpSecondary, 2, 0, 240); break; case 17: set->draw(lpSecondary, 18, 170, 240); set->draw(lpSecondary, 2, 80, 240); break; case 18: set->draw(lpSecondary, 13, 230, 240); set->draw(lpSecondary, 2, 160, 240); break; case 19: set->draw(lpSecondary, 6, 290, 240); set->draw(lpSecondary, 2, 240, 240); break; case 20: set->draw(lpSecondary, 2, 320, 240); break; case 21: set->draw(lpSecondary, 10, 640-290, 240); set->draw(lpSecondary, 2, 640-240, 240); break; case 22: set->draw(lpSecondary, 16, 640-230, 240); set->draw(lpSecondary, 2, 640-160, 240); break; case 23: set->draw(lpSecondary, 20, 640-170, 240); set->draw(lpSecondary, 2, 640-80, 240); break; case 24: set->draw(lpSecondary, 22, 640-110, 240); set->draw(lpSecondary, 2, 640, 240); break; } return TRUE; } int ConvertTileToTileSet(int tile){ switch(tile){ case 10:return 0; case 20:return 1; default:return 0; } } BOOL Render3D(USHORT tfront[25]){ //Remember all rendering needs to be backwards with the closest row last //and the furthest row first int i=0; for(i=24;i>=21;i--){ if(tfront[i]>0) RenderTFrontTile(i, &g_cTileSets[ConvertTileToTileSet(tfront[i])]); } for(i=16;i<=19;i++){ if(tfront[i]>0) RenderTFrontTile(i, &g_cTileSets[ConvertTileToTileSet(tfront[i])]); } if(tfront[20]>0) RenderTFrontTile(20, &g_cTileSets[ConvertTileToTileSet(tfront[20])]); for(i=15;i>=13;i--){ if(tfront[i]>0) RenderTFrontTile(i, &g_cTileSets[ConvertTileToTileSet(tfront[i])]); } for(i=9;i<=11;i++){ if(tfront[i]>0) RenderTFrontTile(i, &g_cTileSets[ConvertTileToTileSet(tfront[i])]); } for(i=4;i<=5;i++){ if(tfront[i]>0) RenderTFrontTile(i, &g_cTileSets[ConvertTileToTileSet(tfront[i])]); } if(tfront[12]>0) RenderTFrontTile(12, &g_cTileSets[ConvertTileToTileSet(tfront[12])]); for(i=8;i>=7;i--){ if(tfront[i]>0) RenderTFrontTile(i, &g_cTileSets[ConvertTileToTileSet(tfront[i])]); } if(tfront[6]>0) RenderTFrontTile(6, &g_cTileSets[ConvertTileToTileSet(tfront[6])]); if(tfront[1]>0) RenderTFrontTile(1, &g_cTileSets[ConvertTileToTileSet(tfront[1])]); if(tfront[3]>0) RenderTFrontTile(3, &g_cTileSets[ConvertTileToTileSet(tfront[3])]); if(tfront[2]>0) RenderTFrontTile(2, &g_cTileSets[ConvertTileToTileSet(tfront[2])]); return TRUE; } void DrawBackground(){ RECT bgRect; bgRect.top=bgRect.left=0; bgRect.right=g_nScreenWidth; bgRect.bottom=g_nScreenHeight; lpSecondary->Blt(&bgRect, lpBackground, &bgRect,DDBLT_WAIT, NULL); } BOOL ComposeFrame(){ DrawBackground(); USHORT temptfront[TFRONT_SIZE]; g_cGameBoard.generateTFront(temptfront, g_cPlayer.GetFace(), g_cPlayer.GetXLoc(), g_cPlayer.GetYLoc()); g_cPlayer.CopyTFront(temptfront); Render3D(g_cPlayer.m_aTFront); return TRUE; } BOOL ProcessFrame(){ ComposeFrame(); return PageFlip(); } BOOL PageFlip(){ RECT rect; rect.top=rect.left=0; rect.bottom=SCREEN_HEIGHT; rect.right=SCREEN_WIDTH; if(lpPrimary->Flip(NULL,DDFLIP_WAIT)==DDERR_SURFACELOST) return RestoreSurfaces(); /* if(lpPrimary->Blt(&rect, lpSecondary, &rect, DDBLT_WAIT, NULL)==DDERR_SURFACELOST) return RestoreSurfaces(); */ return TRUE; } BOOL RestoreSurfaces(){ BOOL result=TRUE; //if(SUCCEEDED(lpDirectDrawObject->RestoreAllSurfaces()))result=result&&TRUE; if(SUCCEEDED(lpBackground->Restore()))result=result&&background.draw(lpBackground); else return FALSE; if(SUCCEEDED(lpPrimary->Restore()))result=result&&background.draw(lpPrimary); else return FALSE; if(SUCCEEDED(lpSecondary->Restore()))result=result&&background.draw(lpSecondary); else return FALSE; //Remember to restore any other surfaces in the game for(int i=0;i<NUM_TILE_SETS;i++){ if(g_cTileSets[i].Restore())result=result&&TRUE; } result=result&&GetImages(); return result; } long CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam){ switch(message){ case WM_ACTIVATEAPP: ActiveApp=wParam;break; case WM_CREATE: break; case WM_KEYDOWN: if(keyboard_handler(wParam))DestroyWindow(hWnd); break; case WM_DESTROY: MusicPlayer.Stop(); ShutDownDirectDraw(); ShowCursor(TRUE); PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0L; } BOOL LoadBackgroundFile(){ return background.load("art\\background.bmp"); } BOOL LoadImages(){ if(!LoadBackgroundFile())return FALSE; if(!defaultImageSet.load("art\\set0001.bmp"))return FALSE; if(!defaultDoorSet.load("art\\set0002.bmp"))return FALSE; return TRUE; } BOOL GetBackground(){ return background.draw(lpBackground); } BOOL GetImages(){ if(!GetBackground())return FALSE; if(!g_cTileSets[0].GetImages(&defaultImageSet))return FALSE; if(!g_cTileSets[1].GetImages(&defaultDoorSet))return FALSE; return TRUE; } BOOL InitImages(){ if(!LoadImages())return FALSE; for(int i=0;i<NUM_TILE_SETS;i++){ g_cTileSets[0].InitTileObjects(); g_cTileSets[1].InitTileObjects(); } if(!GetImages())return FALSE; return TRUE; } BOOL keyboard_handler(WPARAM keystroke){ //keyboard handler BOOL result=FALSE; switch(keystroke){ case VK_ESCAPE: result=TRUE; break; #ifdef TEST_RENDERING1 case 'T':global_test_number++; if(global_test_number>24)global_test_number=0;break; #endif //Remember to make it so cannot pass through tiles case VK_UP:{ if(g_cPlayer.m_aTFront[6]>0){ switch(g_cGameBoard.GetTileType(g_cPlayer.m_aTFront[6])){ case WALL:break; case DOOR:g_cPlayer.Move(FORWARD, 2);break; } }else g_cPlayer.Move(FORWARD, 1); }break; case VK_DOWN: if(g_cPlayer.m_aTFront[0]>0){ switch(g_cGameBoard.GetTileType(g_cPlayer.m_aTFront[0])){ case WALL:break; case DOOR:g_cPlayer.Move(BACKWARD, 2);break; } }else g_cPlayer.Move(BACKWARD, 1); break; case VK_LEFT: g_cPlayer.Turn(LEFT); break; case VK_RIGHT: g_cPlayer.Turn(RIGHT); break; } return result; } void ReleaseSurfaces(){ for(int i=0;i<NUM_TILE_SETS;i++){ g_cTileSets[i].Release(); } if(lpSecondary!=NULL) lpSecondary->Release(); if(lpPrimary!=NULL) lpPrimary->Release(); if(lpBackground!=NULL) lpBackground->Release(); } void ShutDownDirectDraw(){ if(lpDirectDrawObject!=NULL){ ReleaseSurfaces(); lpDirectDrawObject->Release(); } }<file_sep>/games/Legacy-Engine/Scrapped/old/lv_tex.h /* lv_tex.h - Header for texture loading functions. */ #ifndef __LV_TEX_H__ #define __LV_TEX_H__ #include <d3d9.h> #include "common.h" #ifdef __cplusplus extern "C"{ #endif /*__cplusplus*/ typedef enum _TEXFILTER_MODE{ FILTER_UNKNOWN = 0, FILTER_NONE = 0, FILTER_POINT = 1, FILTER_LINEAR = 2, FILTER_BILINEAR = 2, FILTER_TRILINEAR = 3, FILTER_ANISOTROPIC = 4, FILTER_FORCE_DWORD = 0xFFFFFFFF }TEXFILTER_MODE; //#endif FILTER_MODE lg_bool Tex_Load( IDirect3DDevice9* lpDevice, lg_lpstr szFilename, D3DPOOL Pool, lg_dword dwTransparent, lg_bool bForceNoMip, IDirect3DTexture9** lppTex); lg_bool Tex_Load_Memory( IDirect3DDevice9* lpDevice, lg_void* pBuffer, lg_dword nSize, D3DPOOL Pool, lg_dword dwTransparent, lg_bool bForceNoMip, IDirect3DTexture9** lppTex); void Tex_SetLoadOptions( lg_bool bUseMipMaps, //If false all mip-mapping will be disabled. lg_bool bUseHWMips, //If true hardware mip-maps will be generated if possible. TEXFILTER_MODE MipFilter, //If the image has to be resisized at all this will be the filter applied. lg_uint nSizeLimit, //Textures will not excede this size. lg_bool bForce16Bit,//If ture all textures will be limited to 16 bits. lg_bool b16Alpha); #define TEXLOAD_GENMIPMAP 0x00000001 #define TEXLOAD_HWMIPMAP 0x00000002 #define TEXLOAD_LINEARMIPFILTER 0x00000004 #define TEXLOAD_POINTMIPFILTER 0x00000000 #define TEXLOAD_FORCE16BIT 0x00000010 #define TEXLOAD_16BITALPHA 0x00000020 void Tex_SetLoadOptionsFlag(lg_dword Flags, lg_uint nSizeLimit); #define SYSTOVID_AUTOGENMIPMAP 0x00000001 #define SYSTOVID_POINTMIPFILTER 0x00000000 #define SYSTOVID_LINEARMIPFILTER 0x00000002 lg_bool Tex_SysToVid( IDirect3DDevice9* lpDevice, IDirect3DTexture9** lppTex, lg_dword Flags); lg_bool Tex_LoadIMG2( IDirect3DDevice9* lpDevice, lg_lpstr szFilename, D3DPOOL Pool, lg_dword Flags, lg_dword SizeLimit, IDirect3DTexture9** lppTex); lg_bool Tex_LoadIMG2_Memory( IDirect3DDevice9* lpDevice, const lg_byte* pBuffer, lg_dword nBufferSize, D3DPOOL Pool, lg_dword Flags, lg_dword nSizeLimit, IDirect3DTexture9** lppTex); #ifdef __cplusplus } #endif /*__cplusplus*/ #endif /*__LV_TEX_H__*/<file_sep>/tools/fs_sys2/fs_lpk.h #ifndef __FS_ARC_H__ #define __FS_ARC_H__ #include "fs_sys2.h" typedef fs_intptr_t BDIO_FILE; static const fs_dword LPK_VERSION = 103; static const fs_dword LPK_TYPE = 0x314B504C; //(*(fs_dword*)"LPK1") static const fs_char8 LPK_VERSIONTXT[] = "1.03"; static const fs_dword LPK_FILE_TYPE_NORMAL = (1<<0); static const fs_dword LPK_FILE_TYPE_ZLIBCMP = (1<<1); static const fs_dword LPK_OPEN_ENABLEWRITE = (1<<0); static const fs_dword LPK_ADD_ZLIBCMP = (1<<1); typedef struct _LPK_FILE_INFO { fs_pathW szFilename; fs_dword nType; fs_dword nOffset; fs_dword nSize; fs_dword nCmpSize; }LPK_FILE_INFO; static const fs_dword LPK_FILE_POS_TEMP = (1<<3); static const fs_dword LPK_FILE_POS_MAIN = (1<<4); typedef struct _LPK_FILE_INFO_EX: public LPK_FILE_INFO { fs_dword nInternalPosition; }LPK_FILE_INFO_EX; class FS_SYS2_EXPORTS CLArchive { public: CLArchive(); ~CLArchive(); fs_bool CreateNewW(fs_cstr16 szFilename); fs_bool CreateNewA(fs_cstr8 szFilename); fs_bool OpenW(fs_cstr16 szFilename, fs_dword Flags=0); fs_bool OpenA(fs_cstr8 szFilename, fs_dword Flags=0); void Close(); fs_bool Save(); fs_dword AddFileW(fs_cstr16 szFilename, fs_cstr16 szNameInArc, fs_dword Flags); fs_dword AddFileA(fs_cstr8 szFilename, fs_cstr8 szNameInArc, fs_dword Flags); fs_dword GetNumFiles(); fs_bool GetFileInfo(fs_dword nRef, LPK_FILE_INFO* pInfo); const LPK_FILE_INFO* GetFileInfo(fs_dword nRef); fs_bool IsOpen(); fs_dword GetFileRef(const fs_pathW szName); fs_byte* ExtractFile(fs_byte* pOut, fs_dword nRef); private: fs_dword m_nType; fs_dword m_nVersion; fs_dword m_nCount; fs_dword m_nInfoOffset; LPK_FILE_INFO_EX* m_pFileList; BDIO_FILE m_File; BDIO_FILE m_TempFile; fs_bool m_bOpen; fs_bool m_bWriteable; fs_dword m_nMainFileWritePos; fs_bool m_bHasChanged; fs_dword m_nCmpThreshold; fs_bool ReadArcInfo(); fs_dword DoAddFile(BDIO_FILE fin, fs_cstr16 szNameInArc, fs_dword dwFlags); }; #endif __FS_ARC_H__<file_sep>/games/Legacy-Engine/Source/lc_sys2/lc_cvar.cpp #include <string.h> #include <stdio.h> #include <math.h> #include <stdlib.h> #include "lc_cvar.h" #include "lg_string.h" #include "common.h" CCvarList::CCvarList(): m_pHashList(LG_NULL) { m_pHashList=new lg_cvar[LC_CVAR_HASH_SIZE]; if(!m_pHashList) return; for(lg_dword i=0; i<LC_CVAR_HASH_SIZE; i++) { m_pHashList[i].Flags=CVAR_EMPTY; m_pHashList[i].pHashNext=LG_NULL; } } CCvarList::~CCvarList() { if(!m_pHashList) return; for(lg_dword i=0; i<LC_CVAR_HASH_SIZE; i++) { lg_cvar* pCvar=m_pHashList[i].pHashNext; while(pCvar) { lg_cvar* pt=pCvar->pHashNext; delete pCvar; pCvar=pt; } } delete[]m_pHashList; } lg_cvar* CCvarList::GetFirst() { for(m_nLastGotten=0; m_nLastGotten<LC_CVAR_HASH_SIZE; m_nLastGotten++) { if(m_pHashList[m_nLastGotten].Flags!=CVAR_EMPTY) { m_pLastGotten=&m_pHashList[m_nLastGotten]; return m_pLastGotten; } } return LG_NULL; } lg_cvar* CCvarList::GetNext() { m_pLastGotten=m_pLastGotten->pHashNext; if(m_pLastGotten) return m_pLastGotten; for(++m_nLastGotten; m_nLastGotten<LC_CVAR_HASH_SIZE; m_nLastGotten++) { if(m_pHashList[m_nLastGotten].Flags!=CVAR_EMPTY) { m_pLastGotten=&m_pHashList[m_nLastGotten]; return m_pLastGotten; } } return LG_NULL; } lg_dword CCvarList::DefToUnsigned(const lg_char* szDef) { CDefs::DEF_VALUE*v=m_Defs.GetDef(szDef); if(!v) return (lg_dword)atol(szDef); return (lg_dword)v->u; } lg_long CCvarList::DefToLong(const lg_char* szDef) { CDefs::DEF_VALUE*v=m_Defs.GetDef(szDef); if(!v) return (lg_long)atol(szDef); return (lg_long)v->u; } lg_float CCvarList::DefToFloat(const lg_char* szDef) { CDefs::DEF_VALUE*v=m_Defs.GetDef(szDef); if(!v) return (lg_float)atof(szDef); return (lg_float)v->u; } lg_dword CCvarList::GenHash(const lg_char* szName) { lg_dword nLen=LG_Min(LG_StrLen(szName), LC_CVAR_MAX_LEN); lg_dword nHash=0; lg_dword i=0; lg_tchar c; for(i=0; i<nLen; i++) { c=szName[i]; //Insure that the hash value is case insensitive //by capitalizing lowercase letters. if((c>='a') && (c<='z')) c-='a'-'A'; nHash+=c; nHash+=(nHash<<10); nHash^=(nHash>>6); } nHash+=(nHash<<3); nHash^=(nHash>>11); nHash+=(nHash<<15); return nHash; } lg_cvar* CCvarList::Get(const lg_char* szName) { lg_dword nHash=GenHash(szName)%LC_CVAR_HASH_SIZE; lg_cvar* p=&m_pHashList[nHash]; if(L_CHECK_FLAG(p->Flags, CVAR_EMPTY)) return LG_NULL; while(p) { if(LG_StrNcCmpA(p->szName, szName, -1)==0) return p; p=p->pHashNext; } return LG_NULL; } lg_cvar* CCvarList::Register(const lg_char* szName, const lg_char* szValue, lg_dword Flags) { if(!LC_CheckName(szName)) return LG_NULL; if(Get(szName)) { //Cvar is already registered. return LG_NULL; } lg_dword nHash=GenHash(szName)%LC_CVAR_HASH_SIZE; //Add the cvar. if(m_pHashList[nHash].Flags==CVAR_EMPTY) { //Add the cvar... LG_StrCopySafeA(m_pHashList[nHash].szName, szName, LC_CVAR_MAX_LEN); m_pHashList[nHash].Flags=0; Set(&m_pHashList[nHash], szValue, &m_Defs); m_pHashList[nHash].pHashNext=LG_NULL; m_pHashList[nHash].Flags=Flags; return &m_pHashList[nHash]; } else { lg_cvar* pNew=new lg_cvar; if(!pNew) return LG_NULL; LG_StrCopySafeA(pNew->szName, szName, LC_CVAR_MAX_LEN); pNew->Flags=0; Set(pNew, szValue, &m_Defs); pNew->Flags=Flags; pNew->pHashNext=m_pHashList[nHash].pHashNext; m_pHashList[nHash].pHashNext=pNew; return pNew; } } lg_bool CCvarList::Define(lg_char* szDef, lg_float fValue) { return m_Defs.AddDef(szDef, fValue); } lg_bool CCvarList::Define(lg_char* szDef, lg_long nValue) { return m_Defs.AddDef(szDef, nValue); } lg_bool CCvarList::Define(lg_char* szDef, lg_dword nValue) { return m_Defs.AddDef(szDef, nValue); } void CCvarList::Set(lg_cvar* cvar, const lg_char* szValue, CDefs* pDefs) { if(L_CHECK_FLAG(cvar->Flags, CVAR_ROM)) return; LG_StrCopySafeA(cvar->szValue, szValue, LC_CVAR_MAX_LEN); if(cvar->szValue[0]=='0' && (cvar->szValue[1]=='x' || cvar->szValue[1]=='X')) { cvar->nValue=L_axtol((lg_char*)szValue); cvar->fValue=(lg_float)(lg_dword)cvar->nValue; return; } CDefs::DEF_VALUE*v=pDefs->GetDef(szValue); if(!v) { cvar->nValue=atoi(szValue); cvar->fValue=(lg_float)atof(szValue); } else { cvar->nValue=v->u; cvar->fValue=v->f; } } void CCvarList::Set(lg_cvar* cvar, lg_float fValue) { if(L_CHECK_FLAG(cvar->Flags, CVAR_ROM)) return; cvar->fValue=fValue; cvar->nValue=(lg_long)fValue; _snprintf(cvar->szValue, LC_CVAR_MAX_LEN, "%f", fValue); } void CCvarList::Set(lg_cvar* cvar, lg_dword nValue) { if(L_CHECK_FLAG(cvar->Flags, CVAR_ROM)) return; cvar->nValue=nValue; cvar->fValue=(lg_float)nValue; _snprintf(cvar->szValue, LC_CVAR_MAX_LEN, "0x%08X", nValue); } void CCvarList::Set(lg_cvar* cvar, lg_long nValue) { if(L_CHECK_FLAG(cvar->Flags, CVAR_ROM)) return; cvar->nValue=nValue; cvar->fValue=(lg_float)nValue; _snprintf(cvar->szValue, LC_CVAR_MAX_LEN, "%d", nValue); } <file_sep>/tools/fs_sys2/fs_file.cpp #include <memory.h> #include "fs_file.h" #include "fs_internal.h" void* CLFile::operator new(fs_size_t Size) { return FS_Malloc( Size, LF_ALLOC_REASON_FILE, "FS", __FILE__, __LINE__); } void CLFile::operator delete(void* pData) { FS_Free(pData, LF_ALLOC_REASON_FILE); } CLFile::CLFile() { } CLFile::~CLFile() { } fs_dword CLFile::Read(void* pOutBuffer, fs_dword nSize) { if(!FS_CheckFlag(m_nAccess, LF_ACCESS_READ)) { FS_ErrPrintW( L"File Read Error: \"%s\" doesn't have read permission.", ERR_LEVEL_ERROR, m_szPathW); return 0; } //We don't need to read anything if the size to read //was zero or if we are at the end of the file. if(!nSize || m_bEOF) return 0; //If somehow the file pointer has gone past the end of the file, //which it shouldn't, then we can't read anything. if(m_nFilePointer>m_nSize) { FS_ErrPrintW( L"File Read Error: Imposible situation the file pointer has gone pas the end of the file.", ERR_LEVEL_ERROR); return 0; } //If the bytes we want to read goes past the end of //the file we need to adjust the reading size. if(m_nSize<(m_nFilePointer+nSize)) { nSize=m_nSize-m_nFilePointer; } //There are two types of read, either a disk read or //a memory read, the memory read is performed if the //access mode is LF_ACCESS_MEMORY. if(FS_CheckFlag(m_nAccess, LF_ACCESS_MEMORY)) { //Doing a memory read... FS_ErrPrintA("Performing memory read...", ERR_LEVEL_SUPERDETAIL); memcpy(pOutBuffer, (void*)((fs_size_t)m_pData+m_nFilePointer), nSize); m_nFilePointer+=nSize; } else { //Doing a disk read... FS_ErrPrintA("Performing disk read...", ERR_LEVEL_SUPERDETAIL); BDIO_Seek(m_BaseFile, m_nBaseFileBegin+m_nFilePointer, LF_SEEK_BEGIN); nSize=BDIO_Read(m_BaseFile, nSize, pOutBuffer); m_nFilePointer+=nSize; } //If we've reached the end of the file, set the EOF flag. m_bEOF=m_nFilePointer>=m_nSize; //FS_ErrPrintW(L"Read %d bytes.", ERR_LEVEL_ERROR, nSize); return nSize; } fs_dword CLFile::Write(const void* pInBuffer, fs_dword nSize) { if(!FS_CheckFlag(m_nAccess, LF_ACCESS_WRITE) || FS_CheckFlag(m_nAccess, LF_ACCESS_MEMORY)) { FS_ErrPrintW( L"File Write Error: \"%s\" doesn't have write permission.", ERR_LEVEL_ERROR, m_szPathW); return 0; } //Seek to the file pointer of the file. BDIO_Seek(m_BaseFile, m_nBaseFileBegin+m_nFilePointer, LF_SEEK_BEGIN); nSize=BDIO_Write(m_BaseFile, nSize, pInBuffer); m_nFilePointer+=nSize; //Update the size of the file. #if 1 if(m_nFilePointer>m_nSize) { m_nSize=m_nFilePointer; } #else !1 m_nSize=BDIO_GetSize(m_BaseFile); #endif //Set the flag if we're at the end of the file. m_bEOF=m_nFilePointer>=m_nSize; return nSize; } fs_dword CLFile::Tell() { return m_nFilePointer; } fs_dword CLFile::Seek(LF_SEEK_TYPE nMode, fs_long nOffset) { switch(nMode) { case LF_SEEK_BEGIN: m_nFilePointer=nOffset; break; case LF_SEEK_CURRENT: m_nFilePointer+=nOffset; break; case LF_SEEK_END: m_nFilePointer=m_nSize+nOffset; break; } //Clamp the new file pointer if seeking in the positive direction //we'll limit it to the size of the file, //if seeking negative, 0. if(m_nFilePointer>m_nSize) { m_nFilePointer=nOffset>=0?m_nSize:0; } FS_ErrPrintA("Seeked to %d out of %d", ERR_LEVEL_SUPERDETAIL, m_nFilePointer, m_nSize); //Set the EOF flag if necessary. m_bEOF=m_nFilePointer>=m_nSize; return m_nFilePointer; } fs_dword CLFile::GetSize() { return m_nSize; } const void* CLFile::GetMemPointer() { if(FS_CheckFlag(m_nAccess, LF_ACCESS_MEMORY)) return m_pData; else return FS_NULL; } fs_bool CLFile::IsEOF() { return m_bEOF; }<file_sep>/samples/D3DDemo/code/MD3Base/MD3PlayerObject.cpp #define D3D_MD3 #include <stdio.h> #include "md3.h" CMD3PlayerObject::CMD3PlayerObject() { m_lpPlayerMesh=NULL; m_dwSkinRef=SKIN_DEFAULT; m_dwUpperAnim=0; m_dwLowerAnim=0; m_fFPSUpper=1.0f; m_fFPSLower=1.0f; m_UpperTransition=TRANSITION_NONE; m_LowerTransition=TRANSITION_NONE; m_dwAnimNextUpper=0; m_dwAnimNextLower=0; m_dwAnimPrevLower=0; m_dwAnimPrevUpper=0; m_fAnimSpeedNextUpper=0.0f; m_fAnimSpeedNextLower=0.0f; m_lCurrentFrameLower=0; m_lCurrentFrameUpper=0; m_lLastSecondFrameUpper=0; m_lLastSecondFrameLower=0; m_dwTransitionCycle=100; //This can be changed for slower or faster transition (should create function). m_lpWeapon=NULL; m_dwLastCycleTimeLower=timeGetTime(); m_dwLastCycleTimeUpper=timeGetTime(); ZeroMemory(&m_AnimationLower, sizeof(MD3ANIMATION)); ZeroMemory(&m_AnimationUpper, sizeof(MD3ANIMATION)); } CMD3PlayerObject::~CMD3PlayerObject() { } HRESULT CMD3PlayerObject::SetWeapon(CMD3WeaponMesh * lpWeapon) { m_lpWeapon=lpWeapon; return S_OK; } HRESULT CMD3PlayerObject::GetAnimation(DWORD * lpUpper, DWORD * lpLower) { if(lpUpper) *lpUpper=m_dwUpperAnim; if(lpLower) *lpLower=m_dwLowerAnim; return S_OK; }; HRESULT CMD3PlayerObject::SetSkinByName(char szSkinName[]) { DWORD dwRef=0; if(!m_lpPlayerMesh) return E_FAIL; if(FAILED(m_lpPlayerMesh->GetSkinRef(&dwRef, szSkinName))){ return E_FAIL; }else{ m_dwSkinRef=dwRef; return S_OK; } } HRESULT CMD3PlayerObject::SetSkinByRef(DWORD dwSkinRef) { m_dwSkinRef=dwSkinRef; return S_OK; } HRESULT CMD3PlayerObject::ApplyAnimation(DWORD dwAnimRef, FLOAT fSpeed, DWORD dwFlags) { if(!m_lpPlayerMesh) return E_FAIL; if( (dwAnimRef >=BOTH_DEATH1) && (dwAnimRef <= BOTH_DEAD3)){ if((dwFlags&MD3APPLYANIM_UPPER)==MD3APPLYANIM_UPPER) { m_dwAnimPrevUpper=m_dwUpperAnim; m_dwUpperAnim=dwAnimRef; m_lpPlayerMesh->GetAnimation(dwAnimRef, &m_AnimationUpper); m_dwLastCycleTimeUpper=timeGetTime(); m_fFPSUpper=fSpeed; } else if((dwFlags&MD3APPLYANIM_LOWER)==MD3APPLYANIM_LOWER) { m_dwAnimPrevLower=m_dwLowerAnim; m_dwLowerAnim=dwAnimRef; m_lpPlayerMesh->GetAnimation(dwAnimRef, &m_AnimationLower); m_dwLastCycleTimeLower=timeGetTime(); m_fFPSLower=fSpeed; } else { m_dwAnimPrevUpper=m_dwUpperAnim; m_dwAnimPrevLower=m_dwLowerAnim; m_dwUpperAnim=dwAnimRef; m_dwLowerAnim=dwAnimRef; m_lpPlayerMesh->GetAnimation(dwAnimRef, &m_AnimationUpper); m_lpPlayerMesh->GetAnimation(dwAnimRef, &m_AnimationLower); m_dwLastCycleTimeUpper=m_dwLastCycleTimeLower=timeGetTime(); m_fFPSUpper=m_fFPSLower=fSpeed; } }else if( (dwAnimRef >= TORSO_GESTURE) && (dwAnimRef <= TORSO_STAND2)){ m_dwAnimPrevUpper=m_dwUpperAnim; m_dwUpperAnim=dwAnimRef; m_lpPlayerMesh->GetAnimation(dwAnimRef, &m_AnimationUpper); m_dwLastCycleTimeUpper=timeGetTime(); m_fFPSUpper=fSpeed; }else if( (dwAnimRef >= LEGS_WALKCR) && (dwAnimRef <= LEGS_TURN)){ m_dwAnimPrevLower=m_dwLowerAnim; m_dwLowerAnim=dwAnimRef; m_dwLastCycleTimeLower=timeGetTime(); m_lpPlayerMesh->GetAnimation(dwAnimRef, &m_AnimationLower); m_fFPSLower=fSpeed; }else{ return E_FAIL; } return S_OK; } HRESULT CMD3PlayerObject::SetAnimation(DWORD dwAnimRef, DWORD dwFlags, FLOAT fSpeed) { BOOL bLower=FALSE; BOOL bUpper=FALSE; BOOL bAlreadyDeath=FALSE; if( (dwAnimRef >=BOTH_DEATH1) && (dwAnimRef <= BOTH_DEAD3)){ bLower=bUpper=TRUE; m_dwAnimNextUpper=m_dwAnimNextLower=dwAnimRef; m_fAnimSpeedNextUpper=m_fAnimSpeedNextLower=fSpeed; if( !((m_dwLowerAnim >=BOTH_DEATH1) && (m_dwLowerAnim <= BOTH_DEAD3)) ){ //If we weren't in a death animation we do a frame transition to a death animation. //Otherwise we fall through and do the chosen transition-type. m_LowerTransition=m_UpperTransition=TRANSITION_FRAMETRANSITION; m_lPrevFrameLower=m_lLastSecondFrameLower; m_lPrevFrameUpper=m_lLastSecondFrameUpper; ApplyAnimation(dwAnimRef, fSpeed, 0); return S_OK; } }else if( (dwAnimRef >= TORSO_GESTURE) && (dwAnimRef <= TORSO_STAND2)){ m_fAnimSpeedNextUpper=fSpeed; m_dwAnimNextUpper=dwAnimRef; bUpper=TRUE; }else if( (dwAnimRef >= LEGS_WALKCR) && (dwAnimRef <= LEGS_TURN)){ //ApplyAnimation(dwAnimRef, fSpeed); m_fAnimSpeedNextLower=fSpeed; m_dwAnimNextLower=dwAnimRef; bLower=TRUE; }else{ return E_FAIL; } if(MD3SETANIM_WAIT==(dwFlags&MD3SETANIM_WAIT)){ if(bLower) m_LowerTransition=TRANSITION_WAITFORANIMATION; if(bUpper) m_UpperTransition=TRANSITION_WAITFORANIMATION; }else if(MD3SETANIM_FRAME==(dwFlags&MD3SETANIM_FRAME)){ if(bLower){ m_LowerTransition=TRANSITION_WAITFORKEYFRAME; m_lPrevFrameLower=m_lLastSecondFrameLower; } if(bUpper){ m_UpperTransition=TRANSITION_WAITFORKEYFRAME; m_lPrevFrameUpper=m_lLastSecondFrameUpper; } }else{ //If no transition was specified we do a closest match interpolation. if(bLower){ m_LowerTransition=TRANSITION_FRAMETRANSITION; m_lPrevFrameLower=m_lLastSecondFrameLower; ApplyAnimation(dwAnimRef, fSpeed, 0); } if(bUpper){ m_UpperTransition=TRANSITION_FRAMETRANSITION; m_lPrevFrameUpper=m_lLastSecondFrameUpper; ApplyAnimation(dwAnimRef, fSpeed, 0); } } return S_OK; } HRESULT CMD3PlayerObject::SetPlayerMesh(CMD3PlayerMesh * lpPlayerMesh) { //Apply the animation. m_lpPlayerMesh=lpPlayerMesh; //Apply default animations. ApplyAnimation(LEGS_IDLE, 1.0f, 0); ApplyAnimation(TORSO_STAND, 1.0f, 0); SetSkinByRef(SKIN_DEFAULT); return S_OK; } HRESULT CMD3PlayerObject::GetFrames( LONG * lpFirstFrame, LONG * lpSecondFrame, FLOAT * lpTime, DWORD dwTimeElapsed, DWORD dwFrameTime, const MD3ANIMATION Animation) { //We get the first frame by dividing the //elapsed time by the frames per second. //And then add the first frame. *lpFirstFrame=dwTimeElapsed/dwFrameTime + Animation.lFirstFrame; //We make sure the frame is within bounds if( (*lpFirstFrame) >= (Animation.lFirstFrame + Animation.lNumFrames)){ (*lpFirstFrame)=Animation.lFirstFrame; //(*dwLastCycle)=timeGetTime(); } //Get the time in between frames. (*lpTime)=(float)( (float)dwTimeElapsed/(float)dwFrameTime ); (*lpTime)-=(LONG)(*lpTime); //Get the second frame. (*lpSecondFrame)=(*lpFirstFrame)+1; //Make sure the second frame is within bounds. if( (*lpSecondFrame)>=(Animation.lFirstFrame + Animation.lNumFrames)){ if(Animation.lLoopingFrames > 0) (*lpSecondFrame)=(*lpFirstFrame)-Animation.lLoopingFrames+1; else (*lpSecondFrame)=Animation.lFirstFrame;//(*lpFirstFrame)-Animation.lLoopingFrames; } return S_OK; } __inline HRESULT CMD3PlayerObject::FrameTransitionAdjust( FRAMETRANSITIONTYPE * lpTransition, MD3ANIMATION * lpAnimation, LONG * lpFirstFrame, LONG * lpSecondFrame, FLOAT * lpTime, LONG * lpPrevFrame, DWORD * dwLastCycleTime, DWORD dwCycleTime, DWORD dwFirstAnim, DWORD dwSecondAnim, FLOAT fSpeed, BOOL bDone, DWORD dwFlags) { switch(*lpTransition) { case TRANSITION_NONE: break; case TRANSITION_WAITFORANIMATION: if( (*lpFirstFrame == (lpAnimation->lFirstFrame+lpAnimation->lNumFrames-2)) || (lpAnimation->lNumFrames==1) ) { (*lpPrevFrame)=(*lpSecondFrame); *lpTransition=TRANSITION_WAITFORKEYFRAME; } break; case TRANSITION_WAITFORKEYFRAME: if((*lpFirstFrame) != (*lpPrevFrame)) break; //Otherwise fall through. case TRANSITION_FRAMETRANSITION: if(*lpTransition==TRANSITION_WAITFORKEYFRAME) { *lpTransition=TRANSITION_FRAMETRANSITION; *dwLastCycleTime=timeGetTime(); ApplyAnimation(dwSecondAnim, fSpeed, dwFlags); dwCycleTime=0; } GetFrames( lpFirstFrame, lpSecondFrame, lpTime, dwCycleTime, m_dwTransitionCycle, *lpAnimation); *lpSecondFrame=*lpFirstFrame; *lpFirstFrame=*lpPrevFrame; if(*lpSecondFrame > lpAnimation->lFirstFrame) { *lpSecondFrame=lpAnimation->lFirstFrame; *lpTime=1.0f; *lpTransition=TRANSITION_NONE; *dwLastCycleTime=timeGetTime(); } else if(lpAnimation->lNumFrames <= 1) { if(bDone) { *lpTime=1.0f; *lpTransition=TRANSITION_NONE; *dwLastCycleTime=timeGetTime(); } } break; } return S_OK; } HRESULT CMD3PlayerObject::Render( const D3DMATRIX& SavedWorldMatrix ) { //We need a speed adjust to display animation at correct speed. if(!this->m_lpPlayerMesh) return 0; LONG lFirstFrameLower=0; LONG lSecondFrameLower=0; FLOAT fTimeLower=0.0f; LONG lFirstFrameUpper=0; LONG lSecondFrameUpper=0; FLOAT fTimeUpper=0.0f; DWORD dwCycleTime=0; DWORD dwAnimCycle=0; BOOL bFrameDone=FALSE; ///////////////////////////// /// Get the lower frames. /// ///////////////////////////// bFrameDone=FALSE; //Get the cycle time for the lower animation. dwCycleTime=timeGetTime()-m_dwLastCycleTimeLower; //Get the animation cycle for the lower frames. dwAnimCycle=(DWORD)(( (FLOAT)( (m_AnimationLower.lNumFrames*1000)/m_AnimationLower.lFramesPerSecond) )*m_fFPSLower); //Insure that the time elapsed is within the animation cycle. //If it isn't reset the animation time. if(m_LowerTransition==TRANSITION_FRAMETRANSITION) dwAnimCycle=m_dwTransitionCycle*m_AnimationLower.lNumFrames; if( dwCycleTime >= dwAnimCycle ){ m_dwLastCycleTimeLower=timeGetTime(); dwCycleTime-=dwAnimCycle; if(m_LowerTransition==TRANSITION_FRAMETRANSITION) bFrameDone=TRUE; } //Get the frames and time according to the animation cycle. GetFrames( &lFirstFrameLower, &lSecondFrameLower, &fTimeLower, dwCycleTime, dwAnimCycle/m_AnimationLower.lNumFrames, m_AnimationLower); FrameTransitionAdjust( &m_LowerTransition, &m_AnimationLower, &lFirstFrameLower, &lSecondFrameLower, &fTimeLower, &m_lPrevFrameLower, &m_dwLastCycleTimeLower, dwCycleTime, m_dwLowerAnim, m_dwAnimNextLower, m_fAnimSpeedNextLower, bFrameDone, MD3APPLYANIM_LOWER); ///////////////////////////// /// Get the Upper frames. /// ///////////////////////////// bFrameDone=FALSE; //Get the cycle time for the upper animation. dwCycleTime=timeGetTime()-m_dwLastCycleTimeUpper; //Get the animation cycle for the upper frames. dwAnimCycle=(DWORD)((FLOAT)(((m_AnimationUpper.lNumFrames)*1000)/m_AnimationUpper.lFramesPerSecond)*m_fFPSUpper); //Insure that the time elapsed is within the animation cycle. if(m_UpperTransition==TRANSITION_FRAMETRANSITION) dwAnimCycle=m_dwTransitionCycle*m_AnimationUpper.lNumFrames; if(dwCycleTime >= dwAnimCycle){ m_dwLastCycleTimeUpper=timeGetTime(); dwCycleTime-=dwAnimCycle; if(m_UpperTransition==TRANSITION_FRAMETRANSITION) bFrameDone=TRUE; } GetFrames( &lFirstFrameUpper, &lSecondFrameUpper, &fTimeUpper, dwCycleTime, dwAnimCycle/m_AnimationUpper.lNumFrames, m_AnimationUpper); FrameTransitionAdjust( &m_UpperTransition, &m_AnimationUpper, &lFirstFrameUpper, &lSecondFrameUpper, &fTimeUpper, &m_lPrevFrameUpper, &m_dwLastCycleTimeUpper, dwCycleTime, m_dwUpperAnim, m_dwAnimNextUpper, m_fAnimSpeedNextUpper, bFrameDone, MD3APPLYANIM_UPPER); //Save the last second frame (for transition purposes). m_lLastSecondFrameUpper=lSecondFrameUpper; m_lLastSecondFrameLower=lSecondFrameLower; //Render the player mesh. if(m_lpPlayerMesh) m_lpPlayerMesh->Render( lFirstFrameUpper, lSecondFrameUpper, fTimeUpper, lFirstFrameLower, lSecondFrameLower, fTimeLower, m_dwSkinRef, m_lpWeapon, SavedWorldMatrix); return S_OK; }<file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/common/common.h #ifndef __COMMON_H__ #define __COMMON_H__ #ifdef _DEBUG #define CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #endif//_DEBUG #ifdef __cplusplus extern "C"{ #endif /* __cplusplus */ /*************************** Legacy Engine types. ****************************/ typedef signed int L_int, *L_pint; typedef unsigned int L_uint, *L_puint; typedef unsigned char L_char, *L_pchar; typedef unsigned char L_byte, *L_pbyte; typedef signed char L_sbyte, *L_psbyte; typedef signed char L_schar, *L_pschar; typedef char *L_str, *L_pstr, *L_lpstr; typedef unsigned short L_word, *L_pword, L_ushort, *L_pushort; typedef signed short L_short, *L_pshort; typedef unsigned long L_dword, *L_pdword, L_ulong, *L_pulong; typedef signed long L_long, *L_plong; typedef float L_float, *L_pfloat; typedef double L_double, *L_pdouble; typedef long double L_ldouble, *L_lpdouble; typedef void L_void, *L_pvoid; typedef struct _L_large_integer{ L_dword dwLowPart; L_long dwHighPart; }L_large_integer, *L_plarge_integer, *L_lplarge_integer; typedef struct _L_rect{ L_long left; L_long top; L_long right; L_long bottom; }L_rect, *L_prect; typedef int L_bool; #define L_true (1) #define L_false (0) typedef long L_result; #define L_succeeded(Status) ((L_result)(Status)>=0) #define L_failed(Status) ((L_result)(Status)<0) /****************************** Legacy Engine definitions. *******************************/ #ifdef __cplusplus #define L_null (0) #else /* __cplusplus */ #define L_null ((void*)0) #endif __cplusplus #define L_CHECK_FLAG(var, flag) ((var&flag)) #define L_max(v1, v2) ((v1)>(v2))?(v1):(v2) #define L_min(v1, v2) ((v1)<(v2))?(v1):(v2) #define L_clamp(v1, min, max) ( (v1)>(max)?(max):(v1)<(min)?(min):(v1) ) /******************************* Legacy Engine Helper Macros. ********************************/ /* L_safe_free is a macro to safely free allocated memory. */ #ifndef L_safe_free #define L_safe_free(p) {if(p){free(p);(p)=L_null;}} #endif /* SAFE_FREE */ #ifndef L_safe_delete_array #define L_safe_delete_array(p) {if(p){delete [] (p);(p)=L_null;}} #endif //L_safe_delete_array #ifndef L_safe_delete #define L_safe_delete(p) {if(p){delete (p);(p)=L_null;}} #endif //L_safe_delete /* L_safe_release is to release com objects safely. */ #ifdef __cplusplus #define L_safe_release(p) {if(p){(p)->Release();(p)=L_null;}} #else /* __cplusplus */ #define L_safe_release(p) {if(p){(p)->lpVtbl->Release((p));(p)=L_null;}} #endif /* __cplusplus */ /**************************************** Legacy Engine replacement functions. ****************************************/ unsigned long L_strncpy(char* szOut, const char* szIn, unsigned long nMax); char* L_strncat(char* szDest, const char* szSrc, unsigned long nMax); int L_strnicmp(char* szOne, char* szTwo, unsigned long nNum); float L_atovalue(char* string); signed long L_atol(char* string); float L_atof(char* string); unsigned long L_axtol(char* string); unsigned long L_strlen(const char* string); int L_mkdir(const char* szDir); void* L_fopen(const char* filename, const char* mode); int L_fclose(void* stream); L_uint L_fread(void* buffer, L_uint size, L_uint count, void* stream); L_uint L_fwrite(const void* buffer, L_uint size, L_uint count, void* stream); L_long L_ftell(void* stream); int L_fseek(void* stream, long offset, int origin); /************************************* Legacy Engine special functions. *************************************/ char* L_getfilepath(char* szDir, const char* szFilename); void Debug_printf(char* format, ...); #ifdef _DEBUG #define L_BEGIN_D_DUMP {_CrtMemState s1, s2, s3;_CrtMemCheckpoint(&s1); #define L_END_D_DUMP(txt) _CrtMemCheckpoint(&s2);\ _CrtMemDifference(&s3, &s1, &s2);\ OutputDebugString("MEMORY USAGE FOR: \""txt"\":\n");\ _CrtMemDumpStatistics(&s3);} #else /*_DEBUG*/ #define L_BEGIN_D_DUMP #define L_END_D_DUMP(txt) #endif /*_DEBUG*/ #ifdef __cplusplus } #endif /* __cplusplus */ #endif /*__COMMON_H__*/<file_sep>/Misc/DBXExporter/DBXExporter/oedbx/library/oedbx/dbxMessage.h //*************************************************************************************** #ifndef dbxMessageH #define dbxMessageH //*************************************************************************************** #include <oedbx/dbxCommon.h> //*************************************************************************************** class AS_EXPORT DbxMessage { public : DbxMessage(InStream ins, int4 address); ~DbxMessage(); int4 GetLength() const { return Length; } // !!! OE stores the message text with 0x0d 0x0a at !!! // !!! the end of each line !!! char * GetText() const { return Text; } void Convert(); void ShowResults(OutStream outs) const; void Analyze(int4 & headerLines, int4 & bodyLines) const; private : void init(); void readMessageText(InStream ins); // Stores the address, the length and the text of the message int4 Address, Length; char * Text; }; //*************************************************************************************** #endif dbxMessageH <file_sep>/tools/img_lib/TexView3/TexView3.h // TexView3.h : main header file for the TexView3 application // #pragma once #ifndef __AFXWIN_H__ #error "include 'stdafx.h' before including this file for PCH" #endif #include "resource.h" // main symbols // CTexView3App: // See TexView3.cpp for the implementation of this class // class CTexView3App : public CWinApp { public: CTexView3App(); // Overrides public: virtual BOOL InitInstance(); // Implementation afx_msg void OnAppAbout(); DECLARE_MESSAGE_MAP() public: afx_msg void OnFileOpen(); public: afx_msg void OnUpdateFileNew(CCmdUI *pCmdUI); public: afx_msg void OnUpdateFileSave(CCmdUI *pCmdUI); public: afx_msg void OnUpdateFileSaveAs(CCmdUI *pCmdUI); public: void RegisterFileType(LPTSTR szExt, BOOL bUnReg=FALSE);//, LPTSTR szDesc, LPTSTR szText, DWORD nIcon); }; extern CTexView3App theApp;<file_sep>/games/Legacy-Engine/Scrapped/old/ws_sys.cpp #include "common.h" #include "ws_sys.h" #include <stdio.h> #include <tchar.h> CWSFile::CWSFile(): m_nMapVersion(0), m_nMapFlags(0), m_nNameCount(0), m_nNameOffset(0), m_nObjectCount(0), m_nObjectOffset(0), m_pNameTable(0), m_bOpen(WS_FALSE) { } CWSFile::~CWSFile() { Close(); } wsBool CWSFile::TempOpen(wspString szFilename) { Close(); fio_callbacks cb; cb.close=L_fclose; cb.read=L_fread; cb.seek=L_fseek; cb.tell=L_ftell; cb.write=L_fwrite; void* fin=L_fopen(szFilename, LOPEN_OPEN_EXISTING, LOPEN_READ); if(!fin) return m_bOpen; //Read the header... cb.read(&m_nMapVersion, sizeof(wsWord), 1, fin); if(m_nMapVersion!=WS_MAP_VERSION) { cb.close(fin); return m_bOpen; } cb.read(&m_nMapFlags, sizeof(wsByte), 1, fin); cb.read(&m_nNameCount, sizeof(wsLong), 1, fin); cb.read(&m_nNameOffset, sizeof(wsLong), 1, fin); cb.read(&m_nObjectCount, sizeof(wsLong), 1, fin); cb.read(&m_nObjectOffset, sizeof(wsLong), 1, fin); #if 1 _tprintf(_T("Map Version: %d\n"), m_nMapVersion); _tprintf(_T("Name Count: %d\n"), m_nNameCount); _tprintf(_T("Name Offset: %d\n"), m_nNameOffset); _tprintf(_T("Object Count: %d\n"), m_nObjectCount); _tprintf(_T("Object Offset: %d\n"), m_nObjectOffset); #endif //Read the string table: //Step 1: Allocate memory for the string table... m_pNameTable=new wsString[m_nNameCount]; if(!m_pNameTable) { cb.close(fin); return m_bOpen; } //Step 2: Seek to the beginning of the name table... cb.seek(fin, m_nNameOffset, LFSEEK_SET); //Stemp 3: Read each name of of the table, //we have a helper function ReadString to read //one string out of the table. for(wsLong i=0; i<m_nNameCount; i++) { ReadString(fin, &cb, m_pNameTable[i]); #if 1 printf("%s\n", m_pNameTable[i]); #endif } m_bOpen=WS_TRUE; return m_bOpen; } void CWSFile::Close() { if(!m_bOpen) return; WS_SAFE_DELETE_ARRAY(m_pNameTable); m_bOpen=WS_FALSE; } wsDword CWSFile::ReadString(void* fin, fio_callbacks* pCB, wsString szOut) { wsChar c; wsDword i=0; do { pCB->read(&c, sizeof(wsChar), 1, fin); //Won't read pas the maximum string length, //but will continue reading the file, so //it will get to the next string. The size of //wsString should be large enough however. if(i>=WS_MAX_STRING_LENGTH) { szOut[WS_MAX_STRING_LENGTH-1]=0; continue; } szOut[i]=c; i++; }while(c!=0); return i; }<file_sep>/tools/ListingGen/GameLister/Main.c #include <windows.h> BOOL WINAPI DllMain( HANDLE hinstDll, DWORD fdwReason, LPVOID lpvReserved) { return TRUE; }<file_sep>/games/Legacy-Engine/Scrapped/libs/ML_lib2008April/ML_lib.c #ifndef ML_LIB_STATIC #include <windows.h> #endif ML_LIB_STATIC #include "ML_lib.h" #include "ML_vec3.h" #include "ML_mat.h" #define ML_DECL_FUNC(name, b) (__cdecl * name )(b) extern void* ML_Vec3AddCB; extern void* ML_Vec3CrossCB; extern void* ML_Vec3DotCB; extern void* ML_Vec3LengthCB; extern void* ML_Vec3LengthSqCB; extern void* ML_Vec3NormalizeCB; extern void* ML_Vec3ScaleCB; extern void* ML_Vec3DistanceCB; extern void* ML_Vec3SubtractCB; extern void* ML_Vec3TransformCB; extern void* ML_Vec3TransformCoordCB; extern void* ML_Vec3TransformNormalCB; extern void* ML_MatMultiplyCB; extern void* ML_MatInverseCB; ml_bool ML_TestSupport(ML_INSTR nInstr); #ifndef ML_LIB_STATIC BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { /* printf("Floating Point: %i\n", ML_TestSupport(ML_INSTR_F)); printf("MMX: %i\n", ML_TestSupport(ML_INSTR_MMX)); printf("SSE: %i\n", ML_TestSupport(ML_INSTR_SSE)); printf("SSE2: %i\n", ML_TestSupport(ML_INSTR_SSE2)); printf("SSE3: %i\n", ML_TestSupport(ML_INSTR_SSE3)); printf("AMD MMX: %i\n", ML_TestSupport(ML_INSTR_AMDMMX)); printf("3DNOW!: %i\n", ML_TestSupport(ML_INSTR_3DNOW)); printf("3DNOW!2: %i\n", ML_TestSupport(ML_INSTR_3DNOW2)); */ //#define SET_ML_INSTR(name) if(ML_TestSupport(name)){ML_SetFuncs(name); OutputDebugString("Using "#name" instructions.\n");} //Always set instructions to FP first that way if a function isn't overriddent it won't be null. ML_SetSIMDSupport(ML_INSTR_F); if(fdwReason>=1 && fdwReason <=2) { ML_SetBestSIMDSupport(); /* Choose which instruction set we want.*/ /* SET_ML_INSTR(ML_INSTR_SSE3) else SET_ML_INSTR(ML_INSTR_SSE2) else SET_ML_INSTR(ML_INSTR_3DNOW2) else SET_ML_INSTR(ML_INSTR_3DNOW) else SET_ML_INSTR(ML_INSTR_SSE) else SET_ML_INSTR(ML_INSTR_F) */ } return TRUE; } #endif ML_LIB_STATIC ML_INSTR ML_FUNC ML_SetBestSIMDSupport() { #ifdef ML_LIB_STATIC #define SET_ML_INSTR(name) if(ML_TestSupport(name)){ML_SetSIMDSupport(name); return name;} #else ML_LIB_STATIC #define SET_ML_INSTR(name) if(ML_TestSupport(name)){ML_SetSIMDSupport(name); OutputDebugString("Using "#name" instructions.\n"); return name;} #endif ML_LIB_STATIC //Always set instructions to FP first that way if a function isn't overriddent it won't be null. ML_SetSIMDSupport(ML_INSTR_F); /* Choose which instruction set we want.*/ SET_ML_INSTR(ML_INSTR_SSE3) else SET_ML_INSTR(ML_INSTR_SSE2) else SET_ML_INSTR(ML_INSTR_3DNOW2) else SET_ML_INSTR(ML_INSTR_3DNOW) else SET_ML_INSTR(ML_INSTR_SSE) else SET_ML_INSTR(ML_INSTR_F) return ML_INSTR_F; } ml_bool ML_TestSupport(ML_INSTR nInstr) { ml_bool bSupport=ML_FALSE; int neax, nebx, necx, nedx; if(nInstr>=ML_INSTR_AMDMMX) neax=0x80000001; else neax=0x00000001; __asm { push ebx mov eax, neax; cpuid mov neax, eax mov nebx, ebx mov necx, ecx mov nedx, edx pop ebx } switch(nInstr) { case ML_INSTR_F: return (nedx>>0)&1; case ML_INSTR_MMX: return (nedx>>23)&1; case ML_INSTR_SSE: return (nedx>>25)&1; case ML_INSTR_SSE2: return (nedx>>26)&1; case ML_INSTR_SSE3: return (necx>>0)&1; case ML_INSTR_AMDMMX: return (nedx>>22)&0x1; case ML_INSTR_3DNOW: return (nedx>>30)&0x1; case ML_INSTR_3DNOW2: return (nedx>>31)&0x1; default: return 0; } return bSupport; } ml_bool ML_SetSIMDSupport(ML_INSTR nInstr) { ML_MatInverseCB=ML_MatInverse_F; switch(nInstr) { default: case ML_INSTR_F: //Vec3 ML_Vec3AddCB=(void*)ML_Vec3Add_F; ML_Vec3CrossCB=(void*)ML_Vec3Cross_F; ML_Vec3DotCB=ML_Vec3Dot_F; ML_Vec3LengthCB=ML_Vec3Length_F; ML_Vec3LengthSqCB=ML_Vec3LengthSq_F; ML_Vec3NormalizeCB=ML_Vec3Normalize_F; ML_Vec3ScaleCB=ML_Vec3Scale_F; ML_Vec3DistanceCB=ML_Vec3Distance_F; ML_Vec3SubtractCB=ML_Vec3Subtract_F; ML_Vec3TransformCB=ML_Vec3Transform_F; ML_Vec3TransformCoordCB=ML_Vec3TransformCoord_F; ML_Vec3TransformNormalCB=ML_Vec3TransformNormal_F; //Mat ML_MatMultiplyCB=ML_MatMultiply_F; break; case ML_INSTR_SSE3: //Vec3 ML_Vec3AddCB=ML_Vec3Add_SSE; ML_Vec3CrossCB=ML_Vec3Cross_SSE; ML_Vec3DotCB=ML_Vec3Dot_SSE3; ML_Vec3LengthCB=ML_Vec3Length_SSE3; ML_Vec3LengthSqCB=ML_Vec3LengthSq_SSE3; ML_Vec3NormalizeCB=ML_Vec3Normalize_SSE3; ML_Vec3ScaleCB=ML_Vec3Scale_SSE; ML_Vec3DistanceCB=ML_Vec3Distance_SSE3; ML_Vec3SubtractCB=ML_Vec3Subtract_SSE; ML_Vec3TransformCB=ML_Vec3Transform_SSE; ML_Vec3TransformCoordCB=ML_Vec3TransformCoord_SSE; ML_Vec3TransformNormalCB=ML_Vec3TransformNormal_SSE; //Mat ML_MatMultiplyCB=ML_MatMultiply_SSE; break; case ML_INSTR_SSE2: case ML_INSTR_SSE: //Vec3 ML_Vec3AddCB=ML_Vec3Add_SSE; ML_Vec3CrossCB=ML_Vec3Cross_SSE; ML_Vec3DotCB=ML_Vec3Dot_SSE; ML_Vec3LengthCB=ML_Vec3Length_SSE; ML_Vec3LengthSqCB=ML_Vec3LengthSq_SSE; ML_Vec3NormalizeCB=ML_Vec3Normalize_SSE; ML_Vec3ScaleCB=ML_Vec3Scale_SSE; ML_Vec3DistanceCB=ML_Vec3Distance_SSE; ML_Vec3SubtractCB=ML_Vec3Subtract_SSE; ML_Vec3TransformCB=ML_Vec3Transform_SSE; ML_Vec3TransformCoordCB=ML_Vec3TransformCoord_SSE; ML_Vec3TransformNormalCB=ML_Vec3TransformNormal_SSE; //Mat ML_MatMultiplyCB=ML_MatMultiply_SSE; break; case ML_INSTR_3DNOW: //Vec3 ML_Vec3AddCB=ML_Vec3Add_3DNOW; ML_Vec3CrossCB=ML_Vec3Cross_3DNOW; ML_Vec3DotCB=ML_Vec3Dot_3DNOW; ML_Vec3LengthCB=ML_Vec3Length_3DNOW; ML_Vec3LengthSqCB=ML_Vec3LengthSq_3DNOW; ML_Vec3SubtractCB=ML_Vec3Subtract_3DNOW; ML_Vec3NormalizeCB=ML_Vec3Normalize_3DNOW; ML_Vec3ScaleCB=ML_Vec3Scale_3DNOW; ML_Vec3DistanceCB=ML_Vec3Distance_3DNOW; ML_Vec3TransformCB=ML_Vec3Transform_3DNOW; ML_Vec3TransformCoordCB=ML_Vec3TransformCoord_3DNOW; ML_Vec3TransformNormalCB=ML_Vec3TransformNormal_3DNOW; //Mat. ML_MatMultiplyCB=ML_MatMultiply_3DNOW; /* //TODO: test all 3DNOW functions and convert the //following: //Mat break; */ }; return ML_TRUE; } <file_sep>/games/Legacy-Engine/Source/lm_sys/lm_ms.h #include "lm_mesh.h" #include "lm_skel.h" lg_uint __cdecl MSWrite(lg_void* file, lg_void* buffer, lg_uint size); class CLMeshMS: public CLMesh2 { friend class CLSkelMS; public: CLMeshMS(void* pModel, char* szName); lg_bool LoadFromMS(void* pModelParam, char* szName); virtual lg_bool Load(LMPath szFile); virtual lg_bool Save(LMPath szFile); }; class CLSkelMS: public CLSkel2{ public: CLSkelMS(void* pModel, char* szName); lg_bool LoadFromMS(void* pModelParam, char* szName); virtual lg_bool Load(LMPath szFile); virtual lg_bool Save(LMPath szFile); }; <file_sep>/games/Legacy-Engine/Source/LMEdit/LMEditView.cpp // LMEditView.cpp : implementation of the CLMEditView class // #include "stdafx.h" #include "LMEdit.h" #include "LMEditDoc.h" #include "LMEditView.h" #define ID_ANIMATION_ANIMATION1 40000 #define ID_ANIMATION_ANIMATION_MAX 41000 #ifdef _DEBUG #define new DEBUG_NEW #endif CLMEditView* g_wndPrimary=NULL; // CLMEditView IMPLEMENT_DYNCREATE(CLMEditView, CView) BEGIN_MESSAGE_MAP(CLMEditView, CView) // Standard printing commands ON_COMMAND(ID_FILE_PRINT, &CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, &CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, &CView::OnFilePrintPreview) ON_WM_CREATE() ON_WM_DESTROY() ON_WM_MOUSEMOVE() ON_COMMAND(ID_ANIMATION_SHOWSKELETON, &CLMEditView::OnAnimationShowskeleton) ON_COMMAND(ID_MESH_TEXTURED, &CLMEditView::OnMeshTextured) ON_COMMAND(ID_MESH_WIREFRAME, &CLMEditView::OnMeshWireframe) ON_COMMAND(ID_MESH_SMOOTHSHADED, &CLMEditView::OnMeshSmoothshaded) ON_COMMAND(ID_MESH_FLATSHADED, &CLMEditView::OnMeshFlatshaded) ON_COMMAND(ID_ANIMATION_DEFAULTMESH, &CLMEditView::OnAnimationDefaultmesh) ON_COMMAND_RANGE(ID_ANIMATION_ANIMATION1, ID_ANIMATION_ANIMATION_MAX, &CLMEditView::OnAnimationAnimationRange) ON_WM_CONTEXTMENU() ON_UPDATE_COMMAND_UI_RANGE(ID_MESH_WIREFRAME, ID_MESH_SMOOTHSHADED, &CLMEditView::OnUpdateMeshRenderMode) ON_UPDATE_COMMAND_UI(ID_ANIMATION_SHOWSKELETON, &CLMEditView::OnUpdateAnimationShowskeleton) ON_WM_MOUSEWHEEL() END_MESSAGE_MAP() // CLMEditView construction/destruction CLMEditView::CLMEditView() : m_pD3D(NULL) , m_pDevice(NULL) , m_nMouseX(0) , m_nMouseY(0) , m_nBBWidth(1024) , m_nBBHeight(1024) , m_bRenderSkel(FALSE) , m_nMeshRenderMode(MESH_RENDER_TEXTURED) , m_nAnim(0) { D3DXMatrixIdentity(&m_matWorld); D3DXMatrixIdentity(&m_matView); OutputDebugString("View window class is being created\n"); g_wndPrimary=this; } CLMEditView::~CLMEditView() { OutputDebugString("View window class is being destroyed!\n"); } BOOL CLMEditView::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs return CView::PreCreateWindow(cs); } // CLMEditView drawing void CLMEditView::OnDraw(CDC* /*pDC*/) { CLMEditDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; // TODO: add draw code for native data here //Render3DScene(FALSE); ProcessAnimation(); } // CLMEditView printing BOOL CLMEditView::OnPreparePrinting(CPrintInfo* pInfo) { // default preparation return DoPreparePrinting(pInfo); } void CLMEditView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add extra initialization before printing } void CLMEditView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add cleanup after printing } // CLMEditView diagnostics #ifdef _DEBUG void CLMEditView::AssertValid() const { CView::AssertValid(); } void CLMEditView::Dump(CDumpContext& dc) const { CView::Dump(dc); } CLMEditDoc* CLMEditView::GetDocument() const // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CLMEditDoc))); return (CLMEditDoc*)m_pDocument; } #endif //_DEBUG // CLMEditView message handlers int CLMEditView::InitD3D(void) { m_pD3D=Direct3DCreate9(D3D_SDK_VERSION); if(m_pD3D) { D3DPRESENT_PARAMETERS pp; memset(&pp, 0, sizeof(pp)); pp.BackBufferWidth=m_nBBWidth; pp.BackBufferHeight=m_nBBHeight; pp.BackBufferFormat=D3DFMT_UNKNOWN; pp.BackBufferCount=1; pp.SwapEffect=D3DSWAPEFFECT_DISCARD; pp.hDeviceWindow=this->m_hWnd; pp.Windowed=TRUE; pp.EnableAutoDepthStencil=TRUE; pp.AutoDepthStencilFormat=D3DFMT_D24S8; pp.Flags=D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL;//D3DPRESENTFLAG_LOCKABLE_BACKBUFFER; pp.FullScreen_RefreshRateInHz=0; pp.PresentationInterval=D3DPRESENT_INTERVAL_ONE; pp.MultiSampleType=D3DMULTISAMPLE_NONE; pp.MultiSampleQuality=0; HRESULT nResult=m_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, NULL, D3DCREATE_HARDWARE_VERTEXPROCESSING, &pp, &m_pDevice); if(FAILED(nResult)) { m_pD3D->Release(); m_pD3D=NULL; m_pDevice=NULL; } } if( NULL == m_pDevice ) { MessageBox("Error: Could not initialize Direct3D.\nMake sure the latest version is installed."); return -1; } CLMeshEdit::s_pDevice=m_pDevice; GetDocument()->SetDevice(m_pDevice); //Set the render modes ResetView(); SetRenderModes(); return 1; } int CLMEditView::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CView::OnCreate(lpCreateStruct) == -1) return -1; InitD3D(); UpdateMenu(); return 0; } void CLMEditView::OnDestroy() { DestroyD3D(); CView::OnDestroy(); } int CLMEditView::Render3DScene(BOOL bPrinter=FALSE) { if(!m_pDevice) return -1; HRESULT Res = m_pDevice->BeginScene(); if( SUCCEEDED( Res ) ) { SetRenderModes(); m_pDevice->SetTexture( 0 , NULL ); D3DCOLOR ClearColor = 0xFF5050FF; m_pDevice->Clear(0,0,D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER,bPrinter?0xFFFFFFFF:ClearColor,1.0f,0); m_pDevice->SetTransform(D3DTS_WORLD, (D3DMATRIX*)&m_matWorld); m_pDevice->SetTransform(D3DTS_VIEW, &m_matView); ML_MAT matProj; if(bPrinter) { ML_MatPerspectiveFovLH(&matProj, D3DX_PI*0.25f, 1.0f, 1.0f, 1000.0f); } else { ML_MatPerspectiveFovLH(&matProj, D3DX_PI*0.25f, (float)GetWidth()/(float)GetHeight(), .1f, 500.0f); } m_pDevice->SetTransform(D3DTS_PROJECTION, (D3DMATRIX*)&matProj); if( false ) // Primitive draw test. { const D3DMATERIAL9 d3d9mtr={ {1.0f, 1.0f, 1.0f, 1.0f},//Diffuse {1.0f, 1.0f, 1.0f, 1.0f},//Ambient {1.0f, 1.0f, 1.0f, 1.0f},//Specular {0.0f, 0.0f, 0.0f, 1.0f},//Emissive 0.0f}; //Power m_pDevice->SetMaterial(&d3d9mtr); CLMeshEdit::MeshVertex vTest[] = { { 1.f,1.f,0 , 0,0,-1 , 1,1 }, { 1.f,0,0 , 0,0,-1 , 0,1 }, { -1.f,0,0 , 0,0,-1 , 0,0 }, }; m_pDevice->SetRenderState(D3DRS_LIGHTING, TRUE); m_pDevice->SetFVF(D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX1); m_pDevice->DrawPrimitiveUP( D3DPT_TRIANGLELIST , 1 , &vTest , sizeof(CLMeshEdit::MeshVertex) ); } CLMeshEdit* pMesh=&GetDocument()->m_cMesh; CLSkelEdit* pSkel=&GetDocument()->m_cSkel; m_pDevice->SetRenderState(D3DRS_LIGHTING, TRUE); pMesh->Render(); //pMesh->RenderNormals(); if(m_bRenderSkel) { m_pDevice->SetRenderState(D3DRS_LIGHTING, FALSE); pSkel->Render(); } m_pDevice->EndScene(); m_pDevice->Present(NULL, NULL, NULL, NULL); } return 0; } LONG CLMEditView::GetWidth(void) { CRect rc; GetClientRect(&rc); return rc.Width();//rc.right-rc.left; } LONG CLMEditView::GetHeight(void) { CRect rc; GetClientRect(&rc); return rc.Height();//rc.right-rc.left; } void CLMEditView::OnMouseMove(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default if(MK_LBUTTON&nFlags && !(MK_CONTROL&nFlags) && !(MK_SHIFT&nFlags)) { //The basic left mouse button with no modifiers simply //rotates the object. D3DXMATRIX MatRot; D3DXMatrixRotationY(&MatRot, (float)(m_nMouseX-point.x)/(float)GetWidth()*4.0f); m_matWorld=MatRot*m_matWorld; D3DXMatrixRotationX(&MatRot, (float)(m_nMouseY-point.y)/(float)GetWidth()*4.0f); m_matWorld=m_matWorld*MatRot; ProcessAnimation(); } else if((MK_LBUTTON&nFlags && MK_CONTROL&nFlags) || MK_MBUTTON&nFlags) { //The control flag moves the camera up and down. m_matView._41+=(float)(m_nMouseX-point.x)*-m_matView._43/1000.0f; m_matView._42+=(float)(m_nMouseY-point.y)*m_matView._43/1000.0f; ProcessAnimation(); } else if(MK_LBUTTON&nFlags && MK_SHIFT&nFlags) { //The shift flag zooms the camera in and out. m_matView._43+=(float)(m_nMouseY-point.y)*-m_matView._43/1000.0f; ProcessAnimation(); } m_nMouseX=point.x; m_nMouseY=point.y; CView::OnMouseMove(nFlags, point); } int CLMEditView::DestroyD3D(void) { int nCount=0; GetDocument()->SetDevice(NULL); CLMeshEdit::s_pDevice=LG_NULL; m_pDevice->SetTexture(0, LG_NULL); if(m_pDevice){nCount=m_pDevice->Release();m_pDevice=NULL;} Err_Printf("There are %d IDirect3DDevice objects left!\n", nCount); if(m_pD3D){nCount=m_pD3D->Release();m_pD3D=NULL;} Err_Printf("There are %d IDirect3D objects left!\n", nCount); return 0; } void CLMEditView::OnPrint(CDC* pDC, CPrintInfo* pInfo) { // TODO: Add your specialized code here and/or call the base class RenderToDC(pDC); CView::OnPrint(pDC, pInfo); } void CLMEditView::RenderToDC(CDC* pDC) { if(!m_pDevice) return; D3DXMATRIX matProj; D3DXMatrixIdentity(&matProj); D3DXMatrixPerspectiveFovLH(&matProj, D3DX_PI/4.0f, 1.0f, 1.0f, 1000.0f); m_pDevice->SetTransform(D3DTS_PROJECTION, &matProj); Render3DScene(TRUE); CDC dcBB; CDC dcImage; IDirect3DSurface9* pBB; //MessageBox("Starting Printing"); m_pDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &pBB); if(FAILED(pBB->GetDC(&dcBB.m_hDC))) { Err_Printf("Could not get DC from back buffer!\nThe back buffer must be lockable.\n"); pBB->Release(); return; } //Create a bitmap for the surface. dcImage.CreateCompatibleDC(&dcBB); CBitmap hBM; D3DSURFACE_DESC desc; //Need to find out the actually bit depth //instead of just putting 32. pBB->GetDesc(&desc); int nBitdepth=desc.Format==D3DFMT_X8R8G8B8?32:16; hBM.CreateBitmap(pDC->GetDeviceCaps(HORZRES), pDC->GetDeviceCaps(VERTRES), 1, nBitdepth, NULL); dcImage.SelectObject(hBM); BOOL bResult=dcImage.StretchBlt( 0, 0, pDC->GetDeviceCaps(HORZRES)-1, m_nBBHeight*pDC->GetDeviceCaps(HORZRES)/m_nBBWidth-1, &dcBB, 0, 0, m_nBBWidth, m_nBBHeight, SRCCOPY); if(!bResult) Err_Printf("Could not copy back buffer to DC!\n"); bResult=pDC->BitBlt( 0, 0, pDC->GetDeviceCaps(HORZRES)-1, m_nBBHeight*pDC->GetDeviceCaps(HORZRES)/m_nBBWidth-1, &dcImage, 0, 0, SRCCOPY); if(!bResult) Err_Printf("Could not blit image to printing surface!"); //MessageBox("Printing!"); pBB->ReleaseDC(dcBB.m_hDC); pBB->Release(); } void CLMEditView::OnAnimationAnimationRange(UINT nID) { m_nAnim=nID-ID_ANIMATION_ANIMATION1+1; UpdateMenu(); } BOOL CLMEditView::ProcessAnimation(void) { CLMeshEdit* pMesh=&GetDocument()->m_cMesh; CLSkelEdit* pSkel=&GetDocument()->m_cSkel; const CLSkel2::SkelAnim* pAnim=pSkel->IsLoaded() ? pSkel->GetAnim(m_nAnim-1) : NULL; if(!pAnim) { pMesh->SetupDefFrame(); pSkel->SetupFrame(0, 0, 0.0f); pMesh->DoTransform(); Render3DScene(); return TRUE; } static lg_dword nTime=timeGetTime(); lg_dword nElapsed=timeGetTime()-nTime; lg_dword nMSPerAnim=(lg_dword)((float)pAnim->nNumFrames/pAnim->fRate*1000.0f); if(nElapsed>nMSPerAnim) { nTime=timeGetTime(); nElapsed=timeGetTime()-nTime; } float fTime=(float)nElapsed/(float)nMSPerAnim*100.0f; pMesh->SetupFrame(m_nAnim-1, fTime, pSkel); //pMesh->PrepareFrame(m_nFrameTemp1, 1, 0.0f); pSkel->SetupFrame(m_nAnim-1, fTime); pMesh->DoTransform(); Render3DScene(); return TRUE; } void CLMEditView::OnAnimationShowskeleton() { m_bRenderSkel=!m_bRenderSkel; } void CLMEditView::UpdateMenu(void) { CMenu* pMenu=GetParent()->GetMenu(); if(!pMenu) return; //We now update the CLSkelEdit* pSkel=&GetDocument()->m_cSkel; if(m_nAnim>pSkel->GetNumAnims()) m_nAnim=0; pMenu->CheckMenuItem(ID_ANIMATION_DEFAULTMESH, m_nAnim==0?MF_CHECKED:MF_UNCHECKED|MF_BYCOMMAND); //Remove menu items CMenu* pAnimMenu=pMenu->GetSubMenu(3); for(int i=0; i<pAnimMenu->GetMenuItemCount(); i++) { if(pAnimMenu->GetMenuItemID(i)>=ID_ANIMATION_ANIMATION1) { pAnimMenu->DeleteMenu(i, MF_BYPOSITION); i--; } } for(DWORD i=0; i<pSkel->GetNumAnims(); i++) { const CLSkel2::SkelAnim* pAnim=pSkel->GetAnim(i); pAnimMenu->InsertMenu(ID_ANIMATION_DEFAULTMESH, MF_BYCOMMAND, ID_ANIMATION_ANIMATION1+i, CString(pAnim->szName) + " Animation"); if(m_nAnim==(i+1)) pAnimMenu->CheckMenuItem(ID_ANIMATION_ANIMATION1+i, MF_CHECKED|MF_BYCOMMAND); } this->DrawMenuBar(); } BOOL CLMEditView::SetRenderModes(void) { if(!m_pDevice) return FALSE; CLMEditDoc* pDoc=GetDocument(); //The basic light is just a directional light pointing at the character. static const D3DLIGHT9 Light={ D3DLIGHT_DIRECTIONAL, //Type {1.0f, 1.0f, 1.0f, 1.0f},//Diffuse {0.25f, 0.0f, 0.0f, 1.0f},//Specular {0.0f, 0.0f, 0.0f, 1.0f},//Ambient {0.0f, 0.0f, 0.0f},//Position {0.0f, 0.0f, 1.0f},//Direction 0.0f,//Range 0.0f,//Falloff 0.0f,//Attenuation0 0.0f,//Attenuation1 0.0f,//Attenuation2 0.0f,//Theta 0.0f};//Phi m_pDevice->SetLight(0, &Light); m_pDevice->LightEnable(0, TRUE); switch(m_nMeshRenderMode) { default: case MESH_RENDER_TEXTURED: m_pDevice->SetRenderState(D3DRS_LIGHTING, TRUE); m_pDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID); m_pDevice->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD); pDoc->m_cMesh.SetRenderTexture(LG_TRUE); break; case MESH_RENDER_WIREFRAME: m_pDevice->SetRenderState(D3DRS_LIGHTING, FALSE); m_pDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME); pDoc->m_cMesh.SetRenderTexture(LG_TRUE); break; case MESH_RENDER_SMOOTHSHADED: m_pDevice->SetRenderState(D3DRS_LIGHTING, TRUE); m_pDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID); m_pDevice->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD); pDoc->m_cMesh.SetRenderTexture(LG_FALSE); break; case MESH_RENDER_FLATSHADED: m_pDevice->SetRenderState(D3DRS_LIGHTING, TRUE); m_pDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID); m_pDevice->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_FLAT); pDoc->m_cMesh.SetRenderTexture(LG_FALSE); break; }; /* Set alpha blending. */ m_pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); m_pDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); m_pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); m_pDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); return TRUE; } void CLMEditView::OnMeshTextured() { m_nMeshRenderMode=(MESH_RENDER_MODE)ID_MESH_TEXTURED; //UpdateMenu(); SetRenderModes(); } void CLMEditView::OnMeshWireframe() { m_nMeshRenderMode=(MESH_RENDER_MODE)ID_MESH_WIREFRAME; //UpdateMenu(); SetRenderModes(); } void CLMEditView::OnMeshSmoothshaded() { m_nMeshRenderMode=(MESH_RENDER_MODE)ID_MESH_SMOOTHSHADED; //UpdateMenu(); SetRenderModes(); } void CLMEditView::OnMeshFlatshaded() { m_nMeshRenderMode=(MESH_RENDER_MODE)ID_MESH_FLATSHADED; //UpdateMenu(); SetRenderModes(); } void CLMEditView::OnAnimationDefaultmesh() { m_nAnim=0; UpdateMenu(); } void CLMEditView::OnUpdate(CView* /*pSender*/, LPARAM lHint, CObject* /*pHint*/) { UpdateMenu(); //When a new objects is opened the 0x00000011 hint will be sent //which means that the view should be reset. if(lHint==0x00000011) ResetView(); } void CLMEditView::OnContextMenu(CWnd* /*pWnd*/, CPoint point) { CMenu mnuView; mnuView.LoadMenu(_T("VIEW_MENU")); CMenu* pContextMenu=mnuView.GetSubMenu(0); pContextMenu->TrackPopupMenu(TPM_LEFTALIGN|TPM_LEFTBUTTON|TPM_RIGHTBUTTON, point.x, point.y, AfxGetMainWnd()); } void CLMEditView::OnUpdateMeshRenderMode(CCmdUI* pCmdUI) { pCmdUI->SetCheck(m_nMeshRenderMode==pCmdUI->m_nID); } void CLMEditView::OnUpdateAnimationShowskeleton(CCmdUI *pCmdUI) { pCmdUI->SetCheck(m_bRenderSkel); } void CLMEditView::ResetView(void) { CLMeshEdit* pMesh=&GetDocument()->m_cMesh; CLSkelEdit* pSkel=&GetDocument()->m_cSkel; D3DXMatrixIdentity(&m_matWorld); D3DXMatrixIdentity(&m_matView); if(pMesh->IsLoaded()) { //float fYMin, fYMax, fZMin; const ML_AABB* aabb; if(aabb=pMesh->GetBoundingBox())//GetMinsAndMaxes(LG_NULL, LG_NULL, &fYMin, &fYMax, &fZMin, LG_NULL)) { m_matView._43=(aabb->v3Max.y-aabb->v3Min.y)*1.5f-aabb->v3Min.z; m_matView._42=(-aabb->v3Min.y-aabb->v3Max.y)/2.0f; } } else if( pSkel->IsLoaded() ) { ml_aabb bounds; if(pSkel->GetMinsAndMaxes(&bounds)) { m_matView._43=(bounds.v3Max.y-bounds.v3Min.y)*1.5f-bounds.v3Min.z; m_matView._42=(-bounds.v3Min.y-bounds.v3Max.y)/2.0f; } } else { m_matView._43=5.f; m_matView._42=0.f; } SetRenderModes(); } BOOL CLMEditView::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt) { m_matView._43+=-zDelta*m_matView._43/1000.0f; return CView::OnMouseWheel(nFlags, zDelta, pt); } <file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/ModelExporter/lm_ms.h #include "..\\legacy3d\\lm_sys.h" class CLegacyMeshMS: public CLegacyMesh { public: CLegacyMeshMS(void* pModel); L_bool LoadFromMS(void* pModelParam); }; class CLegacySkelMS: public CLegacySkeleton{ public: CLegacySkelMS(void* pModel); L_bool LoadFromMS(void* pModelParam); }; <file_sep>/games/Legacy-Engine/Source/engine/lg_fxmgr.cpp #include <d3dx9.h> #include "lg_fxmgr.h" #include "lg_func.h" #include "lg_err.h" #include "lg_err_ex.h" #include "lf_sys2.h" #include "lc_sys2.h" #include "lg_cvars.h" CLFxMgr* CLFxMgr::s_pFxMgr=LG_NULL; CLFxMgr::CLFxMgr(IDirect3DDevice9* pDevice, lg_dword nMaxFx): CLHashMgr(nMaxFx, "FxMgr"), m_pDevice(LG_NULL), m_nPool(D3DPOOL_MANAGED) { //If the effect manager already exists then we made an error somewhere. if(s_pFxMgr) { throw new CLError( LG_ERR_DEFAULT, __FILE__, __LINE__, LG_TEXT("The Effect Manager can only be initialized once.")); } //Store the global manager. s_pFxMgr=this; //Save a copy of the device. m_pDevice=pDevice; m_pDevice->AddRef(); //Load the default effect: m_pItemList[0].pItem=DoLoad(CV_Get(CVAR_fxm_DefaultFx)->szValue, 0); LG_strncpy(m_pItemList[0].szName, CV_Get(CVAR_fxm_DefaultFx)->szValue, LG_MAX_PATH); //m_pDefItem=this->DoLoad(CV_Get(CVAR_fxm_DefaultFx)->szValue, 0); if(m_pItemList[0].pItem) Err_Printf("FxMgr: Default effect is \"%s\".", CV_Get(CVAR_fxm_DefaultFx)->szValue); else Err_Printf("FxMgr: Could not load default effect."); Err_Printf("FxMgr: Initialized with %u effects available.", m_nMaxItems); } CLFxMgr::~CLFxMgr() { //Clear global manager. s_pFxMgr=LG_NULL; //Release all effects. UnloadItems(); DoDestroy(m_pItemList[0].pItem); //Release Direct3D LG_SafeRelease(m_pDevice); //Base class deallocates memory. } void CLFxMgr::Invalidate() { //Starting at 0 will clear invalidate the default for(lg_dword i=0; i<m_nMaxItems; i++) { if(m_pItemList[i].nHashCode!=CLHashMgr::HM_EMPTY_NODE){ DoDestroy(m_pItemList[i].pItem); } } } void CLFxMgr::Validate() { //Load all other effects, note that the default effect //is included because it is at 0. for(lg_dword i=0; i<m_nMaxItems; i++) { if(m_pItemList[i].nHashCode!=CLHashMgr::HM_EMPTY_NODE) m_pItemList[i].pItem=DoLoad(m_pItemList[i].szName, m_pItemList[i].nFlags); } if(m_pItemList[0].pItem) Err_Printf("FxMgr: Default effect is \"%s\".", CV_Get(CVAR_fxm_DefaultFx)->szValue); else Err_Printf("FxMgr: Could not load default effect."); } ID3DXEffect* CLFxMgr::DoLoad(lg_path szFilename, lg_dword nFlags) { //Open the file, we open with memory access. LF_FILE3 fileFx=LF_Open(szFilename, LF_ACCESS_MEMORY|LF_ACCESS_READ, LF_OPEN_EXISTING); if(!fileFx) return LG_NULL; ID3DXEffect* pOut=LG_NULL; ID3DXBuffer* pErrMsg=LG_NULL; HRESULT hRes=D3DXCreateEffect( m_pDevice, LF_GetMemPointer(fileFx), LF_GetSize(fileFx), LG_NULL, LG_NULL, 0, LG_NULL, &pOut, &pErrMsg); LF_Close(fileFx); if(LG_FAILED(hRes)) { pOut=LG_NULL; Err_Printf("FxMgr::FxLoad ERROR: \"%s\"", (const char*)pErrMsg->GetBufferPointer()); pErrMsg->Release(); pOut=LG_NULL; } else { D3DXHANDLE hBT; pOut->FindNextValidTechnique(NULL, &hBT); //Err_Printf("FxMgr: Found technique \"%s\".", hBT); } return pOut; } void CLFxMgr::DoDestroy(ID3DXEffect* pItem) { LG_SafeRelease(pItem); } void CLFxMgr::SetEffect(fxm_fx effect) { if(effect==CLHashMgr::HM_DEFAULT_ITEM) ;//m_pDevice->SetEffect(nStage, m_pDefFx); else if(effect) ;//m_pDevice->SetEffect(nStage, m_pItemList[effect-1].pFx); else ;//m_pDevice->SetEffect(nStage, 0); } //Temp method only: ID3DXEffect* CLFxMgr::GetInterface(fxm_fx effect) { return effect?m_pItemList[effect-1].pItem:m_pItemList[0].pItem; /* if(effect==CLHashMgr::HM_DEFAULT_ITEM) return m_pDefItem;//m_pDevice->SetEffect(nStage, m_pDefFx); else if(effect) return m_pItemList[effect-1].pItem;//m_pDevice->SetEffect(nStage, m_pItemList[effect-1].pFx); else return m_pDefItem;//m_pDevice->SetEffect(nStage, 0); */ } fxm_fx CLFxMgr::FXM_LoadFx(lg_path szFilename, lg_dword nFlags) { return s_pFxMgr->Load(szFilename, nFlags); } void CLFxMgr::FXM_SetEffect(fxm_fx effect) { return s_pFxMgr->SetEffect(effect); } ID3DXEffect* CLFxMgr::FXM_GetInterface(fxm_fx effect) { return s_pFxMgr->GetInterface(effect); }<file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/common/lf_sys.h /* lf_sys.h Header for teh Legacy file system. Copyright (c) 2006, <NAME>. */ #ifndef __LF_SYS_H__ #define __LF_SYS_H__ #include "common.h" #ifdef __cplusplus extern "C"{ #endif /*__cplusplus*/ #define FS_CHECK_EXIT if(!g_bFSInited){LF_SetError("LF Error: File system not initialized."); return 0;} #define MAX_F_PATH 260 #define TYPE_DATASTREAM 0x00000001 #define TYPE_FILESTREAM 0x00000002 typedef void* LF_FILE2; typedef enum _LF_MOVETYPE{ MOVETYPE_SET=0, MOVETYPE_CUR=1, MOVETYPE_END=2, MOVETYPE_FORCE_DWORD=0xFFFFFFFFl }LF_MOVETYPE; /************************************* File system initialization stuff. *************************************/ L_bool LF_Init(char* dir, L_dword Flags); #define LFINIT_CHECKARCHIVESFIRST 0x00000001 L_bool LF_Shutdown(); L_bool LF_AddArchive(L_lpstr szFilename); L_bool LF_CloseAllArchives(); L_bool LF_ChangeDir(const char* dirname); L_bool LF_ShowPaths(const char* szLimit, L_int (*OutputFunc)(const char*, ...)); char* LF_GetDir(char* buffer, int maxlen); void LF_SetError(char* format, ...); char* LF_GetLastError(); /*************************************** File input output functions. ***************************************/ #define LF_ACCESS_READ 0x00000001 #define LF_ACCESS_WRITE 0x00000002 #define LF_ACCESS_MEMORY 0x00000004 #define LF_ACCESS_DONTSEARCHARCHIVES 0x00000008 typedef enum _LFCREATE{ LFCREATE_UNKNOWN=0, LFCREATE_OPEN_EXISTING=1, LFCREATE_CREATE_NEW=2, LFCREATE_FORCE_DWORD=0xFFFFFFFF}LFCREATE; LF_FILE2 File_Open(L_lpstr szFilename, L_dword dwSize, L_dword dwAccess, LFCREATE nCreate); L_bool File_Close(LF_FILE2 lpFile2); L_dword File_Read(LF_FILE2 lpFile2, L_dword dwByesToRead, L_void* lpBuffer); L_dword File_Write(LF_FILE2 lpFile2, L_dword dwBytesToWrite, L_void* lpBuffer); L_dword File_Seek(LF_FILE2 lpFile2, L_long nMoveDist, LF_MOVETYPE nMoveType); L_dword File_Tell(LF_FILE2 lpFile2); L_dword File_GetSize(LF_FILE2 lpFile2); void* File_GetMemPointer(LF_FILE2 lpFile2, L_dword* lpSize); /**************************************** Archiving functions, reading and writing. ****************************************/ /* The _SEARCHPATHS structure is used to hold information about files that are contained within Legacy Archive (lpk) files. It is sort of an indexing system to quickly load files from within the lpks.*/ typedef struct _SEARCHPATHS{ char m_szFilename[MAX_F_PATH]; char m_szLibrary[MAX_F_PATH]; char m_szNameInLibrary[MAX_F_PATH]; struct _SEARCHPATHS* m_next; }SEARCHPATHS, *PSEARCHPATHS; #define ARC_VERSION (101) #define ARC_VERSIONTXT ("1.01") #define LARCHIVE_TYPE (*(unsigned long*)"LPK1") typedef struct _ARCHEADER{ unsigned long m_nType; unsigned long m_nVersion; unsigned long m_nCount; }ARCHEADER; #define ARCHEADER_SIZE 12 typedef struct _ARCENTRY2{ char m_szFilename[MAX_F_PATH]; unsigned long m_nType; unsigned long m_nOffset; unsigned long m_nInfoOffset; unsigned long m_nCmpSize; unsigned long m_nUncmpSize; struct _ARCENTRY2* m_next; }ARCENTRY2, *PARCENTRY2; #define ARCHTYPE_DEFAULT 0x00000000 #define ARCHTYPE_ZLIBC 0x00000001 #define ARCENTRY2_SIZE (MAX_F_PATH+20) typedef void* HLARCHIVE; HLARCHIVE Arc_Open(char* szFilename); int Arc_Close(HLARCHIVE hArchive); unsigned long Arc_Extract(HLARCHIVE hArchive, char* szFile, void* lpBuffer); unsigned long Arc_GetNumFiles(HLARCHIVE hArchive); const char* Arc_GetFilename(HLARCHIVE hArchive, unsigned long nFile); unsigned long Arc_GetFileSize(HLARCHIVE hArchive, char* szFile); typedef int (*PERCENTAGEFUNC)(void*, unsigned int, char* szOutput); int Arc_Archive( char* szArchive, char* szPath, unsigned long dwFlags, PERCENTAGEFUNC pPercentageFunc); #define ARCHIVE_COMPRESS 0x00000010 #ifdef __cplusplus } #endif /*__cplusplus*/ #endif /* __LF_SYS_H__*/<file_sep>/games/Legacy-Engine/Source/sdk/lw_ent_sdk.h #ifndef __LW_ENT_SDK_H__ #define __LW_ENT_SDK_H__ #include "lw_ai_sdk.h" #include "ML_lib.h" #ifdef __LEGACY_GAME__ #include "lg_list_stack.h" #endif __LEGACY_GAME__ //Definitions //MAX_O_REGIONS is the number of regions that //an entity can occupy at any given time. //Maps should be designed so that no more //than two regions are occupied at a time, //but since it is possible that more regions //can be occupied we set a higher limit. #define MAX_O_REGIONS 8 struct LEntitySrv #ifdef __LEGACY_GAME__ : public CLListStack::LSItem{ #else !__LEGACY_GAME__ { lg_dword m_nLSItemSpace[4]; //Filler space #endif __LEGACY_GAME__ //Physical properties of the entity: ML_MAT m_matPos; //Position/orientation matrix (position: meters. rotation: radians.). ML_VEC3 m_v3Vel; //Velocity (meters/sec). ML_VEC3 m_v3AngVel; //Angular velocity (radians/sec). ML_VEC3 m_v3Torque; //Torque vector (N m) (Technically meters is ignored by the engine and a default of 1 m is assumed). ML_VEC3 m_v3Thrust; //Thrust force of object (Newtons) (Self propelled movement). ML_VEC3 m_v3Impulse;//Impulses applied to the object (self propelled (jumping), or from being shot by a bullet for example). ML_VEC3 m_v3ExtFrc; //External forces acting on object (Newtons). lg_float m_fMass; //Mass (Kilograms). ML_AABB m_aabbBody; //Square space occupied (volume: meters^3). lg_dword m_nPhysFlags; //Flags relating to the physical body (shape, etc). //Some additional information //The following vector arrays are for At, Up, and Right vectors (non translated). ML_VEC3 m_v3Face[3]; //3 vectors describing where the entity is facing (obtained from m_matPos). ML_VEC3 m_v3Look[3]; //3 vectors describing what the entity is looking at. //The look is described by yaw pitch and roll lg_float m_fLook[3]; //Animation information lg_dword m_nAnimFlags1; lg_dword m_nAnimFlags2; //Information about the entity relative to the world: lg_dword m_nNumRegions; //The number of regions the entity is occupying. lg_dword m_nRegions[MAX_O_REGIONS]; //References to the regions the entity is occupying. //The physics engine body of the entity: lg_void* m_pPhysBody; //Physics engine body. //Additional information for entity: //Flags 1: //BIT 0: 0 inert, 1 intelligent. lg_dword m_nFlags1; //32 slots for misc flags. lg_dword m_nFlags2; //32 more slots for misc flags. lg_dword m_nMode1; //32 bits for information about the mode the entity is in. lg_dword m_nMode2; //32 more bits (a mode might be: walking, running, jumping, ducking, etc). lg_dword m_nUEID; //The unique ID of this entity (accross all clients). lg_byte m_pData[1024]; //1 Kilobyte for all additional information. lg_dword m_nCmdsActive; lg_dword m_nCmdsPressed; lg_float m_fAxis[2]; //The AI functionality: CLWAIBase* m_pAI; //Entity function stuff lg_dword m_nFuncs; //The object script lg_path m_szObjScript; //Ent Flags: static const lg_dword EF_1_INERT=0x00000000; static const lg_dword EF_1_INT =0x00000001; static const lg_dword EF_1_BLANK=0x00000002; //Physics Flags: static const lg_dword EF_PHYS_SPHERE= 0x00000001; static const lg_dword EF_PHYS_CYLINDER=0x00000002; static const lg_dword EF_PHYS_BOX= 0x00000004; static const lg_dword EF_PHYS_CAPSULE= 0x00000008; }; #endif __LW_ENT_SDK_H__<file_sep>/games/Legacy-Engine/Scrapped/UnitTests/VarTest/var_mgr.h #pragma once #include <map> #include "var_var.h" namespace var_sys{ class CVarMgr { private: struct MapKeyCompare { bool operator()(const var_char* s1, const var_char* s2) const { return _tcsicmp(s1, s2) < 0; } }; struct DefItem{ var_float fValue; var_long nValue; }; var_word m_nNextVarToCreate; const var_word m_nMaxVars; CVar* m_pVarMem; typedef std::map<const var_char*, CVar*, MapKeyCompare> CVarMap; CVarMap m_VarMap; typedef std::map<const var_char*, DefItem, MapKeyCompare> CDefMap; CDefMap m_DefMap; private: static CDefMap* s_pDefMap; public: static bool DefToValues(const var_char* def, var_float * fValue, var_long * nValue); private: CVar* CreateNewVar(const var_char* name); public: CVarMgr(var_word nMaxVars); ~CVarMgr(void); template <typename T> void Define(const var_char* def, T value) { m_DefMap[def].fValue=(var_float)value; m_DefMap[def].nValue=(var_long)value; } template <typename T> lg_var Register (const var_char* name, T value, var_word flags) { //Note that there are two exit points in the register function. //If all goes well and the variable is registered, then the first //exit point will be reached, and a new variable will be returend. //If either the variable already existed, or it could not be //created because the manager is filled up, then the NULL variable //will be returned. if(!m_VarMap.count(name)) { CVar* pOut = NULL; pOut=CreateNewVar(name); if(pOut) { m_VarMap[name]=pOut; pOut->Set((T)value); pOut->SetFlags(flags); //First return point, all went well. return *pOut; } } //Second return point, variable could not be created. return Get(_T("NULL")); } lg_var Get(const var_char* name); lg_var operator[](const var_char* name); void DebugPrintList(); }; } //namespace var_sys <file_sep>/games/Huckl/Readme.txt Huckleberry's Adventure v1.00 Copyright (C) 2000, <NAME> for Beem Software This folder inlcudes: Huckl.exe - The Huckleberry executable. Readme.txt - This File. Instructions: At the main menu you can press the number corresponding to your choice. While playing the raft will sail down the river. Read the text and choose the best answer. You will have had to read the book 'The Adventures of Huckleberry Finn' to complete the game. If you guess wrong Huck will get an unrewarding surprise but you will be allowed to continue. Note: This game was developed as a project for my Junior Year English Class during the Huckleberry Finn unit. ======================================================= === Version History === === for Huckleberry's Adventure === ======================================================= v1.00 HE(January 18, 2000 ???) Hacked Edition replaced the retail version so the game would not have to be restarted if you lost. v1.00 Retail version. Now your choices are listed a main menu and story were put in the game. v1.00c Included with this package on T and F could be pressed.<file_sep>/samples/D3DDemo/code/GFX3D9/D3DImage.c /* D3DImage.c - Functionality for D3D images. Copyright (c) 2003 <NAME> */ #include <d3dx9.h> #include "GFX3D9.h" /* The image vertex type. */ #define IMGVERTEX_TYPE \ ( \ D3DFVF_XYZRHW| \ D3DFVF_DIFFUSE| \ D3DFVF_TEX1 \ ) /* The image vertex structure. */ typedef struct tagIMGVERTEX{ float x, y, z, rhw; D3DCOLOR Diffuse; float tu, tv; }IMGVERTEX, *LPIMGVERTEX; /* The image structure. */ typedef struct tagD3DIMAGE{ LPDIRECT3DTEXTURE9 lpTexture; LPDIRECT3DVERTEXBUFFER9 lpVB; IMGVERTEX vImage[4]; DWORD dwWidth; DWORD dwHeight; BOOL bIsColor; LPDIRECT3DDEVICE9 lpDevice; }D3DIMAGE, *LPD3DIMAGE; __inline void SetVertices(LPD3DIMAGE lpImage, DWORD dwWidth, DWORD dwHeight){ /* Set up the initial vertices. */ lpImage->vImage[0].x=(float)dwWidth; lpImage->vImage[0].y=(float)dwHeight; lpImage->vImage[0].z=0.0f; lpImage->vImage[0].rhw=1.0f; lpImage->vImage[0].Diffuse=0xFFFFFFFFl; lpImage->vImage[0].tu=1.0f; lpImage->vImage[0].tv=1.0f; lpImage->vImage[1].x=0.0f; lpImage->vImage[1].y=(float)dwHeight; lpImage->vImage[1].z=0.0f; lpImage->vImage[1].rhw=1.0f; lpImage->vImage[1].Diffuse=0xFFFFFFFFl; lpImage->vImage[1].tu=0.0f; lpImage->vImage[1].tv=1.0f; lpImage->vImage[2].x=0.0f; lpImage->vImage[2].y=0.0f; lpImage->vImage[2].z=0.0f; lpImage->vImage[2].rhw=1.0f; lpImage->vImage[2].Diffuse=0xFFFFFFFFl; lpImage->vImage[2].tu=0.0f; lpImage->vImage[2].tv=0.0f; lpImage->vImage[3].x=(float)dwWidth; lpImage->vImage[3].y=0.0f; lpImage->vImage[3].z=0.0f; lpImage->vImage[3].rhw=1.0f; lpImage->vImage[3].Diffuse=0xFFFFFFFFl; lpImage->vImage[3].tu=1.0f; lpImage->vImage[3].tv=0.0f; } HD3DIMAGE CopyD3DImage( HD3DIMAGE lpImageSrc) { if(!lpImageSrc) return NULL; return CreateD3DImageFromTexture( ((LPD3DIMAGE)lpImageSrc)->lpDevice, ((LPD3DIMAGE)lpImageSrc)->dwWidth, ((LPD3DIMAGE)lpImageSrc)->dwHeight, ((LPD3DIMAGE)lpImageSrc)->lpTexture); } HD3DIMAGE CreateD3DImageFromFileA( LPDIRECT3DDEVICE9 lpDevice, char szFilename[MAX_PATH], DWORD dwWidth, DWORD dwHeight, D3DCOLOR dwTransparent) { HRESULT hr=0; D3DSURFACE_DESC TexDesc; LPD3DIMAGE lpImage=NULL; if(!lpDevice) return NULL; lpImage=malloc(sizeof(D3DIMAGE)); if(lpImage==NULL) return NULL; ZeroMemory(&TexDesc, sizeof(D3DSURFACE_DESC)); lpImage->lpTexture=NULL; lpImage->lpVB=NULL; /* Load the texture. */ hr=D3DXCreateTextureFromFileExA( lpDevice, szFilename, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_FILTER_POINT, D3DX_FILTER_POINT, dwTransparent, NULL, NULL, &lpImage->lpTexture); if(FAILED(hr)){ SAFE_FREE(lpImage); return NULL; } lpImage->lpDevice=lpDevice; lpImage->lpDevice->lpVtbl->AddRef(lpImage->lpDevice); lpImage->lpTexture->lpVtbl->GetLevelDesc(lpImage->lpTexture, 0, &TexDesc); if(dwHeight==-1) dwHeight=TexDesc.Height; lpImage->dwHeight=dwHeight; if(dwWidth==-1) dwWidth=TexDesc.Width; lpImage->dwWidth=dwWidth; lpImage->bIsColor=FALSE; SetVertices(lpImage, dwWidth, dwHeight); /* Create the vertex buffer by validate image. */ if(!ValidateD3DImage( (HD3DIMAGE)lpImage)) { SAFE_RELEASE( (lpImage->lpTexture) ); SAFE_RELEASE( (lpImage->lpDevice) ); SAFE_FREE(lpImage); return NULL; } return (HD3DIMAGE)lpImage; } HD3DIMAGE CreateD3DImageFromFileW( LPDIRECT3DDEVICE9 lpDevice, WCHAR szFilename[MAX_PATH], DWORD dwWidth, DWORD dwHeight, D3DCOLOR dwTransparent) { HRESULT hr=0; D3DSURFACE_DESC TexDesc; LPD3DIMAGE lpImage=NULL; if(!lpDevice) return NULL; lpImage=malloc(sizeof(D3DIMAGE)); if(lpImage==NULL) return NULL; ZeroMemory(&TexDesc, sizeof(D3DSURFACE_DESC)); lpImage->lpTexture=NULL; lpImage->lpVB=NULL; /* Load the texture. */ hr=D3DXCreateTextureFromFileExW( lpDevice, szFilename, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_FILTER_POINT, D3DX_FILTER_POINT, dwTransparent, NULL, NULL, &lpImage->lpTexture); if(FAILED(hr)){ SAFE_FREE(lpImage); return NULL; } lpImage->lpDevice=lpDevice; lpImage->lpDevice->lpVtbl->AddRef(lpImage->lpDevice); lpImage->lpTexture->lpVtbl->GetLevelDesc(lpImage->lpTexture, 0, &TexDesc); if(dwHeight==-1) dwHeight=TexDesc.Height; lpImage->dwHeight=dwHeight; if(dwWidth==-1) dwWidth=TexDesc.Width; lpImage->dwWidth=dwWidth; lpImage->bIsColor=FALSE; SetVertices(lpImage, dwWidth, dwHeight); /* Create the vertex buffer by validate image. */ if(!ValidateD3DImage( (HD3DIMAGE)lpImage)) { SAFE_RELEASE( (lpImage->lpTexture) ); SAFE_RELEASE( (lpImage->lpDevice) ); SAFE_FREE(lpImage); return NULL; } return (HD3DIMAGE)lpImage; } HD3DIMAGE CreateD3DImageFromTexture( LPDIRECT3DDEVICE9 lpDevice, DWORD dwWidth, DWORD dwHeight, LPDIRECT3DTEXTURE9 lpTexture) { HRESULT hr=0; D3DSURFACE_DESC TexDesc; LPD3DIMAGE lpImage=NULL; if(!lpDevice) return NULL; lpImage=malloc(sizeof(D3DIMAGE)); if(lpImage==NULL) return NULL; ZeroMemory(&TexDesc, sizeof(D3DSURFACE_DESC)); lpImage->lpTexture=NULL; lpImage->lpVB=NULL; /* Set the texture. */ lpTexture->lpVtbl->AddRef(lpTexture); lpImage->lpTexture=lpTexture; lpImage->lpDevice=lpDevice; lpImage->lpDevice->lpVtbl->AddRef(lpImage->lpDevice); lpImage->lpTexture->lpVtbl->GetLevelDesc(lpImage->lpTexture, 0, &TexDesc); if(dwHeight==-1) dwHeight=TexDesc.Height; lpImage->dwHeight=dwHeight; if(dwWidth==-1) dwWidth=TexDesc.Width; lpImage->dwWidth=dwWidth; lpImage->bIsColor=FALSE; SetVertices(lpImage, dwWidth, dwHeight); /* Create the vertex buffer by validate image. */ if(!ValidateD3DImage( (HD3DIMAGE)lpImage)) { SAFE_RELEASE( (lpImage->lpTexture) ); SAFE_RELEASE( (lpImage->lpDevice) ); SAFE_FREE(lpImage); return NULL; } return (HD3DIMAGE)lpImage; } HD3DIMAGE CreateD3DImageFromColor( LPDIRECT3DDEVICE9 lpDevice, DWORD dwWidth, DWORD dwHeight, D3DCOLOR dwColor) { HRESULT hr=0; LPD3DIMAGE lpImage=NULL; if(!lpDevice) return NULL; lpImage=malloc(sizeof(D3DIMAGE)); lpImage->lpTexture=NULL; lpImage->lpVB=NULL; lpImage->dwHeight=dwHeight; lpImage->dwWidth=dwWidth; lpImage->bIsColor=TRUE; SetVertices(lpImage, dwWidth, dwHeight); lpImage->lpDevice=lpDevice; lpImage->lpDevice->lpVtbl->AddRef(lpImage->lpDevice); /* Set the color. */ lpImage->vImage[0].Diffuse=dwColor; lpImage->vImage[1].Diffuse=dwColor; lpImage->vImage[2].Diffuse=dwColor; lpImage->vImage[3].Diffuse=dwColor; /* Create the vertex buffer by validate image. */ if(!ValidateD3DImage( (HD3DIMAGE)lpImage)) { SAFE_RELEASE( (lpImage->lpTexture) ); SAFE_RELEASE( (lpImage->lpDevice) ); SAFE_FREE(lpImage); return NULL; } return (HD3DIMAGE)lpImage; } BOOL InvalidateD3DImage( HD3DIMAGE lpImage) { if(!lpImage) return FALSE; /* Release the vertex buffer. The texture is managed so we don't need to release it. */ SAFE_RELEASE( (((LPD3DIMAGE)lpImage)->lpVB) ); return TRUE; } BOOL ValidateD3DImage( HD3DIMAGE lpImage) { HRESULT hr=0; if(!lpImage) return FALSE; if( (((LPD3DIMAGE)lpImage)->lpVB) ) return FALSE; /* Create the vertex buffer. */ hr=((LPD3DIMAGE)lpImage)->lpDevice->lpVtbl->CreateVertexBuffer( ((LPD3DIMAGE)lpImage)->lpDevice, sizeof(IMGVERTEX)*4, 0, IMGVERTEX_TYPE, D3DPOOL_DEFAULT, &((LPD3DIMAGE)lpImage)->lpVB, NULL); if(FAILED(hr)) return FALSE; return TRUE; } BOOL DeleteD3DImage( HD3DIMAGE lpImage) { if(!lpImage) return FALSE; /* Release the texture and VB. */ SAFE_RELEASE( (((LPD3DIMAGE)lpImage)->lpTexture) ); SAFE_RELEASE( (((LPD3DIMAGE)lpImage)->lpVB) ); SAFE_RELEASE( (((LPD3DIMAGE)lpImage)->lpDevice) ); SAFE_FREE(lpImage); return TRUE; } BOOL RenderD3DImage( HD3DIMAGE lpImage, LONG x, LONG y) { HRESULT hr=0; IMGVERTEX vFinalImage[4]; DWORD dwPrevFVF=0; DWORD dwOldCullMode=0; LPVOID lpVertices=NULL; LPDIRECT3DTEXTURE9 lpOldTexture=NULL; LPDIRECT3DVERTEXSHADER9 lpOldVS=NULL; DWORD dwOldAlphaEnable=0, dwOldSrcBlend=0, dwOldDestBlend=0, dwOldAlphaA=0; DWORD dwZEnable=0; if(!lpImage) return FALSE; if(!((LPD3DIMAGE)lpImage)->lpVB) return FALSE; /* Copy over the final image. */ vFinalImage[0]=((LPD3DIMAGE)lpImage)->vImage[0]; vFinalImage[1]=((LPD3DIMAGE)lpImage)->vImage[1]; vFinalImage[2]=((LPD3DIMAGE)lpImage)->vImage[2]; vFinalImage[3]=((LPD3DIMAGE)lpImage)->vImage[3]; /* Apply the position. */ vFinalImage[0].x+=x; vFinalImage[0].y+=y; vFinalImage[1].x+=x; vFinalImage[1].y+=y; vFinalImage[2].x+=x; vFinalImage[2].y+=y; vFinalImage[3].x+=x; vFinalImage[3].y+=y; /* Copy over the transformed vertices. */ hr=((LPD3DIMAGE)lpImage)->lpVB->lpVtbl->Lock(((LPD3DIMAGE)lpImage)->lpVB, 0, sizeof(IMGVERTEX)*4, &lpVertices, 0); if(FAILED(hr)) return FALSE; memcpy(lpVertices, &vFinalImage, sizeof(IMGVERTEX)*4); hr=((LPD3DIMAGE)lpImage)->lpVB->lpVtbl->Unlock(((LPD3DIMAGE)lpImage)->lpVB); /* Set the texture. */ ((LPD3DIMAGE)lpImage)->lpDevice->lpVtbl->GetTexture(((LPD3DIMAGE)lpImage)->lpDevice, 0, (LPDIRECT3DBASETEXTURE9*)&lpOldTexture); ((LPD3DIMAGE)lpImage)->lpDevice->lpVtbl->SetTexture(((LPD3DIMAGE)lpImage)->lpDevice, 0, (LPDIRECT3DBASETEXTURE9)((LPD3DIMAGE)lpImage)->lpTexture); /* Get and set FVF. */ ((LPD3DIMAGE)lpImage)->lpDevice->lpVtbl->GetFVF(((LPD3DIMAGE)lpImage)->lpDevice, &dwPrevFVF); ((LPD3DIMAGE)lpImage)->lpDevice->lpVtbl->SetFVF(((LPD3DIMAGE)lpImage)->lpDevice, IMGVERTEX_TYPE); /* Get and set vertex shader. */ ((LPD3DIMAGE)lpImage)->lpDevice->lpVtbl->GetVertexShader(((LPD3DIMAGE)lpImage)->lpDevice, &lpOldVS); ((LPD3DIMAGE)lpImage)->lpDevice->lpVtbl->SetVertexShader(((LPD3DIMAGE)lpImage)->lpDevice, NULL); /* Get and set cull mode. */ ((LPD3DIMAGE)lpImage)->lpDevice->lpVtbl->GetRenderState(((LPD3DIMAGE)lpImage)->lpDevice, D3DRS_CULLMODE, &dwOldCullMode); ((LPD3DIMAGE)lpImage)->lpDevice->lpVtbl->SetRenderState(((LPD3DIMAGE)lpImage)->lpDevice, D3DRS_CULLMODE, D3DCULL_CCW); /* Set alpha blending. */ ((LPD3DIMAGE)lpImage)->lpDevice->lpVtbl->GetRenderState(((LPD3DIMAGE)lpImage)->lpDevice, D3DRS_ALPHABLENDENABLE, &dwOldAlphaEnable); ((LPD3DIMAGE)lpImage)->lpDevice->lpVtbl->SetRenderState(((LPD3DIMAGE)lpImage)->lpDevice, D3DRS_ALPHABLENDENABLE, TRUE); ((LPD3DIMAGE)lpImage)->lpDevice->lpVtbl->GetRenderState(((LPD3DIMAGE)lpImage)->lpDevice, D3DRS_SRCBLEND, &dwOldSrcBlend); ((LPD3DIMAGE)lpImage)->lpDevice->lpVtbl->SetRenderState(((LPD3DIMAGE)lpImage)->lpDevice, D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); ((LPD3DIMAGE)lpImage)->lpDevice->lpVtbl->GetRenderState(((LPD3DIMAGE)lpImage)->lpDevice, D3DRS_DESTBLEND, &dwOldDestBlend); ((LPD3DIMAGE)lpImage)->lpDevice->lpVtbl->SetRenderState(((LPD3DIMAGE)lpImage)->lpDevice, D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); ((LPD3DIMAGE)lpImage)->lpDevice->lpVtbl->GetTextureStageState(((LPD3DIMAGE)lpImage)->lpDevice, 0, D3DTSS_ALPHAARG1, &dwOldAlphaA); ((LPD3DIMAGE)lpImage)->lpDevice->lpVtbl->SetTextureStageState(((LPD3DIMAGE)lpImage)->lpDevice, 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); /* Get and set z-buffer status. */ ((LPD3DIMAGE)lpImage)->lpDevice->lpVtbl->GetRenderState(((LPD3DIMAGE)lpImage)->lpDevice, D3DRS_ZENABLE, &dwZEnable); ((LPD3DIMAGE)lpImage)->lpDevice->lpVtbl->SetRenderState(((LPD3DIMAGE)lpImage)->lpDevice, D3DRS_ZENABLE, FALSE); /* Render the image. */ ((LPD3DIMAGE)lpImage)->lpDevice->lpVtbl->SetStreamSource(((LPD3DIMAGE)lpImage)->lpDevice, 0, ((LPD3DIMAGE)lpImage)->lpVB, 0, sizeof(IMGVERTEX)); ((LPD3DIMAGE)lpImage)->lpDevice->lpVtbl->DrawPrimitive(((LPD3DIMAGE)lpImage)->lpDevice, D3DPT_TRIANGLEFAN, 0, 2); /* Restore all saved values. */ ((LPD3DIMAGE)lpImage)->lpDevice->lpVtbl->SetTexture(((LPD3DIMAGE)lpImage)->lpDevice, 0, (LPDIRECT3DBASETEXTURE9)lpOldTexture); SAFE_RELEASE(lpOldTexture); ((LPD3DIMAGE)lpImage)->lpDevice->lpVtbl->SetFVF(((LPD3DIMAGE)lpImage)->lpDevice, dwPrevFVF); ((LPD3DIMAGE)lpImage)->lpDevice->lpVtbl->SetVertexShader(((LPD3DIMAGE)lpImage)->lpDevice, lpOldVS); ((LPD3DIMAGE)lpImage)->lpDevice->lpVtbl->SetRenderState(((LPD3DIMAGE)lpImage)->lpDevice, D3DRS_CULLMODE, dwOldCullMode); /* Restore alpha blending state. */ ((LPD3DIMAGE)lpImage)->lpDevice->lpVtbl->SetRenderState(((LPD3DIMAGE)lpImage)->lpDevice, D3DRS_ALPHABLENDENABLE, dwOldAlphaEnable); ((LPD3DIMAGE)lpImage)->lpDevice->lpVtbl->SetRenderState(((LPD3DIMAGE)lpImage)->lpDevice, D3DRS_SRCBLEND, dwOldSrcBlend); ((LPD3DIMAGE)lpImage)->lpDevice->lpVtbl->SetRenderState(((LPD3DIMAGE)lpImage)->lpDevice, D3DRS_DESTBLEND, dwOldDestBlend); ((LPD3DIMAGE)lpImage)->lpDevice->lpVtbl->SetTextureStageState(((LPD3DIMAGE)lpImage)->lpDevice, 0, D3DTSS_ALPHAARG1, dwOldAlphaA); /* Restore Z-Buffering status. */ ((LPD3DIMAGE)lpImage)->lpDevice->lpVtbl->SetRenderState(((LPD3DIMAGE)lpImage)->lpDevice, D3DRS_ZENABLE, dwZEnable); return TRUE; } BOOL RenderD3DImageEx( HD3DIMAGE lpImage, LONG nXDest, LONG nYDest, LONG nWidthDest, LONG nHeightDest, LONG nXSrc, LONG nYSrc, LONG nWidthSrc, LONG nHeightSrc) { D3DIMAGE FinalImage; if(!lpImage) return FALSE; ZeroMemory(&FinalImage, sizeof(D3DIMAGE)); FinalImage=*(LPD3DIMAGE)lpImage; FinalImage.dwWidth=nWidthDest; FinalImage.dwHeight=nHeightDest; FinalImage.vImage[0].x=(float)nWidthDest; FinalImage.vImage[0].y=(float)nHeightDest; FinalImage.vImage[1].y=(float)nHeightDest; FinalImage.vImage[3].x=(float)nWidthDest; /* Discover the proper texture coords. */ FinalImage.vImage[0].tu=(float)(nWidthSrc+nXSrc)/(float)GetD3DImageWidth(lpImage); FinalImage.vImage[0].tv=(float)(nHeightSrc+nYSrc)/(float)GetD3DImageHeight(lpImage); FinalImage.vImage[1].tu=(float)nXSrc/(float)GetD3DImageWidth(lpImage); FinalImage.vImage[1].tv=(float)(nHeightSrc+nYSrc)/(float)GetD3DImageHeight(lpImage); FinalImage.vImage[2].tu=(float)nXSrc/(float)GetD3DImageWidth(lpImage); FinalImage.vImage[2].tv=(float)nYSrc/(float)GetD3DImageHeight(lpImage); FinalImage.vImage[3].tu=(float)(nWidthSrc+nXSrc)/GetD3DImageWidth(lpImage); FinalImage.vImage[3].tv=(float)nYSrc/(float)GetD3DImageHeight(lpImage); return RenderD3DImage((HD3DIMAGE)&FinalImage, nXDest, nYDest); } BOOL RenderD3DImageRelativeEx( HD3DIMAGE lpImage, float fXDest, float fYDest, float fWidthDest, float fHeightDest, LONG nXSrc, LONG nYSrc, LONG nWidthSrc, LONG nHeightSrc) { D3DIMAGE FinalImage; LONG dwScreenWidth=0, dwScreenHeight=0; D3DVIEWPORT9 ViewPort; if(!lpImage) return FALSE; ZeroMemory(&FinalImage, sizeof(D3DIMAGE)); ZeroMemory(&ViewPort, sizeof(D3DVIEWPORT9)); ((LPD3DIMAGE)lpImage)->lpDevice->lpVtbl->GetViewport(((LPD3DIMAGE)lpImage)->lpDevice, &ViewPort); dwScreenWidth=ViewPort.Width; dwScreenHeight=ViewPort.Height; FinalImage=*(LPD3DIMAGE)lpImage; /* Scale down the dest values. */ fWidthDest/=100.0f; fHeightDest/=100.0f; fXDest/=100.0f; fYDest/=100.0f; FinalImage.dwWidth=(LONG)(fWidthDest*(float)dwScreenWidth); FinalImage.dwHeight=(LONG)(fHeightDest*(float)dwScreenHeight); FinalImage.vImage[0].x=(float)FinalImage.dwWidth; FinalImage.vImage[0].y=(float)FinalImage.dwHeight; FinalImage.vImage[1].y=(float)FinalImage.dwHeight; FinalImage.vImage[3].x=(float)FinalImage.dwWidth; /* Discover the proper texture coords. */ FinalImage.vImage[0].tu=(float)(nWidthSrc+nXSrc)/(float)GetD3DImageWidth(lpImage); FinalImage.vImage[0].tv=(float)(nHeightSrc+nYSrc)/(float)GetD3DImageHeight(lpImage); FinalImage.vImage[1].tu=(float)nXSrc/(float)GetD3DImageWidth(lpImage); FinalImage.vImage[1].tv=(float)(nHeightSrc+nYSrc)/(float)GetD3DImageHeight(lpImage); FinalImage.vImage[2].tu=(float)nXSrc/(float)GetD3DImageWidth(lpImage); FinalImage.vImage[2].tv=(float)nYSrc/(float)GetD3DImageHeight(lpImage); FinalImage.vImage[3].tu=(float)(nWidthSrc+nXSrc)/(float)GetD3DImageWidth(lpImage); FinalImage.vImage[3].tv=(float)nYSrc/(float)GetD3DImageHeight(lpImage); return RenderD3DImage((HD3DIMAGE)&FinalImage, (LONG)(fXDest*dwScreenWidth), (LONG)(fYDest*dwScreenHeight)); } LONG GetD3DImageWidth(HD3DIMAGE lpImage) { if(!lpImage) return 0; return ((LPD3DIMAGE)lpImage)->dwWidth; } LONG GetD3DImageHeight(HD3DIMAGE lpImage) { if(!lpImage) return 0; return ((LPD3DIMAGE)lpImage)->dwHeight; }<file_sep>/tools/img_lib/img_lib2/img_lib/img_private.h #ifndef __IMG_PRIVATE_H__ #define __IMG_PRIVATE_H__ #include "img_lib.h" //This is the structure of the image format. //All loaders need to fill this data structure in. typedef struct _IMAGE_S { img_word nWidth; //Image Width img_word nHeight; //Image Hieght img_byte nBitDepth; //Color Depth in bits per pixel img_byte nPaletteBitDepth;//Bits per pixel in the palette entries. img_word nPaletteEntries; //Number of palette entries. img_dword nDataSize; //Size of the image data in bytes. img_dword nPaletteSize; //Size of the palette in bytes. IMGORIENT nOrient; //Image Orientation. IMGFMT nDataFmt; //Image Data Format IMGFMT nPaletteFmt; //Image Palette Format void* pImage; //Image Data. void* pPalette; //Palette Data. char* szDescripton; //Some user space to put a description of the image. }IMAGE_S, *PIMAGE_S; /* The structure for the callback functions used when opening the image.*/ typedef struct _IMG_CALLBACKS{ img_int (IMG_FUNC *close)(img_void* stream); img_int (IMG_FUNC *seek)(img_void* stream, img_long offset, img_int origin); img_long (IMG_FUNC *tell)(img_void* stream); img_uint (IMG_FUNC *read)(img_void* buffer, img_uint size, img_uint count, img_void* stream); }IMG_CALLBACKS, *PIMG_CALLBACKS; HIMG IMG_LoadTGACallbacks(img_void* stream, IMG_CALLBACKS* lpCB); HIMG IMG_LoadBMPCallbacks(img_void* stream, IMG_CALLBACKS* lpCB); HIMG IMG_LoadGIFCallbacks(img_void* stream, IMG_CALLBACKS* lpCB); HIMG IMG_LoadJPGCallbacks(img_void* stream, IMG_CALLBACKS* lpCB); HIMG IMG_LoadPNGCallbacks(img_void* stream, IMG_CALLBACKS* lpCB); img_void* img_file_open(img_void* pData, img_dword nSize); img_int img_file_close(img_void* stream); img_int img_file_seek(img_void* stream, img_long offset, img_int origin); img_long img_file_tell(img_void* stream); img_uint img_file_read(img_void* buffer, img_uint size, img_uint count, img_void* stream); #endif __IMG_PRIVATE_H__<file_sep>/games/Legacy-Engine/Source/lm_sys/lm_xexp.cpp #include <d3dx9.h> #include <rmxftmpl.h> #include <rmxfguid.h> #pragma comment(lib, "d3dx9.lib") #pragma comment(lib, "dxguid.lib") #include "lm_xexp.h" #include "lg_malloc.h" lg_bool CLMeshXExp::SaveAsX(char* szFilename) { lg_result nResult=0; ID3DXFile* pFile=NULL; ID3DXFileSaveObject* pFileSave=NULL; ID3DXFileSaveData *pFileSaveRoot=NULL; try { if(LG_FAILED(D3DXFileCreate(&pFile))) throw "Could not create ID3DXFile interface."; nResult=pFile->RegisterTemplates((void*)D3DRM_XTEMPLATES, D3DRM_XTEMPLATE_BYTES); if(LG_FAILED(nResult)) throw "Could not register templates I."; nResult=pFile->RegisterTemplates((void*)XSKINEXP_TEMPLATES, strlen(XSKINEXP_TEMPLATES)); if(LG_FAILED(nResult)) throw "Could not register templates II."; nResult=pFile->CreateSaveObject(szFilename, D3DXF_FILESAVE_TOFILE, D3DXF_FILEFORMAT_TEXT,&pFileSave); if(LG_FAILED(nResult)) throw "Could not create save object."; nResult = pFileSave->AddDataObject(TID_D3DRMFrame, "Scene_Root", NULL, 0, NULL, &pFileSaveRoot); if(LG_FAILED(nResult)) throw "Could not add the root object."; if(!AddMesh(pFileSaveRoot)) throw "Could not add the mesh."; pFileSave->Save(); L_safe_release(pFileSaveRoot); L_safe_release(pFileSave); L_safe_release(pFile); return LG_TRUE; } catch(lg_pstr szError) { MessageBox(NULL, szError, "lmsh X file exporter", MB_ICONERROR); L_safe_release(pFileSaveRoot); L_safe_release(pFileSave); L_safe_release(pFile); return LG_FALSE; } } lg_bool CLMeshXExp::AddMesh(void* SaveRoot) { ID3DXFileSaveData* pFileSaveRoot=(ID3DXFileSaveData*)SaveRoot; ID3DXFileSaveData* pMesh=NULL; ID3DXFileSaveData* pTempXData=NULL; lg_byte* pData=NULL; //The following pointers are not allocated //they point to areas of pData ML_VEC3* pVerts=NULL; XMESH_INDEX* pIndex=NULL; ML_VEC2* pTU=NULL; try { lg_result nResult=0; //The biggest data structure we will need will be the size of //the actuall mesh, so only that much memory must be allocated. //The first thing we need is to create the base of the mesh. lg_dword nVertOffset=4; lg_dword nTriCountOffset=nVertOffset+m_nNumVertices*sizeof(ML_VEC3); lg_dword nIndexOffset=nTriCountOffset+4; lg_dword nSize=nIndexOffset+m_nNumTriangles*sizeof(XMESH_INDEX); pData=(lg_byte*)malloc(nSize); if(!pData) throw "Could not allocate data for exporting."; ML_VEC3* pVerts=(ML_VEC3*)(pData+nVertOffset); XMESH_INDEX* pIndex=(XMESH_INDEX*)(pData+nIndexOffset); //Copy the vertices lg_dword i=0; memcpy(pData, &m_nNumVertices, 4); for(i=0; i<m_nNumVertices; i++) { pVerts[i].x=m_pVertices[i].x; pVerts[i].y=m_pVertices[i].y; pVerts[i].z=m_pVertices[i].z; } //Copy the indices lg_dword j=0; memcpy(pData+nTriCountOffset, &m_nNumTriangles, 4); for(i=0, j=0; i<m_nNumTriangles; i++, j+=3) { pIndex[i].nNumVert=3; pIndex[i].v[0]=m_pIndexes[j]; pIndex[i].v[1]=m_pIndexes[j+1]; pIndex[i].v[2]=m_pIndexes[j+2]; } //Add the base mesh. nResult=pFileSaveRoot->AddDataObject(TID_D3DRMMesh, m_szMeshName, NULL, nSize, pData, &pMesh); if(LG_FAILED(nResult)) throw "Could not add base mesh data."; //Since the normal structure is basically the same //we only need to change pVerts to the normals. for(i=0; i<m_nNumVertices; i++) { pVerts[i].x=m_pVertices[i].nx; pVerts[i].y=m_pVertices[i].ny; pVerts[i].z=m_pVertices[i].nz; } nResult=pMesh->AddDataObject(TID_D3DRMMeshNormals, NULL, NULL, nSize, pData, &pTempXData); if(LG_FAILED(nResult)) throw "Could add mesh normals."; L_safe_release(pTempXData); //Now we need to copy the tex coord data... pTU=(ML_VEC2*)(pData+4); for(i=0; i<m_nNumVertices; i++) { pTU[i].x=m_pVertices[i].tu; pTU[i].y=m_pVertices[i].tv; } //We need to adjust nSize for this one. nSize=4+m_nNumVertices*sizeof(ML_VEC2); nResult=pMesh->AddDataObject(TID_D3DRMMeshTextureCoords, NULL, NULL, nSize, pData, &pTempXData); if(LG_FAILED(nResult)) throw "Could not add texture coordinates."; L_safe_release(pTempXData); L_safe_release(pMesh); L_safe_free(pData); return LG_TRUE; } catch (lg_pstr szError) { MessageBox(NULL, szError, "lmsh X file exporter", MB_ICONERROR); L_safe_release(pTempXData); L_safe_release(pMesh); L_safe_free(pData); return LG_FALSE; } }<file_sep>/games/Legacy-Engine/Scrapped/old/lp_sys.h //Legacy Physics (unusued) #ifndef __LP_SYS_H__ #define __LP_SYS_H__ #include "lw_map.h" #include "ML_lib.h" #include "lg_types.h" typedef enum _TRACE_RESULT{ TRACE_INAIR=0, TRACE_HITGROUND, TRACE_ONGROUND, TRACE_HITCEILING, }TRACE_RESULT; class CLPhysBody { friend class CLPhysics; private: ML_AABB m_aabbBase; //Untransformed AABB ML_AABB m_aabbCurrent; //Transformed AABB ML_AABB m_aabbCat; //AABB which combines current aabb with proposed next aabb ML_AABB m_aabbNext; //The next aabb ML_VEC3 m_v3Pos; ML_VEC3 m_v3PhysVel; ML_VEC3 m_v3ScaleVel; lg_float m_fMass; lg_dword m_nRegions[8]; lg_dword m_nNumRegions; CLPhysBody* m_pNext; void CalculateAABBs(); void WorldClip(CLWorldMap* pMap, lg_bool bSlide); void RegionClip(LW_REGION_EX* pRegion, lg_bool bSlide); lg_dword BlockClip(LW_GEO_BLOCK_EX* pBlock, lg_bool bSlide); lg_dword BlockCollision( LW_GEO_BLOCK_EX* pBlock, const ML_VEC3* pVel, lg_float* pColTime, ML_PLANE* pHitPlane, lg_bool bAABBCheck=LG_FALSE); void ClipVel(ML_VEC3* pOut, ML_VEC3* pIn, ML_PLANE* pPlane, lg_float overbounce); static ML_VEC3 s_v3WishVel; static lg_dword s_nCollisionCount; static lg_bool s_bWasInBlock; public: void GetPosition(ML_VEC3* v3Pos); void SetVelocity(ML_VEC3* v3Vel); void GetVelocity(ML_VEC3* v3Vel); void GetAABB(ML_AABB* aabb); void Process(lg_float fTime, CLWorldMap* pMap); void Update(); void Collision(CLPhysBody* pBody, float fTime); //TRACE_RESULT GroundTrace(LW_REGION_EX* pRegion, ML_PLANE* pGround); }; class CLPhysics { private: CLPhysBody* m_pFirstBody; CLWorldMap* m_pMap; public: CLPhysics(); ~CLPhysics(); CLPhysBody* AddBody(ML_VEC3* v3Pos, ML_AABB* aabb, lg_float fMass); void SetWorld(CLWorldMap* pMap); void Processes(lg_dword nTimeStep); void RemoveBody(CLPhysBody* pBody); void RemoveAllBodies(); }; #endif __LP_SYS_H__<file_sep>/games/Legacy-Engine/Source/engine/lg_skin_mgr.h #ifndef __LG_SKIN_MGR_H__ #define __LG_SKIN_MGR_H__ #include "lg_types.h" #include "lg_hash_mgr.h" #include "lm_skin.h" #include "lg_list_stack.h" typedef hm_item sm_item; struct SkinItem: public CLListStack::LSItem { public: CLSkin Skin; }; LG_CACHE_ALIGN class CLSkinMgr: public CLHashMgr<SkinItem> { private: //We are using a list stack to create and destroy //materials, in the manner as for the CLMeshMgr and CLSkelMgr. SkinItem* m_pSkinMem; CLListStack m_stkSkin; SkinItem m_DefSkin; public: /* PRE: Specify the maximum number of materials in nMaxSkin POST: Ready for use. */ CLSkinMgr(lg_dword nMaxSkin); /* PRE: N/A POST: Manager is destroyed. */ ~CLSkinMgr(); private: //Internally used methods. virtual SkinItem* DoLoad(lg_path szFilename, lg_dword nFlags); virtual void DoDestroy(SkinItem* pItem); public: /* PRE: skin should be loaded. POST: Obtains the interfaces as specified. */ CLSkin* GetInterface(sm_item skin); //Static stuff: private: static CLSkinMgr* s_pSkinMgr; public: static CLSkin* SM_Load(lg_path szFilename, lg_dword nFlags); }; #endif __LG_SKIN_MGR_H__<file_sep>/games/Explor2002/Source/Game/tiles.cpp #include <ddraw.h> #include "defines.h" #include "tiles.h" extern LPDIRECTDRAW lpDirectDrawObject; extern DWORD g_dwTransparentColor; CTileObject::CTileObject(int width, int height){ m_nWidth=width; m_nHeight=height; m_lpTileImage=NULL; m_rectSource.top=m_rectSource.left=0; m_rectSource.right=m_nWidth; m_rectSource.bottom=m_nHeight; CreateSurface(); } CTileObject::~CTileObject(){ SAFE_DELETE(m_lpTileImage); /* m_lpTileImage=NULL; delete[]m_lpTileImage; */ } BOOL CTileObject::load(CBitmapReader *buffer, int x, int y, int w, int h){ return buffer->draw(m_lpTileImage, m_nWidth, m_nHeight, w, h, x, y); } void CTileObject::Release(){ SAFE_RELEASE(m_lpTileImage); /* if(m_lpTileImage!=NULL) m_lpTileImage->Release(); */ } BOOL CTileObject::Restore(){ if(m_lpTileImage) if(SUCCEEDED(m_lpTileImage->Restore()))return TRUE; return FALSE; } void CTileObject::draw(LPDIRECTDRAWSURFACE dest, int x, int y, int w, int h){ RECT rectDest; rectDest.left=x-w/2; rectDest.right=rectDest.left+w; rectDest.top=y-h/2; rectDest.bottom=rectDest.top+h; dest->Blt(&rectDest,m_lpTileImage,&m_rectSource, DDBLT_KEYSRC|DDBLT_WAIT,NULL); } void CTileObject::CreateSurface(){ DDSURFACEDESC ddsd; ddsd.dwSize=sizeof(ddsd); ddsd.dwFlags=DDSD_CAPS|DDSD_HEIGHT|DDSD_WIDTH; ddsd.ddsCaps.dwCaps=DDSCAPS_OFFSCREENPLAIN; ddsd.dwHeight=m_nHeight; ddsd.dwWidth=m_nWidth; DDCOLORKEY ddck; ddck.dwColorSpaceLowValue=ddck.dwColorSpaceHighValue=g_dwTransparentColor; if(FAILED(lpDirectDrawObject->CreateSurface(&ddsd, &m_lpTileImage, NULL))){ m_lpTileImage=NULL; } m_lpTileImage->SetColorKey(DDCKEY_SRCBLT, &ddck); } <file_sep>/games/Explor2002/Source_Old/ExplorED DOS/dosexplored/MAPBOARD.CPP #include "mapboard.h" #include <stdio.h> unsigned short ExplorMap::tbase(int tx, int ty) { return tx + fileHeader.mapWidth*(ty-1)-1; } int ExplorMap::getTileStat(int x, int y, int propnum) { return prop[propnum][TBASE]; } int ExplorMap::getTileStat(int x, int y) { return tiles[TBASE]; } int ExplorMap::boardEdit(int x, int y, unsigned int propedit, unsigned int newvalue) { if(propedit>fileHeader.mapNumProperty) return 210; prop[propedit][TBASE] = newvalue; if((prop[propedit][TBASE] < 0) || ((prop[propedit][TBASE] < 0))) prop[propedit][TBASE] = 0;//reset if value less than 0 return 0; } int ExplorMap::boardEdit(int x, int y) { char buffer[80]; switch (tiles[TBASE]){ case 0: tiles[TBASE] = 10; return 10; case 10: tiles[TBASE] = 20; return 20; case 20: tiles[TBASE] = 0; return 0; default: //In case the current tile was not valid it is reset to zero tiles[TBASE] = 0; return 201; } } int ExplorMap::resetBoard(void) { int i; int j; for(i=0; i<NUMTILES; i++){ tiles[i]=0; for(j=0;j<fileHeader.mapNumProperty; j++) prop[j][i]=0; } return 0; } int ExplorMap::openMap(char openmap[FNAMELEN]) { FILE *openfile; int i; if((openfile = fopen(openmap, "rb"))==NULL) return 101; fread(&fileHeader, sizeof(fileHeader), (size_t)1, openfile); //Check Map statistics to make sure it is valid // if not return error code. if(fileHeader.mapType != 19781){ fclose(openfile); return 110; } if(fileHeader.mapVersion != 3){ fclose(openfile); return 115; } fread(&tiles, fileHeader.mapTileDataSize, (size_t)1, openfile); for (i=0; i<fileHeader.mapNumProperty; i++){ fread(&prop[i], fileHeader.mapPropertyDataSize, (size_t)1, openfile); } fclose(openfile); } int ExplorMap::saveMap(char openmap[FNAMELEN]) { FILE *savefile; int i; if((savefile = fopen(openmap, "wb"))==NULL) return 101; fileHeader.mapPropertyDataSize = sizeof(prop[0])*fileHeader.mapNumProperty; fileHeader.mapTileDataSize = sizeof(tiles); fileHeader.mapDataSize = fileHeader.mapTileDataSize + fileHeader.mapPropertyDataSize*fileHeader.mapNumProperty; fileHeader.mapFileSize = fileHeader.mapDataSize + sizeof(fileHeader); fwrite(&fileHeader, sizeof(fileHeader), (size_t)1, savefile); fwrite(&tiles, fileHeader.mapTileDataSize, (size_t)1, savefile); for(i=0; i<fileHeader.mapNumProperty; i++) fwrite(&prop[i], fileHeader.mapTileDataSize, (size_t)1, savefile); fclose(savefile); return 0; }<file_sep>/games/Legacy-Engine/Scrapped/libs/lf_sys1/la_sys.c #include <stdio.h> #include <malloc.h> #include <memory.h> #ifdef _DEBUG #include <windows.h> #include <stdlib.h> #include <crtdbg.h> #endif /*_DEBUG*/ #include <common.h> #include "lf_sys.h" #include "zlib\zlib.h" typedef struct _ARCHIVE{ ARCHEADER m_Header; char m_szFilename[MAX_F_PATH]; ARCENTRY2* m_lpFilelist; FILE* m_fArchive; }ARCHIVE, *PARCHIVE; /************************************** The archive extraction utility. ***************************************/ HLARCHIVE Arc_Open(char* szFilename) { ARCHIVE* lpNewArchive=NULL; unsigned long i=0; lpNewArchive=malloc(sizeof(ARCHIVE)); if(!lpNewArchive) return L_null; memset(lpNewArchive, 0, sizeof(ARCHIVE)); lpNewArchive->m_fArchive=L_fopen(szFilename, LOPEN_OPEN_EXISTING, LOPEN_READ);//"rb"); if(!lpNewArchive->m_fArchive) { free(lpNewArchive); return L_null; } L_strncpy(lpNewArchive->m_szFilename, szFilename, MAX_F_PATH); /* Read the file type. */ L_fread(&lpNewArchive->m_Header.m_nType, 1, 4, lpNewArchive->m_fArchive); if(lpNewArchive->m_Header.m_nType!=LARCHIVE_TYPE) { L_fclose(lpNewArchive->m_fArchive); free(lpNewArchive); return L_null; } /* Get the version. */ L_fread(&lpNewArchive->m_Header.m_nVersion, 1, 4, lpNewArchive->m_fArchive); if(lpNewArchive->m_Header.m_nVersion!=ARC_VERSION) { L_fclose(lpNewArchive->m_fArchive); free(lpNewArchive); return L_null; } /* Read the number of files. */ L_fread(&lpNewArchive->m_Header.m_nCount, 1, 4, lpNewArchive->m_fArchive); if(lpNewArchive->m_Header.m_nCount<1) { L_fclose(lpNewArchive->m_fArchive); free(lpNewArchive); return L_null; } /* Allocate memory for the file information and read it. */ lpNewArchive->m_lpFilelist=malloc(lpNewArchive->m_Header.m_nCount*sizeof(ARCENTRY2)); if(!lpNewArchive->m_lpFilelist) { L_fclose(lpNewArchive->m_fArchive); free(lpNewArchive); return L_null; } for(i=0; i<lpNewArchive->m_Header.m_nCount; i++) { size_t nRead=0; L_bool bFailed=L_false; /* #define READ_COMPONENT(comp, size) {nRead=L_fread(&lpNewArchive->m_lpFilelist[i].comp, \ 1, size, lpNewArchive->m_fArchive);\ if(nRead<size)bFailed=L_true;} */ #define READ_COMPONENT(comp, size) if(L_fread(&lpNewArchive->m_lpFilelist[i].comp, 1, size, lpNewArchive->m_fArchive)<size)bFailed=L_true nRead=L_fread( &lpNewArchive->m_lpFilelist[i].m_szFilename, 1, MAX_F_PATH, lpNewArchive->m_fArchive); if(nRead<MAX_F_PATH) bFailed=L_true; READ_COMPONENT(m_nType, 4); READ_COMPONENT(m_nOffset, 4); READ_COMPONENT(m_nInfoOffset, 4); READ_COMPONENT(m_nCmpSize, 4); READ_COMPONENT(m_nUncmpSize, 4); L_fseek(lpNewArchive->m_fArchive, ARCHEADER_SIZE+ARCENTRY2_SIZE*(i+1), SEEK_SET); if(bFailed) { L_fclose(lpNewArchive->m_fArchive); free(lpNewArchive->m_lpFilelist); free(lpNewArchive); return L_null; } } L_fseek(lpNewArchive->m_fArchive, 0, SEEK_SET); return lpNewArchive; } int Arc_Close(HLARCHIVE hArchive) { ARCHIVE* lpArchive=hArchive; if(!lpArchive) return 0; L_fclose(lpArchive->m_fArchive); free(lpArchive->m_lpFilelist); free(lpArchive); return 1; } unsigned long Arc_GetFileSize(HLARCHIVE hArchive, char* szFile) { ARCHIVE* lpArchive=hArchive; ARCENTRY2* lpEntry=NULL; unsigned long i=0; if(!lpArchive || !szFile) return 0; for(i=0, lpEntry=NULL; i<lpArchive->m_Header.m_nCount; i++) { if(L_strnicmp(szFile, lpArchive->m_lpFilelist[i].m_szFilename, 0)) return lpArchive->m_lpFilelist[i].m_nUncmpSize; } return 0; } unsigned long Arc_ExtractZLIBC(FILE* fin, ARCENTRY2* lpEntry, void* lpBuffer) { void* lpTempBuffer=L_null; L_dword nRead=0; L_dword nUncmp=0; lpTempBuffer=malloc(lpEntry->m_nCmpSize); if(!lpTempBuffer) return 0; L_fseek(fin, lpEntry->m_nOffset, SEEK_SET); nRead=L_fread(lpTempBuffer, 1, lpEntry->m_nCmpSize, fin); nUncmp=lpEntry->m_nUncmpSize; if(uncompress(lpBuffer, &nUncmp, lpTempBuffer, nRead)!=Z_OK) { free(lpTempBuffer); return 0; } free(lpTempBuffer); return nUncmp; } unsigned long Arc_ExtractDefault(FILE* fin, ARCENTRY2* lpEntry, void* lpBuffer) { if(L_fseek(fin, lpEntry->m_nOffset, SEEK_SET)) { return 0; } return L_fread(lpBuffer, 1, lpEntry->m_nUncmpSize, fin); } unsigned long Arc_Extract(HLARCHIVE hArchive, char* szFile, void* lpBuffer) { ARCHIVE* lpArchive=hArchive; ARCENTRY2* lpEntry=NULL; unsigned long i=0; if(!lpArchive || !szFile || !lpBuffer) return 0; for(i=0, lpEntry=NULL; i<lpArchive->m_Header.m_nCount; i++) { if(L_strnicmp(szFile, lpArchive->m_lpFilelist[i].m_szFilename, 0)) { lpEntry=&lpArchive->m_lpFilelist[i]; break; } } if(!lpEntry) return 0; switch(lpEntry->m_nType) { default: case ARCHTYPE_DEFAULT: return Arc_ExtractDefault(lpArchive->m_fArchive, lpEntry, lpBuffer); case ARCHTYPE_ZLIBC: return Arc_ExtractZLIBC(lpArchive->m_fArchive, lpEntry, lpBuffer); } } unsigned long Arc_GetNumFiles(HLARCHIVE hArchive) { ARCHIVE* lpArchive=hArchive; if(!lpArchive) return 0; return lpArchive->m_Header.m_nCount; } const char* Arc_GetFilename(HLARCHIVE hArchive, unsigned long nFile) { ARCHIVE* lpArchive=hArchive; if(!lpArchive) return NULL; if(nFile<1 || nFile>lpArchive->m_Header.m_nCount) return NULL; return lpArchive->m_lpFilelist[nFile-1].m_szFilename; } #ifdef _DEBUG extern int g_nNumFilesOpen; BOOL WINAPI DllMain(HINSTANCE hInst, DWORD fdwReason, LPVOID lpReserved) { static _CrtMemState s1, s2, s3; char szTemp[1024]; _snprintf(szTemp, 1023, "There are %d files open!\n", g_nNumFilesOpen); OutputDebugStringA(szTemp); switch(fdwReason) { //case DLL_THREAD_ATTACH: case DLL_PROCESS_ATTACH: _CrtMemCheckpoint(&s1); break; //case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: OutputDebugString("MEMORY USAGE FOR \"lf_sys.dll\"\"\n"); _CrtMemCheckpoint(&s2); _CrtMemDifference(&s3, &s1, &s2); _CrtMemDumpStatistics(&s3); _CrtDumpMemoryLeaks(); break; } return TRUE; } #endif /*_DEBUG*/ <file_sep>/games/Legacy-Engine/Source/LMEdit/lv_texmgr.h #pragma once #include "common.h" #ifdef __cplusplus extern "C" #endif lg_bool Tex_Load( IDirect3DDevice9* lpDevice, lg_lpstr szFilename, D3DPOOL Pool, lg_dword dwTransparent, lg_bool bForceNoMip, IDirect3DTexture9** lppTex); #ifdef __cplusplus extern "C" #endif IDirect3DTexture9* Tex_Load2( lg_lpstr szFilename, #ifdef __cplusplus lg_bool bForceNoMip=LG_FALSE); #else lg_bool bForceNoMip); #endif #ifdef __cplusplus extern "C" #endif void Tex_SetDevice(IDirect3DDevice9* pDevice);<file_sep>/samples/D3DDemo/code/MD3Base/MD3.h /* MD3.h - Header for MD3 File Format Copyright (c) 2003 <NAME> Portions Copyright (c) 1999 ID Software */ #ifndef __MD3_H__ #define __MD3_H__ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #define MD3BASE_EXPORTS #include "md3file.h" #ifdef D3D_MD3 #include <d3d9.h> #include "md3texdb.h" #endif /* D3D_MD3 */ #if (defined(WIN32) || defined(WIN64)) #include <windows.h> #else /* (defined(WIN32) || defined(WIN64))*/ typedef float FLOAT; typedef int BOOL; typedef unsigned short WORD; typedef unsigned long DWORD; typedef signed short SHORT; typedef signed long LONG; #define FALSE 0 #define TRUE 1 #endif /* (defined(WIN32) || defined(WIN64)) */ /* Skin file structures. */ typedef struct tagMD3SKIN{ char szMeshName[MAX_QPATH]; char szSkinPath[MAX_PATH]; }MD3SKIN, *LPMD3SKIN; /* Animation definitions types and structures. */ typedef enum tagMD3SEX{ MD3SEX_MALE=0x00000000l, MD3SEX_FEMALE, MD3SEX_MACHINE, MD3SEX_OTHER, MD3SEX_DEFAULT }MD3SEX; typedef enum tagMD3FOOTSTEP{ MD3FOOTSTEP_BOOT=0x00000000l, MD3FOOTSTEP_ENERGY, MD3FOOTSTEP_OTHER, MD3FOOTSTEP_DEFAULT }MD3FOOTSTEP; typedef struct tagMD3ANIMATION{ LONG lFirstFrame; LONG lNumFrames; LONG lLoopingFrames; LONG lFramesPerSecond; }MD3ANIMATION; /* Animation definitions. */ #define BOTH_DEATH1 0 #define BOTH_DEAD1 1 #define BOTH_DEATH2 2 #define BOTH_DEAD2 3 #define BOTH_DEATH3 4 #define BOTH_DEAD3 5 #define TORSO_GESTURE 6 #define TORSO_ATTACK 7 #define TORSO_ATTACK2 8 #define TORSO_DROP 9 #define TORSO_RAISE 10 #define TORSO_STAND 11 #define TORSO_STAND2 12 #define LEGS_WALKCR 13 #define LEGS_WALK 14 #define LEGS_RUN 15 #define LEGS_BACK 16 #define LEGS_SWIM 17 #define LEGS_JUMP 18 #define LEGS_LAND 19 #define LEGS_JUMPB 20 #define LEGS_LANDB 21 #define LEGS_IDLE 22 #define LEGS_IDLECR 23 #define LEGS_TURN 24 /* The number of MD3 animations (Quake 3 Arena specific). */ #define MD3_NUM_ANIMS 25 /* The following is MD3 implimentation for Direct3D. */ #ifdef D3D_MD3 #ifdef __cplusplus class MD3BASE_EXPORTS CMD3Mesh; class MD3BASE_EXPORTS CMD3TextureDB; class MD3BASE_EXPORTS CMD3SkinFile; class MD3BASE_EXPORTS CMD3ObjectMesh; class MD3BASE_EXPORTS CMD3WeaponMesh; #endif /* __cplusplus */ /* The MD3 vertex format. */ #define D3DMD3VERTEX_TYPE (D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX1) typedef struct tagD3DMD3VERTEX{ D3DVECTOR Postion; /* Position of vertex. */ D3DVECTOR Normal; /* The normal of the vertex. */ FLOAT tu, tv; /* Texture coordinates. */ }D3DMD3VERTEX, *LPD3DMD3VERTEX; /* The Direct3DMD3 functionality. */ #ifdef __cplusplus #ifdef UNICODE #define LoadMD3 LoadMD3W #else /* UNICODE */ #define LoadMD3 LoadMD3A #endif /* UNICODE */ #define MD3TEXRENDER_NOCULL 0x00000001l class MD3BASE_EXPORTS CMD3Mesh { protected: MD3FILE m_md3File; LPDIRECT3DVERTEXBUFFER9 * m_lppVB; D3DMD3VERTEX * m_lpVertices; LPDIRECT3DINDEXBUFFER9 * m_lppIB; LPDIRECT3DDEVICE9 m_lpDevice; MD3VECTOR ** m_lppNormals; BOOL m_bMD3Loaded; /* Whether or not MD3 is loaded. */ BOOL m_bValid; /* Whether or not the MD3 is valid for D3D usage. */ DWORD m_dwNumSkins; /* Total number of skins in the mesh. */ D3DPOOL m_Pool; /* The Pool Direct3D objects should be created in. */ HRESULT CreateVB(); HRESULT DeleteVB(); HRESULT CreateIB(); HRESULT DeleteIB(); HRESULT CreateNormals(); HRESULT CreateModel(); HRESULT DeleteModel(); public: CMD3Mesh(); ~CMD3Mesh(); HRESULT LoadMD3A( char szFilename[MAX_PATH], LPDWORD lpBytesRead, LPDIRECT3DDEVICE9 lpDevice, D3DPOOL Pool); HRESULT LoadMD3W( WCHAR szFilename[MAX_PATH], LPDWORD lpBytesRead, LPDIRECT3DDEVICE9 lpDevice, D3DPOOL Pool); HRESULT ClearMD3(); HRESULT Render( CMD3SkinFile * lpSkin, FLOAT fTime, LONG lFirstFrame, LONG lNextFrame, DWORD dwFlags); HRESULT RenderWithTexture( LPDIRECT3DTEXTURE9 lpTexture, LONG lMesh, FLOAT fTime, LONG lFirstFrame, LONG lNextFrame, DWORD dwFlags); HRESULT Invalidate(); HRESULT Validate(); HRESULT SetSkinRefs( CMD3SkinFile * lpSkin); HRESULT GetTagTranslation( DWORD dwTagRef, FLOAT fTime, LONG dwFirstFrame, LONG dwSecondFrame, D3DMATRIX * Translation); HRESULT GetNumTags( LONG * lpNumTags); HRESULT GetTagName( LONG lRef, char szTagName[MAX_QPATH]); HRESULT GetShader( LONG lMesh, LONG lShader, char szShaderName[MAX_QPATH], LONG * lpShaderNum); HRESULT GetNumMeshes( LONG * lpNumMeshes); HRESULT DumpDebug(); }; #endif /* __cplusplus */ /* The texture database functionality. */ #ifdef __cplusplus /* CMD3TextureDB is not UNICODE compatible. */ class MD3BASE_EXPORTS CMD3TextureDB { protected: CMD3Texture * m_lpFirst; DWORD m_dwNumTextures; public: CMD3TextureDB(); ~CMD3TextureDB(); HRESULT GetNumTextures(DWORD * dwNumTex); HRESULT AddTexture(LPDIRECT3DDEVICE9 lpDevice, char szTexName[]); HRESULT AddTexture(LPDIRECT3DTEXTURE9 lpTexture, char szTexName[]); HRESULT GetTexture(DWORD dwRef, LPDIRECT3DTEXTURE9 * lppTexture); HRESULT GetTexture(char szTexName[], LPDIRECT3DTEXTURE9 * lppTexture); HRESULT SetRenderTexture(DWORD dwRef, DWORD dwStage, LPDIRECT3DDEVICE9 lpDevice); HRESULT SetRenderTexture(LPSTR szTexName, DWORD dwStage, LPDIRECT3DDEVICE9 lpDevice); HRESULT DeleteTexture(DWORD dwRef); HRESULT DeleteTexture(LPSTR szTexName); HRESULT ClearDB(); }; #endif /* __cplusplus */ /* The MD3 Skin file functionality. */ #ifdef __cplusplus #ifdef UNICODE #define LoadSkin LoadSkinW #else /* UNICODE */ #define LoadSkin LoadSkinA #endif /* UNICODE */ #define MD3SKINCREATE_REMOVEDIR 0x00000001l #define MD3SKINCREATE_STATICTEXDB 0x00000002l #define MD3SKINCREATE_DYNAMICTEXDB 0x00000004l #define S_SKINNULL 0x00000002l class MD3BASE_EXPORTS CMD3SkinFile { public: CMD3SkinFile(); ~CMD3SkinFile(); HRESULT LoadSkinA( LPDIRECT3DDEVICE9 lpDevice, char szFilename[MAX_PATH], DWORD dwFlags, LPVOID lpTexDB); HRESULT LoadSkinW( LPDIRECT3DDEVICE9 lpDevice, WCHAR szFilename[MAX_PATH], DWORD dwFlags, LPVOID lpTexDB); HRESULT GetTexturePointer( DWORD dwRef, LPDIRECT3DTEXTURE9 * lppTexture); HRESULT SetRenderTexture( DWORD dwRef, LPDIRECT3DDEVICE9 lpDevice); HRESULT UnloadSkin(); HRESULT SetSkin( LPDIRECT3DDEVICE9 lpDevice, DWORD dwRef); HRESULT SetSkinRef( char szName[], DWORD dwRef); static HRESULT ClearTexDB(); protected: HRESULT CreateSkinFile(DWORD dwNumSkins); HRESULT DeleteSkinFile(); HRESULT ObtainTextures(LPDIRECT3DDEVICE9 lpDevice, char szTexPath[], DWORD dwFlags, LPVOID lpTexDB); HRESULT ReadSkins(HANDLE hFile, DWORD dwNumSkinsToRead, DWORD * dwNumSkinsRead, DWORD dwFlags); BOOL ParseLine(MD3SKIN *, LPSTR); /* Member variables. */ MD3SKIN * m_lpSkins; /* The MD3 skins. */ DWORD * m_lpSkinRef; /* Which skin is which reference. */ BOOL m_bRefsSet; /* Whether or not references are set. */ DWORD m_dwNumSkins; /* Number of skins in this file. */ BOOL m_bLoaded; /* Whether or not a skin file is loaded. */ BOOL m_bUseStaticDB; /* Whether or not to use static texture DB. */ static CMD3TextureDB m_md3TexDB; /* The MD3 skin texture database. */ LPDIRECT3DTEXTURE9 * m_lppTextures; /* Pointers to the textures used by this file. */ }; #endif /* __cplusplus */ /* The animation class. Methodes for compiling and obtaining info from animation.cfg files for MD3. */ #ifdef __cplusplus #ifdef UNICODE #define LoadAnimation LoadAnimationW #else /* UNICODE */ #define LoadAnimation LoadAnimationA #endif /* UNICODE */ #define MD3ANIM_ADJUST 0x00000001l class MD3BASE_EXPORTS CMD3Animation { protected: MD3SEX m_nSex; MD3FOOTSTEP m_nFootStep; SHORT m_nHeadOffset[3]; LONG m_lLegOffset; MD3ANIMATION m_Animations[MD3_NUM_ANIMS]; HRESULT ReadAnimations(HANDLE hFile, DWORD dwNumLines); HRESULT ParseLine(LPVOID lpDataOut, LPSTR szLineIn, DWORD * lpAnimRef); public: CMD3Animation(); ~CMD3Animation(); HRESULT LoadAnimationA(char szFilename[]); HRESULT LoadAnimationW(WCHAR szFilename[]); HRESULT GetAnimation(DWORD dwRef, MD3ANIMATION * lpAnimation, DWORD dwFlags); }; #endif /* __cplusplus */ /* The player mesh functionality. */ #ifdef __cplusplus typedef enum tagMD3DETAIL{ DETAIL_HIGH=0x00000000l, DETAIL_MEDIUM, DETAIL_LOW }MD3DETAIL; #define SKIN_DEFAULT 0 class MD3BASE_EXPORTS CMD3PlayerMesh { protected: CMD3Mesh m_meshHead; CMD3SkinFile * m_skinHead; CMD3Mesh m_meshUpper; CMD3SkinFile * m_skinUpper; CMD3Mesh m_meshLower; CMD3SkinFile * m_skinLower; CMD3Animation m_Animation; CMD3TextureDB m_TexDB; WORD m_nLowerUpperTag; WORD m_nUpperHeadTag; WORD m_nUpperWeaponTag; DWORD m_dwNumSkins; DWORD m_dwDefaultSkin; char ** m_szSkinName; LPDIRECT3DDEVICE9 m_lpDevice; BOOL m_bLoaded; HRESULT GetLink(CMD3Mesh * lpFirst, char szTagName[], WORD * lpTagRef); HRESULT GetSkinsA(char szDir[]); HRESULT GetSkinsW(WCHAR szDir[]); public: CMD3PlayerMesh(); ~CMD3PlayerMesh(); HRESULT GetAnimation(DWORD dwAnimRef, MD3ANIMATION * lpAnimation); HRESULT GetSkinRef(DWORD * lpRef, char szSkinName[]); HRESULT Render( LONG lUpperFirstFrame, LONG lUpperSecondFrame, FLOAT fUpperTime, LONG lLowerFirstFrame, LONG lLowerSecondFrame, FLOAT fLowerTime, DWORD dwSkinRef, CMD3WeaponMesh * lpWeapon, const D3DMATRIX& SavedWorldMatrix); HRESULT LoadA(LPDIRECT3DDEVICE9 lpDevice, char szDir[], MD3DETAIL nDetail); HRESULT LoadW(LPDIRECT3DDEVICE9 lpDevice, WCHAR szDir[], MD3DETAIL nDetail); HRESULT Clear(); HRESULT Invalidate(); HRESULT Validate(); }; #endif /* __cplusplus */ /* The player object manages animations. */ #ifdef __cplusplus /* The flags for the SetAnimation function. */ #define MD3SETANIM_WAIT 0x00000010l /* Wait for the current animation to finish. */ #define MD3SETANIM_FRAME 0x00000020l /* Wait for the next key-frame. */ #define MD3SETANIM_FORCELOOP 0x00000040l typedef enum tagFRAMETRANSITIONTYPE{ TRANSITION_NONE=0x00000000l, TRANSITION_WAITFORANIMATION, TRANSITION_WAITFORKEYFRAME, TRANSITION_FRAMETRANSITION, }FRAMETRANSITIONTYPE; #define MD3APPLYANIM_UPPER 0x00000001l #define MD3APPLYANIM_LOWER 0x00000002l class MD3BASE_EXPORTS CMD3PlayerObject { protected: CMD3PlayerMesh * m_lpPlayerMesh; /* Pointer to the player mesh. */ DWORD m_dwLastCycleTimeLower; /* The last time the lower cycle was completed. */ DWORD m_dwLastCycleTimeUpper; /* The last time the upper cycle was completed. */ FLOAT m_fFPSUpper; /* Speed adjust for the upper animation. */ FLOAT m_fFPSLower; /* Speed adjust for the lower animation. */ DWORD m_dwSkinRef; /* The current skin reference. */ DWORD m_dwUpperAnim; /* The reference for the torso animation. */ MD3ANIMATION m_AnimationUpper; /* The data for the torso animation. */ DWORD m_dwLowerAnim; /* The reference for the legs animation. */ MD3ANIMATION m_AnimationLower; /* The data for the legs animation. */ CMD3WeaponMesh * m_lpWeapon; FRAMETRANSITIONTYPE m_LowerTransition; FRAMETRANSITIONTYPE m_UpperTransition; LONG m_lPrevFrameUpper; LONG m_lPrevFrameLower; DWORD m_dwAnimNextLower; DWORD m_dwAnimNextUpper; DWORD m_dwAnimPrevLower; DWORD m_dwAnimPrevUpper; FLOAT m_fAnimSpeedNextLower; FLOAT m_fAnimSpeedNextUpper; LONG m_lCurrentFrameLower; LONG m_lCurrentFrameUpper; LONG m_lLastSecondFrameLower; LONG m_lLastSecondFrameUpper; DWORD m_dwTransitionCycle; __inline HRESULT FrameTransitionAdjust( FRAMETRANSITIONTYPE * lpTransition, MD3ANIMATION * lpAnimation, LONG * lpFirstFrame, LONG * lpSecondFrame, FLOAT * lpTime, LONG * lpPrevFrame, DWORD * dwLastCycleTime, DWORD dwCycleTime, DWORD dwFirstAnim, DWORD dwSecondAnim, FLOAT fSpeed, BOOL bDone, DWORD dwFlags); HRESULT GetFrames( LONG * lpFirstFrame, LONG * lpSecondFrame, FLOAT * lpTime, DWORD dwTimeElapsed, DWORD dwFrameTime, const MD3ANIMATION Animation); /* Gets the correct frame and time data for animation. */ HRESULT ApplyAnimation( DWORD dwAnimRef, FLOAT fSpeed, DWORD dwFlags); public: CMD3PlayerObject(); /* Constructor. */ ~CMD3PlayerObject(); /* Destructor. */ HRESULT SetAnimation(DWORD dwAnimRef, DWORD dwFlags, FLOAT fSpeed); /* Sets the current animation. */ HRESULT GetAnimation(DWORD * lpUpper, DWORD * lpLower); /* Gets the animation. */ HRESULT SetPlayerMesh(CMD3PlayerMesh * lpPlayerMesh); /* Sets the current player mesh. */ /* Should remove weapon from render and have a setweapon option. */ HRESULT Render( const D3DMATRIX& WorldMatrix ); /* Renders the mesh with appropriate animation. */ HRESULT SetSkinByRef(DWORD dwSkinRef); /* Sets the skin. */ HRESULT SetSkinByName(char szSkinName[MAX_QPATH]); /* Sets the skin based on it's name. */ HRESULT SetWeapon(CMD3WeaponMesh * lpWeapon); }; #endif /* __cplusplus */ /* The Weapon Mesh Class. */ #ifdef __cplusplus class MD3BASE_EXPORTS CMD3WeaponMesh { protected: CMD3Mesh m_meshWeapon; CMD3Mesh m_meshBarrel; CMD3Mesh m_meshFlash; CMD3Mesh m_meshHand; CMD3TextureDB m_TexDB; LPDIRECT3DTEXTURE9 * m_lpFlashTex; LPDIRECT3DTEXTURE9 * m_lpWeaponTex; LPDIRECT3DTEXTURE9 * m_lpBarrelTex; LPDIRECT3DDEVICE9 m_lpDevice; BOOL m_bBarrel; WORD m_nTagWeapon; WORD m_nTagBarrel; WORD m_nTagFlash; BOOL m_bLoaded; HRESULT GetLink(CMD3Mesh * lpFirst, char szTagName[], WORD * lpTagRef); HRESULT TextureExtension(char szShader[MAX_PATH]); public: CMD3WeaponMesh(); ~CMD3WeaponMesh(); HRESULT Clear(); HRESULT Render(BOOL bFlash, const D3DMATRIX& WorldMatrix); HRESULT Load(LPDIRECT3DDEVICE9 lpDevice, char szDir[], MD3DETAIL nDetail); HRESULT Invalidate(); HRESULT Validate(); }; #endif /* __cplusplus */ /* The Custom Mesh class. */ #ifdef __cplusplus class MD3BASE_EXPORTS CMD3ObjectMesh { protected: CMD3Mesh m_meshObject; CMD3TextureDB m_TexDB; LPDIRECT3DTEXTURE9 * m_lppObjTex; BOOL m_bLoaded; HRESULT TextureExtension(LPDIRECT3DDEVICE9 lpDevice, char szShader[MAX_PATH]); public: CMD3ObjectMesh(); ~CMD3ObjectMesh(); HRESULT Render(LPDIRECT3DDEVICE9 lpDevice , const D3DMATRIX& WorldMatrix ); HRESULT Load(LPDIRECT3DDEVICE9 lpDevice, char szFile[], MD3DETAIL nDetail); HRESULT Clear(); HRESULT Invalidate(); HRESULT Validate(LPDIRECT3DDEVICE9 lpDevice); }; #endif /* __cplusplus */ #endif /* D3D_MD3 */ #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __MD3_H__ */ <file_sep>/Misc/GamepadToKey/GamepadToKey/GPTKXInputHandler.cpp #include "GPTKXInputHandler.h" #include <windows.h> #include <xinput.h> enum class xi_button { NONE , DUP , // D-Pad DDOWN , // D-Pad DLEFT , // D-Pad DRIGHT , // D-Pad START , BACK , L3 , // Left Thumb (Stick) R3 , // Right Thumb (Stick) L1 , // Left Bumper (LB) R1 , // Right Bumper (RB) A , // A or X B , // B or Circle X , // X or Square Y , // Y or Triangle L2 , // Left Trigger (LT) R2 , // Right Trigger (RT) LUP , // Left Stick Direction LDOWN , // Left Stick Direction LLEFT , // Left Stick Direction LRIGHT , // Left Stick Direction RUP , // Right Stick Direction RDOWN , // Right Stick Direction RLEFT , // Right Stick Direction RRIGHT , // Right Stick Direction COUNT , }; static const struct xiButtonToKey { xi_button Button; DWORD Key; } JOYSTICK_ButtonToKeyTable[] = { { xi_button::DUP , 'W' }, { xi_button::DDOWN , 'S' }, { xi_button::DLEFT , 'A' }, { xi_button::DRIGHT , 'D' }, { xi_button::START , VK_RETURN }, { xi_button::BACK , VK_ESCAPE }, { xi_button::L3 , VK_NEXT }, { xi_button::R3 , VK_PRIOR }, { xi_button::L1 , VK_OEM_4 }, { xi_button::R1 , VK_OEM_6 }, { xi_button::A , VK_CONTROL }, { xi_button::B , 'Z' }, { xi_button::X , 'X' }, { xi_button::Y , 'C' }, { xi_button::L2 , VK_OEM_COMMA }, { xi_button::R2 , VK_OEM_PERIOD }, { xi_button::LUP , 'W' }, { xi_button::LDOWN , 'S' }, { xi_button::LLEFT , 'A' }, { xi_button::LRIGHT , 'D' }, { xi_button::RUP , VK_NUMPAD8 }, { xi_button::RDOWN , VK_NUMPAD2 }, { xi_button::RLEFT , VK_NUMPAD4 }, { xi_button::RRIGHT , VK_NUMPAD6 }, }; class GPTKXInputHandler { #define countof(b) (sizeof(b)/sizeof(0[(b)])) private: DWORD m_ControllerIndex; float m_RightAxis[2]; float m_LeftAxis[2]; bool m_ButtonsDownThisFrame[static_cast<unsigned>(xi_button::COUNT)]; bool m_ButtonsDown[static_cast<unsigned>(xi_button::COUNT)]; bool m_ButtonsPressed[static_cast<unsigned>(xi_button::COUNT)]; bool m_ButtonsReleased[static_cast<unsigned>(xi_button::COUNT)]; public: GPTKXInputHandler( DWORD ControllerIndex ) : m_ControllerIndex( ControllerIndex ) { zero( &m_RightAxis ); zero( &m_LeftAxis ); zero( &m_ButtonsDownThisFrame ); zero( &m_ButtonsDown ); zero( &m_ButtonsPressed ); zero( &m_ButtonsReleased ); } template<typename T>static void zero( T* Item ){ memset( Item , 0 , sizeof(*Item) ); }; bool IsDown( xi_button Button ) { unsigned Index = static_cast<unsigned>(Button); if( 0 <= Index && Index < countof(m_ButtonsDown) ) { return m_ButtonsDown[Index]; } return false; } bool WasPressed( xi_button Button ) { unsigned Index = static_cast<unsigned>(Button); if( 0 <= Index && Index < countof(m_ButtonsPressed) ) { return m_ButtonsPressed[Index]; } return false; } bool WasReleased( xi_button Button ) { unsigned Index = static_cast<unsigned>(Button); if( 0 <= Index && Index < countof(m_ButtonsReleased) ) { return m_ButtonsReleased[Index]; } return false; } void Update() { UpdateHeldButtons(); UpdatePressesAndReleases(); } private: bool IsDownThisFrame( xi_button Button ) { unsigned Index = static_cast<unsigned>(Button); if( 0 <= Index && Index < countof(m_ButtonsDownThisFrame) ) { return m_ButtonsDownThisFrame[Index]; } return false; } void SetDownThisFrame( xi_button Button , bool bSet ) { unsigned Index = static_cast<unsigned>(Button); if( 0 <= Index && Index < countof(m_ButtonsDownThisFrame) ) { m_ButtonsDownThisFrame[Index] = bSet; } } void SetDown( xi_button Button , bool bSet ) { unsigned Index = static_cast<unsigned>(Button); if( 0 <= Index && Index < countof(m_ButtonsDown) ) { m_ButtonsDown[Index] = bSet; } } void SetPressed( xi_button Button , bool bSet ) { unsigned Index = static_cast<unsigned>(Button); if( 0 <= Index && Index < countof(m_ButtonsPressed) ) { m_ButtonsPressed[Index] = bSet; } } void SetReleased( xi_button Button , bool bSet ) { unsigned Index = static_cast<unsigned>(Button); if( 0 <= Index && Index < countof(m_ButtonsReleased) ) { m_ButtonsReleased[Index] = bSet; } } void UpdateHeldButtons() { if( !(0<= m_ControllerIndex && m_ControllerIndex < XUSER_MAX_COUNT ) ) { return; } // Helper functions. auto IsBetween = []( const auto& v1 , const auto& min , const auto& max) -> bool{ return (v1>=min) && (v1<=max); }; XINPUT_STATE State; zero( &State ); DWORD Res = XInputGetState( m_ControllerIndex , &State ); bool bConnected = ERROR_SUCCESS == Res; zero( &m_RightAxis ); zero( &m_LeftAxis ); zero( &m_ButtonsDownThisFrame ); if( bConnected ) { //Get button states: //Regular buttons: if( 0 != (State.Gamepad.wButtons&XINPUT_GAMEPAD_DPAD_UP) ){ SetDownThisFrame( xi_button::DUP , true ); } if( 0 != (State.Gamepad.wButtons&XINPUT_GAMEPAD_DPAD_DOWN) ){ SetDownThisFrame( xi_button::DDOWN , true ); } if( 0 != (State.Gamepad.wButtons&XINPUT_GAMEPAD_DPAD_LEFT) ){ SetDownThisFrame( xi_button::DLEFT , true ); } if( 0 != (State.Gamepad.wButtons&XINPUT_GAMEPAD_DPAD_RIGHT) ){ SetDownThisFrame( xi_button::DRIGHT , true ); } if( 0 != (State.Gamepad.wButtons&XINPUT_GAMEPAD_START) ){ SetDownThisFrame( xi_button::START , true ); } if( 0 != (State.Gamepad.wButtons&XINPUT_GAMEPAD_BACK) ){ SetDownThisFrame( xi_button::BACK , true ); } if( 0 != (State.Gamepad.wButtons&XINPUT_GAMEPAD_LEFT_THUMB) ){ SetDownThisFrame( xi_button::L3 , true ); } if( 0 != (State.Gamepad.wButtons&XINPUT_GAMEPAD_RIGHT_THUMB) ){ SetDownThisFrame( xi_button::R3 , true ); } if( 0 != (State.Gamepad.wButtons&XINPUT_GAMEPAD_LEFT_SHOULDER) ){ SetDownThisFrame( xi_button::L1 , true ); } if( 0 != (State.Gamepad.wButtons&XINPUT_GAMEPAD_RIGHT_SHOULDER) ){ SetDownThisFrame( xi_button::R1 , true ); } if( 0 != (State.Gamepad.wButtons&XINPUT_GAMEPAD_A) ){ SetDownThisFrame( xi_button::A , true ); } if( 0 != (State.Gamepad.wButtons&XINPUT_GAMEPAD_B) ){ SetDownThisFrame( xi_button::B , true ); } if( 0 != (State.Gamepad.wButtons&XINPUT_GAMEPAD_X) ){ SetDownThisFrame( xi_button::X , true ); } if( 0 != (State.Gamepad.wButtons&XINPUT_GAMEPAD_Y) ){ SetDownThisFrame( xi_button::Y , true ); } //Trigger buttons if( State.Gamepad.bLeftTrigger > XINPUT_GAMEPAD_TRIGGER_THRESHOLD ){ SetDownThisFrame( xi_button::L2 , true ); } if( State.Gamepad.bRightTrigger > XINPUT_GAMEPAD_TRIGGER_THRESHOLD ){ SetDownThisFrame( xi_button::R2 , true ); } //Left stick buttons: if( State.Gamepad.sThumbLX > XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE ){ SetDownThisFrame( xi_button::LRIGHT , true ); } if( State.Gamepad.sThumbLX < -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE ){ SetDownThisFrame( xi_button::LLEFT , true ); } if( State.Gamepad.sThumbLY > XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE ){ SetDownThisFrame( xi_button::LUP , true ); } if( State.Gamepad.sThumbLY < -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE ){ SetDownThisFrame( xi_button::LDOWN , true ); } //Right stick buttons: if( State.Gamepad.sThumbRX > XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE ){ SetDownThisFrame( xi_button::RRIGHT , true ); } if( State.Gamepad.sThumbRX < -XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE ){ SetDownThisFrame( xi_button::RLEFT , true ); } if( State.Gamepad.sThumbRY > XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE ){ SetDownThisFrame( xi_button::RUP , true ); } if( State.Gamepad.sThumbRY < -XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE ){ SetDownThisFrame( xi_button::RDOWN , true ); } m_RightAxis[0] = State.Gamepad.sThumbRX/32767.f; m_RightAxis[1] = State.Gamepad.sThumbRY/32767.f; m_LeftAxis[0] = State.Gamepad.sThumbLX/32767.f; m_LeftAxis[1] = State.Gamepad.sThumbLY/32767.f; if( IsBetween( State.Gamepad.sThumbRX, -XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE , XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE ) ) { m_RightAxis[0] = 0; } if( IsBetween( State.Gamepad.sThumbRY, -XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE , XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE ) ) { m_RightAxis[1] = 0; } if( IsBetween( State.Gamepad.sThumbLX, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE , XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE ) ) { m_LeftAxis[0] = 0; } if( IsBetween( State.Gamepad.sThumbLY, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE , XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE ) ) { m_LeftAxis[1] = 0; } } } void UpdatePressesAndReleases() { for( unsigned ButtonIndex = 0; ButtonIndex < static_cast<unsigned>(xi_button::COUNT); ButtonIndex++ ) { xi_button Button = static_cast<xi_button>(ButtonIndex); bool bHeld = IsDownThisFrame( Button ); if( bHeld ) { //If the button wasn't down, set as pressed. SetPressed( Button , !IsDown(Button) ); SetReleased( Button , false ); SetDown( Button , true ); } else { //If the button was already down, set the deactivated flags... SetReleased( Button , IsDown(Button) ); SetDown( Button , false ); SetPressed( Button , false ); } } } #undef countof }; static GPTKXInputHandler GPTKXInputHandler_Player1XInput( 0 ); void GPTKXInputHandler_Init() { XInputEnable( TRUE ); } void GPTKXInputHandler_Deinit() { XInputEnable( FALSE ); } void GPTKXInputHandler_Update( float DeltaTime , GPTKKeyHandler Handler , void* CbExtra ) { GPTKXInputHandler_Player1XInput.Update(); for( const xiButtonToKey& Mapping : JOYSTICK_ButtonToKeyTable ) { if( GPTKXInputHandler_Player1XInput.WasPressed(Mapping.Button) ) { Handler( Mapping.Key , WM_KEYDOWN , CbExtra ); } if( GPTKXInputHandler_Player1XInput.WasReleased(Mapping.Button) ) { Handler( Mapping.Key , WM_KEYUP , CbExtra ); } } } <file_sep>/games/Explor2002/Source/Game/gMapboard.cpp #include <stdlib.h> #include <stdio.h> #include <windows.h> #include "gmapboard.h" #include "defines.h" //About ADJUSTMENT. It was necessary to add this as when compling //under microsoft the program was reading 2 bytes more for the file //header than it should have. #define ADJUSTMENT sizeof(unsigned short) #define DEFWALL 10 //a definition of the default wall CGameMap::CGameMap() { for(int i=0;i<256;i++) m_nType[i]=WALL; mapLoaded=FALSE; tiles=new USHORT; prop=new USHORT; } CGameMap::~CGameMap() { tiles = NULL; delete []tiles; prop=NULL; delete []prop; } void CGameMap::SetTileType(int index, TileType newType){ m_nType[index]=newType; } TileType CGameMap::GetTileType(int index){ return m_nType[index]; } BOOL CGameMap::generateTFront(USHORT tfront[25], const Direction FaceDirection, const int xloc, const int yloc) { if(!mapLoaded)return FALSE; if(xloc<1||xloc>getMapWidth())return FALSE; if(yloc<1||yloc>getMapHeight())return FALSE; switch(FaceDirection){ case NORTH:{ //row behind tfront[0]=getTileStat(xloc, yloc+1); //row on tfront[1]=getTileStat(xloc-1, yloc); tfront[2]=getTileStat(xloc, yloc); tfront[3]=getTileStat(xloc+1, yloc); //row in front tfront[4]=getTileStat(xloc-2, yloc-1); tfront[5]=getTileStat(xloc-1, yloc-1); tfront[6]=getTileStat(xloc, yloc-1); tfront[7]=getTileStat(xloc+1, yloc-1); tfront[8]=getTileStat(xloc+2, yloc-1); //2 rows in front tfront[9]=getTileStat(xloc-3, yloc-2); tfront[10]=getTileStat(xloc-2, yloc-2); tfront[11]=getTileStat(xloc-1, yloc-2); tfront[12]=getTileStat(xloc, yloc-2); tfront[13]=getTileStat(xloc+1, yloc-2); tfront[14]=getTileStat(xloc+2, yloc-2); tfront[15]=getTileStat(xloc+3, yloc-2); //3 rows in front tfront[16]=getTileStat(xloc-4, yloc-3); tfront[17]=getTileStat(xloc-3, yloc-3); tfront[18]=getTileStat(xloc-2, yloc-3); tfront[19]=getTileStat(xloc-1, yloc-3); tfront[20]=getTileStat(xloc, yloc-3); tfront[21]=getTileStat(xloc+1, yloc-3); tfront[22]=getTileStat(xloc+2, yloc-3); tfront[23]=getTileStat(xloc+3, yloc-3); tfront[24]=getTileStat(xloc+4, yloc-3); break;} case EAST:{ //row behind tfront[0]=getTileStat(xloc-1, yloc); //row on tfront[1]=getTileStat(xloc, yloc-1); tfront[2]=getTileStat(xloc, yloc); tfront[3]=getTileStat(xloc, yloc+1); //row in front tfront[4]=getTileStat(xloc+1, yloc-2); tfront[5]=getTileStat(xloc+1, yloc-1); tfront[6]=getTileStat(xloc+1, yloc); tfront[7]=getTileStat(xloc+1, yloc+1); tfront[8]=getTileStat(xloc+1, yloc+2); //2 rows in front tfront[9]=getTileStat(xloc+2, yloc-3); tfront[10]=getTileStat(xloc+2, yloc-2); tfront[11]=getTileStat(xloc+2, yloc-1); tfront[12]=getTileStat(xloc+2, yloc); tfront[13]=getTileStat(xloc+2, yloc+1); tfront[14]=getTileStat(xloc+2, yloc+2); tfront[15]=getTileStat(xloc+2, yloc+3); //3 rows in front tfront[16]=getTileStat(xloc+3, yloc-4); tfront[17]=getTileStat(xloc+3, yloc-3); tfront[18]=getTileStat(xloc+3, yloc-2); tfront[19]=getTileStat(xloc+3, yloc-1); tfront[20]=getTileStat(xloc+3, yloc); tfront[21]=getTileStat(xloc+3, yloc+1); tfront[22]=getTileStat(xloc+3, yloc+2); tfront[23]=getTileStat(xloc+3, yloc+3); tfront[24]=getTileStat(xloc+3, yloc+4); break;} case SOUTH:{ //row behind tfront[0]=getTileStat(xloc, yloc-1); //row on tfront[1]=getTileStat(xloc+1, yloc); tfront[2]=getTileStat(xloc, yloc); tfront[3]=getTileStat(xloc-1, yloc); //row in front tfront[4]=getTileStat(xloc+2, yloc+1); tfront[5]=getTileStat(xloc+1, yloc+1); tfront[6]=getTileStat(xloc, yloc+1); tfront[7]=getTileStat(xloc-1, yloc+1); tfront[8]=getTileStat(xloc-2, yloc+1); //2 rows in front tfront[9]=getTileStat(xloc+3, yloc+2); tfront[10]=getTileStat(xloc+2, yloc+2); tfront[11]=getTileStat(xloc+1, yloc+2); tfront[12]=getTileStat(xloc, yloc+2); tfront[13]=getTileStat(xloc-1, yloc+2); tfront[14]=getTileStat(xloc-2, yloc+2); tfront[15]=getTileStat(xloc-3, yloc+2); //3 rows in front tfront[16]=getTileStat(xloc+4, yloc+3); tfront[17]=getTileStat(xloc+3, yloc+3); tfront[18]=getTileStat(xloc+2, yloc+3); tfront[19]=getTileStat(xloc+1, yloc+3); tfront[20]=getTileStat(xloc, yloc+3); tfront[21]=getTileStat(xloc-1, yloc+3); tfront[22]=getTileStat(xloc-2, yloc+3); tfront[23]=getTileStat(xloc-3, yloc+3); tfront[24]=getTileStat(xloc-4, yloc+3); break;} case WEST:{ //row behind tfront[0]=getTileStat(xloc+1, yloc); //row on tfront[1]=getTileStat(xloc, yloc+1); tfront[2]=getTileStat(xloc, yloc); tfront[3]=getTileStat(xloc, yloc-1); //row in front tfront[4]=getTileStat(xloc-1, yloc+2); tfront[5]=getTileStat(xloc-1, yloc+1); tfront[6]=getTileStat(xloc-1, yloc); tfront[7]=getTileStat(xloc-1, yloc-1); tfront[8]=getTileStat(xloc-1, yloc-2); //2 rows in front tfront[9]=getTileStat(xloc-2, yloc+3); tfront[10]=getTileStat(xloc-2, yloc+2); tfront[11]=getTileStat(xloc-2, yloc+1); tfront[12]=getTileStat(xloc-2, yloc); tfront[13]=getTileStat(xloc-2, yloc-1); tfront[14]=getTileStat(xloc-2, yloc-2); tfront[15]=getTileStat(xloc-2, yloc-3); //3 rows in front tfront[16]=getTileStat(xloc-3, yloc+4); tfront[17]=getTileStat(xloc-3, yloc+3); tfront[18]=getTileStat(xloc-3, yloc+2); tfront[19]=getTileStat(xloc-3, yloc+1); tfront[20]=getTileStat(xloc-3, yloc); tfront[21]=getTileStat(xloc-3, yloc-1); tfront[22]=getTileStat(xloc-3, yloc-2); tfront[23]=getTileStat(xloc-3, yloc-3); tfront[24]=getTileStat(xloc-3, yloc-4); break;} } return TRUE; } USHORT CGameMap::getNumProperty(void)const{ if(!mapLoaded)return 0; return fileHeader.mapNumProperty; } USHORT CGameMap::getMapWidth(void)const{ if(!mapLoaded)return 0; return fileHeader.mapWidth; } USHORT CGameMap::getMapHeight(void)const{ if(!mapLoaded)return 0; return fileHeader.mapHeight; } USHORT CGameMap::tbase(int tx, int ty)const{ if(!mapLoaded)return 0; return tx + fileHeader.mapWidth*(ty-1)-1; } USHORT CGameMap::getTileStat(int x, int y, int propnum)const{ if(!mapLoaded)return 0; if(x<1||x>fileHeader.mapWidth)return 0; if(y<1||y>fileHeader.mapHeight)return 0; if(propnum<1||propnum>fileHeader.mapNumProperty)return 0; return prop[fileHeader.mapWidth*fileHeader.mapHeight*(propnum-1)+tbase(x, y)]; } USHORT CGameMap::getTileStat(int x, int y)const{ if(!mapLoaded)return 0; if(x<1||x>getMapWidth())return DEFWALL; if(y<1||y>getMapWidth())return DEFWALL; return tiles[tbase(x, y)]; } /* int CGameMap::boardEdit(int x, int y, unsigned int propnum, unsigned int newvalue) { if(propnum>fileHeader.mapNumProperty) return 210; prop[fileHeader.mapWidth*fileHeader.mapHeight*(propnum-1)+tbase(x, y)]=newvalue; if((prop[fileHeader.mapWidth*fileHeader.mapHeight*(propnum-1)+tbase(x, y)]<0)) prop[fileHeader.mapWidth*fileHeader.mapHeight*(propnum-1)+tbase(x, y)]=0; //reset if value is less than zero return 0; } */ /* int CGameMap::boardEdit(int x, int y) { switch (tiles[tbase(x, y)]){ case 0: tiles[tbase(x, y)] = 10; return 10; case 10: tiles[tbase(x, y)] = 20; return 20; case 20: tiles[tbase(x, y)] = 0; return 0; default: tiles[tbase(x, y)] = 0; return 201; } } */ /* int CGameMap::resetBoard(void) { ZeroMemory(tiles, fileHeader.mapTileDataSize); ZeroMemory(prop, fileHeader.mapTileDataSize*fileHeader.mapNumProperty); return 0; } */ int CGameMap::openMap(char openmap[_MAX_PATH]) { //Use createfile to open the map data from file HANDLE openfile; DWORD bytesread; if((openfile=CreateFile(openmap, GENERIC_READ, FILE_SHARE_READ, (LPSECURITY_ATTRIBUTES)NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, (HANDLE)NULL))==INVALID_HANDLE_VALUE)return 101; ReadFile(openfile, &fileHeader, sizeof(fileHeader)-ADJUSTMENT, &bytesread, NULL); //Check Map statistics to make sure it is valid // if not return error code. if(!strcmp("EM", fileHeader.mapType)){ CloseHandle(openfile); return 110; } if(fileHeader.mapVersion != 3){ CloseHandle(openfile); return 115; } { tiles = NULL; delete [] tiles; tiles = new USHORT[fileHeader.mapHeight*fileHeader.mapWidth]; } ReadFile(openfile, tiles, fileHeader.mapTileDataSize, &bytesread, NULL); { prop = NULL; delete [] prop; prop = new USHORT[fileHeader.mapHeight*fileHeader.mapWidth*fileHeader.mapNumProperty]; } ReadFile(openfile, prop, fileHeader.mapPropertyDataSize, &bytesread, NULL); CloseHandle(openfile); mapLoaded=TRUE; return 0; } /* int CGameMap::saveMap(char openmap[_MAX_PATH]) { FILE *savefile; if((savefile = fopen(openmap, "wb"))==NULL) return 101; fileHeader.mapTileDataSize = fileHeader.mapWidth*fileHeader.mapHeight*sizeof(USHORT); fileHeader.mapPropertyDataSize=fileHeader.mapTileDataSize*fileHeader.mapNumProperty; fileHeader.mapDataSize = fileHeader.mapTileDataSize + fileHeader.mapPropertyDataSize; fileHeader.mapFileSize = fileHeader.mapDataSize + sizeof(fileHeader); fwrite(&fileHeader, sizeof(fileHeader)-ADJUSTMENT, (size_t)1, savefile); fwrite(tiles, fileHeader.mapTileDataSize, (size_t)1, savefile); fwrite(prop, fileHeader.mapPropertyDataSize, (size_t)1, savefile); fclose(savefile); return 0; } */<file_sep>/games/Explor2002/Source/ExplorED/Wxplored.h /* wxplored.h - Header for WinExplorED */ #ifndef __WXPLORED_H__ #define __WXPLORED_H__ enum LASTMOVETYPE{SAVE, EDIT, OPEN}; void EditWindowPaint(HWND hWnd, int minX, int minY); BOOL RegisterEditWindowClass(void); BOOL RegisterWindowClass(void); //BOOL RegisterStatusWindowClass(void); LRESULT MainWindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); LRESULT EditWindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); BOOL MainCommandProc(HWND hMainWnd, WORD wCommand, WORD wNotify, HWND hControl); int GetOpenFileName(HWND hWnd, char *filename); int GetSaveFileName(HWND hWnd, char *filename); BOOL HorzScrollManager(HWND hWnd, WORD nScrollCode); BOOL TranslatePoints(HWND hWnd, POINTS &points); BOOL VertScrollManager(HWND hWnd, WORD nScrollCode); BOOL UpdateScrollBar(HWND hWnd); #endif<file_sep>/games/Legacy-Engine/Source/engine/lg_skin_mgr.cpp #include "lg_skin_mgr.h" CLSkinMgr* CLSkinMgr::s_pSkinMgr=LG_NULL; CLSkinMgr::CLSkinMgr(lg_dword nMaxSkin) : CLHashMgr(nMaxSkin, "SkinMgr") , m_pSkinMem(LG_NULL) { s_pSkinMgr=this; //Prepare the list stack. m_pSkinMem=new SkinItem[m_nMaxItems]; if(!m_pSkinMem) throw LG_ERROR(LG_ERR_OUTOFMEMORY, LG_NULL); m_stkSkin.Init(m_pSkinMem, m_nMaxItems, sizeof(SkinItem)); //Setup the default skin m_pItemList[0].pItem=&m_DefSkin; } CLSkinMgr::~CLSkinMgr() { CLHashMgr::UnloadItems(); m_stkSkin.Clear(); LG_SafeDeleteArray(m_pSkinMem); } SkinItem* CLSkinMgr::DoLoad(lg_path szFilename, lg_dword nFlags) { SkinItem* pOut = (SkinItem*)m_stkSkin.Pop(); if(!pOut) return LG_NULL; if(!pOut->Skin.Load(szFilename)) { m_stkSkin.Push(pOut); pOut=LG_NULL; } return pOut; } void CLSkinMgr::DoDestroy(SkinItem* pItem) { if(!pItem) return; //All we have to do is push the item back on the stack //no unloading is necessary since the material is a //fixed size. m_stkSkin.Push(pItem); } CLSkin* CLSkinMgr::GetInterface(sm_item skin) { return skin?&m_pItemList[skin-1].pItem->Skin:LG_NULL; } CLSkin* CLSkinMgr::SM_Load(lg_path szFilename, lg_dword nFlags) { sm_item skin=s_pSkinMgr->Load(szFilename, nFlags); return s_pSkinMgr->GetInterface(skin); } <file_sep>/games/Legacy-Engine/Source/lf_sys2/lf_win.c #if 0 #ifdef _DEBUG #include <windows.h> #include <crtdbg.h> #define L_BEGIN_D_DUMP {_CrtMemState s1, s2, s3;_CrtMemCheckpoint(&s1); #define L_END_D_DUMP(txt) _CrtMemCheckpoint(&s2);\ _CrtMemDifference(&s3, &s1, &s2);\ OutputDebugString("MEMORY USAGE FOR: \""txt"\":\n");\ _CrtMemDumpStatistics(&s3);} BOOL WINAPI DllMain(HINSTANCE hInst, DWORD fdwReason, LPVOID lpvReserved) { static _CrtMemState s1, s2, s3; static BOOL bFirst=TRUE; switch(fdwReason) { case DLL_PROCESS_ATTACH: //case DLL_THREAD_ATTACH: if(bFirst) { OutputDebugString("Starting lf_sys2.dll\n"); _CrtMemCheckpoint(&s1); bFirst=FALSE; } break; case DLL_PROCESS_DETACH: //case DLL_THREAD_DETACH: OutputDebugString("Stopping lf_sys2.dll\n"); _CrtMemCheckpoint(&s2); _CrtMemDifference(&s3, &s1, &s2); OutputDebugString("MEMORY USAGE FOR: \"lf_sy2.dll\":\n"); _CrtMemDumpStatistics(&s3); { //char szTemp[10]; //sprintf(szTemp, "%u ", g_nBlocks); //OutputDebugString(szTemp); //OutputDebugString("allocations left.\n"); } break; } return TRUE; } #endif #endif<file_sep>/Misc/DBXExporter/DBXExporter/oedbx/library/dbxCommon.cpp //*************************************************************************************** #define AS_OE_IMPLEMENTATION #include <oedbx/dbxCommon.h> #include <windows.h> #include <strstream> //*************************************************************************************** std::string FileTime2String(int1 * str) { FILETIME * filetimeSrc = (FILETIME *)str, filetimeLocal; SYSTEMTIME systime; if(!FileTimeToLocalFileTime( filetimeSrc, &filetimeLocal)) { return "Error converting to local time !"; } else { if(!FileTimeToSystemTime(&filetimeLocal, &systime)) return "Error converting to system time !"; } std::ostrstream ostr; ostr << std::setw(4) << std::setfill('0') << systime.wYear << "/" << std::setw(2) << std::setfill('0') << systime.wMonth << "/" << std::setw(2) << std::setfill('0') << systime.wDay << " " << std::setw(2) << std::setfill('0') << systime.wHour << ":" << std::setw(2) << std::setfill('0') << systime.wMinute << ":" << std::setw(2) << std::setfill('0') << systime.wSecond << std::ends; return ostr.str(); } OutStream rows2File(OutStream outs,int4 address, int1 * values, int4 length) { for(int4 i=0;i<length;i+=16) { std::ostrstream strStr; std::string str; bool isUsed = false, isLong = false; for(int4 j=0;(i+j<length) && (j<0x10);++j) { if((j&0x3) == 0) { strStr << " "; if(*((int4 *)(values+i+j))!=0) { isLong = true; isUsed = true; } else { isLong = false; strStr << " "; str += " "; } } if(isLong) { int1 value = values[i+j]; strStr << std::setw(2) << std::hex << std::setfill('0') << ((int)value); if((value<0x20)||(value>0x7f)) str += '.'; else str += value; } } strStr << std::ends; if(isUsed) outs << std::right << std::setw(8) << std::hex << (address+i) << " :" << std::left << std::setw(38) << (strStr.str()) << str << std::endl; } return outs; } <file_sep>/tools/QInstall/README.md QInstall ======== Quick and Dirty Application Installer. Quick and Dirty Application Installer Copyright (c) 2002, 2003 <NAME> ------ Usage: ------ Basically this program just copies files from one location to another future version may allow uninstall, and browse ability. Ender User: Just active QInstall from the installation directory, everything should take itself from there. Developer: In order the create an installation process there must be a file called QInstall.ini in the same directory as QInstall. QInstall.ini must contain four statements (each statement ends with a semicolin ';'. Return carriages will be ingnored so you can put statements in separate lines. All statments look like this: statmentidentifier="statementstring"; Four statmentidentifiers must be defined: name /* The name of the app */ installto /* Directory to install to*/ installfrom /* directory to install from better not have trailing slash*/ runonexit /* the app to run when the installation completes */ installto and installfrom can have parse strings. A parse strings will be replace by the operating system. The following parse strings are available: %defaultdrive% /* Is replace with the same drive as windows is installed to */ %currentdir% /* The currently active directory */ Remeber all lines must end with a semicolin ';'. This readme file should not be included with distributed programs. Example of usage: name = "QInstall Demo Application"; installto = "%defaultdrive%\DemoApp\"; installfrom = "%currentdir%\DemoInstall\"; runonexit = "QTestApp.exe"; Notice: Browse button does not do anything in this version. ------ About: ------ This is basically a bang up job I made so I could have an installer for old floppy-disk programs that I copied onto CD-ROM. In the future I plan on developing a more functional installer, which will be easier to use and have more features. ---------------- Version History: ---------------- 0.50 (March 06, 2003) Directory and sub directories copied. Program is laid out better. 0.01 (December 31 2002) A banged up job, browse button doesn't do anything<file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/lv_init.c /* lv_init.c - Video initialization functions for Legacy 3D Copyright (c) 2006, <NAME> */ #include "common.h" #include <windowsx.h> #include "lg_sys.h" #include "lv_init.h" L_dword LV_StringToD3DFMT(char* szfmt); L_dword LV_D3DFMTToBitDepth(D3DFORMAT fmt); char* LV_D3DFMTToString(D3DFORMAT fmt); /*************************************************************** LV_Init() This initializes all of the basic Direct3D stuff used in the game. It doens't load 3D models, or textures, but it sets the render mode, and it does call the function to set all of the requested render and sampler stetes. It doesn't create any Direct3D objects except for the IDirect3D9 interface, and the IDirect3DDevice9 interface (except for the graphical console, and the reason this is initialized here is because it always exists for the duration of the game, and it is destroyed in LV_Shutdown. LV_Init uses the cvars to initialize the game, so the cvars must be register and set to the desired values before calling this function. ****************************************************************/ L_result LV_Init(L3DGame* lpGame) { D3DPRESENT_PARAMETERS pp; CVar* cvar=NULL; L_dword dwBehaviorFlags=0; L_dword dwVertexProcFlag=0; L_result nResult=0x00000000l; /* To initialize the video we need to create an IDirect3D interface, set the present parameters, then create the device. */ if(!lpGame) return -1; if(!lpGame->m_Console || !lpGame->m_cvars) return -1; /* First create the IDirect3D interface. */ Err_Printf("Creating IDirect3D9 interface..."); lpGame->v.m_lpD3D=Direct3DCreate9(D3D_SDK_VERSION); if(lpGame->v.m_lpD3D) Err_Printf("IDirect3D9 interface created at 0x%08X.", lpGame->v.m_lpD3D); else { Err_Printf("Failed to create IDirect3D9 interface."); MessageBox( lpGame->m_hwnd, "This application requires ""DirectX 9.0c", "Legacy3D", MB_OK|MB_ICONINFORMATION); return -1; } /* Get the Direct3D setup parameters from teh cvarlist. */ cvar=CVar_GetCVar(lpGame->m_cvars, "v_AdapterID"); lpGame->v.m_nAdapterID=cvar?(int)cvar->value:D3DADAPTER_DEFAULT; cvar=CVar_GetCVar(lpGame->m_cvars, "v_DeviceType"); lpGame->v.m_nDeviceType=cvar?(int)cvar->value:D3DDEVTYPE_HAL; cvar=CVar_GetCVar(lpGame->m_cvars, "v_VertexProc"); dwVertexProcFlag=cvar?(int)cvar->value:D3DCREATE_SOFTWARE_VERTEXPROCESSING; if(CVar_GetValue(lpGame->m_cvars, "v_FPU_Preserve", NULL)) dwBehaviorFlags|=D3DCREATE_FPU_PRESERVE; if(CVar_GetValue(lpGame->m_cvars, "v_MultiThread", NULL)) dwBehaviorFlags|=D3DCREATE_MULTITHREADED; if(CVar_GetValue(lpGame->m_cvars, "v_PureDevice", NULL)) dwBehaviorFlags|=D3DCREATE_PUREDEVICE; if(CVar_GetValue(lpGame->m_cvars, "v_DisableDriverManagement", NULL)) dwBehaviorFlags|=D3DCREATE_DISABLE_DRIVER_MANAGEMENT; if(CVar_GetValue(lpGame->m_cvars, "v_AdapterGroupDevice", NULL)) dwBehaviorFlags|=D3DCREATE_ADAPTERGROUP_DEVICE; /* Make sure the adapter is valid. */ if(lpGame->v.m_nAdapterID >= lpGame->v.m_lpD3D->lpVtbl->GetAdapterCount(lpGame->v.m_lpD3D)) { Err_Printf( "Adapter %i not available, using default adapter.", lpGame->v.m_nAdapterID); CVar_Set(lpGame->m_cvars, "v_AdatperID", "ADAPTER_DEFAULT"); lpGame->v.m_nAdapterID=0; } /* Show the adapter identifier information. */ { D3DADAPTER_IDENTIFIER9 adi; memset(&adi, 0, sizeof(adi)); lpGame->v.m_lpD3D->lpVtbl->GetAdapterIdentifier( lpGame->v.m_lpD3D, lpGame->v.m_nAdapterID, 0, &adi); Err_Printf("Using \"%s\".", adi.Description); } /* We set the present parameters using the cvars. */ memset(&pp, 0, sizeof(pp)); Err_Printf("Initialzing present parameters from cvarlist..."); if(!LV_SetPPFromCVars(lpGame, &pp)) { Err_Printf("Could not initialize present parameters."); L_safe_release(lpGame->v.m_lpD3D); return -1; } Err_Printf("Present parameters initialization complete."); /* Check to see that the adapter type is available. */ if(L_failed(nResult= lpGame->v.m_lpD3D->lpVtbl->CheckDeviceType( lpGame->v.m_lpD3D, lpGame->v.m_nAdapterID, lpGame->v.m_nDeviceType, pp.BackBufferFormat, pp.BackBufferFormat, pp.Windowed))) { Err_PrintDX("CheckDeviceType", nResult); Err_Printf("Cannot use selected device type, defaulting."); /* If the HAL device can't be used then CreateDevice will fail. */ lpGame->v.m_nDeviceType=D3DDEVTYPE_HAL; } Err_Printf("Creating IDirect3DDevice9 interface..."); nResult=lpGame->v.m_lpD3D->lpVtbl->CreateDevice( lpGame->v.m_lpD3D, lpGame->v.m_nAdapterID, lpGame->v.m_nDeviceType, lpGame->m_hwnd, dwBehaviorFlags|dwVertexProcFlag, &pp, &lpGame->v.m_lpDevice); Err_PrintDX("IDirect3D9::CreateDevice", nResult); /* If we failed to create the device, we can try a some different vertex processing modes, if it still fails we exit. */ while(L_failed(nResult)) { if(dwVertexProcFlag==D3DCREATE_SOFTWARE_VERTEXPROCESSING) break; else if(dwVertexProcFlag==D3DCREATE_HARDWARE_VERTEXPROCESSING) { dwVertexProcFlag=D3DCREATE_MIXED_VERTEXPROCESSING; CVar_Set(lpGame->m_cvars, "v_VertexProc", "VERT_MIXED"); } else { dwVertexProcFlag=D3DCREATE_SOFTWARE_VERTEXPROCESSING; CVar_Set(lpGame->m_cvars, "v_VertexProc", "VERT_SOFTWARE"); } nResult=lpGame->v.m_lpD3D->lpVtbl->CreateDevice( lpGame->v.m_lpD3D, lpGame->v.m_nAdapterID, lpGame->v.m_nDeviceType, lpGame->m_hwnd, dwBehaviorFlags|dwVertexProcFlag, &pp, &lpGame->v.m_lpDevice); Err_PrintDX("IDirect3D9::CreateDevice", nResult); } if(L_succeeded(nResult)) { Err_Printf( "IDirect3DDevice9 interface created at 0x%08X", lpGame->v.m_lpDevice); Err_Printf("Using the following Present Parameters:"); LV_PrintPP(&pp); } else { Err_Printf( "Failed to create IDirect3DDevice9 interface.", nResult); Err_Printf( "Try software vertex processing."); L_safe_release(lpGame->v.m_lpD3D); return -1; } /* Display allowed formats, and also set a few cvars that control them. The allowed formats function only deals with the basic formats, not any advanced or compressed texture formats.*/ LV_SupportedTexFormats( lpGame->m_cvars, lpGame->v.m_lpD3D, lpGame->v.m_nAdapterID, lpGame->v.m_nDeviceType, pp.BackBufferFormat); /* Set the default viewport, we don't actually need to do this because d3d will set the default viewport for us. */ /* { D3DVIEWPORT9 ViewPort; ViewPort.X=0; ViewPort.Y=0; ViewPort.Width=(L_dword)CVar_GetValue(lpGame->m_cvars, "v_Width", L_null); ViewPort.Height=(L_dword)CVar_GetValue(lpGame->m_cvars, "v_Height", L_null); ViewPort.MinZ=0.0f; ViewPort.MaxZ=1.0f; lpGame->v.m_lpDevice->lpVtbl->SetViewport(lpGame->v.m_lpDevice, &ViewPort); } */ /* With everything initialized we can set the sampler and render states. */ Err_Printf("Calling LV_SetStates..."); if(!LV_SetStates(lpGame)) Err_Printf("An error occured while setting the sampler and render states."); /* Once the video is initialized, we can initalize the graphical console. */ Err_Printf("Initializing console graphical interface..."); lpGame->v.m_lpVCon=VCon_Create( lpGame->m_Console, lpGame->m_cvars, lpGame->v.m_lpDevice); /* If the creation of the graphical console fails, the game can still run, but any calls to VCon_ functions will fail because the lpVCon data item is null.*/ if(!lpGame->v.m_lpVCon) Err_Printf("Graphical console creation failed, feature not available."); /* some test stuff. */ lpGame->v.m_lpTestObj=LVT_CreateTest(lpGame->v.m_lpDevice); return 0x00000000l; } L_bool LV_SupportedTexFormats(HCVARLIST cvars, IDirect3D9* lpD3D, UINT nAdapterID, UINT nDeviceType, D3DFORMAT dfmt) { L_result nResult=0; Err_Printf("Supported Texture Formats:"); /* We check to see which texture formats are supported, we are only checking the ones that we plan on using in this application. We set appropriate cvars for the texture formats, so that when we call the texture loading funcitons, they can check the cvars to determine what format to generate the textrues. This code is not bug proof as it doesn't set an cvars that note that D3DFMT_R5G6B5 textures are supported, it just assumes they are supported (pretty much all video cards I've encountered support this format that is why I assume it will work.*/ #define TEX_CHECK(fmt) IDirect3D9_CheckDeviceFormat(lpD3D,nAdapterID,nDeviceType,dfmt,0,D3DRTYPE_TEXTURE, fmt); nResult=TEX_CHECK(D3DFMT_A8R8G8B8); if(L_failed(nResult))CVar_Set(cvars, "v_32BitTextureAlpha", "FALSE"); else Err_Printf(" %s", LV_D3DFMTToString(D3DFMT_A8R8G8B8)); nResult=TEX_CHECK(D3DFMT_X8R8G8B8) if(L_failed(nResult))CVar_Set(cvars, "v_Force16BitTextures", "TRUE"); else Err_Printf(" %s", LV_D3DFMTToString(D3DFMT_X8R8G8B8)); nResult=TEX_CHECK(D3DFMT_A1R5G5B5) if(L_failed(nResult))CVar_Set(cvars, "v_16BitTextureAlpha", "FALSE"); else Err_Printf(" %s", LV_D3DFMTToString(D3DFMT_A1R5G5B5)); nResult=TEX_CHECK(D3DFMT_X1R5G5B5) if(L_succeeded(nResult))Err_Printf(" %s", LV_D3DFMTToString(D3DFMT_X1R5G5B5)); nResult=TEX_CHECK(D3DFMT_R5G6B5) if(L_succeeded(nResult))Err_Printf(" %s", LV_D3DFMTToString(D3DFMT_R5G6B5)); return L_true; } /********************************************************* LV_Shutdown() This uninitialized everything that was initialized in LV_Init(), it doesn't necessarly shut down other items that were initialized by Direct3D such as textures and vertex buffers used by in the game. This function should only be called after all Direct3D pool objects have been released. ***********************************************************/ L_result LV_Shutdown(L3DGame* lpGame) { L_ulong nNumLeft=0; if(!lpGame) return -1; if(!(lpGame->v.m_lpDevice)) { Err_Printf("Device not available for game shutdown."); return L_false; } /* Some test stuff. */ LVT_Delete(lpGame->v.m_lpTestObj); /* Destroy the graphical console, then shutdown the video. */ Err_Printf("Destroying gconsole graphical interface."); VCon_Delete(lpGame->v.m_lpVCon); lpGame->v.m_lpVCon=L_null; Err_Printf("Releasing IDirect3DDevice9 interface..."); nNumLeft=lpGame->v.m_lpDevice->lpVtbl->Release(lpGame->v.m_lpDevice); Err_Printf( "Released IDirect3DDevice9 interface at 0x%08X with %i references left.", lpGame->v.m_lpDevice, nNumLeft); lpGame->v.m_lpDevice=NULL; Err_Printf("Releasing IDirect3D9 interface..."); if(lpGame->v.m_lpD3D) { nNumLeft=lpGame->v.m_lpD3D->lpVtbl->Release(lpGame->v.m_lpD3D); Err_Printf( "Released IDirect3D9 interface at 0x%08X with %i references left.", lpGame->v.m_lpD3D, nNumLeft); } return 0x00000000l; } /*********************************************** LV_CorrectWindowSize() Adjusts the window size so that the client area is the specified width and height. Called from LV_SetPPFromCVars. ************************************************/ L_bool LV_CorrectWindowSize( HWND hWnd, DWORD nWidth, DWORD nHeight) { RECT rc; SetRect(&rc, 0, 0, nWidth, nHeight); AdjustWindowRectEx( &rc, GetWindowStyle(hWnd), GetMenu(hWnd)!=NULL, GetWindowExStyle(hWnd)); SetWindowPos( hWnd, NULL, 0, 0, rc.right-rc.left, rc.bottom-rc.top, SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE); return L_true; } L_bool LV_PrintPP(D3DPRESENT_PARAMETERS* pp) { Err_Printf(" Resolution: %iX%iX%i(%s) at %iHz, %s", pp->BackBufferWidth, pp->BackBufferHeight, LV_D3DFMTToBitDepth(pp->BackBufferFormat), LV_D3DFMTToString(pp->BackBufferFormat), pp->FullScreen_RefreshRateInHz, pp->Windowed?"WINDOWED":"FULL SCREEN"); Err_Printf(" FSAA %s (%i)", pp->MultiSampleType==D3DMULTISAMPLE_NONE?"Disabled":"Enabled", pp->MultiSampleQuality); Err_Printf(" Back Buffers: %i, Swap Effect: %s", pp->BackBufferCount, pp->SwapEffect==D3DSWAPEFFECT_DISCARD?"DISCARD":pp->SwapEffect==D3DSWAPEFFECT_FLIP?"FLIP":"COPY"); Err_Printf(" Flags: %s%s%s%s", L_CHECK_FLAG(pp->Flags, D3DPRESENTFLAG_DEVICECLIP)?"DEVICECLIP ":"", L_CHECK_FLAG(pp->Flags, D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL)?"DISCARD_DEPTHSTRENCIL ":"", L_CHECK_FLAG(pp->Flags, D3DPRESENTFLAG_LOCKABLE_BACKBUFFER)?"LOCKABLE_BACKBUFFER ":"", L_CHECK_FLAG(pp->Flags, D3DPRESENTFLAG_VIDEO)?"VIDEO ":""); Err_Printf(" Device Window At 0x%08X", pp->hDeviceWindow); Err_Printf(" Auto Depth Stencil %s (%s)", pp->EnableAutoDepthStencil?"Enabled":"Disabled", LV_D3DFMTToString(pp->AutoDepthStencilFormat)); Err_Printf(" Presentation Interval: %i", pp->PresentationInterval); return L_true; } /********************************************************** LV_SetPPFromCVars() This sets the D3DPRESENT_PARAMETERS structure based on the cvars. It also does some checking to make sure that the settings are valid for the device, and chenges them as necesary. This function is called in LV_Init, and LV_Restart. ***********************************************************/ int LV_SetPPFromCVars( L3DGame* lpGame, D3DPRESENT_PARAMETERS* pp) { CVar* cvar=NULL; DWORD dwFlags=0; L_long nBackBufferFmt=0; L_dword nBitDepth=0; L_bool bCheck=0; HCVARLIST cvarlist; HLCONSOLE hConsole; L_result nResult=0; L_dword nQualityLevels=0; if(!pp || !lpGame->m_cvars) return 0; cvarlist=lpGame->m_cvars; hConsole=lpGame->m_Console; /* This function will attemp to get the appropriate values for the present parameters from the cvars, if it can't get the cvar it will SET_PP_FROM_CVAR an appropriate default value, that should work on most systems. */ #define SET_PP_FROM_CVAR(prpr, cvarname, defvalue) {cvar=CVar_GetCVar(cvarlist, cvarname);\ pp->prpr=cvar?(int)cvar->value:defvalue;\ if(!cvar)\ Err_Printf("Could not get \"%s\" for video initialization.", cvarname);} SET_PP_FROM_CVAR(BackBufferWidth, "v_Width", 640); SET_PP_FROM_CVAR(BackBufferHeight, "v_Height", 480); /* Create the back buffer format. */ cvar=CVar_GetCVar(cvarlist, "v_BitDepth"); if(cvar)nBitDepth=(int)cvar->value; /* Transform the bit depth to a D3DFORMAT, not if the bit depth is not valid, we just go for D3DFMT_R5G6B5.*/ if(nBitDepth==32) pp->BackBufferFormat=D3DFMT_X8R8G8B8; else if(nBitDepth==16) pp->BackBufferFormat=D3DFMT_R5G6B5; else if(nBitDepth==15) pp->BackBufferFormat=D3DFMT_X1R5G5B5; else { nBitDepth=16; pp->BackBufferFormat=D3DFMT_R5G6B5; CVar_Set(cvarlist, "v_BitDepth", "16"); } SET_PP_FROM_CVAR(BackBufferCount, "v_ScreenBuffers", 1); SET_PP_FROM_CVAR(SwapEffect, "v_SwapEffect", D3DSWAPEFFECT_DISCARD); pp->hDeviceWindow=lpGame->m_hwnd; nQualityLevels=(int)CVar_GetValue(lpGame->m_cvars, "v_FSAAQuality", &bCheck); if(!bCheck) { Err_Printf("Could not get \"v_FSAAQuality\" for video initialization."); nQualityLevels=0; } SET_PP_FROM_CVAR(Windowed, "v_Windowed", L_false); SET_PP_FROM_CVAR(EnableAutoDepthStencil, "v_EnableAutoDepthStencil", TRUE); SET_PP_FROM_CVAR(AutoDepthStencilFormat, "v_AutoDepthStencilFormat", D3DFMT_D16); /* Set the flags. */ cvar=CVar_GetCVar(cvarlist, "v_LockableBackBuffer"); if(cvar) if(cvar->value) dwFlags|=D3DPRESENTFLAG_LOCKABLE_BACKBUFFER; cvar=CVar_GetCVar(cvarlist, "v_DiscardDepthStencil"); if(cvar) if(cvar->value) dwFlags|=D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL; cvar=CVar_GetCVar(cvarlist, "v_DeviceClip"); if(cvar) if(cvar->value) dwFlags|=D3DPRESENTFLAG_DEVICECLIP; cvar=CVar_GetCVar(cvarlist, "v_VideoHint"); if(cvar) if(cvar->value) dwFlags|=D3DPRESENTFLAG_VIDEO; pp->Flags=dwFlags; SET_PP_FROM_CVAR(FullScreen_RefreshRateInHz, "v_RefreshRate", D3DPRESENT_RATE_DEFAULT); cvar=CVar_GetCVar(cvarlist, "v_EnableVSync"); if(cvar) bCheck=(int)cvar->value; else { Err_Printf("Could not get desired vsync from cvarlist, defaulting."); bCheck=L_false; } if(bCheck) { pp->PresentationInterval=D3DPRESENT_INTERVAL_ONE; } else pp->PresentationInterval=D3DPRESENT_INTERVAL_IMMEDIATE; /* Now we do need to make some adjustment depending on some of the cvars. */ /* If we are windowed we need to set certain presentation parameters. */ if(pp->Windowed) { D3DDISPLAYMODE dmode; memset(&dmode, 0, sizeof(dmode)); //pp->PresentationInterval=0; LV_CorrectWindowSize( lpGame->m_hwnd, pp->BackBufferWidth, pp->BackBufferHeight); lpGame->v.m_lpD3D->lpVtbl->GetAdapterDisplayMode( lpGame->v.m_lpD3D, lpGame->v.m_nAdapterID, &dmode); pp->BackBufferFormat=dmode.Format; } if(!nQualityLevels) { pp->MultiSampleType=D3DMULTISAMPLE_NONE; pp->MultiSampleQuality=0; } else { pp->MultiSampleType=D3DMULTISAMPLE_NONMASKABLE; pp->MultiSampleQuality=nQualityLevels-1; nQualityLevels=0; /* Check if multisample type is available. */ nResult=lpGame->v.m_lpD3D->lpVtbl->CheckDeviceMultiSampleType( lpGame->v.m_lpD3D, lpGame->v.m_nAdapterID, lpGame->v.m_nDeviceType, pp->BackBufferFormat, pp->Windowed, pp->MultiSampleType, &nQualityLevels); if(L_failed(nResult)) { Err_Printf("FSAA mode not allowed, using default."); pp->MultiSampleType=D3DMULTISAMPLE_NONE; pp->MultiSampleQuality=0; CVar_Set(lpGame->m_cvars, "v_FSAAQuality", "0"); } else { if(pp->MultiSampleQuality>=nQualityLevels) { pp->MultiSampleQuality=nQualityLevels-1; } //Err_Printf("FSAA Sample Quality set to: %i", pp->MultiSampleQuality+1); } if((pp->MultiSampleType>0) && (pp->SwapEffect!=D3DSWAPEFFECT_DISCARD)) { Con_SendMessage(hConsole, "FSAA not allowed unless swap effect is DISCARD."); pp->MultiSampleType=D3DMULTISAMPLE_NONE; pp->MultiSampleQuality=0; } if((pp->MultiSampleType>0) && (L_CHECK_FLAG(dwFlags, D3DPRESENTFLAG_LOCKABLE_BACKBUFFER))) { Err_Printf("FSAA not allowed with Lockable Back Buffer."); pp->MultiSampleType=D3DMULTISAMPLE_NONE; pp->MultiSampleQuality=0; } } /* Check to see if the display format is supported. */ /* Make sure the display mode is valid. */ /* If we are windowed we need to set certain values. */ if(pp->Windowed) { pp->FullScreen_RefreshRateInHz=0; lpGame->v.m_nBackBufferFormat=pp->BackBufferFormat; } /* Make sure the format is valid. */ if(!pp->Windowed) { L_uint nCount=0; L_uint i=0; L_bool bDisplayAllowed=L_false; D3DDISPLAYMODE dmode; memset(&dmode, 0, sizeof(dmode)); if(lpGame->v.m_lpD3D->lpVtbl->GetAdapterModeCount( lpGame->v.m_lpD3D, lpGame->v.m_nAdapterID, pp->BackBufferFormat)<1) { /* We are assuming that the device supports the R5G6B5 format, if not then IDirect3D::CreateDevice will fail and we can't do anything. */ pp->BackBufferFormat=D3DFMT_R5G6B5; CVar_Set(lpGame->m_cvars, "v_BitDepth", "16"); Err_Printf("Could not use selected bit depth, defaulting."); } nCount=lpGame->v.m_lpD3D->lpVtbl->GetAdapterModeCount( lpGame->v.m_lpD3D, lpGame->v.m_nAdapterID, pp->BackBufferFormat); if(nCount<1) { Err_Printf("Cannot find a suitable display mode."); return 0; } for(i=0; i<nCount; i++) { lpGame->v.m_lpD3D->lpVtbl->EnumAdapterModes( lpGame->v.m_lpD3D, lpGame->v.m_nAdapterID, pp->BackBufferFormat, i, &dmode); if((dmode.Width==pp->BackBufferWidth) && (dmode.Height==pp->BackBufferHeight)) { /* The display mode is acceptable. */ bDisplayAllowed=L_true; break; } } if(!bDisplayAllowed) { Err_Printf( "The display mode of %ix%i is not allowed, defaulting.", pp->BackBufferWidth, pp->BackBufferHeight); /* We are assuming 640x480 will work, if not, then IDirect3D9::CreateDevice will fail anyway. */ pp->BackBufferWidth=640; pp->BackBufferHeight=480; CVar_Set(lpGame->m_cvars, "v_Width", "640"); CVar_Set(lpGame->m_cvars, "v_Height", "480"); } lpGame->v.m_nBackBufferFormat=pp->BackBufferFormat; } return 1; } /***************************************************** LV_SetStates() Goes through each of the sampler and render states that the game uses, and according the the cvars it sets them. This function is called when a smapler or render state cvar changes, when LV_Init is called, and when LV_ValidateGraphics is called. ******************************************************/ L_bool LV_SetStates(L3DGame* lpGame) { /* If there is no device, there is no point in setting any sampler states. */ if(!lpGame->v.m_lpDevice) return L_false; /*********************** Set the filter mode. ************************/ LV_SetFilterMode(lpGame, (L_int)CVar_GetValue(lpGame->m_cvars, FILTER_MODE, L_null), 0); if(CVar_GetValue(lpGame->m_cvars, "v_DebugWireframe", L_null)) { IDirect3DDevice9_SetRenderState(lpGame->v.m_lpDevice, D3DRS_FILLMODE, D3DFILL_WIREFRAME); } else { IDirect3DDevice9_SetRenderState(lpGame->v.m_lpDevice, D3DRS_FILLMODE, D3DFILL_SOLID); } return L_true; } /********************************************************* LV_SetFilterMode() Sets the texture filter mode for a particular texture stage. Probably should impliment error checking to make sure the selected filter mode is valid on the device. Called by LV_SetStates(). *********************************************************/ L_bool LV_SetFilterMode(L3DGame* lpGame, L_int nFilterMode, L_dword dwStage) { switch(nFilterMode) { default: case FILTER_UNKNOWN: CVar_Set(lpGame->m_cvars, FILTER_MODE, "POINT"); /* Fall through and set filter mode to point. */ case FILTER_POINT: /* 1 is point filtering, see LG_RegisterCVars(). */ IDirect3DDevice9_SetSamplerState(lpGame->v.m_lpDevice, dwStage, D3DSAMP_MAGFILTER, D3DTEXF_POINT); IDirect3DDevice9_SetSamplerState(lpGame->v.m_lpDevice, dwStage, D3DSAMP_MINFILTER, D3DTEXF_POINT); IDirect3DDevice9_SetSamplerState(lpGame->v.m_lpDevice, dwStage, D3DSAMP_MIPFILTER, D3DTEXF_POINT); break; case FILTER_BILINEAR: /* 2 is bilinear filtering. */ IDirect3DDevice9_SetSamplerState(lpGame->v.m_lpDevice, dwStage, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); IDirect3DDevice9_SetSamplerState(lpGame->v.m_lpDevice, dwStage, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); IDirect3DDevice9_SetSamplerState(lpGame->v.m_lpDevice, dwStage, D3DSAMP_MIPFILTER, D3DTEXF_POINT); break; case FILTER_TRILINEAR: /* 3 is trilinear filtering. */ IDirect3DDevice9_SetSamplerState(lpGame->v.m_lpDevice, dwStage, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); IDirect3DDevice9_SetSamplerState(lpGame->v.m_lpDevice, dwStage, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); IDirect3DDevice9_SetSamplerState(lpGame->v.m_lpDevice, dwStage, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR); break; case FILTER_ANISOTROPIC: /* 4 is anisotropic filtering. */ { L_dword nMaxAnisotropy=0; D3DCAPS9 d3dcaps; memset(&d3dcaps, 0, sizeof(D3DCAPS9)); IDirect3DDevice9_GetDeviceCaps(lpGame->v.m_lpDevice, &d3dcaps); IDirect3DDevice9_SetSamplerState(lpGame->v.m_lpDevice, dwStage, D3DSAMP_MAGFILTER, D3DTEXF_ANISOTROPIC); IDirect3DDevice9_SetSamplerState(lpGame->v.m_lpDevice, dwStage, D3DSAMP_MINFILTER, D3DTEXF_ANISOTROPIC); IDirect3DDevice9_SetSamplerState(lpGame->v.m_lpDevice, dwStage, D3DSAMP_MIPFILTER, D3DTEXF_ANISOTROPIC); nMaxAnisotropy=(L_dword)CVar_GetValue(lpGame->m_cvars, FILTER_MAXANISOTROPY, L_null); if((nMaxAnisotropy<1) || (nMaxAnisotropy>d3dcaps.MaxAnisotropy)) { nMaxAnisotropy=d3dcaps.MaxAnisotropy; CVar_SetValue(lpGame->m_cvars, FILTER_MAXANISOTROPY, (float)nMaxAnisotropy); } break; } } Err_Printf("Texture filter mode: %s", CVar_Get(lpGame->m_cvars, FILTER_MODE, L_null)); return L_true; } L_dword LV_D3DFMTToBitDepth(D3DFORMAT fmt) { #define FMT_TO_BITDEPTH(f, b) if(fmt==f)return b; FMT_TO_BITDEPTH(D3DFMT_UNKNOWN, 0) FMT_TO_BITDEPTH(D3DFMT_R8G8B8, 24) FMT_TO_BITDEPTH(D3DFMT_A8R8G8B8, 32) FMT_TO_BITDEPTH(D3DFMT_X8R8G8B8, 32) FMT_TO_BITDEPTH(D3DFMT_R5G6B5, 16) FMT_TO_BITDEPTH(D3DFMT_X1R5G5B5, 16) FMT_TO_BITDEPTH(D3DFMT_A1R5G5B5, 16) FMT_TO_BITDEPTH(D3DFMT_A4R4G4B4, 16) FMT_TO_BITDEPTH(D3DFMT_R3G3B2, 8) FMT_TO_BITDEPTH(D3DFMT_A8, 8) FMT_TO_BITDEPTH(D3DFMT_A8R3G3B2, 16) FMT_TO_BITDEPTH(D3DFMT_X4R4G4B4, 16) FMT_TO_BITDEPTH(D3DFMT_A2B10G10R10, 32) FMT_TO_BITDEPTH(D3DFMT_A8B8G8R8, 32) FMT_TO_BITDEPTH(D3DFMT_X8B8G8R8, 32) FMT_TO_BITDEPTH(D3DFMT_G16R16, 32) FMT_TO_BITDEPTH(D3DFMT_A2R10G10B10, 32) FMT_TO_BITDEPTH(D3DFMT_A16B16G16R16, 64) FMT_TO_BITDEPTH(D3DFMT_A8P8, 16) FMT_TO_BITDEPTH(D3DFMT_P8, 8) FMT_TO_BITDEPTH(D3DFMT_L8, 8) FMT_TO_BITDEPTH(D3DFMT_A8L8, 16) FMT_TO_BITDEPTH(D3DFMT_A4L4, 8) FMT_TO_BITDEPTH(D3DFMT_V8U8, 16) FMT_TO_BITDEPTH(D3DFMT_L6V5U5, 16) FMT_TO_BITDEPTH(D3DFMT_X8L8V8U8, 32) FMT_TO_BITDEPTH(D3DFMT_Q8W8V8U8, 32) FMT_TO_BITDEPTH(D3DFMT_V16U16, 32) FMT_TO_BITDEPTH(D3DFMT_A2W10V10U10, 32) FMT_TO_BITDEPTH(D3DFMT_UYVY, 0) FMT_TO_BITDEPTH(D3DFMT_R8G8_B8G8, 16) FMT_TO_BITDEPTH(D3DFMT_YUY2, 0) FMT_TO_BITDEPTH(D3DFMT_G8R8_G8B8, 16) FMT_TO_BITDEPTH(D3DFMT_DXT1, 32) FMT_TO_BITDEPTH(D3DFMT_DXT2, 32) FMT_TO_BITDEPTH(D3DFMT_DXT3, 32) FMT_TO_BITDEPTH(D3DFMT_DXT4, 32) FMT_TO_BITDEPTH(D3DFMT_DXT5, 32) FMT_TO_BITDEPTH(D3DFMT_D16_LOCKABLE, 16) FMT_TO_BITDEPTH(D3DFMT_D32, 32) FMT_TO_BITDEPTH(D3DFMT_D15S1, 16) FMT_TO_BITDEPTH(D3DFMT_D24S8, 32) FMT_TO_BITDEPTH(D3DFMT_D24X8, 32) FMT_TO_BITDEPTH(D3DFMT_D24X4S4, 32) FMT_TO_BITDEPTH(D3DFMT_D16, 16) FMT_TO_BITDEPTH(D3DFMT_D32F_LOCKABLE, 32) FMT_TO_BITDEPTH(D3DFMT_D24FS8, 32) FMT_TO_BITDEPTH(D3DFMT_L16, 16) FMT_TO_BITDEPTH(D3DFMT_VERTEXDATA, 0) FMT_TO_BITDEPTH(D3DFMT_INDEX16, 16) FMT_TO_BITDEPTH(D3DFMT_INDEX32, 32) FMT_TO_BITDEPTH(D3DFMT_Q16W16V16U16, 64) FMT_TO_BITDEPTH(D3DFMT_MULTI2_ARGB8, 32) FMT_TO_BITDEPTH(D3DFMT_R16F, 16) FMT_TO_BITDEPTH(D3DFMT_G16R16F, 32) FMT_TO_BITDEPTH(D3DFMT_A16B16G16R16F, 64) FMT_TO_BITDEPTH(D3DFMT_R32F, 32) FMT_TO_BITDEPTH(D3DFMT_G32R32F, 64) FMT_TO_BITDEPTH(D3DFMT_A32B32G32R32F, 128) FMT_TO_BITDEPTH(D3DFMT_CxV8U8, 16) return 0; } L_dword LV_StringToD3DFMT(char* szfmt) { #define STRING_TO_FMT(fmt) if(L_strnicmp(szfmt, #fmt, 0))return fmt; STRING_TO_FMT(D3DFMT_UNKNOWN) STRING_TO_FMT(D3DFMT_R8G8B8) STRING_TO_FMT(D3DFMT_A8R8G8B8) STRING_TO_FMT(D3DFMT_X8R8G8B8) STRING_TO_FMT(D3DFMT_R5G6B5) STRING_TO_FMT(D3DFMT_X1R5G5B5) STRING_TO_FMT(D3DFMT_A1R5G5B5) STRING_TO_FMT(D3DFMT_A4R4G4B4) STRING_TO_FMT(D3DFMT_R3G3B2) STRING_TO_FMT(D3DFMT_A8) STRING_TO_FMT(D3DFMT_A8R3G3B2) STRING_TO_FMT(D3DFMT_X4R4G4B4) STRING_TO_FMT(D3DFMT_A2B10G10R10) STRING_TO_FMT(D3DFMT_A8B8G8R8) STRING_TO_FMT(D3DFMT_X8B8G8R8) STRING_TO_FMT(D3DFMT_G16R16) STRING_TO_FMT(D3DFMT_A2R10G10B10) STRING_TO_FMT(D3DFMT_A16B16G16R16) STRING_TO_FMT(D3DFMT_A8P8) STRING_TO_FMT(D3DFMT_P8) STRING_TO_FMT(D3DFMT_L8) STRING_TO_FMT(D3DFMT_A8L8) STRING_TO_FMT(D3DFMT_A4L4) STRING_TO_FMT(D3DFMT_V8U8) STRING_TO_FMT(D3DFMT_L6V5U5) STRING_TO_FMT(D3DFMT_X8L8V8U8) STRING_TO_FMT(D3DFMT_Q8W8V8U8) STRING_TO_FMT(D3DFMT_V16U16) STRING_TO_FMT(D3DFMT_A2W10V10U10) STRING_TO_FMT(D3DFMT_UYVY) STRING_TO_FMT(D3DFMT_R8G8_B8G8) STRING_TO_FMT(D3DFMT_YUY2) STRING_TO_FMT(D3DFMT_G8R8_G8B8) STRING_TO_FMT(D3DFMT_DXT1) STRING_TO_FMT(D3DFMT_DXT2) STRING_TO_FMT(D3DFMT_DXT3) STRING_TO_FMT(D3DFMT_DXT4) STRING_TO_FMT(D3DFMT_DXT5) STRING_TO_FMT(D3DFMT_D16_LOCKABLE) STRING_TO_FMT(D3DFMT_D32) STRING_TO_FMT(D3DFMT_D15S1) STRING_TO_FMT(D3DFMT_D24S8) STRING_TO_FMT(D3DFMT_D24X8) STRING_TO_FMT(D3DFMT_D24X4S4) STRING_TO_FMT(D3DFMT_D16) STRING_TO_FMT(D3DFMT_D32F_LOCKABLE) STRING_TO_FMT(D3DFMT_D24FS8) STRING_TO_FMT(D3DFMT_L16) STRING_TO_FMT(D3DFMT_VERTEXDATA) STRING_TO_FMT(D3DFMT_INDEX16) STRING_TO_FMT(D3DFMT_INDEX32) STRING_TO_FMT(D3DFMT_Q16W16V16U16) STRING_TO_FMT(D3DFMT_MULTI2_ARGB8) STRING_TO_FMT(D3DFMT_R16F) STRING_TO_FMT(D3DFMT_G16R16F) STRING_TO_FMT(D3DFMT_A16B16G16R16F) STRING_TO_FMT(D3DFMT_R32F) STRING_TO_FMT(D3DFMT_G32R32F) STRING_TO_FMT(D3DFMT_A32B32G32R32F) STRING_TO_FMT(D3DFMT_CxV8U8) STRING_TO_FMT(D3DFMT_FORCE_DWORD) return D3DFMT_UNKNOWN; } char* LV_D3DFMTToString(D3DFORMAT fmt) { #define FMT_TO_STRING(f) if(f==fmt)return #f; FMT_TO_STRING(D3DFMT_UNKNOWN) FMT_TO_STRING(D3DFMT_R8G8B8) FMT_TO_STRING(D3DFMT_A8R8G8B8) FMT_TO_STRING(D3DFMT_X8R8G8B8) FMT_TO_STRING(D3DFMT_R5G6B5) FMT_TO_STRING(D3DFMT_X1R5G5B5) FMT_TO_STRING(D3DFMT_A1R5G5B5) FMT_TO_STRING(D3DFMT_A4R4G4B4) FMT_TO_STRING(D3DFMT_R3G3B2) FMT_TO_STRING(D3DFMT_A8) FMT_TO_STRING(D3DFMT_A8R3G3B2) FMT_TO_STRING(D3DFMT_X4R4G4B4) FMT_TO_STRING(D3DFMT_A2B10G10R10) FMT_TO_STRING(D3DFMT_A8B8G8R8) FMT_TO_STRING(D3DFMT_X8B8G8R8) FMT_TO_STRING(D3DFMT_G16R16) FMT_TO_STRING(D3DFMT_A2R10G10B10) FMT_TO_STRING(D3DFMT_A16B16G16R16) FMT_TO_STRING(D3DFMT_A8P8) FMT_TO_STRING(D3DFMT_P8) FMT_TO_STRING(D3DFMT_L8) FMT_TO_STRING(D3DFMT_A8L8) FMT_TO_STRING(D3DFMT_A4L4) FMT_TO_STRING(D3DFMT_V8U8) FMT_TO_STRING(D3DFMT_L6V5U5) FMT_TO_STRING(D3DFMT_X8L8V8U8) FMT_TO_STRING(D3DFMT_Q8W8V8U8) FMT_TO_STRING(D3DFMT_V16U16) FMT_TO_STRING(D3DFMT_A2W10V10U10) FMT_TO_STRING(D3DFMT_UYVY) FMT_TO_STRING(D3DFMT_R8G8_B8G8) FMT_TO_STRING(D3DFMT_YUY2) FMT_TO_STRING(D3DFMT_G8R8_G8B8) FMT_TO_STRING(D3DFMT_DXT1) FMT_TO_STRING(D3DFMT_DXT2) FMT_TO_STRING(D3DFMT_DXT3) FMT_TO_STRING(D3DFMT_DXT4) FMT_TO_STRING(D3DFMT_DXT5) FMT_TO_STRING(D3DFMT_D16_LOCKABLE) FMT_TO_STRING(D3DFMT_D32) FMT_TO_STRING(D3DFMT_D15S1) FMT_TO_STRING(D3DFMT_D24S8) FMT_TO_STRING(D3DFMT_D24X8) FMT_TO_STRING(D3DFMT_D24X4S4) FMT_TO_STRING(D3DFMT_D16) FMT_TO_STRING(D3DFMT_D32F_LOCKABLE) FMT_TO_STRING(D3DFMT_D24FS8) FMT_TO_STRING(D3DFMT_L16) FMT_TO_STRING(D3DFMT_VERTEXDATA) FMT_TO_STRING(D3DFMT_INDEX16) FMT_TO_STRING(D3DFMT_INDEX32) FMT_TO_STRING(D3DFMT_Q16W16V16U16) FMT_TO_STRING(D3DFMT_MULTI2_ARGB8) FMT_TO_STRING(D3DFMT_R16F) FMT_TO_STRING(D3DFMT_G16R16F) FMT_TO_STRING(D3DFMT_A16B16G16R16F) FMT_TO_STRING(D3DFMT_R32F) FMT_TO_STRING(D3DFMT_G32R32F) FMT_TO_STRING(D3DFMT_A32B32G32R32F) FMT_TO_STRING(D3DFMT_CxV8U8) FMT_TO_STRING(D3DFMT_FORCE_DWORD) return "D3DFMT_UNKNOWN"; } <file_sep>/games/Legacy-Engine/Scrapped/old/lv_texmgr.cpp #include "lv_texmgr.h" #include "lv_tex.h" #include "lg_err_ex.h" #include "lg_err.h" #include "lf_sys2.h" #include "lg_func.h" #if 0 extern "C" IDirect3DTexture9* Tex_Load2(lg_cstr szFilename, lg_bool bForceNoMip) { if(!CLTexMgr::s_pTexMgr) { Err_Printf("Tex_Load Error: Texture manager not initialized."); return LG_NULL; } return CLTexMgr::s_pTexMgr->LoadTexture(szFilename, bForceNoMip); } extern "C" IDirect3DTexture9* Tex_Load2_Memory(lg_void* pBuffer, lg_dword nSize, lg_bool bForceNoMip) { if(!CLTexMgr::s_pTexMgr) { Err_Printf("Tex_Load_Memory Error: Texture manager not initialized."); return LG_NULL; } return CLTexMgr::s_pTexMgr->LoadTexture(pBuffer, nSize, bForceNoMip); } #endif class CLTexMgr* CLTexMgr::s_pTexMgr=LG_NULL; CLTexMgr::CLTexMgr(): m_pDevice(LG_NULL), m_pDefaultTex(LG_NULL), m_pFirst(LG_NULL) { s_pTexMgr=this; } CLTexMgr::~CLTexMgr() { UnInit(); } void CLTexMgr::Init(IDirect3DDevice9* pDevice, lg_cstr szDefaultTex, lg_dword Flags, lg_uint nSizeLimit) { if(m_pDevice) UnInit(); Tex_SetLoadOptionsFlag(Flags, nSizeLimit); m_pDevice=pDevice; m_pDevice->AddRef(); //Should create a default texture. lg_bool bResult=Tex_Load( m_pDevice, (lg_lpstr)szDefaultTex, D3DPOOL_DEFAULT, 0x00000000, LG_FALSE, &m_pDefaultTex); if(!bResult) { m_pDefaultTex=LG_NULL; Err_Printf("Could not load default texture \"%s\"", szDefaultTex); MessageBox(0, "No default texture", 0, 0); } } void CLTexMgr::UnInit() { ClearCache(); L_safe_release(m_pDefaultTex); L_safe_release(m_pDevice); } IDirect3DTexture9* CLTexMgr::GetTexture(lg_cstr szFilename) { lg_char szName[MAX_TEX_NAME]; LF_GetFileNameFromPath(szName, szFilename); TEX_LINK* pLink=m_pFirst; while(pLink) { if(L_strnicmp(szName, pLink->szName, 0)) return pLink->pTex; pLink=pLink->pNext; } return m_pDefaultTex; } IDirect3DTexture9* CLTexMgr::LoadTexture(lg_void* pData, lg_dword nSize, lg_bool bForceNoMipMap) { //The texture loading function that laods from memory is a little //different because it only loads the texture, it doesn't //save a copy of the texture. IDirect3DTexture9* pNewTex=LG_NULL; //Attempt to load the texture. if(!Tex_Load_Memory( m_pDevice, pData, nSize, D3DPOOL_DEFAULT, 0x00000000, bForceNoMipMap, &pNewTex)) { if(m_pDefaultTex) m_pDefaultTex->AddRef(); return m_pDefaultTex; } return pNewTex; } IDirect3DTexture9* CLTexMgr::LoadTexture(lg_cstr szFilename, lg_bool bForceNoMipMap) { lg_char szName[MAX_TEX_NAME]; LF_GetFileNameFromPath(szName, szFilename); //First try to get the texture if it already has been loaded. IDirect3DTexture9* pNewTex=GetTexture(szFilename); if(pNewTex!=m_pDefaultTex) { pNewTex->AddRef(); return pNewTex; } //Then attempt to load the texture. if(!Tex_Load( m_pDevice, (lg_lpstr)szFilename, D3DPOOL_DEFAULT, 0x00000000, bForceNoMipMap, &pNewTex)) { if(m_pDefaultTex) m_pDefaultTex->AddRef(); return m_pDefaultTex; } TEX_LINK* pNewLink=new TEX_LINK; //If we're out of memory we have some serious problems. if(!pNewLink) throw CLError(LG_ERR_OUTOFMEMORY, __FILE__, __LINE__); pNewLink->pNext=m_pFirst; m_pFirst=pNewLink; pNewLink->pTex=pNewTex; LG_strncpy(pNewLink->szName, szName, MAX_TEX_NAME); pNewTex->AddRef(); return pNewTex; } void CLTexMgr::ClearCache() { TEX_LINK* pLink=m_pFirst; TEX_LINK* pNext=LG_NULL; while(pLink) { pNext=pLink->pNext; L_safe_release(pLink->pTex); L_safe_delete(pLink); pLink=pNext; } m_pFirst=LG_NULL; }<file_sep>/tools/QInstall/Source/resource.h //{{NO_DEPENDENCIES}} // Microsoft Developer Studio generated include file. // Used by Resource.rc // #define IDD_MAINDLG 101 #define IDD_RUNDIALOG 102 #define IDI_ICON1 103 #define IDC_INSTALL 1000 #define IDC_QUIT 1001 #define IDC_BROWSE 1002 #define IDC_INSTALLPATH 1003 #define IDC_PNAME 1004 #define IDC_INSTALLFROM 1005 #define IDC_COPYINGWORD 1006 #define IDC_COPIEDFILE 1007 #define IDC_CONTINUE 1008 #define IDC_RUNPROGRAM 1009 #define IDC_PNAME2 1010 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 104 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1011 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif <file_sep>/games/Legacy-Engine/Source/engine/li_sys.cpp /***************************************************************************** li_sys.cpp - Legacy Engine Input. The CLInput class is used to get all "game input" (not console input), note that when this class detects that the console key was pressed it notifies the game that it needs to get input from windows. This class uses DirectInput8, and a keyboard and mouse are always supported. Note that this class is by no means error proof and as it stands right now if there is no mouse installed in the system, the program will crash. *****************************************************************************/ #include "li_sys.h" #include "lg_err.h" #include "lg_func.h" CLInput::CLInput(): m_pDI(LG_NULL), m_pKB(LG_NULL), m_pMouse(LG_NULL), m_bExclusiveKB(LG_FALSE), m_bExclusiveMouse(LG_FALSE), m_nConKey(0), m_bInitialized(LG_FALSE), m_hwnd(LG_NULL), m_nLastX(0), m_nLastY(0), m_bSmoothMouse(LG_FALSE), m_fXSense(0.01f), m_fYSense(0.01f) { memset(m_kbData, 0, sizeof(m_kbData)); memset(&m_mouseState, 0, sizeof(m_mouseState)); s_pCmds=m_Commands; s_pAxis=&m_Axis; m_nCmdsActive[0]=0; m_nCmdsPressed[0]=0; m_fAxis[0]=0.0f; m_fAxis[1]=0.0f; } CLInput::~CLInput() { if(m_bInitialized) { Err_Printf("Calling LI_Shutdown..."); LI_Shutdown(); } } const lg_byte* CLInput::GetKBData() { return m_kbData; } const DIMOUSESTATE2* CLInput::GetMouseData() { return &m_mouseState; } void CLInput::InitCommands() { m_Commands[COMMAND_MOVEFORWARD].Init( COMMAND_MOVEFORWARD, DEV_KB, DIK_W); m_Commands[COMMAND_MOVEBACK].Init( COMMAND_MOVEBACK, DEV_KB, DIK_S); m_Commands[COMMAND_MOVERIGHT].Init( COMMAND_MOVERIGHT, DEV_KB, DIK_D); m_Commands[COMMAND_MOVELEFT].Init( COMMAND_MOVELEFT, DEV_KB, DIK_A); m_Commands[COMMAND_MOVEUP].Init( COMMAND_MOVEUP, DEV_KB, DIK_SPACE); m_Commands[COMMAND_MOVEDOWN].Init( COMMAND_MOVEUP, DEV_KB, DIK_LCONTROL); m_Commands[COMMAND_SPEED].Init( COMMAND_SPEED, DEV_KB, DIK_LSHIFT); m_Commands[COMMAND_TURNRIGHT].Init( COMMAND_TURNRIGHT, DEV_KB, DIK_RIGHT); m_Commands[COMMAND_TURNLEFT].Init( COMMAND_TURNLEFT, DEV_KB, DIK_LEFT); m_Commands[COMMAND_PRIMARY_WEAPON].Init( COMMAND_PRIMARY_WEAPON, DEV_MOUSE, 0); } CLICommand* CLInput::GetCommand(LI_COMMAND cmd) { return &m_Commands[cmd]; } CLICommand* CLInput::GetCommands() { return &m_Commands[0]; } CLAxis* CLInput::GetAxis() { return &m_Axis; } void CLInput::UpdateCommands() { m_nCmdsActive[0]=0; m_nCmdsPressed[0]=0; for(lg_dword i=0; i<COMMAND_COUNT; i++) { lg_byte nState; switch(m_Commands[i].m_nDevice) { case DEV_KB: nState=m_kbData[m_Commands[i].m_nButton]&0x80; break; case DEV_MOUSE: nState=m_mouseState.rgbButtons[m_Commands[i].m_nButton]&0x80; break; case DEV_JOYSTICK: break; } if(nState) { if(m_Commands[i].m_bActive) m_Commands[i].m_bWasActivated=LG_FALSE; else m_Commands[i].m_bWasActivated=LG_TRUE; m_Commands[i].m_bActive=LG_TRUE; m_Commands[i].m_bWillDeactivate=LG_TRUE; } else { m_Commands[i].m_bActive=LG_FALSE; m_Commands[i].m_bWasActivated=LG_FALSE; m_Commands[i].m_bWillDeactivate=LG_FALSE; } if(m_Commands[i].m_bActive) { LG_SetFlag(m_nCmdsActive[i/32], (1<<((i/32)+i))); } if(m_Commands[i].m_bWasActivated) { LG_SetFlag(m_nCmdsPressed[i/32], (1<<((i/32)+i))); } } //The axis should be able to come from either the keyboard or the mouse... //Ignor the const qualifier when updating the axis. (lg_long)(m_Axis.nX)=m_mouseState.lX; (lg_long)(m_Axis.nY)=m_mouseState.lY; m_fAxis[0]=m_Axis.nX*m_fXSense; m_fAxis[1]=m_Axis.nY*m_fYSense; } lg_result CLInput::LI_Update(lg_dword Flags) { #ifdef _DEBUG lg_result nResult; #endif _DEBUG //Update the keyboard. if(L_CHECK_FLAG(Flags, LI_UPDATE_KB)) { m_pKB->Acquire(); #ifdef _DEBUG nResult=m_pKB->GetDeviceState(sizeof(m_kbData), (lg_void*)&m_kbData); if(LG_FAILED(nResult)) Err_PrintDX("IDirectInputDevice8::GetDeviceState (KB)", nResult); #else _DEBUG m_pKB->GetDeviceState(sizeof(m_kbData), (lg_void*)&m_kbData); #endif _DEBUG } //Get mouse input... if(L_CHECK_FLAG(Flags, LI_UPDATE_MOUSE)) { //m_mouseStateLast=m_mouseStateNow; m_nLastX=m_mouseState.lX; m_nLastY=m_mouseState.lY; m_pMouse->Acquire(); #ifdef _DEBUG nResult=m_pMouse->GetDeviceState(sizeof(DIMOUSESTATE2), (lg_void*)&m_mouseState); if(LG_FAILED(nResult)) Err_PrintDX("IDirectInputDevice8::GetDeviceState (Mouse)", nResult); #else _DEBUG m_pMouse->GetDeviceState(sizeof(DIMOUSESTATE2), (lg_void*)&m_mouseState); #endif _DEBUG //This is a relatively simply way to cause mouse //smoothing. if(m_bSmoothMouse) { m_mouseState.lX=(m_mouseState.lX+m_nLastX)/2; m_mouseState.lY=(m_mouseState.lY+m_nLastY)/2; } } //Update all commands. UpdateCommands(); //Check to see if the console key was pressed, //if it was we'll unacquire the keyboard and return //a message stating that the console should be opened. if(m_kbData[m_nConKey]&0x80) { m_pKB->Unacquire(); memset(m_kbData, 0, sizeof(m_kbData)); memset(&m_mouseState, 0, sizeof(m_mouseState)); return LIS_CONSOLE; } return LIS_OK; } void CLInput::LI_ResetStates() { m_pMouse->Unacquire(); m_pKB->Unacquire(); m_pMouse->Acquire(); m_pKB->Acquire(); m_pMouse->GetDeviceState(sizeof(DIMOUSESTATE2), (lg_void*)&m_mouseState); m_pKB->GetDeviceState(sizeof(m_kbData), (lg_void*)&m_kbData); } /////////////////////////////////// /// LI_Init() and LI_Shutdown() /// /// Create and destory input /// /////////////////////////////////// lg_bool CLInput::LI_Init(HWND hwnd, lg_dword nFlags, lg_byte nConKey) { //If we are already initialized we'll just call shutdown, //this will in effect reset the input. LI_Shutdown(); m_nConKey=nConKey; m_hwnd=hwnd; lg_result nResult=0; lg_dword dwFmt=0; nResult=DirectInput8Create(GetModuleHandle(LG_NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&m_pDI, LG_NULL); if(LG_FAILED(nResult)) { Err_Printf("Could not create IDirectInput8 interface."); Err_PrintDX("DirectInput8Create", nResult); m_bInitialized=LG_FALSE; return LG_FALSE; } Err_Printf("Created IDirectInput8 interface at 0x%08X.", m_pDI); //Create keyboard. Err_Printf("Initializing keyboard..."); LI_InitKB(nFlags); //Create the mouse. Err_Printf("Initializing mouse..."); LI_InitMouse(nFlags); //Set commands. InitCommands(); m_bInitialized=LG_TRUE; return LG_TRUE; } void CLInput::LI_InitKB(lg_dword Flags) { lg_result nResult=m_pDI->CreateDevice(GUID_SysKeyboard, &m_pKB, NULL); if(LG_FAILED(nResult)) { Err_Printf("Could not create keyboard."); Err_PrintDX("IDirectInput8::CreateDevice", nResult); m_pKB=LG_NULL; return; } else Err_Printf("Created IDirectInputDevice9 keyboard at 0x%08X.", m_pKB); Err_Printf("Setting up keyboard input..."); nResult=m_pKB->SetDataFormat(&c_dfDIKeyboard); Err_PrintDX("IDirectInputDevice8::SetDataFormat", nResult); lg_dword dwFmt=DISCL_FOREGROUND; if(L_CHECK_FLAG(Flags, LINPUT_EXCLUSIVEKB)) { Err_Printf("KB input EXCLUSIVE."); dwFmt|=DISCL_EXCLUSIVE; m_bExclusiveKB=LG_TRUE; } else { Err_Printf("KB input NONEXCLUSIVE."); dwFmt|=DISCL_NONEXCLUSIVE; m_bExclusiveKB=LG_FALSE; } if(L_CHECK_FLAG(Flags, LINPUT_DISABLEWINKEY)) { Err_Printf("KB input NOWINKEY."); dwFmt|=DISCL_NOWINKEY; } nResult=m_pKB->SetCooperativeLevel(m_hwnd, dwFmt); Err_PrintDX("IDirectInputDevice8::SetCooperativeLevel", nResult); } void CLInput::LI_InitMouse(lg_dword Flags) { lg_result nResult=m_pDI->CreateDevice(GUID_SysMouse, &m_pMouse, NULL); if(LG_FAILED(nResult)) { Err_Printf("Could not create mouse."); Err_PrintDX("IDirectInput8::CreateDevice", nResult); m_pMouse=LG_NULL; return; } else Err_Printf("Created IDirectInputDevice9 mouse at 0x%08X.", m_pKB); Err_Printf("Setting up mouse input..."); nResult=m_pMouse->SetDataFormat(&c_dfDIMouse2); Err_PrintDX("IDirectInputDevice8::SetDataFormat", nResult); lg_dword dwFmt=DISCL_FOREGROUND; if(L_CHECK_FLAG(Flags, LINPUT_EXCLUSIVEMOUSE)) { Err_Printf("Mouse input EXCLUSIVE."); dwFmt|=DISCL_EXCLUSIVE; m_bExclusiveMouse=LG_TRUE; } else { Err_Printf("Mouse input NONEXCLUSIVE (not recommended)."); dwFmt|=DISCL_NONEXCLUSIVE; m_bExclusiveMouse=LG_FALSE; } nResult=m_pMouse->SetCooperativeLevel(m_hwnd, dwFmt); Err_PrintDX("IDirectInputDevice8::SetCooperativeLevel", nResult); m_bSmoothMouse=L_CHECK_FLAG(Flags, LINPUT_SMOOTHMOUSE); if(m_bSmoothMouse) Err_Printf("Mouse input SMOOTH."); } void CLInput::LI_Shutdown() { if(!m_bInitialized) return; lg_ulong nNumLeft=0; Err_Printf("Releasing IDirectInputDevice8 mouse interface..."); if(m_pMouse) { m_pMouse->Unacquire(); nNumLeft=m_pMouse->Release(); Err_Printf("Released IDirectInputDevice8 mouse interface at 0x%08X with %d references left.", m_pKB, nNumLeft); m_pMouse=LG_NULL; } Err_Printf("Releasing IDirectInputDevice8 keyboard interface..."); if(m_pKB) { m_pKB->Unacquire(); nNumLeft=m_pKB->Release(); Err_Printf("Released IDirectInputDevice8 keyboard interface at 0x%08X with %d references left.", m_pKB, nNumLeft); m_pKB=LG_NULL; } Err_Printf("Releasing IDirectInput8 interface..."); if(m_pDI) { nNumLeft=m_pDI->Release(); Err_Printf("Released IDirectInput8 interface at 0x%08X with %d references left.", m_pDI, nNumLeft); m_pDI=LG_NULL; } m_bInitialized=LG_FALSE; }<file_sep>/games/Legacy-Engine/Scrapped/old/ls_load.h #ifndef __LS_LOAD_H__ #define __LS_LOAD_H__ #include <dsound.h> #include "common.h" #ifdef __cplusplus extern "C" #endif /*__cplusplus*/ lg_bool LS_LoadSound( IDirectSound8* lpDS, IDirectSoundBuffer8** lppBuffer, lg_dword dwBufferFlags, char* szFilename); #endif /* __LS_LOAD_H__*/<file_sep>/games/Legacy-Engine/Source/common/lg_sdk.h /* The Legacy Engine SDK Header File, do not modify. */ #ifndef __LG_SDK_H__ #define __LG_SDK_H__ #include "lg_types.h" #endif __LG_SDK_H__<file_sep>/games/Legacy-Engine/Source/engine/ls_sys.cpp #include "ls_sys.h" #include "lg_err.h" #include "lg_cvars.h" #include "lg_malloc.h" #include "ls_sndfile.h" #include "../lc_sys2/lc_sys2.h" CLSndMgr::CLSndMgr(): m_pAudioContext(LG_NULL), m_pAudioDevice(LG_NULL) { } CLSndMgr::~CLSndMgr() { if(m_bSndAvailable) LS_Shutdown(); } void CLSndMgr::Music_Start(lg_str szPath) { if(!m_MusicTrack.Load(szPath)) { Err_Printf("Music_Start ERROR: Could not load music track \"%s\".", szPath); return; } Music_UpdateVolume();//m_MusicTrack.SetVolume(CV_Get(CVAR_s_MusicVolume)->nValue); m_MusicTrack.Play(LG_TRUE); } void CLSndMgr::Music_UpdateVolume() { m_MusicTrack.SetVolume(CV_Get(CVAR_s_MusicVolume)->nValue); } void CLSndMgr::Music_Pause() { m_MusicTrack.Pause(); } void CLSndMgr::Music_Stop() { m_MusicTrack.Stop(); } void CLSndMgr::Music_Resume() { m_MusicTrack.Play(LG_TRUE); } void CLSndMgr::Update() { //Update streaming audio. //Process audio... //m_TestSnd2.Update(); m_MusicTrack.Update(); alcProcessContext(m_pAudioContext); //Suspend the context till the next frame... alcSuspendContext(m_pAudioContext); } lg_bool CLSndMgr::LS_Init() { ALCenum nALCError; const ALCchar* szDevice=alcGetString(LG_NULL, ALC_DEFAULT_DEVICE_SPECIFIER);// szDevice[]="DirectSound3D"; m_pAudioDevice=alcOpenDevice((const ALCchar*)szDevice); nALCError=alcGetError(LG_NULL); if(!m_pAudioDevice) { Err_Printf("Sound Init ERROR %u: Could not create audio device.", nALCError); m_bSndAvailable=LG_FALSE; return LG_FALSE; } Err_Printf("Created \"%s\" audio device at 0x%08X", alcGetString(m_pAudioDevice, ALC_DEVICE_SPECIFIER), m_pAudioDevice); m_pAudioContext=alcCreateContext(m_pAudioDevice, LG_NULL); nALCError=alcGetError(m_pAudioDevice); if(!m_pAudioContext) { Err_Printf("Sound Init ERROR %u: Could not create audio context.", nALCError); alcCloseDevice(m_pAudioDevice); m_bSndAvailable=LG_FALSE; return LG_FALSE; } Err_Printf("Created audio context at 0x%08X", m_pAudioContext); nALCError=alcGetError(m_pAudioDevice); if(!alcMakeContextCurrent(m_pAudioContext)) { Err_Printf("Sount Init ERROR %u: Could not make sound context current."); alcDestroyContext(m_pAudioContext); alcCloseDevice(m_pAudioDevice); m_bSndAvailable=LG_FALSE; return LG_FALSE; } Err_Printf("Audio system extensions:"); if(alcIsExtensionPresent(m_pAudioDevice, "ALC_EXT_EFX")) Err_Printf("ACL_EXT_EFX"); if(alcIsExtensionPresent(m_pAudioDevice, "ALC_EXT_CAPTURE")) Err_Printf("ALC_EXT_CAPTURE"); //const ALCchar* szExt=alcGetString(m_pAudioDevice, ALC_EXTENSIONS); //Err_Printf("%s", szExt); alGetError(); m_bSndAvailable=LG_TRUE; return LG_TRUE; } void CLSndMgr::LS_Shutdown() { //Close the music track... m_MusicTrack.Close(); ALCenum nALCError; /* Make sure the audio was initialized, because if it hasn't been there is no point in shutting it donw. */ if(!m_bSndAvailable) { Err_Printf("Sound Shutdown ERROR: Audio was not initialized, nothing to shut down."); return; } Err_Printf("Destroying audio device at 0x%08X...", m_pAudioContext); alcMakeContextCurrent(LG_NULL); alcDestroyContext(m_pAudioContext); Err_Printf("Closing device at 0x%08X...", m_pAudioDevice); alcCloseDevice(m_pAudioDevice); nALCError=alcGetError(LG_NULL); if(nALCError!=ALC_NO_ERROR) { Err_Printf("Sound Shutdown ERROR %u: Could not close device properly.", nALCError); } m_bSndAvailable=LG_FALSE; return; } lg_bool CLSndMgr::LS_LoadSoundIntoBuffer(ALuint sndBuffer, lg_str szFilename) { CLSndFile sndFile; if(!sndFile.Open(szFilename)) return LG_FALSE; ALvoid* pData=LG_Malloc(sndFile.GetDataSize()); sndFile.Read(pData, sndFile.GetDataSize()); ALenum nFormat=GetALFormat(sndFile.GetNumChannels(), sndFile.GetBitsPerSample()); alBufferData(sndBuffer, nFormat, pData, sndFile.GetDataSize(), sndFile.GetSamplesPerSecond()); LG_Free(pData); alGetError(); return LG_TRUE; } ALenum CLSndMgr::GetALFormat(lg_dword nChannels, lg_dword nBPS) { //Only the following sound file formats are supported... if(nChannels==1 && nBPS==8) return AL_FORMAT_MONO8; else if(nChannels==1 && nBPS==16) return AL_FORMAT_MONO16; else if(nChannels==2 && nBPS==8) return AL_FORMAT_STEREO8; else if(nChannels==2 && nBPS==16) return AL_FORMAT_STEREO16; else return -1; }<file_sep>/samples/Project3/src/project3/Main.java /* Main.java - Entry point and windows management for Project3. <NAME> Project 3 CS 1400-002 Copyright (c) 2006, <NAME> */ package project3; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; public class Main extends JFrame implements ActionListener { private static String m_szAppName="Winter Wonderland"; private JButton m_btnPower1; private JButton m_btnPower2; private JButton m_btnCycleLights; private ImageIcon m_imgBG; private JLabel m_lblImg; private javax.swing.Timer m_time; private int m_nRefreshRate=250; private SceneLight m_pStrand1[]; private boolean m_bStrand1On=true; private int m_nStrand1LightCount=0; private int m_nStrand1Pattern=0; private int m_nStrand1Extra=0; private SceneLight m_pStrand2[]; private boolean m_bStrand2On=true; private int m_nStrand2LightCount=0; private boolean m_bReady=false; //Ready value means we are ready to update. private Random m_rnd=new Random(); public Main() { //Setup the window. super(m_szAppName); setBounds(20, 20, 640, 480); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); setResizable(false); //Create the buttons. //FlowLayout flow=new FlowLayout(); setLayout(null); //flow.setAlignment(FlowLayout.LEFT); m_btnPower1=new JButton("Power 1"); m_btnPower2=new JButton("Power 2"); m_btnCycleLights=new JButton("Cycle Lights"); m_btnPower1.addActionListener(this); m_btnPower2.addActionListener(this); m_btnCycleLights.addActionListener(this); m_btnPower1.setBounds(0, 0, 110, 30); m_btnPower2.setBounds(0, 0, 110, 30); m_btnCycleLights.setBounds(0, 0, 110, 30); m_btnPower1.setLocation(10, 10); m_btnPower2.setLocation(10, 45); m_btnCycleLights.setLocation(125, 10); //Create the background //Toolkit kit = Toolkit.getDefaultToolkit(); //m_imgBG=kit.getImage("background.jpg"); m_imgBG=new ImageIcon("background.jpg"); m_lblImg=new JLabel(m_imgBG); m_lblImg.setBounds(0, 0, m_imgBG.getIconWidth(), m_imgBG.getIconHeight()); setupLights(); add(m_btnPower1); add(m_btnPower2); add(m_btnCycleLights); add(m_lblImg); //Create the timer. m_time=new javax.swing.Timer(m_nRefreshRate, this); m_time.setInitialDelay(m_nRefreshRate); m_time.start(); validate(); m_bReady=true; } private int lightColor(int n) { switch(n%4) { default: case 0:return 0xFF0000; case 1:return 0x00FF00; case 2:return 0x0000FF; case 3:return 0xFFFF00; } } private void setupLights() { int i=0, j=0, n=0; //int nColor=0; //Create the standard lights. m_pStrand1=new SceneLight[32]; //Base of the roof. for(i=0, n=0; i<16; i++,n++) { m_pStrand1[n]=new SceneLight(lightColor(n), 34*i+66, 155); add(m_pStrand1[n]); } //Right side. for(i=0; i<3; i++, n++) { m_pStrand1[n]=new SceneLight(lightColor(n), 560-i*23, 125-i*28); add(m_pStrand1[n]); } //Top. for(i=0; i<11; i++, n++) { m_pStrand1[n]=new SceneLight(lightColor(n), 482-i*35, 69); add(m_pStrand1[n]); } //Left side. for(i=0; i<2; i++, n++) { m_pStrand1[n]=new SceneLight(lightColor(n), 108-i*23, 95+i*30); add(m_pStrand1[n]); } m_nStrand1LightCount=n; //Add the icicle lights (strand 2). m_pStrand2=new SceneLight[38]; for(i=0, n=0; i<15; i++) { for(j=0; j<3-i%2; j++, n++) { m_pStrand2[n]=new SceneLight(0xFFFFFF, 37*i+63, 160+j*20); add(m_pStrand2[n]); } } m_nStrand2LightCount=n; } private void messageBox(String szMessage) { JOptionPane.showMessageDialog(this, szMessage); } private void power1() { m_bStrand1On=!m_bStrand1On; float fNewIntensity=m_bStrand1On?1.0f:0.25f; for(int i=0; i<m_nStrand1LightCount; i++) { m_pStrand1[i].setIntensity(fNewIntensity); } } private void power2() { m_bStrand2On=!m_bStrand2On; float fNewIntensity=m_bStrand2On?1.0f:0.25f; for(int i=0; i<m_nStrand2LightCount; i++) { m_pStrand2[i].setIntensity(fNewIntensity); } } private void changeLightCycle() { m_nStrand1Pattern++; if(m_nStrand1Pattern>1) m_nStrand1Pattern=0; } public void actionPerformed(ActionEvent e) { if(!m_bReady) return; Object src=e.getSource(); if(src==m_btnPower1) { power1(); } else if(src==m_btnPower2) { power2(); } else if(src==m_btnCycleLights) { m_nStrand1Extra=0; changeLightCycle(); } else if(src==m_time) { //Call timed refresh on the time //and return so we don't call it twice. timedRefresh(); return; } timedRefresh(); } private void processLightPattern1() { float fNewIntensity=1.0f; if(m_nStrand1Extra>20) m_nStrand1Extra=0; if(m_nStrand1Extra<10) fNewIntensity=1.0f-(float)m_nStrand1Extra*0.07f; else fNewIntensity=1.0f-(float)(20-m_nStrand1Extra)*0.07f; m_nStrand1Extra++; for(int i=0; i<m_nStrand1LightCount; i++) { m_pStrand1[i].setIntensity(fNewIntensity); } } private void processLightPattern2() { if(m_nStrand1Extra>3) m_nStrand1Extra=0; for(int i=0; i<m_nStrand1LightCount; i++) { if((i%4)==m_nStrand1Extra) { m_pStrand1[i].setIntensity(1.0f); } else { m_pStrand1[i].setIntensity(0.25f); } } m_nStrand1Extra++; } private void timedRefresh() { //Process strand 1. if(m_bStrand1On) { switch(m_nStrand1Pattern) { default: case 0: processLightPattern1(); break; case 1: processLightPattern2(); break; } } //Make strand 2 twinkle a little bit if(m_bStrand2On) { for(int i=0; i<m_nStrand2LightCount; i++) { float fNewIntensity=(float)(100-m_rnd.nextInt(30))/100.0f; m_pStrand2[i].setIntensity(fNewIntensity); } } validate(); } //Entry point for Project3 public static void main(String[] args) { Main win=new Main(); } } <file_sep>/games/Legacy-Engine/Source/engine/lg_fxmgr.h /* lg_fxmgr.h - The effect manager. Copryight (c) 2008 <NAME> */ #ifndef __LG_FXMGR_H__ #define __LG_FXMGR_H__ #include <d3d9.h> #include <d3dx9.h> #include "lg_types.h" #include "lg_hash_mgr.h" //All effects are represented by fxm_fx, in this way they //are not specifically Direct3D based. Rather they are a //reference. typedef hm_item fxm_fx; class CLFxMgr: public CLHashMgr<ID3DXEffect>{ public: //Flags: private: //Internal data, strictly initialized in the constructor. D3DPOOL m_nPool; IDirect3DDevice9* m_pDevice; //The device. public: /* Constructor PRE: Direct3D must be initialized. POST: The instance is created. */ CLFxMgr(IDirect3DDevice9* pDevice, lg_dword nMaxFx); /* PRE: N/A. POST: Destroys everything, unloads all effects, and deallocates all memory associated. Note that after the manager is destroyed, any effects that have been obtained are still usable as only the reference count is decreased. Any effects obtained must still be released. */ ~CLFxMgr(); /* PRE: N/A POST: Sets the specified effect for rendering in the specified stage. */ void SetEffect(fxm_fx effect); /* PRE: N/A POST: Returns the interface of the effect, this will not be used in the future. */ ID3DXEffect* GetInterface(fxm_fx effect); /* PRE: Called if device was lost. POST: Prepares the effect manager for a reset. */ void Invalidate(); /* PRE: Device must be reset. POST: Validates all effects. */ void Validate(); private: //Internal methods: /* PRE: Called only from the load method. POST: Basically a check to see if a effect is already loaded in the manager. If it is, it is returned and Loadeffect ends quickly. If it isn't The manager knows it must load the effect. */ fxm_fx GetEffect(lg_path szFilename, lg_dword* pHash); /* PRE: Called only from the load method. POST: This actually loads a direct3d effect and returns it, it uses all internal flags to decide how the effect is to be loaded. */ virtual ID3DXEffect* DoLoad(lg_path szFilename, lg_dword nFlags); virtual void DoDestroy(ID3DXEffect* pItem); private: //The static effect manager is so effects can be loaded on demand //without having acces to teh established effect manager within //the game class. static CLFxMgr* s_pFxMgr; public: /* PRE: The CLTMgr must be initialized. POST: If the specified effect is available it is loaded, see the public member Loadeffect for more details. */ static fxm_fx FXM_LoadFx(lg_path szFilename, lg_dword nFlags); /* PRE: effect must be a effect obtained with FXM_LoadFx*, or 0 for no effect. POST: The effect set will be used for rendering. */ static void FXM_SetEffect(fxm_fx effect); /* PRE: Temp only. POST: Returns interface specified, or teh default one. */ static ID3DXEffect* FXM_GetInterface(fxm_fx effect); }; #endif __LG_FXMGR_H__<file_sep>/games/Legacy-Engine/Source/lf_sys2/lf_misc.c #include <string.h> #include "lf_sys2.h" /*************************************************** Pathname getting functions, retrieve filename path, or short filename from a full path ***************************************************/ lf_str LF_GetFileNameFromPathA(lf_str szFileName, lf_cstr szFullPath) { lf_dword dwLen=strlen(szFullPath); lf_dword i=0, j=0; for(i=dwLen; i>0; i--) { if(szFullPath[i]=='\\' || szFullPath[i]=='/') { i++; break; } } for(j=0 ;i<dwLen+1; i++, j++) { szFileName[j]=szFullPath[i]; } return szFileName; } lf_wstr LF_GetFileNameFromPathW(lf_wstr szFileName, lf_cwstr szFullPath) { lf_dword dwLen=wcslen(szFullPath); lf_dword i=0, j=0; for(i=dwLen; i>0; i--) { if(szFullPath[i]=='\\' || szFullPath[i]=='/') { i++; break; } } for(j=0 ;i<dwLen+1; i++, j++) { szFileName[j]=szFullPath[i]; } return szFileName; } lf_str LF_GetShortNameFromPathA(lf_str szName, lf_cstr szFullPath) { lf_dword dwLen=strlen(szFullPath); lf_dword i=0, j=0; for(i=dwLen; i>0; i--) { if(szFullPath[i]=='\\' || szFullPath[i]=='/') { i++; break; } } for(j=0 ;i<dwLen+1; i++, j++) { szName[j]=szFullPath[i]; if(szName[j]=='.') { szName[j]=0; break; } } return szName; } lf_wstr LF_GetShortNameFromPathW(lf_wstr szName, lf_cwstr szFullPath) { lf_dword dwLen=wcslen(szFullPath); lf_dword i=0, j=0; for(i=dwLen; i>0; i--) { if(szFullPath[i]=='\\' || szFullPath[i]=='/') { i++; break; } } for(j=0 ;i<dwLen+1; i++, j++) { szName[j]=szFullPath[i]; if(szName[j]=='.') { szName[j]=0; break; } } return szName; } lf_str LF_GetDirFromPathA(lf_str szDir, lf_cstr szFullPath) { lf_dword dwLen=strlen(szFullPath); lf_long i=0; for(i=(lf_long)dwLen-1; i>=0; i--) { if(szFullPath[i]=='\\' || szFullPath[i]=='/') break; } strncpy(szDir, szFullPath, i+1); szDir[i+1]=0; return szDir; } lf_wstr LF_GetDirFromPathW(lf_wstr szDir, lf_cwstr szFullPath) { lf_dword dwLen=wcslen(szFullPath); lf_long i=0; for(i=(lf_long)dwLen-1; i>=0; i--) { if(szFullPath[i]=='\\' || szFullPath[i]=='/') break; } wcsncpy(szDir, szFullPath, i+1); szDir[i+1]=0; return szDir; } <file_sep>/tools/ListingGen/GameLister/GameLister.cpp #include <stdio.h> #include "GameLister.h" #include "resource.h" #define COPYSTRINGEX(out, in) {if(out){delete[]out;out=NULL;}if(in){out=new char[strlen(in)+1];if(out)memcpy(out, in, strlen(in)+1);}} #define GETTEXTEX(out, ctlid){hwndTemp=GetDlgItem(hwnd, ctlid);dwLen=GetWindowTextLength(hwndTemp);if(dwLen<1){out=NULL;}else{out=new char[dwLen+1];GetWindowText(hwndTemp, out, dwLen+1);}} static const char szModule[]="GameLister.dll"; static RECT g_rcWindow; typedef enum tagDLGSCREENS{ SCREEN_FINISHED=0, SCREEN_TITLEDESC, SCREEN_SYSREQ, SCREEN_SHIPPING, SCREEN_TERMS }DLGSCREENS; typedef struct tagDGLRESULT { int nResult; RECT rcWindow; }DLGRESULT, *LPDLGRESULT; // The function that acquires the lister. // CLister * ObtainLister() { return new CGameLister; } /////////////////////////////////////// // The callbacks for the dialog box. // /////////////////////////////////////// // Callback for the terms. // BOOL CALLBACK Terms(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { static CGameLister * lpLister=NULL; char * szShippingTerms=NULL; char * szFeedbackTerms=NULL; char * szWarrantyTerms=NULL; switch(uMsg) { case WM_INITDIALOG: MoveWindow( hwnd, g_rcWindow.left, g_rcWindow.top, g_rcWindow.right-g_rcWindow.left, g_rcWindow.bottom-g_rcWindow.top, TRUE); if(lpLister==NULL) { lpLister=(CGameLister*)lParam; SetDlgItemText(hwnd, IDC_TERMSHIP, "Shipping costs are actual PLUS handling, packaging, and materials fee."); SetDlgItemText(hwnd, IDC_TERMFEEDBACK, "I leave feedback upon feedback, that way I know if everything has gone smoothly and has been completed successfully as planned. Please keep in mind, if you do not let me know what has gone wrong I will not know and assume all is well, if you let me know before leaving a negative or a neutral feedback I will try to fix any and all problems that have occurred."); SetDlgItemText(hwnd, IDC_TERMWARRANTY, "This item is guaranteed not to be Dead-On-Arriaval (DOA)."); } else { SetDlgItemText(hwnd, IDC_TERMSHIP, lpLister->m_szShippingTerms); SetDlgItemText(hwnd, IDC_TERMFEEDBACK, lpLister->m_szFeedbackTerms); SetDlgItemText(hwnd, IDC_TERMWARRANTY, lpLister->m_szWarrantyTerms); } break; case WM_COMMAND: { switch(LOWORD(wParam)) { case IDC_PREV: //fall through. case IDC_NEXT: { HWND hwndTemp=NULL; DWORD dwLen=0; GETTEXTEX(szShippingTerms, IDC_TERMSHIP); GETTEXTEX(szFeedbackTerms, IDC_TERMFEEDBACK); GETTEXTEX(szWarrantyTerms, IDC_TERMWARRANTY); lpLister->SetShippingTerms(szShippingTerms); lpLister->SetFeedbackTerms(szFeedbackTerms); lpLister->SetWarrantyTerms(szWarrantyTerms); SAFE_DELETE_ARRAY(szShippingTerms); SAFE_DELETE_ARRAY(szFeedbackTerms); SAFE_DELETE_ARRAY(szWarrantyTerms); GetWindowRect(hwnd, &g_rcWindow); EndDialog(hwnd, LOWORD(wParam)); break; } default: break; } break; } case WM_CLOSE: EndDialog(hwnd, 0); break; default: return FALSE; } return TRUE; } // Callback to acquire shipping and payment info. // BOOL CALLBACK ShipPay(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { static CGameLister * lpLister=NULL; char * szShippingCost=NULL; char * szShippingInfo=NULL; char * szPaymentOptions=NULL; switch(uMsg) { case WM_INITDIALOG: MoveWindow( hwnd, g_rcWindow.left, g_rcWindow.top, g_rcWindow.right-g_rcWindow.left, g_rcWindow.bottom-g_rcWindow.top, TRUE); if(lpLister==NULL) { lpLister=(CGameLister*)lParam; SetDlgItemText(hwnd, IDC_COST, "ACTUAL plus handling, packaging, and materials fee"); SetDlgItemText(hwnd, IDC_SHIPINFO, "E-Mail me or use ebay's calculator if a shipping cost estimate is desired. Any USPS shipping options may be added at the cost of the buyer. I ship worldwide. Item usually ships business day after payment is recieved."); SetDlgItemText(hwnd, IDC_PAYOPTION, "I accept Paypal and US Money Order/Cashiers Check only. Payment must be in United States Dollars (USD), and should be sent within 10 days of the auction end."); } else { SetDlgItemText(hwnd, IDC_COST, lpLister->m_szShippingCost); SetDlgItemText(hwnd, IDC_SHIPINFO, lpLister->m_szShippingInfo); SetDlgItemText(hwnd, IDC_PAYOPTION, lpLister->m_szPaymentOptions); } break; case WM_COMMAND: { switch(LOWORD(wParam)) { case IDC_PREV: //fall through. case IDC_NEXT: { HWND hwndTemp=NULL; DWORD dwLen=0; GETTEXTEX(szShippingCost, IDC_COST); GETTEXTEX(szShippingInfo, IDC_SHIPINFO); GETTEXTEX(szPaymentOptions, IDC_PAYOPTION); lpLister->SetShippingInfo(szShippingCost, szShippingInfo); lpLister->SetPaymentOptions(szPaymentOptions); SAFE_DELETE_ARRAY(szShippingCost); SAFE_DELETE_ARRAY(szShippingInfo); SAFE_DELETE_ARRAY(szPaymentOptions); GetWindowRect(hwnd, &g_rcWindow); EndDialog(hwnd, LOWORD(wParam)); break; } default: break; } break; } case WM_CLOSE: EndDialog(hwnd, 0); break; default: return FALSE; } return TRUE; } // Callback to acquire system requirements. // BOOL CALLBACK SysRequire(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { static CGameLister * lpLister=NULL; char * szOS=NULL; char * szCPU=NULL; char * szRAM=NULL; char * szCD=NULL; char * szHDD=NULL; char * szVideo=NULL; char * szSound=NULL; char * szInput=NULL; char * szOther=NULL; char * szRecommended=NULL; switch(uMsg) { case WM_INITDIALOG: MoveWindow( hwnd, g_rcWindow.left, g_rcWindow.top, g_rcWindow.right-g_rcWindow.left, g_rcWindow.bottom-g_rcWindow.top, TRUE); if(lpLister==NULL) { lpLister=(CGameLister*)lParam; } else { //Attemp to replace the values. SetDlgItemText(hwnd, IDC_OS, lpLister->m_szOS); SetDlgItemText(hwnd, IDC_CPU, lpLister->m_szCPU); SetDlgItemText(hwnd, IDC_RAM, lpLister->m_szRAM); SetDlgItemText(hwnd, IDC_CD, lpLister->m_szCD); SetDlgItemText(hwnd, IDC_HDD, lpLister->m_szHDD); SetDlgItemText(hwnd, IDC_VIDEO, lpLister->m_szVideo); SetDlgItemText(hwnd, IDC_SOUND, lpLister->m_szSound); SetDlgItemText(hwnd, IDC_INPUT, lpLister->m_szInput); SetDlgItemText(hwnd, IDC_OTHER, lpLister->m_szOther); SetDlgItemText(hwnd, IDC_RECOMMENDED, lpLister->m_szRecommended); } break; case WM_COMMAND: { switch(LOWORD(wParam)) { case IDC_NEXT: //Fall through case IDC_PREV: { HWND hwndTemp=NULL; DWORD dwLen=0; GETTEXTEX(szOS, IDC_OS); GETTEXTEX(szCPU, IDC_CPU); GETTEXTEX(szRAM, IDC_RAM); GETTEXTEX(szCD, IDC_CD); GETTEXTEX(szHDD, IDC_HDD); GETTEXTEX(szVideo, IDC_VIDEO); GETTEXTEX(szSound, IDC_SOUND); GETTEXTEX(szInput, IDC_INPUT); GETTEXTEX(szOther, IDC_OTHER); GETTEXTEX(szRecommended, IDC_RECOMMENDED); lpLister->SetSystemRequirements( szOS, szCPU, szRAM, szCD, szHDD, szVideo, szSound, szInput, szOther, szRecommended); SAFE_DELETE_ARRAY(szOS); SAFE_DELETE_ARRAY(szCPU); SAFE_DELETE_ARRAY(szRAM); SAFE_DELETE_ARRAY(szCD); SAFE_DELETE_ARRAY(szHDD); SAFE_DELETE_ARRAY(szVideo); SAFE_DELETE_ARRAY(szSound); SAFE_DELETE_ARRAY(szInput); SAFE_DELETE_ARRAY(szOther); SAFE_DELETE_ARRAY(szRecommended); GetWindowRect(hwnd, &g_rcWindow); EndDialog(hwnd, LOWORD(wParam)); break; } } break; } case WM_CLOSE: EndDialog(hwnd, 0); break; default: return FALSE; } return TRUE; } // Callback to acquire title, type, and descriptions. // BOOL CALLBACK TitleDesc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { static CGameLister * lpLister=NULL; char * szCondition=NULL; switch(uMsg) { case WM_INITDIALOG: { MoveWindow( hwnd, g_rcWindow.left, g_rcWindow.top, g_rcWindow.right-g_rcWindow.left, g_rcWindow.bottom-g_rcWindow.top, TRUE); if(lpLister==NULL) { lpLister=(CGameLister*)lParam; } else { //Attempt to restore previous text. SetDlgItemText(hwnd, IDC_ITEMNAME, lpLister->m_szItemName); SetDlgItemText(hwnd, IDC_ITEMTYPE, lpLister->m_szItemType); SetDlgItemText(hwnd, IDC_DESC1, lpLister->m_szItemDesc1); SetDlgItemText(hwnd, IDC_DESC2, lpLister->m_szItemDesc2); SetDlgItemText(hwnd, IDC_CONDITION, lpLister->m_szItemCondition); } break; } case WM_COMMAND: { switch(LOWORD(wParam)) { case IDC_NEXT: { char * szTemp=NULL, * szTemp2=NULL; DWORD dwLen=0; HWND hwndTemp=NULL; //Get and set the item name and type. GETTEXTEX(szTemp, IDC_ITEMNAME); GETTEXTEX(szTemp2, IDC_ITEMTYPE); lpLister->SetItemName(szTemp, szTemp2); SAFE_DELETE_ARRAY(szTemp); SAFE_DELETE_ARRAY(szTemp2); //Get and set the item descriptions. GETTEXTEX(szTemp, IDC_DESC1); GETTEXTEX(szTemp2, IDC_DESC2); lpLister->SetItemDesc(szTemp, szTemp2); SAFE_DELETE_ARRAY(szTemp); SAFE_DELETE_ARRAY(szTemp2); GETTEXTEX(szCondition, IDC_CONDITION); lpLister->SetItemCondition(szCondition); SAFE_DELETE_ARRAY(szCondition); //Finish up the dialog and specify that next was set. GetWindowRect(hwnd, &g_rcWindow); EndDialog(hwnd, LOWORD(wParam)); break; } case IDC_PREV: EndDialog(hwnd, IDC_PREV); break; } return TRUE; } case WM_CLOSE: EndDialog(hwnd, 0); break; default: return FALSE; } return TRUE; } BOOL CGameLister::RunDialog(HWND hwndParent) { DLGSCREENS nScreen=SCREEN_TITLEDESC; int nResult=0; SetRect(&g_rcWindow, 0, 0, 609, 409); do { nResult=0; switch(nScreen) { case SCREEN_TITLEDESC: { nResult=DialogBoxParam( GetModuleHandle(szModule), MAKEINTRESOURCE(IDD_TITLEDESC), hwndParent, TitleDesc, (LPARAM)this); if(nResult==IDC_NEXT) { nScreen=SCREEN_SYSREQ; break; } else { nScreen=SCREEN_FINISHED; return FALSE; break; } break; } case SCREEN_SYSREQ: { nResult=DialogBoxParam( GetModuleHandle(szModule), MAKEINTRESOURCE(IDD_SYSREQ), hwndParent, SysRequire, (LPARAM)this); switch(nResult) { case IDC_PREV: nScreen=SCREEN_TITLEDESC; break; case IDC_NEXT: nScreen=SCREEN_SHIPPING; break; default: nScreen=SCREEN_FINISHED; return FALSE; break; } break; } case SCREEN_SHIPPING: { nResult=DialogBoxParam( GetModuleHandle(szModule), MAKEINTRESOURCE(IDD_SHIPPAY), hwndParent, ShipPay, (LPARAM)this); switch(nResult) { case IDC_PREV: nScreen=SCREEN_SYSREQ; break; case IDC_NEXT: nScreen=SCREEN_TERMS; break; default: nScreen=SCREEN_FINISHED; return FALSE; break; } break; } case SCREEN_TERMS: { nResult=DialogBoxParam( GetModuleHandle(szModule), MAKEINTRESOURCE(IDD_TERMS), hwndParent, Terms, (LPARAM)this); switch(nResult) { case IDC_PREV: nScreen=SCREEN_SHIPPING; break; case IDC_NEXT: nScreen=SCREEN_FINISHED; break; default: nScreen=SCREEN_FINISHED; return FALSE; break; } break; } default: nScreen=SCREEN_FINISHED; break; } }while(nScreen != SCREEN_FINISHED); return TRUE; } BOOL CGameLister::SaveListing(char szFilename[MAX_PATH]) { MessageBox(NULL, "This Template does not support the save feature!", "GameLister", MB_OK|MB_ICONERROR); return TRUE; } BOOL CGameLister::LoadListing(char szFilename[MAX_PATH]) { return FALSE; } BOOL CGameLister::CreateListing(char szFilename[MAX_PATH]) { FILE * fout=NULL; fout=fopen(szFilename, "w"); //Begin the table and print out the item name and type. fprintf(fout, "<table border=5 cellspacing=0>"); fprintf(fout, "<tr><th bgcolor=0xFFB0B0FF><font color=0x00000000>"); if(m_szItemName) fprintf(fout, "<h1>%s</h1>", m_szItemName); if(m_szItemType) fprintf(fout, "<h2>%s</h2>", m_szItemType); fprintf(fout, "</font></th></tr>"); //Print the item description. fprintf(fout, "<tr><td bgcolor=white>"); if(m_szItemDesc1) fprintf(fout, "<font color=black>%s</font>", m_szItemDesc1); if(m_szItemDesc2) fprintf(fout, "<p><font color=darkred>%s</font>", m_szItemDesc2); fprintf(fout, "</td></tr>"); //Print the condition of the item. if(m_szItemCondition) { fprintf(fout, "<tr><th bgcolor=orange><font color=black><big>Item Condition</big></font></th></tr>"); fprintf(fout, "<tr><td>%s</td></tr>", m_szItemCondition); } //Print the system requirements. fprintf(fout, "<tr><th bgcolor=orange>System Requirements</th></tr>"); fprintf(fout, "<tr><td><ul>"); if(m_szOS) fprintf(fout, "<li><b>OS:</b> %s.</li>", m_szOS); if(m_szCPU) fprintf(fout, "<li><b>CPU:</b> %s.</li>", m_szCPU); if(m_szRAM) fprintf(fout, "<li><b>RAM:</b> %s.</li>", m_szRAM); if(m_szCD) fprintf(fout, "<li><b>CD/DVD-ROM Speed:</b> %s.</li>", m_szCD); if(m_szHDD) fprintf(fout, "<li><b>Drive Space:</b> %s.</li>", m_szHDD); if(m_szVideo) fprintf(fout, "<li><b>Video:</b> %s.</li>", m_szVideo); if(m_szSound) fprintf(fout, "<li><b>Sound:</b> %s.</li>", m_szSound); if(m_szInput) fprintf(fout, "<li><b>Input:</b> %s.</li>", m_szInput); if(m_szOther) fprintf(fout, "<li><b>Other:</b> %s.</li>", m_szOther); fprintf(fout, "</ul></td></tr>"); if(m_szRecommended) { fprintf(fout, "<tr><th bgcolor=orange>Recommended</th></tr>"); fprintf(fout, "<tr><td>%s</td></tr>", m_szRecommended); } //Close the table fprintf(fout, "</table><p>"); //Start the shipping and payment table. fprintf(fout, "<table border=5 cellspacing=0>"); //Start the shipping information. fprintf(fout, "<tr><th bgcolor=black><font color=white>Shipping Information</font></th></tr><tr><td>"); if(m_szShippingCost) fprintf(fout, "Shipping is<big><b>%s</b></big>.", m_szShippingCost); if(m_szShippingInfo) fprintf(fout, " %s", m_szShippingInfo); fprintf(fout, "</td></tr>"); //Start the payment information. if(m_szPaymentOptions) fprintf(fout, "<tr><th bgcolor=black><font color=white>Payment Options</th></tr><tr><td>%s</td></tr>", m_szPaymentOptions); //Close the table. fprintf(fout, "</table><p>"); //Print the last table terms and conditions. fprintf(fout, "<table border=5 cellspacing=0><tr><th bgcolor=darkblue><font color=white>Terms and Conditions</font></th></tr>"); fprintf(fout, "<tr><td>"); if(m_szShippingTerms) fprintf(fout, "<b>Shipping:</b> %s<p>", m_szShippingTerms); if(m_szFeedbackTerms) fprintf(fout, "<b>Feedback:</b> %s<p>", m_szFeedbackTerms); if(m_szWarrantyTerms) fprintf(fout, "<b>Warranty:</b> %s<p>", m_szWarrantyTerms); fprintf(fout, "</td></tr></table>"); //We're done. Close the file. fclose(fout); return TRUE; } BOOL CGameLister::SetItemName(LPSTR szItemName, LPSTR szItemType) { COPYSTRINGEX(m_szItemName, szItemName); COPYSTRINGEX(m_szItemType, szItemType); return TRUE; } BOOL CGameLister::SetItemDesc(LPSTR szItemDesc1, LPSTR szItemDesc2) { COPYSTRINGEX(m_szItemDesc1, szItemDesc1); COPYSTRINGEX(m_szItemDesc2, szItemDesc2); return TRUE; } BOOL CGameLister::SetItemCondition(LPSTR szItemCondition) { COPYSTRINGEX(m_szItemCondition, szItemCondition); return TRUE; } BOOL CGameLister::SetSystemRequirements( LPSTR szOS, LPSTR szCPU, LPSTR szRAM, LPSTR szCD, LPSTR szHDD, LPSTR szVideo, LPSTR szSound, LPSTR szInput, LPSTR szOther, LPSTR szRecommended) { COPYSTRINGEX(m_szOS, szOS); COPYSTRINGEX(m_szCPU, szCPU); COPYSTRINGEX(m_szRAM, szRAM); COPYSTRINGEX(m_szCD, szCD); COPYSTRINGEX(m_szHDD, szHDD); COPYSTRINGEX(m_szVideo, szVideo); COPYSTRINGEX(m_szSound, szSound); COPYSTRINGEX(m_szInput, szInput); COPYSTRINGEX(m_szOther, szOther); COPYSTRINGEX(m_szRecommended, szRecommended); return TRUE; } BOOL CGameLister::SetShippingInfo(LPSTR szShippingCost, LPSTR szShippingInfo) { COPYSTRINGEX(m_szShippingCost, szShippingCost); COPYSTRINGEX(m_szShippingInfo, szShippingInfo); return TRUE; } BOOL CGameLister::SetPaymentOptions(LPSTR szPaymentOptions) { COPYSTRINGEX(m_szPaymentOptions, szPaymentOptions); return TRUE; } BOOL CGameLister::SetShippingTerms(LPSTR szShippingTerms) { COPYSTRINGEX(m_szShippingTerms, szShippingTerms); return TRUE; } BOOL CGameLister::SetFeedbackTerms(LPSTR szFeedbackTerms) { COPYSTRINGEX(m_szFeedbackTerms, szFeedbackTerms); return TRUE; } BOOL CGameLister::SetWarrantyTerms(LPSTR szWarrantyTerms) { COPYSTRINGEX(m_szWarrantyTerms, szWarrantyTerms); return TRUE; }<file_sep>/games/Legacy-Engine/Scrapped/UnitTests/lc_demo/lc_loadfp.c #include <windows.h> #include "..\..\lc_sys\src\lc_sys.h" /* Legacy Console Function Pointers. */ LPCON_CREATE pCon_Create=NULL; LPCON_DELETE pCon_Delete=NULL; LPCON_SENDMESSAGE pCon_SendMessage=NULL; LPCON_SENDERRORMSG pCon_SendErrorMsg=NULL; LPCON_SENDCOMMAND pCon_SendCommand=NULL; LPCON_SETCURRENT pCon_SetCurrent=NULL; LPCON_ERASECURRENT pCon_EraseCurrent=NULL; LPCON_CLEAR pCon_Clear=NULL; LPCON_GETNUMENTRIES pCon_GetNumEntries=NULL; LPCON_GETENTRY pCon_GetEntry=NULL; LPCON_REGISTERCMD pCon_RegisterCmd=NULL; LPCON_ONCHAR pCon_OnChar=NULL; LPCON_ATTACHCVARLIST pCon_AttachCVarList=NULL; LPCON_CREATEDLGBOX pCon_CreateDlgBox=NULL; LPCCPARSE_GETPARAM pCCParse_GetParam=NULL; LPCCPARSE_GETFLOAT pCCParse_GetFloat=NULL; LPCCPARSE_GETINT pCCParse_GetInt=NULL; LPCCPARSE_CHECKPARAM pCCParse_CheckParam=NULL; LPCVAR_CREATELIST pCVar_CreateList=NULL; LPCVAR_DELETELIST pCVar_DeleteList=NULL; LPCVAR_SET pCVar_Set=NULL; LPCVAR_SETVALUE pCVar_SetValue=NULL; LPCVAR_GET pCVar_Get=NULL; LPCVAR_GETVALUE pCVar_GetValue=NULL; LPCVAR_GETCVAR pCVar_GetCVar=NULL; LPCVAR_GETFIRSTCVAR pCVar_GetFirstCVar=NULL; LPCVAR_ADDDEF pCVar_AddDef=NULL; LPCVAR_GETDEF pCVar_GetDef=NULL; int ObtainFunctions(HMODULE hDllFile) { /* If we fail to get one function, the function will return false. */ #define GET_FUNC(name) {p##name=(void*)GetProcAddress(hDllFile, #name); \ if(p##name==NULL)return 0;} GET_FUNC(Con_Create); GET_FUNC(Con_Delete); GET_FUNC(Con_SendMessage); GET_FUNC(Con_SendErrorMsg); GET_FUNC(Con_SendCommand); GET_FUNC(Con_SetCurrent); GET_FUNC(Con_EraseCurrent); GET_FUNC(Con_Clear); GET_FUNC(Con_GetNumEntries); GET_FUNC(Con_GetEntry); GET_FUNC(Con_RegisterCmd); GET_FUNC(Con_OnChar); GET_FUNC(Con_AttachCVarList); GET_FUNC(Con_CreateDlgBox); GET_FUNC(CCParse_GetParam); GET_FUNC(CCParse_GetFloat); GET_FUNC(CCParse_GetInt); GET_FUNC(CCParse_CheckParam); GET_FUNC(CVar_CreateList); GET_FUNC(CVar_DeleteList); GET_FUNC(CVar_Set); GET_FUNC(CVar_SetValue); GET_FUNC(CVar_Get); GET_FUNC(CVar_GetValue); GET_FUNC(CVar_GetCVar); GET_FUNC(CVar_GetFirstCVar); GET_FUNC(CVar_AddDef); GET_FUNC(CVar_GetDef); /* We return true if we got all the functions. */ return 1; } <file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/lv_font2.h #ifndef __LV_FONT2_H__ #define __LV_FONT2_H__ #include <d3d9.h> #include "common.h" #ifdef __cplusplus extern "C"{ #endif /*__cplusplus*/ typedef void* HLVFONT2; typedef struct _LVFONT_DIMS{ L_byte nCharWidth; L_byte nCharHeight; L_bool bD3DXFont; L_dword dwD3DColor; }LVFONT_DIMS; HLVFONT2 Font_Create2( IDirect3DDevice9* lpDevice, char* szFont, L_byte dwWidth, L_byte dwHeight, L_bool bD3DXFont, L_byte dwWidthInFile, L_byte dwHeightInFile, L_dword dwD3DColor); L_bool Font_Delete2(HLVFONT2 hFont); L_bool Font_GetDims(HLVFONT2 hFont, LVFONT_DIMS* pDims); L_bool Font_Begin2(HLVFONT2 hFont); L_bool Font_End2(HLVFONT2 hFont); L_bool Font_DrawString2(HLVFONT2 hFont, char* szString, L_long x, L_long y); L_bool Font_Validate2(HLVFONT2 hFont); L_bool Font_Invalidate2(HLVFONT2 hFont); #ifdef __cplusplus } #endif /*__cplusplus*/ #endif /*__LV_FONT2_H__*/<file_sep>/games/Legacy-Engine/Source/common/lg_malloc.h #ifndef __LG_MALLOC_H__ #define __LG_MALLOC_H__ typedef unsigned int lgm_size_t; #ifdef __cplusplus extern "C" void* LG_Malloc(lgm_size_t size); extern "C" void LG_Free(void* p); extern "C" void LG_MemDbgOutput(); #else !__cplusplus void* LG_Malloc(lgm_size_t size); void LG_Free(void* p); void LG_MemDbOutput(); #endif __cplusplus #endif __LG_MALLOC_H__<file_sep>/tools/MConvert/README.md MConvert ======== Convert currency from one system to another.<file_sep>/Misc/Prinsc/Readme.txt Printc: by Beem Software Code to scroll print out onto the screen. Use at will programmers.<file_sep>/games/Legacy-Engine/Scrapped/old/le_test.h #ifndef __LE_TEST_H__ #define __LE_TEST_H__ #include <dinput.h> #include <al/al.h> #include "le_3dbase.h" /* #include "le_camera.h" #include "le_sys.h" #include "lm_d3d.h" #include "lt_sys.h" #include "lg_sys.h" */ class CLJack: public CLBase3DEntity { private: //const DIMOUSESTATE2* m_pMouse; //CLICommand* m_pCmds; CLSkel* m_pWalk; CLSkel* m_pStand; CLSkel* m_pJump; NewtonJoint* m_UpVec; public: virtual void Initialize(ML_VEC3* v3Pos); virtual void ProcessAI(); //virtual void Render(); }; class CLBlaineEnt: public CLBase3DEntity { private: CLSkel* m_pWalk; CLSkel* m_pStand; lg_dword m_nLastAIUpdate; lg_float m_fRotation; ALuint m_Snd; ALuint m_SndBuffer; NewtonJoint* m_UpVec; public: virtual void Initialize(ML_VEC3* v3Pos); virtual void ProcessAI(); }; class CLMonaEnt: public CLBase3DEntity { public: virtual void Initialize(ML_VEC3* v3Pos); virtual void ProcessAI(); }; class CLBarrelEnt: public CLBase3DEntity { public: virtual void Initialize(ML_VEC3* v3Pos); virtual void ProcessAI(); }; #endif __LE_TEST_H__<file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/common/common.c /*************************************************************** File: common.c Copyright (c) 2006, <NAME> Purpose: All of the types and functions that are universal are contained in common.c and common.h. These two files are used not just for Legacy 3D, but for lc_sys.dll and la_sys.dll. ***************************************************************/ #include "common.h" #include <direct.h> #include <stdio.h> #ifdef _DEBUG #include <stdio.h> #include <stdarg.h> void __stdcall OutputDebugStringA(const char* lpOutputString); #endif /*_DEBUG*/ /**************************************** Legacy Engine replacement functions. ****************************************/ void* L_fopen(const char* filename, const char* mode) { return fopen(filename, mode); } int L_fclose(void* stream) { return fclose(stream); } L_uint L_fread(void* buffer, L_uint size, L_uint count, void* stream) { return fread(buffer, size, count, stream); } L_uint L_fwrite(const void* buffer, L_uint size, L_uint count, void* stream) { return fwrite(buffer, size, count, stream); } L_long L_ftell(void* stream) { return ftell(stream); } int L_fseek(void* stream, long offset, int origin) { return fseek(stream, offset, origin); } /********************************************** L_mkdir() Makes a directory, including subdirectory. **********************************************/ int L_mkdir(const char* szDir) { L_dword dwLen=L_strlen(szDir); L_dword i=0; /* We use a cheat here so we can temporarily change the string. */ char* szTemp=(char*)szDir; char c=0; if(!szDir) return L_false; /* The idea here is to go through the string, find each subdirectory, then create a directory till we get to the final folder. */ for(i=0; i<=dwLen; i++) { c=szDir[i]; if(c=='\\' || c=='/') { szTemp[i]=0; _mkdir(szDir); szTemp[i]=c; } } return L_true; } char* L_getfilepath(char* szDir, const char* szFilename) { L_dword dwLen=L_strlen(szFilename); L_dword i=0; for(i=dwLen-1; i>=0; i--) { if(szFilename[i]=='\\' || szFilename[i]=='/') break; } L_strncpy(szDir, szFilename, i+2); return szDir; } char* L_strncat(char* szDest, const char* szSrc, unsigned long nMax) { L_dword dwLen=L_strlen(szDest); L_strncpy(&szDest[dwLen], szSrc, nMax-dwLen); return szDest; } /******************************************************************* L_CopyString() Copies a string, up till a 0 is reached or the max is reached whichever comes first. Appends a null terminating character at the end of the string. Returns the number of characters copied. *******************************************************************/ unsigned long L_strncpy(char* szOut, const char* szIn, unsigned long nMax) { unsigned long i=0; if((szOut==L_null) || (szIn==L_null)) return 0; for(i=0; szIn[i]!=0, i<nMax; i++) { szOut[i]=szIn[i]; } if(i<nMax) szOut[i]=0; else szOut[nMax-1]=0; return i; } /********************************************** L_strnlen() Returns the length of the specified string. **********************************************/ unsigned long L_strlen(const char* string) { unsigned long count=0; while (string[count]) count++; return count; } /************************************************************ L_strnicmp() Compare two strings without regard to case of a certain number of characters long. Returns 0 if not the same, otherwize returns nonzero. This function is not used in exactly the same way that the _strnicmp stdlib function is used. ************************************************************/ int L_strnicmp(char* szOne, char* szTwo, unsigned long nNum) { unsigned long i=0; unsigned long nLen1=0, nLen2=0; char c1=0, c2=0; if((szOne==L_null) || (szTwo==L_null)) return 0; nLen1=L_strlen(szOne); nLen2=L_strlen(szTwo); if(nNum>0) { if(nLen1>nNum) nLen1=nNum; if(nLen2>nNum) nLen2=nNum; } if(nLen1!=nLen2) return 0; for(i=0; i<nLen1; i++) { if(szOne[i]!=szTwo[i]) { c1=szOne[i]; c2=szTwo[i]; if( (c1>='a') && (c1<='z') ) c1 -= ('a'-'A'); if( (c2>='a') && (c2<='z') ) c2 -= ('a'-'A'); if(c1==c2) continue; return 0; } } return 1; } /***************************************************** L_axtol() Converts a hexidecimal string to a unsigned long. *****************************************************/ unsigned long L_axtol(char* string) { int i=0; char c=0; unsigned long nHexValue=0; /*int sign=1;*/ /*sign=(string[0]=='-')?-1:1;*/ /* Make sure it is actually a hex string. */ if(!L_strnicmp("0X", string, 2)/* && !L_StringICompare("-0X", string, 3)*/) return 0x00000000l; /* The idea behind this is keep adding to value, until we reach an invalid character, or the end of the string. */ for(i=2/*(sign>0)?2:3*/, nHexValue=0x00000000; string[i]!=0; i++) { c=string[i]; if(c>='0' && c<='9') nHexValue=(nHexValue<<4)|(c-'0'); else if(c>='a' && c<='f') nHexValue=(nHexValue<<4)|(c-'a'+10); else if(c>='A' && c<='F') nHexValue=(nHexValue<<4)|(c-'A'+10); else break; } return /*sign**/nHexValue; } /******************************************* L_atof() Converts a string to a floating point. *******************************************/ float L_atof(char* string) { /* Check for a hexidecimal value. */ int sign=1; int i=0; float fValue=0.0f; signed long total=0, decimal=0; double value=0.0f; char c=0; /* Check for sign. */ sign=(string[0]=='-')?-1:1; for(i=(sign>0)?0:1, total=0, value=0.0f, decimal=-1; ;i++) { c=string[i]; if(c=='.') { decimal=total; continue; } if(c<'0' || c>'9') break; value=value*10+(c-'0'); total++; } if (decimal==-1) return (float)(value*sign); while(total>decimal) { value /= 10; total--; } return(float)(value*sign); } /************************************************************* L_atovalue() Converts a string to a floating point, but checks to see if the value is a hexidecimal. *************************************************************/ float L_atovalue(char* string) { /* Check to see if it is a hex. */ if((string[0]=='0') && (string[1]=='x' || string[1]=='X')) return (float)L_axtol(string); /* Figure its a float*/ return (float)L_atof(string); } /**************************************** L_atol() Converts a string to a long. *****************************************/ signed long L_atol(char* string) { signed long lValue=0; char c=0; int i=0; int sign=1; sign=(string[0]=='-')?-1:1; for(i=(sign>0)?0:1, lValue=0; ;i++) { c=string[i]; if(c<'0' || c>'9') break; lValue=lValue*10+c-'0'; } return sign*lValue; } /********************************************* Debug_printf() In debug mode with print a string to the debugger window. *********************************************/ void Debug_printf(char* format, ...) { #ifdef _DEBUG char szOutput[1024]; va_list arglist=L_null; /* Allocate memory for output, we free when we exit the function. */ if(!format) return; /* We use _vsnprintf so we can print arguments, and also so we can limit the number of characters, put to the output buffer by the max string length allowed in the console. */ va_start(arglist, format); _vsnprintf(szOutput, 1023, format, arglist); va_end(arglist); OutputDebugStringA(szOutput); #endif /* _DEBUG */ } <file_sep>/games/Legacy-Engine/Source/common/lg_malloc.cpp /* lg_malloc.cpp - Memory management for the game. */ #include <malloc.h> #include "lg_malloc.h" #ifdef _DEBUG #include <windows.h> #include <stdio.h> extern "C" unsigned long g_nBlocks=0; #endif _DEBUG extern "C" void* LG_Malloc(lgm_size_t size) { #ifdef _DEBUG g_nBlocks++; //#define CHECK_SIZE 264 #ifdef CHECK_SIZE if(size==CHECK_SIZE) OutputDebugString(":::BYTES ALLOCATED:::\n"); #endif #endif _DEBUG return malloc(size); } extern "C" void LG_Free(void* p) { #ifdef _DEBUG g_nBlocks--; #endif _DEBUG free(p); } extern "C" void LG_MemDbgOutput() { #ifdef _DEBUG char szTemp[128]; sprintf(szTemp, "%d allocations left.\n", g_nBlocks); OutputDebugString(szTemp); #endif _DEBUG } #ifdef USE_LG_NEW void* operator new (lgm_size_t size) { return LG_Malloc(size); } void operator delete (void* p) { LG_Free(p); } #endif USE_LG_NEW <file_sep>/tools/MConvert/Source/MConvert.h #ifndef _MCONVERT_H_ #define _MCONVERT_H_ #define MAX_NAMELEN 255 #define MAX_CODELEN 3 #define MAX_ENTRIES 12 //This must change class ExData { public: int GetConversionInfo(); char countryName[MAX_ENTRIES][MAX_NAMELEN]; char countryCode[MAX_ENTRIES][MAX_CODELEN]; double exchangeRate[MAX_ENTRIES]; int numentries; }; #endif<file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/lg_cmd.c /************************************************************** File: lg_cmd.c Copyright (c) 2006, <NAME> Purpose: Contains the command function for the console. It also contains the function that registers the console commands, and various functions that are called by console commands. **************************************************************/ #include "common.h" #include <stdio.h> #include <io.h> #include "lv_init.h" #include "lv_reset.h" #include "lg_cmd.h" #include "lg_sys.h" #include <lf_sys.h> #include "lv_test.h" #define MAX_T_LEN (1024) int LGC_DisplayDeviceCaps(char* szDeviceName, D3DCAPS9* lpcaps); int LGC_Dir(const char* szParams); int LGC_Extract(const char* szParams); /************************************************************** LGC_RegConCmds() Called from LG_Init(), it registers all of the console commands so that when a user types one it it will actually get processed. As sort of a standard the value of all console commands start with CONF_ then are appended with the function name. **************************************************************/ int LGC_RegConCmds(HLCONSOLE hConsole) { #define REG_CMD(name) Con_RegisterCmd(hConsole, #name, CONF_##name) REG_CMD(QUIT); REG_CMD(VRESTART); REG_CMD(DIR); REG_CMD(EXTRACT); REG_CMD(D3DCAPS); REG_CMD(VIDMEM); //REG_CMD(HARDVRESTART); REG_CMD(TEXFORMATS); REG_CMD(LOADMODEL); REG_CMD(VERSION); return 1; } /************************************************************* LGC_ConCommand() This is the command function for the console, by design the pExtra parameter is a pointe to the game structure. All of the console commands are managed in this function, except for the built in commands. *************************************************************/ int LGC_ConCommand(unsigned long nCommand, const char* szParams, HLCONSOLE hConsole, void* pExtra) { int nResult=1; L3DGame* lpGame=(L3DGame*)pExtra; /* This function isn't tested, so I don't know if it works or not. */ switch(nCommand) { case CONF_VERSION: { Err_PrintVersion(); break; } case CONF_LOADMODEL: { char szFilename[1024]; if(CCParse_GetParam(szFilename, szParams, 1)) LVT_LoadModel(szFilename); else Err_Printf("Usage: LOADMODEL filename$"); break; } case CONF_TEXFORMATS: LV_SupportedTexFormats( lpGame->m_cvars, lpGame->v.m_lpD3D, lpGame->v.m_nAdapterID, lpGame->v.m_nDeviceType, lpGame->v.m_nBackBufferFormat); break; case CONF_VIDMEM: { L_dword nMem=IDirect3DDevice9_GetAvailableTextureMem(lpGame->v.m_lpDevice); Err_Printf("Estimated available video memory: %iMB", nMem/1024/1024); break; } case CONF_D3DCAPS: { D3DCAPS9 d3dcaps; D3DADAPTER_IDENTIFIER9 adi; memset(&d3dcaps, 0, sizeof(D3DCAPS9)); nResult=IDirect3DDevice9_GetDeviceCaps(lpGame->v.m_lpDevice, &d3dcaps); if(L_failed(nResult)) { Err_PrintDX("IDirect3DDevice9::GetDeviceCaps", nResult); return 0; } memset(&adi, 0, sizeof(adi)); lpGame->v.m_lpD3D->lpVtbl->GetAdapterIdentifier( lpGame->v.m_lpD3D, lpGame->v.m_nAdapterID, 0, &adi); LGC_DisplayDeviceCaps(adi.Description, &d3dcaps); nResult=1; break; } case CONF_EXTRACT: LGC_Extract(szParams); break; case CONF_DIR: LGC_Dir(szParams); break; /* case CONF_HARDVRESTART: // Should save game, and shut it down. LV_Shutdown(lpGame); LV_Init(lpGame); // Should load saved game. break; */ case CONF_VRESTART: LV_Restart(lpGame); break; case CONF_CVARUPDATE: { /* Means the game console told us a cvar was updated, so we may need to change a setting. */ char szCVarName[MAX_T_LEN]; if(!CCParse_GetParam(szCVarName, szParams, 1)) { Err_Printf("Could not get name of cvar to update."); break; } /* Check to see if a sampler or render state cvar has been changed if so, call LV_SetStates.*/ if( L_strnicmp(szCVarName, FILTER_MODE, 0) || L_strnicmp(szCVarName, FILTER_MAXANISOTROPY, 0) || L_strnicmp(szCVarName, "v_DebugWireframe", 0)) { /* Break if the device is not initialized, this happens because the set command gets called when we are loading config.cfg, and the device hasn't been initialized yet. */ if(!lpGame->v.m_lpDevice) break; else { Err_Printf("Calling LV_SetStates..."); if(!LV_SetStates(lpGame)) Err_Printf("An error occured while setting the sampler and render states."); } } break; } case CONF_QUIT: CVar_Set(lpGame->m_cvars, "l_ShouldQuit", "TRUE"); break; default: nResult=0; break; } return nResult; } /********************************************************* LGC_Extract() Routine for the EXTRACT console command, note that extract is designed to extract files from lpks, if a output file is specified the file will be renamed if not it will maintain it's original path and name. Also note that if extract is called on a file that is not in an LPK it will still "extract" the in that it will read the file, and write the new file. **********************************************************/ int LGC_Extract(const char* szParams) { LF_FILE2 fin=L_null; LF_FILE2 fout=L_null; L_byte nByte=0; L_dword i=0; char szFile[MAX_T_LEN]; char szOutputFile[MAX_T_LEN]; char szOutputDir[MAX_T_LEN]; if(!CCParse_GetParam(szFile, szParams, 1)) { Err_Printf("Usage: EXTRACT filename$ [outputfile$]"); return 1; } if(!CCParse_GetParam(szOutputFile, szParams, 2)) { _snprintf(szOutputFile, MAX_T_LEN-1, "%s", szFile); } /* Make sure the output directory exists. */ for(i=L_strlen(szOutputFile); i>=0; i--) { if(szOutputFile[i]=='\\') { L_strncpy(szOutputDir, szFile, i+1); break; } if(i==0) { L_strncpy(szOutputDir, ".\\", MAX_T_LEN-1); break; } } L_mkdir(szOutputDir); Err_Printf("Extracting \"%s\" to \"%s\"...", szFile, szOutputFile); /* We have to open with the LF_ACCESS_MEMORY flag, in case our output file is a file with the exact same name, this happens if we call extract on a file, that is not in an archive. */ fin=File_Open(szFile, 0, LF_ACCESS_READ|LF_ACCESS_MEMORY, LFCREATE_OPEN_EXISTING); if(!fin) { Err_Printf("Could not open \"%s\".", szFile); return 1; } fout=File_Open(szOutputFile, 0, LF_ACCESS_WRITE, LFCREATE_CREATE_NEW); if(!fout) { File_Close(fin); Err_Printf("Could not open \"%s\" for writing.", szOutputFile); return 1; } /* This is one way to copy a file, it isn't the fastest though. */ while(File_Read(fin, 1, &nByte)) { File_Write(fout, 1, &nByte); } File_Close(fout); File_Close(fin); Err_Printf("Finnished extracting \"%s\"", szFile); return 1; } /*************************************************** LGC_Dir() && LGC_Files() Functions that display all of the files in the search path. LGC_Dir is the master function, and will first show all files in archives, and then LGC_Files goes through all the files on the disk. ***************************************************/ int LGC_Files(char* szPath, char* szLimit) { long Handle=0; struct _finddata_t data; char szDir[MAX_T_LEN]; L_bool bLimit=L_false; szDir[0]=0; bLimit=L_strlen(szLimit); memset(&data, 0, sizeof(data)); _snprintf(szDir, MAX_T_LEN-1, "%s*.*", szPath); Handle=_findfirst(szDir, &data); if(Handle==-1) return L_false; do { if(L_CHECK_FLAG(data.attrib, _A_SUBDIR)) { if(L_strnicmp("..", data.name, 0) || (L_strnicmp(".", data.name, 0))) continue; _snprintf(szDir, MAX_T_LEN-1, "%s%s\\", szPath, data.name); LGC_Files(szDir, szLimit); } else { _snprintf(szDir, MAX_T_LEN-1, "%s%s", szPath+2, data.name); if(bLimit) { if(L_strnicmp(szLimit, szDir, L_strlen(szLimit))) Err_Printf(" \"%s\", DISK", szDir); } else Err_Printf(" \"%s\", DISK", szDir); } } while(_findnext(Handle, &data)!=-1); _findclose(Handle); return L_true; } int LGC_Dir(const char* szParams) { char szLimit[MAX_T_LEN]; szLimit[0]=0; CCParse_GetParam(szLimit, szParams, 1); Err_Printf("Directory of \"%s\"", LF_GetDir(L_null, 0)); //Err_Printf("Files found in archives:"); LF_ShowPaths(szLimit, Err_Printf); //Err_Printf("Files found on disk:"); LGC_Files(".\\", szLimit); return 1; } /***************************************************************** LGC_DisplayDeviceCaps() Called by the console command D3DCAPS, this dumps all of the D3DCAPS9 information to the console. *****************************************************************/ int LGC_DisplayDeviceCaps(char* szDeviceName, D3DCAPS9* lpcaps) { D3DCAPS9 d3dcaps=*lpcaps; char szDeviceType[4]; L_result nResult=0; if(!lpcaps) return 0; #define CAPFLAG(a, b) Err_Printf(" "#b"=%s", (L_CHECK_FLAG(d3dcaps.a, b)?"YES":"NO")) switch(d3dcaps.DeviceType) { case D3DDEVTYPE_HAL: L_strncpy(szDeviceType, "HAL", 4); break; case D3DDEVTYPE_REF: L_strncpy(szDeviceType, "REF", 4); break; case D3DDEVTYPE_SW: L_strncpy(szDeviceType, "SW", 4); break; } Err_Printf("\"%s\" (%s) Capabilities:", szDeviceName, szDeviceType); Err_Printf(" Adapter Ordinal: %i", d3dcaps.AdapterOrdinal); //Err_Printf(" Caps: %s", L_CHECK_FLAG(d3dcaps.Caps, D3DCAPS_READ_SCANLINE)?"D3DCAPS_READ_SCANLINE":""); Err_Printf("Driver Caps:"); CAPFLAG(Caps, D3DCAPS_READ_SCANLINE); Err_Printf("Driver Caps 2:"); CAPFLAG(Caps2, D3DCAPS2_CANAUTOGENMIPMAP), CAPFLAG(Caps2, D3DCAPS2_CANCALIBRATEGAMMA), CAPFLAG(Caps2, D3DCAPS2_CANMANAGERESOURCE), CAPFLAG(Caps2, D3DCAPS2_DYNAMICTEXTURES), CAPFLAG(Caps2, D3DCAPS2_FULLSCREENGAMMA), Err_Printf("Driver Caps 3:"); CAPFLAG(Caps2, D3DCAPS2_RESERVED); CAPFLAG(Caps3, D3DCAPS3_ALPHA_FULLSCREEN_FLIP_OR_DISCARD); CAPFLAG(Caps3, D3DCAPS3_COPY_TO_VIDMEM); CAPFLAG(Caps3, D3DCAPS3_COPY_TO_SYSTEMMEM); CAPFLAG(Caps3, D3DCAPS3_LINEAR_TO_SRGB_PRESENTATION); CAPFLAG(Caps3, D3DCAPS3_RESERVED); Err_Printf("Available Presentation Intervals:"); CAPFLAG(PresentationIntervals, D3DPRESENT_INTERVAL_IMMEDIATE); CAPFLAG(PresentationIntervals, D3DPRESENT_INTERVAL_ONE); CAPFLAG(PresentationIntervals, D3DPRESENT_INTERVAL_TWO); CAPFLAG(PresentationIntervals, D3DPRESENT_INTERVAL_THREE); CAPFLAG(PresentationIntervals, D3DPRESENT_INTERVAL_FOUR); Err_Printf("Cursor Caps:"); CAPFLAG(CursorCaps, D3DCURSORCAPS_COLOR); CAPFLAG(CursorCaps, D3DCURSORCAPS_LOWRES); Err_Printf("Device Caps:"); CAPFLAG(DevCaps, D3DDEVCAPS_CANBLTSYSTONONLOCAL); CAPFLAG(DevCaps, D3DDEVCAPS_CANRENDERAFTERFLIP); CAPFLAG(DevCaps, D3DDEVCAPS_DRAWPRIMITIVES2); CAPFLAG(DevCaps, D3DDEVCAPS_DRAWPRIMITIVES2EX); CAPFLAG(DevCaps, D3DDEVCAPS_DRAWPRIMTLVERTEX); CAPFLAG(DevCaps, D3DDEVCAPS_EXECUTESYSTEMMEMORY); CAPFLAG(DevCaps, D3DDEVCAPS_EXECUTEVIDEOMEMORY); CAPFLAG(DevCaps, D3DDEVCAPS_HWRASTERIZATION); CAPFLAG(DevCaps, D3DDEVCAPS_HWTRANSFORMANDLIGHT); CAPFLAG(DevCaps, D3DDEVCAPS_NPATCHES); CAPFLAG(DevCaps, D3DDEVCAPS_PUREDEVICE); CAPFLAG(DevCaps, D3DDEVCAPS_QUINTICRTPATCHES); CAPFLAG(DevCaps, D3DDEVCAPS_RTPATCHES); CAPFLAG(DevCaps, D3DDEVCAPS_RTPATCHHANDLEZERO); CAPFLAG(DevCaps, D3DDEVCAPS_SEPARATETEXTUREMEMORIES); CAPFLAG(DevCaps, D3DDEVCAPS_TEXTURENONLOCALVIDMEM); CAPFLAG(DevCaps, D3DDEVCAPS_TEXTURESYSTEMMEMORY); CAPFLAG(DevCaps, D3DDEVCAPS_TEXTUREVIDEOMEMORY); CAPFLAG(DevCaps, D3DDEVCAPS_TLVERTEXSYSTEMMEMORY); CAPFLAG(DevCaps, D3DDEVCAPS_TLVERTEXVIDEOMEMORY); Err_Printf("Miscellaneous Driver Primitive Caps:"); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_MASKZ); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_CULLNONE); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_CULLCW); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_CULLCCW); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_COLORWRITEENABLE); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_CLIPPLANESCALEDPOINTS); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_CLIPTLVERTS); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_TSSARGTEMP); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_BLENDOP); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_NULLREFERENCE); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_INDEPENDENTWRITEMASKS); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_PERSTAGECONSTANT); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_FOGANDSPECULARALPHA); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_SEPARATEALPHABLEND); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_MRTINDEPENDENTBITDEPTHS); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_MRTPOSTPIXELSHADERBLENDING); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_FOGVERTEXCLAMPED); Err_Printf("Raster Drawing Caps:"); CAPFLAG(RasterCaps, D3DPRASTERCAPS_ANISOTROPY); CAPFLAG(RasterCaps, D3DPRASTERCAPS_COLORPERSPECTIVE); CAPFLAG(RasterCaps, D3DPRASTERCAPS_DITHER); CAPFLAG(RasterCaps, D3DPRASTERCAPS_DEPTHBIAS); CAPFLAG(RasterCaps, D3DPRASTERCAPS_FOGRANGE); CAPFLAG(RasterCaps, D3DPRASTERCAPS_FOGTABLE); CAPFLAG(RasterCaps, D3DPRASTERCAPS_FOGVERTEX); CAPFLAG(RasterCaps, D3DPRASTERCAPS_MIPMAPLODBIAS); CAPFLAG(RasterCaps, D3DPRASTERCAPS_MULTISAMPLE_TOGGLE); CAPFLAG(RasterCaps, D3DPRASTERCAPS_SCISSORTEST); CAPFLAG(RasterCaps, D3DPRASTERCAPS_SLOPESCALEDEPTHBIAS); CAPFLAG(RasterCaps, D3DPRASTERCAPS_WBUFFER); CAPFLAG(RasterCaps, D3DPRASTERCAPS_WFOG); CAPFLAG(RasterCaps, D3DPRASTERCAPS_ZBUFFERLESSHSR); CAPFLAG(RasterCaps, D3DPRASTERCAPS_ZFOG); CAPFLAG(RasterCaps, D3DPRASTERCAPS_ZTEST); Err_Printf("Z-Buffer Comparison Caps:"); CAPFLAG(ZCmpCaps, D3DPCMPCAPS_ALWAYS); CAPFLAG(ZCmpCaps, D3DPCMPCAPS_EQUAL); CAPFLAG(ZCmpCaps, D3DPCMPCAPS_GREATER); CAPFLAG(ZCmpCaps, D3DPCMPCAPS_GREATEREQUAL); CAPFLAG(ZCmpCaps, D3DPCMPCAPS_LESS); CAPFLAG(ZCmpCaps, D3DPCMPCAPS_LESSEQUAL); CAPFLAG(ZCmpCaps, D3DPCMPCAPS_NEVER); CAPFLAG(ZCmpCaps, D3DPCMPCAPS_NOTEQUAL); Err_Printf("Source Blend Caps:"); CAPFLAG(SrcBlendCaps, D3DPBLENDCAPS_BLENDFACTOR); CAPFLAG(SrcBlendCaps, D3DPBLENDCAPS_BOTHINVSRCALPHA); CAPFLAG(SrcBlendCaps, D3DPBLENDCAPS_BOTHSRCALPHA); CAPFLAG(SrcBlendCaps, D3DPBLENDCAPS_DESTALPHA); CAPFLAG(SrcBlendCaps, D3DPBLENDCAPS_DESTCOLOR); CAPFLAG(SrcBlendCaps, D3DPBLENDCAPS_INVDESTALPHA); CAPFLAG(SrcBlendCaps, D3DPBLENDCAPS_INVDESTCOLOR); CAPFLAG(SrcBlendCaps, D3DPBLENDCAPS_INVSRCALPHA); CAPFLAG(SrcBlendCaps, D3DPBLENDCAPS_INVSRCCOLOR); CAPFLAG(SrcBlendCaps, D3DPBLENDCAPS_ONE); CAPFLAG(SrcBlendCaps, D3DPBLENDCAPS_SRCALPHA); CAPFLAG(SrcBlendCaps, D3DPBLENDCAPS_SRCALPHASAT); CAPFLAG(SrcBlendCaps, D3DPBLENDCAPS_SRCCOLOR); CAPFLAG(SrcBlendCaps, D3DPBLENDCAPS_ZERO); Err_Printf("Dest Blend Caps:"); CAPFLAG(DestBlendCaps, D3DPBLENDCAPS_BLENDFACTOR); CAPFLAG(DestBlendCaps, D3DPBLENDCAPS_BOTHINVSRCALPHA); CAPFLAG(DestBlendCaps, D3DPBLENDCAPS_BOTHSRCALPHA); CAPFLAG(DestBlendCaps, D3DPBLENDCAPS_DESTALPHA); CAPFLAG(DestBlendCaps, D3DPBLENDCAPS_DESTCOLOR); CAPFLAG(DestBlendCaps, D3DPBLENDCAPS_INVDESTALPHA); CAPFLAG(DestBlendCaps, D3DPBLENDCAPS_INVDESTCOLOR); CAPFLAG(DestBlendCaps, D3DPBLENDCAPS_INVSRCALPHA); CAPFLAG(DestBlendCaps, D3DPBLENDCAPS_INVSRCCOLOR); CAPFLAG(DestBlendCaps, D3DPBLENDCAPS_ONE); CAPFLAG(DestBlendCaps, D3DPBLENDCAPS_SRCALPHA); CAPFLAG(DestBlendCaps, D3DPBLENDCAPS_SRCALPHASAT); CAPFLAG(DestBlendCaps, D3DPBLENDCAPS_SRCCOLOR); CAPFLAG(DestBlendCaps, D3DPBLENDCAPS_ZERO); Err_Printf("Alpha Test Comparison Caps:"); CAPFLAG(AlphaCmpCaps, D3DPCMPCAPS_ALWAYS); CAPFLAG(AlphaCmpCaps, D3DPCMPCAPS_EQUAL); CAPFLAG(AlphaCmpCaps, D3DPCMPCAPS_GREATER); CAPFLAG(AlphaCmpCaps, D3DPCMPCAPS_GREATEREQUAL); CAPFLAG(AlphaCmpCaps, D3DPCMPCAPS_LESS); CAPFLAG(AlphaCmpCaps, D3DPCMPCAPS_LESSEQUAL); CAPFLAG(AlphaCmpCaps, D3DPCMPCAPS_NEVER); CAPFLAG(AlphaCmpCaps, D3DPCMPCAPS_NOTEQUAL); Err_Printf("Shading Operations Caps:"); CAPFLAG(ShadeCaps, D3DPSHADECAPS_ALPHAGOURAUDBLEND); CAPFLAG(ShadeCaps, D3DPSHADECAPS_COLORGOURAUDRGB); CAPFLAG(ShadeCaps, D3DPSHADECAPS_FOGGOURAUD); CAPFLAG(ShadeCaps, D3DPSHADECAPS_SPECULARGOURAUDRGB); Err_Printf("Texture Mapping Caps:"); CAPFLAG(TextureCaps, D3DPTEXTURECAPS_ALPHA); CAPFLAG(TextureCaps, D3DPTEXTURECAPS_ALPHAPALETTE); CAPFLAG(TextureCaps, D3DPTEXTURECAPS_CUBEMAP); CAPFLAG(TextureCaps, D3DPTEXTURECAPS_CUBEMAP_POW2); CAPFLAG(TextureCaps, D3DPTEXTURECAPS_MIPCUBEMAP); CAPFLAG(TextureCaps, D3DPTEXTURECAPS_MIPMAP); CAPFLAG(TextureCaps, D3DPTEXTURECAPS_MIPVOLUMEMAP); CAPFLAG(TextureCaps, D3DPTEXTURECAPS_NONPOW2CONDITIONAL); CAPFLAG(TextureCaps, D3DPTEXTURECAPS_NOPROJECTEDBUMPENV); CAPFLAG(TextureCaps, D3DPTEXTURECAPS_PERSPECTIVE); CAPFLAG(TextureCaps, D3DPTEXTURECAPS_POW2); CAPFLAG(TextureCaps, D3DPTEXTURECAPS_PROJECTED); CAPFLAG(TextureCaps, D3DPTEXTURECAPS_SQUAREONLY); CAPFLAG(TextureCaps, D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE); CAPFLAG(TextureCaps, D3DPTEXTURECAPS_VOLUMEMAP); CAPFLAG(TextureCaps, D3DPTEXTURECAPS_VOLUMEMAP_POW2); Err_Printf("Texture Filter Caps:"); CAPFLAG(TextureFilterCaps, D3DPTFILTERCAPS_MINFPOINT); CAPFLAG(TextureFilterCaps, D3DPTFILTERCAPS_MINFLINEAR); CAPFLAG(TextureFilterCaps, D3DPTFILTERCAPS_MINFANISOTROPIC); CAPFLAG(TextureFilterCaps, D3DPTFILTERCAPS_MINFPYRAMIDALQUAD); CAPFLAG(TextureFilterCaps, D3DPTFILTERCAPS_MINFGAUSSIANQUAD); CAPFLAG(TextureFilterCaps, D3DPTFILTERCAPS_MIPFPOINT); CAPFLAG(TextureFilterCaps, D3DPTFILTERCAPS_MIPFLINEAR); CAPFLAG(TextureFilterCaps, D3DPTFILTERCAPS_MAGFPOINT); CAPFLAG(TextureFilterCaps, D3DPTFILTERCAPS_MAGFLINEAR); CAPFLAG(TextureFilterCaps, D3DPTFILTERCAPS_MAGFANISOTROPIC); CAPFLAG(TextureFilterCaps, D3DPTFILTERCAPS_MAGFPYRAMIDALQUAD); CAPFLAG(TextureFilterCaps, D3DPTFILTERCAPS_MAGFGAUSSIANQUAD); Err_Printf("Cube Texture Filter Caps:"); CAPFLAG(CubeTextureFilterCaps, D3DPTFILTERCAPS_MINFPOINT); CAPFLAG(CubeTextureFilterCaps, D3DPTFILTERCAPS_MINFLINEAR); CAPFLAG(CubeTextureFilterCaps, D3DPTFILTERCAPS_MINFANISOTROPIC); CAPFLAG(CubeTextureFilterCaps, D3DPTFILTERCAPS_MINFPYRAMIDALQUAD); CAPFLAG(CubeTextureFilterCaps, D3DPTFILTERCAPS_MINFGAUSSIANQUAD); CAPFLAG(CubeTextureFilterCaps, D3DPTFILTERCAPS_MIPFPOINT); CAPFLAG(CubeTextureFilterCaps, D3DPTFILTERCAPS_MIPFLINEAR); CAPFLAG(CubeTextureFilterCaps, D3DPTFILTERCAPS_MAGFPOINT); CAPFLAG(CubeTextureFilterCaps, D3DPTFILTERCAPS_MAGFLINEAR); CAPFLAG(CubeTextureFilterCaps, D3DPTFILTERCAPS_MAGFANISOTROPIC); CAPFLAG(CubeTextureFilterCaps, D3DPTFILTERCAPS_MAGFPYRAMIDALQUAD); CAPFLAG(CubeTextureFilterCaps, D3DPTFILTERCAPS_MAGFGAUSSIANQUAD); Err_Printf("Volume Texture Filter Caps:"); CAPFLAG(VolumeTextureFilterCaps, D3DPTFILTERCAPS_MINFPOINT); CAPFLAG(VolumeTextureFilterCaps, D3DPTFILTERCAPS_MINFLINEAR); CAPFLAG(VolumeTextureFilterCaps, D3DPTFILTERCAPS_MINFANISOTROPIC); CAPFLAG(VolumeTextureFilterCaps, D3DPTFILTERCAPS_MINFPYRAMIDALQUAD); CAPFLAG(VolumeTextureFilterCaps, D3DPTFILTERCAPS_MINFGAUSSIANQUAD); CAPFLAG(VolumeTextureFilterCaps, D3DPTFILTERCAPS_MIPFPOINT); CAPFLAG(VolumeTextureFilterCaps, D3DPTFILTERCAPS_MIPFLINEAR); CAPFLAG(VolumeTextureFilterCaps, D3DPTFILTERCAPS_MAGFPOINT); CAPFLAG(VolumeTextureFilterCaps, D3DPTFILTERCAPS_MAGFLINEAR); CAPFLAG(VolumeTextureFilterCaps, D3DPTFILTERCAPS_MAGFANISOTROPIC); CAPFLAG(VolumeTextureFilterCaps, D3DPTFILTERCAPS_MAGFPYRAMIDALQUAD); CAPFLAG(VolumeTextureFilterCaps, D3DPTFILTERCAPS_MAGFGAUSSIANQUAD); Err_Printf("Texture Address Caps:"); CAPFLAG(TextureAddressCaps, D3DPTADDRESSCAPS_BORDER); CAPFLAG(TextureAddressCaps, D3DPTADDRESSCAPS_CLAMP); CAPFLAG(TextureAddressCaps, D3DPTADDRESSCAPS_INDEPENDENTUV); CAPFLAG(TextureAddressCaps, D3DPTADDRESSCAPS_MIRROR); CAPFLAG(TextureAddressCaps, D3DPTADDRESSCAPS_MIRRORONCE); CAPFLAG(TextureAddressCaps, D3DPTADDRESSCAPS_WRAP); Err_Printf("Volume Texture Address Caps:"); CAPFLAG(VolumeTextureAddressCaps, D3DPTADDRESSCAPS_BORDER); CAPFLAG(VolumeTextureAddressCaps, D3DPTADDRESSCAPS_CLAMP); CAPFLAG(VolumeTextureAddressCaps, D3DPTADDRESSCAPS_INDEPENDENTUV); CAPFLAG(VolumeTextureAddressCaps, D3DPTADDRESSCAPS_MIRROR); CAPFLAG(VolumeTextureAddressCaps, D3DPTADDRESSCAPS_MIRRORONCE); CAPFLAG(VolumeTextureAddressCaps, D3DPTADDRESSCAPS_WRAP); Err_Printf("Line Caps:"); CAPFLAG(LineCaps, D3DLINECAPS_ALPHACMP); CAPFLAG(LineCaps, D3DLINECAPS_ANTIALIAS); CAPFLAG(LineCaps, D3DLINECAPS_BLEND); CAPFLAG(LineCaps, D3DLINECAPS_FOG); CAPFLAG(LineCaps, D3DLINECAPS_TEXTURE); CAPFLAG(LineCaps, D3DLINECAPS_ZTEST); Err_Printf("Device Limits:"); Err_Printf(" Max Texture Width: %i", d3dcaps.MaxTextureWidth); Err_Printf(" Max Texture Height: %i", d3dcaps.MaxTextureHeight); Err_Printf(" Max Volume Extent: %i", d3dcaps.MaxVolumeExtent); Err_Printf(" Max Texture Repeat: %i", d3dcaps.MaxTextureRepeat); Err_Printf(" Max Texture Aspect Ratio: %i", d3dcaps.MaxTextureAspectRatio); Err_Printf(" Max Anisotropy: %i", d3dcaps.MaxAnisotropy); Err_Printf(" Max W-Based Depth Value: %f", d3dcaps.MaxVertexW); Err_Printf(" Guard Band Left: %f", d3dcaps.GuardBandLeft); Err_Printf(" Guard Band Top: %f", d3dcaps.GuardBandTop); Err_Printf(" Gaurd Band Right: %f", d3dcaps.GuardBandRight); Err_Printf(" Guard Band Bottom: %f", d3dcaps.GuardBandBottom); Err_Printf(" Extents Adjust: %f", d3dcaps.ExtentsAdjust); Err_Printf("Stencil Caps:"); CAPFLAG(StencilCaps, D3DSTENCILCAPS_KEEP); CAPFLAG(StencilCaps, D3DSTENCILCAPS_ZERO); CAPFLAG(StencilCaps, D3DSTENCILCAPS_REPLACE); CAPFLAG(StencilCaps, D3DSTENCILCAPS_INCRSAT); CAPFLAG(StencilCaps, D3DSTENCILCAPS_DECRSAT); CAPFLAG(StencilCaps, D3DSTENCILCAPS_INVERT); CAPFLAG(StencilCaps, D3DSTENCILCAPS_INCR); CAPFLAG(StencilCaps, D3DSTENCILCAPS_DECR); CAPFLAG(StencilCaps, D3DSTENCILCAPS_TWOSIDED); Err_Printf("FVF Caps:"); CAPFLAG(FVFCaps, D3DFVFCAPS_DONOTSTRIPELEMENTS); CAPFLAG(FVFCaps, D3DFVFCAPS_PSIZE); CAPFLAG(FVFCaps, D3DFVFCAPS_TEXCOORDCOUNTMASK); Err_Printf("Texture Operation Caps:"); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_ADD); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_ADDSIGNED); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_ADDSIGNED2X); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_ADDSMOOTH); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_BLENDCURRENTALPHA); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_BLENDDIFFUSEALPHA); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_BLENDFACTORALPHA); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_BLENDTEXTUREALPHA); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_BLENDTEXTUREALPHAPM); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_BUMPENVMAP); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_BUMPENVMAPLUMINANCE); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_DISABLE); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_DOTPRODUCT3); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_LERP); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_MODULATE); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_MODULATE2X); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_MODULATE4X); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_MODULATEALPHA_ADDCOLOR); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_MODULATECOLOR_ADDALPHA); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_MODULATEINVALPHA_ADDCOLOR); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_MODULATEINVCOLOR_ADDALPHA); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_MULTIPLYADD); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_PREMODULATE); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_SELECTARG1); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_SELECTARG2); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_SUBTRACT); Err_Printf("Multi-Texture Limits:"); Err_Printf(" Max Texture Blend Stages: %i", d3dcaps.MaxTextureBlendStages); Err_Printf(" Max Simultaneous Textures: %i", d3dcaps.MaxSimultaneousTextures); Err_Printf("Vertex Processing Caps:"); CAPFLAG(VertexProcessingCaps, D3DVTXPCAPS_DIRECTIONALLIGHTS); CAPFLAG(VertexProcessingCaps, D3DVTXPCAPS_LOCALVIEWER); CAPFLAG(VertexProcessingCaps, D3DVTXPCAPS_MATERIALSOURCE7); CAPFLAG(VertexProcessingCaps, D3DVTXPCAPS_NO_TEXGEN_NONLOCALVIEWER); CAPFLAG(VertexProcessingCaps, D3DVTXPCAPS_POSITIONALLIGHTS); CAPFLAG(VertexProcessingCaps, D3DVTXPCAPS_TEXGEN); CAPFLAG(VertexProcessingCaps, D3DVTXPCAPS_TEXGEN_SPHEREMAP); CAPFLAG(VertexProcessingCaps, D3DVTXPCAPS_TWEENING); Err_Printf("Device Limits:"); Err_Printf(" Max Active Lights: %i", d3dcaps.MaxActiveLights); Err_Printf(" Max User Clip Planes: %i", d3dcaps.MaxUserClipPlanes); Err_Printf(" Max Vertex Blend Matrices: %i", d3dcaps.MaxVertexBlendMatrices); Err_Printf(" Max Vertex Blend Matrix Index: %i", d3dcaps.MaxVertexBlendMatrixIndex); Err_Printf(" Max Point Size: %f", d3dcaps.MaxPointSize); Err_Printf(" Max Primitive Count: %i", d3dcaps.MaxPrimitiveCount); Err_Printf(" Max Vertex Index: %i", d3dcaps.MaxVertexIndex); Err_Printf(" Max Streams: %i", d3dcaps.MaxStreams); Err_Printf(" Max Stream Stride: %i", d3dcaps.MaxStreamStride); Err_Printf(" Vertex Shader Version: 0x%04X 0x%04X", HIWORD(d3dcaps.VertexShaderVersion), LOWORD(d3dcaps.VertexShaderVersion)); Err_Printf(" Max Vertex Shader Const: %i", d3dcaps.MaxVertexShaderConst); Err_Printf(" Pixel Shader Version: 0x%04X 0x%04X", HIWORD(d3dcaps.PixelShaderVersion), LOWORD(d3dcaps.PixelShaderVersion)); Err_Printf(" Pixel Shader 1x Max Value: %f", d3dcaps.PixelShader1xMaxValue); Err_Printf("Device Caps 2:"); CAPFLAG(DevCaps2, D3DDEVCAPS2_ADAPTIVETESSRTPATCH); CAPFLAG(DevCaps2, D3DDEVCAPS2_ADAPTIVETESSNPATCH); CAPFLAG(DevCaps2, D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES); CAPFLAG(DevCaps2, D3DDEVCAPS2_DMAPNPATCH); CAPFLAG(DevCaps2, D3DDEVCAPS2_PRESAMPLEDDMAPNPATCH); CAPFLAG(DevCaps2, D3DDEVCAPS2_STREAMOFFSET); CAPFLAG(DevCaps2, D3DDEVCAPS2_VERTEXELEMENTSCANSHARESTREAMOFFSET); Err_Printf("Device Limits:"); Err_Printf(" Max Npatch Tessellation Level: %f", d3dcaps.MaxNpatchTessellationLevel); //Err_Printf(" Min Antialiased Line Width: %i", d3dcaps.MinAntialiasedLineWidth); //Err_Printf(" Max Antialiased Line Width: %i", d3dcaps.MaxAntialiasedLineWidth); Err_Printf(" Master Adapter Ordinal: %i", d3dcaps.MasterAdapterOrdinal); Err_Printf(" Adapter Ordinal In Group: %i", d3dcaps.AdapterOrdinalInGroup); Err_Printf(" Number Of Adapters In Group: %i", d3dcaps.NumberOfAdaptersInGroup); Err_Printf("Vertex Data Bytes:"); CAPFLAG(DeclTypes, D3DDTCAPS_UBYTE4); CAPFLAG(DeclTypes, D3DDTCAPS_UBYTE4N); CAPFLAG(DeclTypes, D3DDTCAPS_SHORT2N); CAPFLAG(DeclTypes, D3DDTCAPS_SHORT4N); CAPFLAG(DeclTypes, D3DDTCAPS_USHORT2N); CAPFLAG(DeclTypes, D3DDTCAPS_USHORT4N); CAPFLAG(DeclTypes, D3DDTCAPS_UDEC3); CAPFLAG(DeclTypes, D3DDTCAPS_DEC3N); CAPFLAG(DeclTypes, D3DDTCAPS_FLOAT16_2); CAPFLAG(DeclTypes, D3DDTCAPS_FLOAT16_4); Err_Printf("Device Limits:"); Err_Printf(" Num Simultaneous Render Targets: %i", d3dcaps.NumSimultaneousRTs); Err_Printf("StretchRect Filter Caps:"); CAPFLAG(StretchRectFilterCaps, D3DPTFILTERCAPS_MINFPOINT); CAPFLAG(StretchRectFilterCaps, D3DPTFILTERCAPS_MAGFPOINT); CAPFLAG(StretchRectFilterCaps, D3DPTFILTERCAPS_MINFLINEAR); CAPFLAG(StretchRectFilterCaps, D3DPTFILTERCAPS_MAGFLINEAR); Err_Printf("Vertex Shader 2.0 Extended Caps:"); CAPFLAG(VS20Caps.Caps, D3DVS20CAPS_PREDICATION); Err_Printf(" Dynamic Flow Control Depth: %i", d3dcaps.VS20Caps.DynamicFlowControlDepth); Err_Printf(" Num Temps: %i", d3dcaps.VS20Caps.NumTemps); Err_Printf(" Static Flow Control Depth: %i", d3dcaps.VS20Caps.StaticFlowControlDepth); Err_Printf("Pixel Shader 2.0 Extended Caps:"); CAPFLAG(PS20Caps.Caps, D3DPS20CAPS_ARBITRARYSWIZZLE); CAPFLAG(PS20Caps.Caps, D3DPS20CAPS_GRADIENTINSTRUCTIONS); CAPFLAG(PS20Caps.Caps, D3DPS20CAPS_PREDICATION); CAPFLAG(PS20Caps.Caps, D3DPS20CAPS_NODEPENDENTREADLIMIT); CAPFLAG(PS20Caps.Caps, D3DPS20CAPS_NOTEXINSTRUCTIONLIMIT); Err_Printf(" Dynamic Flow Control Depth: %i", d3dcaps.PS20Caps.DynamicFlowControlDepth); Err_Printf(" Num Temps: %i", d3dcaps.PS20Caps.NumTemps); Err_Printf(" Static Flow Control Depth: %i", d3dcaps.PS20Caps.StaticFlowControlDepth); Err_Printf(" Num Instruction Slots: %i", d3dcaps.PS20Caps.NumInstructionSlots); Err_Printf("Vertex Texture Filter Caps:"); CAPFLAG(VertexTextureFilterCaps, D3DPTFILTERCAPS_MINFPOINT); CAPFLAG(VertexTextureFilterCaps, D3DPTFILTERCAPS_MINFLINEAR); CAPFLAG(VertexTextureFilterCaps, D3DPTFILTERCAPS_MINFANISOTROPIC); CAPFLAG(VertexTextureFilterCaps, D3DPTFILTERCAPS_MINFPYRAMIDALQUAD); CAPFLAG(VertexTextureFilterCaps, D3DPTFILTERCAPS_MINFGAUSSIANQUAD); CAPFLAG(VertexTextureFilterCaps, D3DPTFILTERCAPS_MIPFPOINT); CAPFLAG(VertexTextureFilterCaps, D3DPTFILTERCAPS_MIPFLINEAR); CAPFLAG(VertexTextureFilterCaps, D3DPTFILTERCAPS_MAGFPOINT); CAPFLAG(VertexTextureFilterCaps, D3DPTFILTERCAPS_MAGFLINEAR); CAPFLAG(VertexTextureFilterCaps, D3DPTFILTERCAPS_MAGFANISOTROPIC); CAPFLAG(VertexTextureFilterCaps, D3DPTFILTERCAPS_MAGFPYRAMIDALQUAD); CAPFLAG(VertexTextureFilterCaps, D3DPTFILTERCAPS_MAGFGAUSSIANQUAD); Err_Printf("Device Limits:"); Err_Printf(" Max Vertex Shader Instructions Executed: %i", d3dcaps.MaxVShaderInstructionsExecuted); Err_Printf(" Max Pixel Shader Instructions Executed: %i", d3dcaps.MaxPShaderInstructionsExecuted); Err_Printf(" Max Vertex Shader 3.0 Instruction Slots: %i", d3dcaps.MaxVertexShader30InstructionSlots); Err_Printf(" Max Pixel Shader 3.0 Instruction Slots: %i", d3dcaps.MaxPixelShader30InstructionSlots); return 1; }<file_sep>/games/Legacy-Engine/Scrapped/tools/Texview2/res/resource.h //{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by Texview2.rc // #define IDD_ABOUTBOX 100 #define IDR_MAINFRAME 128 #define IDR_TEXVIETYPE 129 #define IDC_VERSION 1000 #define ID_VIEW_LINEARFILTER 32773 #define ID_VIEW_POINTFILTER 32774 #define ID_VIEW_ALPHACHANNEL 32775 #define ID_VIEW_IMAGE 32776 #define ID_VIEW_BLACKBG 32777 #define ID_TOOLS_REGISTERFILETYPES 32778 #define ID_VIEW_SIZE 0x0000FF01 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_3D_CONTROLS 1 #define _APS_NEXT_RESOURCE_VALUE 134 #define _APS_NEXT_COMMAND_VALUE 32779 #define _APS_NEXT_CONTROL_VALUE 1001 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif <file_sep>/games/Explor2002/Source/Game/DirectMidi.cpp // DirectMidi.cpp: implementation of the CDirectMidi class. //Copyright <NAME>, 2000 //Last updated October 12, 2000 //This code is adapted from the DirectMusic Tutorial 1 that //shipped with the DirectX 7.0a SDK. What I've done is //encapsulate it in a class, fix the numerous typos, and //tidy it up. //To use this, your game must be multithreaded. In Visual C++ //6.0, go to the Project menu, select Settings, select the C++ //tab, select Code Generation from the pulldown edit box, //then select Multithreaded from the Use Run-time Library //pull-down edit box. //Include dxguid.lib in the linker settings. #include <direct.h> //for _getcwd #include "DirectMidi.h" //DirectMusic needs wide characters - here's a conversion macro #define MULTI_TO_WIDE( x,y ) MultiByteToWideChar(CP_ACP,\ MB_PRECOMPOSED,y,-1,x,_MAX_PATH); CDirectMidi::CDirectMidi(){ //constructor //default values for member variables m_bInitialized=FALSE; //uninitialized m_pPerf=NULL; //performance m_pLoader=NULL; //loader m_pMIDIseg=NULL; //midi segment m_pSegState=NULL; //segment state //start DirectMusic MIDI player if(FAILED(CoInitialize(NULL)))return; //init COM if(FAILED(CreatePerformance()))return; //create performance if(FAILED(m_pPerf->Init(NULL,NULL,NULL)))return; //init it if(FAILED(m_pPerf->AddPort(NULL)))return; //add default port if(FAILED(CreateLoader()))return; //create MIDIloader //OK, we succeeded m_bInitialized=TRUE; } CDirectMidi::~CDirectMidi(){ //destructor if(!m_bInitialized)return; //bail if not ready Stop(); //stop music (paranoia) //unload instruments m_pMIDIseg->SetParam(GUID_Unload,-1,0,0,(void*)m_pPerf); //release the segment. m_pMIDIseg->Release(); //close down and release the performance object. m_pPerf->CloseDown(); m_pPerf->Release(); // release the loader object. m_pLoader->Release(); //release COM CoUninitialize(); } BOOL CDirectMidi::CreatePerformance(void){ //create performance return SUCCEEDED(CoCreateInstance( CLSID_DirectMusicPerformance,NULL,CLSCTX_INPROC, IID_IDirectMusicPerformance2,(void**)&m_pPerf)); } BOOL CDirectMidi::CreateLoader(void){ return SUCCEEDED(CoCreateInstance(CLSID_DirectMusicLoader, NULL,CLSCTX_INPROC,IID_IDirectMusicLoader, (void**)&m_pLoader)); } BOOL CDirectMidi::LoadMIDISegment(char* szMidiFileName){ //load MIDI segment DMUS_OBJECTDESC ObjDesc; //get current folder char szDir[_MAX_PATH]; if(_getcwd(szDir,_MAX_PATH)==NULL)return FALSE; //make wide version of current folder WCHAR wszDir[_MAX_PATH]; MULTI_TO_WIDE(wszDir,szDir); //make wide version of midi file name WCHAR wszMidiFileName[_MAX_PATH]; MULTI_TO_WIDE(wszMidiFileName,szMidiFileName); //send loader to current folder HRESULT hr=m_pLoader->SetSearchDirectory( GUID_DirectMusicAllTypes,wszDir,FALSE); if(FAILED(hr))return FALSE; //bail if failed //describe segment object type ObjDesc.guidClass=CLSID_DirectMusicSegment; ObjDesc.dwSize=sizeof(DMUS_OBJECTDESC); wcscpy(ObjDesc.wszFileName,wszMidiFileName); ObjDesc.dwValidData=DMUS_OBJ_CLASS|DMUS_OBJ_FILENAME; m_pLoader->GetObject(&ObjDesc, IID_IDirectMusicSegment2,(void**)&m_pMIDIseg); m_pMIDIseg->SetParam(GUID_StandardMIDIFile, -1,0,0,(void*)m_pPerf); m_pMIDIseg->SetParam(GUID_Download,-1,0,0,(void*)m_pPerf); return TRUE; } void CDirectMidi::Load(char* filename){ //load file if(!m_bInitialized)return; //bail if not ready //release old music if(m_pMIDIseg){ //if there is old music, flush it m_pMIDIseg->Release(); m_pMIDIseg=NULL; } //load the new LoadMIDISegment(filename); } void CDirectMidi::Play(){ //play loaded music if(!m_bInitialized)return; //bail if not ready if(m_pMIDIseg&&m_pPerf){ //no bad pointers m_pMIDIseg->SetRepeats(0xFFFFFFFF); //repeat lotsa times m_pPerf->PlaySegment(m_pMIDIseg,0,0,&m_pSegState); //play } } void CDirectMidi::Stop(){ //stop playing music if(!m_bInitialized)return; //bail if not ready if(m_pPerf)m_pPerf->Stop(NULL,NULL,0,0); //stop } BOOL CDirectMidi::IsPlaying(){ //TRUE if playing if(!m_bInitialized)return FALSE; //bail if not ready if(m_pPerf) //if loaded return m_pPerf->IsPlaying(m_pMIDIseg,NULL)==S_OK; else return FALSE; } void CDirectMidi::Toggle(){ //toggle stop/play if(!m_bInitialized)return; //bail if not ready if(m_pPerf) //if loaded if(IsPlaying())Stop(); else Play(); //toggle } <file_sep>/games/Legacy-Engine/Source/lf_sys2/lf_err.c #include <string.h> #include <stdarg.h> #include <stdlib.h> #include <stdio.h> #include "lf_sys2.h" LF_ERR_LEVEL g_nErrLevel=ERR_LEVEL_NOTICE; void (__cdecl*g_pfnErrPrint)(lf_cwstr szFormat)=LF_NULL; void LF_SetErrLevel(LF_ERR_LEVEL nLevel) { g_nErrLevel=nLevel; } void LF_SYS2_EXPORTS LF_SetErrPrintFn(void (__cdecl*pfn)(lf_cwstr szFormat)) { g_pfnErrPrint=pfn; } #define LF_ERR_MAX_OUTPUT 511 void LF_ErrPrintW(lf_cwstr szFormat, LF_ERR_LEVEL nErrLevel, ...) { lf_wchar_t szOutput[LF_ERR_MAX_OUTPUT+1]; va_list arglist=LF_NULL; //Don't print the message if the current error level //is greater than the error level of the message. if((nErrLevel<g_nErrLevel) || !g_pfnErrPrint) return; va_start(arglist, nErrLevel); //_vsnwprintf(szOutput, 1022, szFormat, arglist); _vsnwprintf_s(szOutput, LF_ERR_MAX_OUTPUT, LF_ERR_MAX_OUTPUT, szFormat, arglist); va_end(arglist); szOutput[wcslen(szOutput)]=0; g_pfnErrPrint(szOutput); } void LF_ErrPrintA(lf_cstr szFormat, LF_ERR_LEVEL nErrLevel, ...) { lf_char szOutput[LF_ERR_MAX_OUTPUT+1]; lf_wchar szOutputW[LF_ERR_MAX_OUTPUT+1]; va_list arglist=LF_NULL; //Don't print the message if the current error level //is greater than the error level of the message. if((nErrLevel<g_nErrLevel) || !g_pfnErrPrint) return; va_start(arglist, nErrLevel); _vsnprintf_s(szOutput, LF_ERR_MAX_OUTPUT, LF_ERR_MAX_OUTPUT, szFormat, arglist); va_end(arglist); szOutput[strlen(szOutput)]=0; mbstowcs(szOutputW, szOutput, LF_ERR_MAX_OUTPUT); g_pfnErrPrint(szOutputW); } void __cdecl LF_DefaultErrPrint(lf_cwstr szFormat) { lf_char szText[LF_ERR_MAX_OUTPUT+1]; wcstombs(szText, szFormat, LF_ERR_MAX_OUTPUT); printf("%s\n", szText); }<file_sep>/tools/img_lib/img_lib2/img_lib/img_lib_types.h #ifndef __IMG_LIB_TYPES_H__ #define __IMG_LIB_TYPES_H__ /* Some types that we will use.*/ typedef unsigned char img_byte; typedef signed char img_sbyte; typedef unsigned short img_word; typedef signed short img_short; typedef unsigned long img_dword; typedef signed long img_long; typedef int img_bool; typedef unsigned int img_uint; typedef signed int img_int; typedef int img_void; typedef char img_char; typedef unsigned short img_wchar; /* A few definitions. */ #define IMG_TRUE (1) #define IMG_FALSE (0) /* A definition for the function type (all functions will be __cdecl, but if for some reason that needed to be changed only the following line needs to be changed. This is not ANSI C, but to make this file ANSI C compatible IMG_FUNC need only to be changed to a blank defintion.*/ #define IMG_FUNC __cdecl #ifdef __cplusplus #define IMG_NULL (0) #else /*__cplusplus*/ #define IMG_NULL ((void*)0) #endif /*__cplusplus*/ /* IMG_SAFE_FREE safely frees memory allocated using malloc (or calloc, etc). IMG_CLAMP insures that the value of v1 is within min and max.*/ #define IMG_SAFE_FREE(p) if(p){free(p);p=IMG_NULL;} #define IMG_CLAMP(v1, min, max) ( (v1)>(max)?(max):(v1)<(min)?(min):(v1) ) /* HIMG is the handle for our image. Obtained by a call to IMG_Open or IMG_OpenCallbacks*/ typedef void* HIMG; /* The seeking parametres for the seek function.*/ #define IMG_SEEK_CUR 1 #define IMG_SEEK_END 2 #define IMG_SEEK_SET 0 /* The IMGORIENT enumeration describes where the upper-left pixel is located in the file.*/ typedef enum _IMGORIENT{ IMGORIENT_BOTTOMLEFT=0, IMGORIENT_BOTTOMRIGHT=1, IMGORIENT_TOPLEFT=2, IMGORIENT_TOPRIGHT=3, IMGORIENT_FORCE_DWORD=0xFFFFFFFF }IMGORIENT; /* The IMGFMT enumeration describes the images pixel format.*/ typedef enum _IMGFMT{ IMGFMT_UNKNOWN=0, IMGFMT_NONE=0, IMGFMT_PALETTE=1, IMGFMT_X1R5G5B5=2, IMGFMT_R5G6B5=3, IMGFMT_R8G8B8=4, IMGFMT_A8R8G8B8=5, IMGFMT_R8G8B8A8=6, IMGFMT_B8G8R8=7, IMGFMT_FORCE_DWORD=0xFFFFFFFF }IMGFMT; /* The IMGFILTER enumeration is used to determine how an images pixels are filter when calls IMG_CopyBits involve shrinking and stretching.*/ typedef enum _IMGFILTER{ IMGFILTER_NONE=0, IMGFILTER_POINT=0, IMGFILTER_LINEAR=1, IMGFILTER_FORCE_DWORD=0xFFFFFFFF }IMGFILTER; /* The IMG_RECT structure is used to describe the rectangluar area that is being copied from on the source image.*/ typedef struct _IMG_RECT{ img_long left; img_long top; img_long right; img_long bottom; }IMG_RECT, *PIMG_RECT; /* The IMG_DES_RECT structure describes the destination images format (size, pixel format, and area to be copied to) for the IMG_CopyBits function.*/ typedef struct _IMG_DEST_RECT{ img_dword nWidth; img_dword nHeight; img_dword nPitch; IMGFMT nFormat; IMGORIENT nOrient; IMG_RECT rcCopy; img_void* pImage; }IMG_DEST_RECT, *PIMG_DEST_RECT; /* IMG_DESC is used when retreiving information about the image stored in an HIMG.*/ typedef struct _IMG_DESC{ img_word Width; img_word Height; img_byte BitsPerPixel; IMGFMT Format; img_word NumPaletteEntries; img_byte PaletteBitDepth; IMGFMT PaletteFormat; }IMG_DESC, *PIMG_DESC; #endif __IMG_LIB_TYPES_H__<file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/ls_load.h #ifndef __LS_LOAD_H__ #define __LS_LOAD_H__ #include <dsound.h> #include "common.h" #ifdef __cplusplus extern "C"{ #endif /*__cplusplus*/ typedef struct _SNDCALLBACKS{ void* (*Snd_CreateFromDisk)(char*); /*void* (*Snd_CreateFromData)(void*, L_dword);*/ L_bool (*Snd_Delete)(void*); L_dword (*Snd_Read)(void*, void*, L_dword); L_bool (*Snd_Reset)(void*); WAVEFORMATEX* (*Snd_GetFormat)(void*, WAVEFORMATEX*); L_dword (*Snd_GetSize)(void*); L_bool (*Snd_IsEOF)(void*); }SNDCALLBACKS, *PSNDCALLBACKS; SNDCALLBACKS* LS_GetCallbacks(char* szType); L_result LS_LoadSound( IDirectSound8* lpDS, IDirectSoundBuffer8** lppBuffer, L_dword dwBufferFlags, char* szFilename); L_result LS_FillBuffer( SNDCALLBACKS* pCB, IDirectSound8* lpDS, IDirectSoundBuffer8** lppBuffer, L_dword dwBufferFlags, char* szFilename); #ifdef __cplusplus extern "C"{ #endif /*__cplusplus*/ #endif /* __LS_LOAD_H__*/<file_sep>/samples/Project5/src/project5/Main.java /* <NAME> CS 2420-002 Project 5 - Zoo Graph Demmo Main - Entry Point and Program Logic */ package project5; import java.io.*; public class Main { private static Zoo s_zoo; /* PRE: s_zoo initialized. POST: Performs menu program logic, and allows exploration of the zoo. */ private static void menuMain(){ boolean bContinue=true; while(bContinue){ System.out.println("Options:"); System.out.println("1) Show animals"); System.out.println("2) Find path"); System.out.println("3) Quit"); int nChoice = bcol.KBInput.readNumberRange(1, 3); switch(nChoice){ case 1: System.out.println(s_zoo); break; case 2: s_zoo.shortestPath(); break; case 3: bContinue=false; break; } } } /* PRE: Entry POST: Exit, all program logic called. */ public static void main(String[] args) throws bcol.BColException{ s_zoo = new Zoo("zoo_graph.txt"); menuMain(); } } <file_sep>/games/Legacy-Engine/Source/lc_sys2/lc_def_ANSI.cpp #include <stdio.h> #include <string.h> #include "lc_def.h" #include "common.h" lg_bool LC_CheckName(const lg_char* szName) { lg_dword nLen=strlen(szName); /* The idea behind the default checks, is that the first number cannot be a number, and no special characters are allowed in the name, this is similar to what c language allows. */ lg_char szNoFirst[]="0123456789"; lg_char szNoAllow[]="{}[]\'\";:.,<>?/\\`~=+)(*&$^%#@!~ "; /* Check to see if the first character is a no allow. */ for(lg_dword i=0, lenallow=strlen(szNoFirst); i<lenallow; i++) { if(szName[0]==szNoFirst[i]) return LG_FALSE; } /* Now make sure no invalid characters are in the string. */ for(lg_dword i=0, lenallow=strlen(szNoAllow); i<lenallow; i++) { for(lg_dword j=0; j<nLen; j++) { if(szName[j]==szNoAllow[i]) return LG_FALSE;; } } return LG_TRUE; } CDefs::CDefs(): m_pHashList(LG_NULL), m_nDefCount(0) { m_pHashList=new DEF[LC_DEF_HASH_SIZE]; for(lg_dword i=0; i<LC_DEF_HASH_SIZE; i++) { m_pHashList[i].bDefined=LG_FALSE; } } CDefs::~CDefs() { Clear(); if(m_pHashList) { delete[]m_pHashList; } //printf("%d definitions.\n", m_nDefCount); } CDefs::DEF_VALUE* CDefs::GetDef(const lg_char* szDef) { lg_dword nHash=GenDefHash(szDef)%LC_DEF_HASH_SIZE; if(!m_pHashList[nHash].bDefined) return LG_NULL; DEF* pDef=&m_pHashList[nHash]; while(pDef) { if(strnicmp(pDef->szDef, szDef, LC_MAX_DEF_LEN)==0) return &pDef->nValue; pDef=pDef->pHashNext; } return LG_NULL; } lg_dword CDefs::GetDefUnsigned(const lg_char* def, lg_bool* bGot) { DEF_VALUE* pValue=GetDef(def); if(bGot) *bGot=pValue?LG_TRUE:LG_FALSE; if(pValue) return (lg_dword)pValue->u; return 0; } lg_long CDefs::GetDefSigned(const lg_char* def, lg_bool* bGot) { DEF_VALUE* pValue=GetDef(def); if(bGot) *bGot=pValue?LG_TRUE:LG_FALSE; if(pValue) return (lg_long)pValue->u; return 0; } lg_float CDefs::GetDefFloat(const lg_char* def, lg_bool* bGot) { DEF_VALUE* pValue=GetDef(def); if(bGot) *bGot=pValue?LG_TRUE:LG_FALSE; if(pValue) return (lg_float)pValue->f; return 0.0f; } lg_bool CDefs::AddDef(const lg_char* szDef, DEF_VALUE* pValue, lg_dword Flags) { if(!LC_CheckName(szDef)) return LG_FALSE; //First check to see if the definition has already been defined. DEF_VALUE* val=GetDef(szDef); if(val) { if(L_CHECK_FLAG(Flags, LC_DEF_NOREDEFINE)) { //printf("Can't redifine.\n"); return LG_FALSE; } else { //printf("Redefining.\n"); *val=*pValue; return LG_TRUE; } } lg_dword nHash=GenDefHash(szDef)%LC_DEF_HASH_SIZE; //LC_Printf("The hash for %s is %d", szDef, nHash); if(!m_pHashList[nHash].bDefined) { //If there is no definition in the hash slot we just //stick the definition in the hash slot. m_pHashList[nHash].bDefined=LG_TRUE; m_pHashList[nHash].nValue=*pValue; m_pHashList[nHash].pHashNext=LG_NULL; strncpy(m_pHashList[nHash].szDef, szDef, LC_MAX_DEF_LEN); } else { //Add the new item (we know it isn't a redefinition because we //already checked). DEF* pNew=new DEF; if(!pNew) return LG_FALSE; pNew->bDefined=LG_TRUE; pNew->nValue=*pValue; pNew->pHashNext=LG_NULL; strncpy(pNew->szDef, szDef, LC_MAX_DEF_LEN); pNew->pHashNext=m_pHashList[nHash].pHashNext; m_pHashList[nHash].pHashNext=pNew; } m_nDefCount++; return LG_TRUE; } lg_bool CDefs::AddDef(const lg_char *szDef, lg_dword nValue, lg_dword Flags) { DEF_VALUE v={(lg_float)nValue, nValue}; return AddDef(szDef, &v, Flags); } lg_bool CDefs::AddDef(const lg_char *szDef, lg_long nValue, lg_dword Flags) { DEF_VALUE v={(lg_float)nValue, nValue}; return AddDef(szDef, &v, Flags); } lg_bool CDefs::AddDef(const lg_char *szDef, lg_float fValue, lg_dword Flags) { DEF_VALUE v={fValue, (lg_long)fValue}; return AddDef(szDef, &v, Flags); } void CDefs::Clear() { if(!m_pHashList) return; for(lg_dword i=0; i<LC_DEF_HASH_SIZE; i++) { //If the slot doesn't have a definition //then there are no child subsequient definitions //with the same hash value, so it is safe to continue //down the list. if(!m_pHashList[i].bDefined) continue; DEF* pDef=m_pHashList[i].pHashNext; while(pDef) { DEF* pTemp=pDef->pHashNext; delete pDef; pDef=pTemp; m_nDefCount--; } m_pHashList[i].bDefined=LG_FALSE; m_nDefCount--; } } lg_dword CDefs::GenDefHash(const lg_char* def) { lg_dword nLen=LG_Min(strlen(def), LC_MAX_DEF_LEN); lg_dword nHash=0; lg_dword i=0; lg_char c; for(i=0; i<nLen; i++) { c=def[i]; //Insure that the hash value is case insensitive //by capitalizing lowercase letters. if((c>='a') && (c<='z')) c-='a'-'A'; nHash+=c; nHash+=(nHash<<10); nHash^=(nHash>>6); } nHash+=(nHash<<3); nHash^=(nHash>>11); nHash+=(nHash<<15); return nHash; }<file_sep>/games/Legacy-Engine/Scrapped/libs/lf_sys1/lf_file.c #include "common.h" #include <memory.h> #include <stdio.h> #include <malloc.h> #include "lf_sys.h" typedef struct _LF_FILE_S{ L_dword dwType; L_dword FileSize; L_dword FilePointer; L_dword dwAccess; char szFilename[MAX_F_PATH]; void* pFileData; void* lpFile; }LF_FILE_S, *LPLF_FILE_S; extern L_bool g_bFSInited; extern char g_szCurDir[MAX_F_PATH]; extern L_bool g_bArchivesFirst; extern SEARCHPATHS* g_SearchPaths; /********************************************************* The File_* functions are used to open files and read them, there is no writing ability implimented, yet. **********************************************************/ /******************************************************************** File_OpenFromData() Opens a file from data. This function creates its own buffer to use to read from, so the data passed to the first parameter should be freed if it is no long going to be used. *********************************************************************/ LF_FILE2 File_OpenFromData(void* lpBuffer, char* szFilename, L_dword nSize, L_dword dwAccess) { LF_FILE_S* lpNewFile=L_null; if(!lpBuffer) return L_null; lpNewFile=malloc(sizeof(LF_FILE_S)); if(!lpNewFile) { free(lpBuffer); return L_null; } lpNewFile->pFileData=malloc(nSize); if(!lpNewFile) { free(lpNewFile); return L_null; } memcpy(lpNewFile->pFileData, lpBuffer, nSize); lpNewFile->dwAccess=dwAccess; lpNewFile->dwType=TYPE_DATASTREAM; lpNewFile->FilePointer=0; lpNewFile->FileSize=nSize; L_strncpy(lpNewFile->szFilename, szFilename, MAX_F_PATH); //lpNewFile->pFileData=lpBuffer; return (LF_FILE2)lpNewFile; } /************************************************************ File_OpenFromArchive() Goes through the archive index, if it finds a matching name it will open that file from the archive. The file can then be used as normal. ************************************************************/ LF_FILE2 File_OpenFromArchive(char* szFilename) { SEARCHPATHS* lpPath=L_null; HLARCHIVE hArchive=L_null; LF_FILE_S* lpNewFile=L_null; void* lpBuffer=L_null; L_dword nSize=0; /* Step 1: Go through the seach paths until the file is found. */ for(lpPath=g_SearchPaths; lpPath; lpPath=lpPath->m_next) { if(L_strnicmp(lpPath->m_szFilename, szFilename, 0)) { hArchive=Arc_Open(lpPath->m_szLibrary); break; } } /* If the file wasn't found the archive won't have been opened. */ if(!hArchive) return L_null; /* Step 2: Allocate memory for the file. */ lpBuffer=malloc(Arc_GetFileSize(hArchive, lpPath->m_szNameInLibrary)); if(!lpBuffer) { Arc_Close(hArchive); return L_null; } /* Step 3: Extract the file into the allocated memory. Close the archive. */ nSize=Arc_Extract(hArchive, lpPath->m_szNameInLibrary, lpBuffer); Arc_Close(hArchive); /* Step 4: Call File_Open from data, then free the allocated memory. */ lpNewFile=(LF_FILE_S*)File_OpenFromData( lpBuffer, lpPath->m_szFilename, nSize, LF_ACCESS_READ|LF_ACCESS_MEMORY); free(lpBuffer); return (LF_FILE2)lpNewFile; } LF_FILE2 File_CreateNew(L_pstr szFilename, L_dword nSize, L_dword dwAccess) { LF_FILE_S* lpNewFile=L_null; void* lpBuffer=L_null; char* szFilenameLong; //_snprintf(szFilenameLong, MAX_F_PATH-1, "%s\\%s", LF_GetDir(L_null, 0), szFilename); szFilenameLong=szFilename; if(L_CHECK_FLAG(dwAccess, LF_ACCESS_MEMORY)) { lpBuffer=malloc(nSize); if(!lpBuffer) { LF_SetError("File_Open: Could not allocate memory for \"%s\".", szFilename); return L_null; } memset(lpBuffer, 0, nSize); lpNewFile=(LF_FILE_S*)File_OpenFromData(lpBuffer, szFilenameLong, nSize, dwAccess); free(lpBuffer); } else { void* fin=L_null; /* Initialize everything to 0. */ LF_MkDir(szFilenameLong); fin=L_fopen(szFilenameLong, LOPEN_CREATE_ALWAYS, LOPEN_WRITE|LOPEN_READ);//"wb"); if(!fin) { LF_SetError("File_Open: Could not open \"%s\" for writing.", szFilename); return L_null; } lpNewFile=malloc(sizeof(LF_FILE_S)); if(!lpNewFile) { L_fclose(fin); LF_SetError("File_Open: Could not allocate memory for \"%s\".", szFilename); return L_null; } memset(lpNewFile, 0, sizeof(LF_FILE_S)); lpNewFile->dwAccess=dwAccess; lpNewFile->dwType=TYPE_FILESTREAM; lpNewFile->FilePointer=0; lpNewFile->FileSize=nSize; lpNewFile->lpFile=fin; lpNewFile->pFileData=L_null; L_strncpy(lpNewFile->szFilename, szFilenameLong, MAX_F_PATH); } return (LF_FILE2)lpNewFile; } LF_FILE2 File_OpenExisting(L_lpstr szFilename, L_dword dwAccess) { LF_FILE_S* lpNewFile=L_null; void* lpBuffer=L_null; L_dword dwSize=0; void* fin=0; L_dword dwRead=0; L_bool bArchiveFirst=g_bArchivesFirst; //Attempt to open from disk first, if that fails, open //from archive. if(bArchiveFirst) { if(!L_CHECK_FLAG(dwAccess, LF_ACCESS_DONTSEARCHARCHIVES)) { lpNewFile=(LF_FILE_S*)File_OpenFromArchive(szFilename); if(lpNewFile) return (LF_FILE2)lpNewFile; } } //Attempt ot open from the disk. fin=L_fopen(szFilename, LOPEN_OPEN_EXISTING, LOPEN_READ|LOPEN_WRITE);//"rb+"); if(!fin) { if(!L_CHECK_FLAG(dwAccess, LF_ACCESS_DONTSEARCHARCHIVES && !bArchiveFirst)) { lpNewFile=(LF_FILE_S*)File_OpenFromArchive(szFilename); if(lpNewFile) return (LF_FILE2)lpNewFile; } LF_SetError("File_Open Error: Could not open \"%s\".", szFilename); return L_null; } /* if(!fin) { LF_SetError("File_Open Error: Could not open \"%s\".", szFilename); return L_null; } */ L_fseek(fin, 0, SEEK_END); dwSize=L_ftell(fin); L_fseek(fin, 0, SEEK_SET); if(dwSize<1) { LF_SetError("File_Open Error: No data found in \"%s\" file.", szFilename); L_fclose(fin); return L_null; } /* If we want to create a file in memory, we read the file, and call File_OpenFromData. Otherwise we open an actual file.*/ if(L_CHECK_FLAG(dwAccess, LF_ACCESS_MEMORY)) { lpBuffer=malloc(dwSize); dwRead=L_fread(lpBuffer, 1, dwSize, fin); if(!lpBuffer) { L_fclose(fin); return L_null; } lpNewFile=(LF_FILE_S*)File_OpenFromData(lpBuffer, szFilename, dwSize, dwAccess); L_fclose(fin); free(lpBuffer); return (LF_FILE2)lpNewFile; } else { lpNewFile=malloc(sizeof(LF_FILE_S)); if(!lpNewFile) { LF_SetError("File_Open Error: Could not allocate memory for \"%s\" file.", szFilename); L_fclose(fin); return L_null; } /* Initialize everything to 0. */ memset(lpNewFile, 0, sizeof(LF_FILE_S)); lpNewFile->dwAccess=dwAccess; lpNewFile->dwType=TYPE_FILESTREAM; lpNewFile->FilePointer=0; lpNewFile->FileSize=dwSize; lpNewFile->lpFile=fin; lpNewFile->pFileData=L_null; L_strncpy(lpNewFile->szFilename, szFilename, MAX_F_PATH); return (LF_FILE2)lpNewFile; } } /**************************************************************** File_Open() Opens a file using the specified flags. If the LFF_MEMBUF flag is specified the file will be opened all the way into memory. If that flag is not specified the file will be opened as a FILE*. ****************************************************************/ LF_FILE2 File_Open(L_lpstr szFilename, L_dword dwSize, L_dword dwAccess, LFCREATE nCreate) { LF_FILE_S* lpNewFile=L_null; char szFullPathNameTemp[MAX_F_PATH]; char* szFullPathName=szFullPathNameTemp; int n=0; /* We should try to open from an archive, firs then result to opening from the actual file system, but the archvie feature hasn't been implimented yet so we are just opening from the disk. */ FS_CHECK_EXIT //Build the full pathname for the file LF_BuildPath(szFullPathNameTemp, szFilename); szFullPathName=szFullPathNameTemp; //Eliminate the directory. /* n=L_strlen(g_szCurDir); if(L_strnicmp(szFullPathNameTemp, g_szCurDir, n)) { switch(szFullPathName[n]) { case '\\': case '/': case 0: szFullPathName=&szFullPathNameTemp[n+1]; break; default: szFullPathName=szFullPathNameTemp; break; } } else szFullPathName=szFullPathNameTemp; */ /* Try to open the file from archive, if that fails, open it from disk. */ /* We will set a default error message now, and hopefully the other functions will change it if they can't open the file.*/ LF_SetError("File_Open: Succeeded."); switch (nCreate) { case LFCREATE_OPEN_EXISTING: return File_OpenExisting(szFullPathName, dwAccess); case LFCREATE_CREATE_NEW: return File_CreateNew(szFullPathName, dwSize, dwAccess); default: return L_null; } } /************************************************* File_Close() Closes the open file and frees any memory. *************************************************/ L_bool File_Close(LF_FILE2 lpFile2) { LF_FILE_S* lpFile=(LF_FILE_S*)lpFile2; FS_CHECK_EXIT if(!lpFile) return L_false; /* If this was a regular file we close the file. */ if(lpFile->dwType==TYPE_FILESTREAM) { if(lpFile->lpFile) L_fclose(lpFile->lpFile); } else { if(L_CHECK_FLAG(lpFile->dwAccess, LF_ACCESS_WRITE)) { void* fout=L_null; fout=L_fopen(lpFile->szFilename, LOPEN_CREATE_NEW, LOPEN_WRITE);//"wb"); if(fout) { L_fwrite(lpFile->pFileData, 1, lpFile->FileSize, fout); L_fclose(fout); } } L_safe_free(lpFile->pFileData); } /* Just free all the memory we allocated. */ L_safe_free(lpFile); LF_SetError("File_Close: Succeeded."); return L_true; } /************************** File_Write() Writes data to file. **************************/ L_dword File_Write(LF_FILE2 lpFile2, L_dword dwBytesToWrite, L_void* lpBuffer) { LF_FILE_S* lpFile=(LF_FILE_S*)lpFile2; FS_CHECK_EXIT if(!lpFile || !lpBuffer || !L_CHECK_FLAG(lpFile->dwAccess, LF_ACCESS_WRITE)|| !dwBytesToWrite) { LF_SetError("File_Write: Invalid Args."); return 0; } LF_SetError("File_Write: Succeeded."); if((lpFile->FileSize<(lpFile->FilePointer+dwBytesToWrite)) && L_CHECK_FLAG(lpFile->dwAccess, LF_ACCESS_MEMORY)) { LF_SetError("File_Write: Could only write %i bytes.", dwBytesToWrite); } /* Copy the data. */ if(lpFile->dwType==TYPE_FILESTREAM) { dwBytesToWrite=L_fwrite(lpBuffer, 1, dwBytesToWrite, lpFile->lpFile); lpFile->FilePointer+=dwBytesToWrite; return dwBytesToWrite; } else { memcpy((void*)((unsigned int)lpFile->pFileData+lpFile->FilePointer), lpBuffer, dwBytesToWrite); lpFile->FilePointer+=dwBytesToWrite; } return dwBytesToWrite; } /*********************************************************************** File_Read() Reads the specified amount of data from the file, into the buffer. Returns the actual number of bytes read. ***********************************************************************/ L_dword File_Read(LF_FILE2 lpFile2, L_dword dwBytesToRead, L_void* lpBuffer) { LF_FILE_S* lpFile=(LF_FILE_S*)lpFile2; FS_CHECK_EXIT if(!lpFile || !lpBuffer) { LF_SetError("File_Read: Invalid argument."); return 0; } if(!L_CHECK_FLAG(lpFile->dwAccess, LF_ACCESS_READ)) { LF_SetError("File_Read: No read access."); return 0; } LF_SetError("File_Read: Succeeded."); /* If we don't need to read anything we won't. */ if(!dwBytesToRead) return 0; /* If the bytes we want to read goes past the end of the file we need to adjust the reading size. */ if(lpFile->FileSize<(lpFile->FilePointer+dwBytesToRead)) { dwBytesToRead=lpFile->FileSize-lpFile->FilePointer; } /* Copy the data. */ if(lpFile->dwType==TYPE_FILESTREAM) { dwBytesToRead=L_fread(lpBuffer, 1, dwBytesToRead, lpFile->lpFile); lpFile->FilePointer+=dwBytesToRead; return dwBytesToRead; } else { memcpy(lpBuffer, (void*)((unsigned int)lpFile->pFileData+lpFile->FilePointer), dwBytesToRead); lpFile->FilePointer+=dwBytesToRead; } return dwBytesToRead; } /********************************************* File_Tell() Tells the location of the data pointer. *********************************************/ L_dword File_Tell(LF_FILE2 lpFile2) { LF_FILE_S* lpFile=(LF_FILE_S*)lpFile2; FS_CHECK_EXIT LF_SetError("File_Tell: Succeeded."); return lpFile->FilePointer; } /************************************************************************* File_Seek() With change the read/write cursor of the given file to the specified position. Returns the actual new position of the file pointer. *************************************************************************/ L_dword File_Seek(LF_FILE2 lpFile2, L_long nMoveDist, LF_MOVETYPE nMoveType) { LF_FILE_S* lpFile=(LF_FILE_S*)lpFile2; L_dword nNewPointer=lpFile->FilePointer; FS_CHECK_EXIT if(lpFile->dwType==TYPE_FILESTREAM) { switch(nMoveType) { case MOVETYPE_SET: L_fseek(lpFile->lpFile, nMoveDist, LFSEEK_SET); break; case MOVETYPE_END: L_fseek(lpFile->lpFile, nMoveDist, LFSEEK_END); break; case MOVETYPE_CUR: L_fseek(lpFile->lpFile, nMoveDist, LFSEEK_CUR); break; } lpFile->FilePointer=L_ftell(lpFile->lpFile); LF_SetError("File_Seek: Succeeded."); return lpFile->FilePointer; } else { switch(nMoveType) { case MOVETYPE_SET: nNewPointer=nMoveDist; break; case MOVETYPE_END: nNewPointer=lpFile->FileSize+nMoveDist; break; case MOVETYPE_CUR: nNewPointer+=nMoveDist; break; } if(nNewPointer<0) nNewPointer=0; if(nNewPointer>lpFile->FileSize) nNewPointer=lpFile->FileSize; lpFile->FilePointer=nNewPointer; LF_SetError("File_Seek: Succeeded."); return lpFile->FilePointer; } } L_dword File_GetSize(LF_FILE2 lpFile2) { LF_FILE_S* lpFile=lpFile2; FS_CHECK_EXIT LF_SetError("File_GetSize: Succeeded."); return lpFile->FileSize; } void* File_GetMemPointer(LF_FILE2 lpFile2, L_dword* lpSize) { LF_FILE_S* lpFile=(LF_FILE_S*)lpFile2; FS_CHECK_EXIT if(lpSize) *lpSize=lpFile->FileSize; LF_SetError("File_GetMemPointer: Succeeded."); return lpFile->pFileData; } /* Functions for fio access compatibility */ void* __cdecl File_fopen(const char* filename, const char* mode) { //Need to impliment this, the difficult part is parsing //the mode options. return L_null; } int __cdecl File_fclose(void* stream) { return File_Close(stream); } int __cdecl File_fseek(void* stream, long offset, int origin) { return File_Seek(stream, offset, (LF_MOVETYPE) origin); } long __cdecl File_ftell(void* stream) { return File_Tell(stream); } unsigned int __cdecl File_fread(void* buffer, unsigned int size, unsigned int count, void* stream) { return File_Read(stream, size*count, buffer); } <file_sep>/games/Legacy-Engine/Source/engine/lg_mtr_mgr.cpp #include "lg_mtr_mgr.h" #include "lg_err.h" #include "lg_err_ex.h" #include "lx_sys.h" #include "lg_tmgr.h" #include "lg_fxmgr.h" CLMtrMgr* CLMtrMgr::s_pMtrMgr=LG_NULL; CLMtrMgr::CLMtrMgr(lg_dword nMaxMtr) : CLHashMgr(nMaxMtr, "MatMgr") , m_pMtrMem(LG_NULL) { s_pMtrMgr=this; //Prepare the list stack. m_pMtrMem=new MtrItem[m_nMaxItems]; if(!m_pMtrMem) throw LG_ERROR(LG_ERR_OUTOFMEMORY, LG_NULL); for(lg_dword i=0; i<m_nMaxItems; i++) { m_stkMtr.Push(&m_pMtrMem[i]); } //Setup the default material, we simply //use the default texture and effect for this. m_DefMtr.Texture=CLHashMgr::HM_DEFAULT_ITEM; m_DefMtr.Effect=CLHashMgr::HM_DEFAULT_ITEM; //Setup the default itme m_pItemList[0].pItem=&m_DefMtr; //m_pDefItem=&m_DefMtr; } CLMtrMgr::~CLMtrMgr() { CLHashMgr::UnloadItems(); m_stkMtr.Clear(); LG_SafeDeleteArray(m_pMtrMem); } MtrItem* CLMtrMgr::DoLoad(lg_path szFilename, lg_dword nFlags) { MtrItem* pOut = (MtrItem*)m_stkMtr.Pop(); if(!pOut) return LG_NULL; lx_mtr mtr; if(!LX_LoadMtr(szFilename, &mtr)) pOut=LG_NULL; else { //If we loaded then let's load the texture, //and effect, note that sometimes a texture //or effect is not specified for a material, //in this case we set them to 0 and the game //can do whatever it wants (whether that be to //not use an effect, or to use the default //effect or texure. pOut->Texture=mtr.szTexture[0]?CLTMgr::TM_LoadTex(mtr.szTexture, 0):0; pOut->Effect=mtr.szFx[0]?CLFxMgr::FXM_LoadFx(mtr.szFx, 0):0; } return pOut; } void CLMtrMgr::DoDestroy(MtrItem* pItem) { if(!pItem) return; //All we have to do is push the item back on the stack //no unloading is necessary since the material is a //fixed size. m_stkMtr.Push(pItem); } void CLMtrMgr::RenderVB(lg_material mtr, IDirect3DDevice9* pDevice, IDirect3DVertexBuffer9* pVB) { //Nothing yet. } void CLMtrMgr::GetInterfaces(lg_material mtr, tm_tex* pTex, ID3DXEffect** pFX) { mtr+=mtr?0:1; #if 0 if(mtr==0 || mtr>=this->m_nMaxItems) { Err_Printf("Tried to get %d", mtr); return; } #endif *pTex=m_pItemList[mtr-1].pItem->Texture; *pFX=CLFxMgr::FXM_GetInterface(m_pItemList[mtr-1].pItem->Effect); } lg_material CLMtrMgr::MTR_Load(lg_path szFilename, lg_dword nFlags) { return s_pMtrMgr->Load(szFilename, nFlags); } void CLMtrMgr::MTR_RenderVB(lg_material mtr, IDirect3DDevice9 *pDevice, IDirect3DVertexBuffer9 *pVB) { s_pMtrMgr->RenderVB(mtr, pDevice, pVB); } void CLMtrMgr::MTR_GetInterfaces(lg_material mtr, tm_tex *pTex, ID3DXEffect **pFX) { s_pMtrMgr->GetInterfaces(mtr, pTex, pFX); } <file_sep>/games/Legacy-Engine/Source/engine/ls_ogg.h /* ls_ogg.h - Header for ogg file support Copyright (c) 2006, <NAME>. */ #ifndef __LS_OGG_H__ #define __LS_OGG_H__ #include <windows.h> #include "common.h" #ifdef __cplusplus extern "C"{ #endif /*__cplusplus*/ lg_void* Ogg_CreateFromDisk(lg_str szFilename); /*lg_void* Ogg_CreateFromData(void* lpData, lg_dword dwDataSize);*/ lg_bool Ogg_Delete(lg_void* lpWave); lg_dword Ogg_Read(lg_void* lpWave, void* lpDest, lg_dword dwSizeToRead); lg_bool Ogg_Reset(lg_void* lpWave); WAVEFORMATEX* Ogg_GetFormat(lg_void* lpWave, WAVEFORMATEX* lpFormat); lg_dword Ogg_GetSize(lg_void* lpWave); lg_bool Ogg_IsEOF(lg_void* lpWave); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /*__LS_OGG_H__*/ <file_sep>/games/Legacy-Engine/Source/lc_sys2/lc_def.h #ifndef __LC_DEF_H__ #define __LC_DEF_H__ #include "lg_types.h" #define LC_MAX_DEF_LEN 16 #define LC_DEF_HASH_SIZE 128 #define LC_DEF_NOREDEFINE 0x00000001 lg_bool LC_CheckName(const lg_char* szName); class CDefs { friend class CConsole; private: public: struct DEF_VALUE{ lg_float f; lg_int u; }; private: struct DEF{ lg_char szDef[LC_MAX_DEF_LEN+1]; DEF_VALUE nValue; DEF* pHashNext; lg_bool bDefined; }; private: DEF* m_pHashList; lg_dword m_nDefCount; lg_dword GenDefHash(const lg_char* def); lg_bool AddDef(const lg_char* szDef, DEF_VALUE* pValue, lg_dword Flags=0); public: DEF_VALUE* GetDef(const lg_char* szDef); public: CDefs(); ~CDefs(); lg_bool AddDef(const lg_char* szDef, lg_float value, lg_dword Flags=0); lg_bool AddDef(const lg_char* szDef, lg_dword value, lg_dword Flags=0); lg_bool AddDef(const lg_char* szDef, lg_long value, lg_dword Flags=0); void Clear(); lg_dword GetDefUnsigned(const lg_char* def, lg_bool* bGot); lg_long GetDefSigned(const lg_char* def, lg_bool* bGot); lg_float GetDefFloat(const lg_char* def, lg_bool* bGot); }; #endif __LC_DEF_H__<file_sep>/games/Legacy-Engine/Source/lm_sys/lm_skel_edit.cpp #include "stdafx.h" #include "lm_skel_edit.h" CLSkelEdit::CLSkelEdit() : CLSkel2() , m_nColor(0xFFFF0000) , m_pSkel(LG_NULL) { } CLSkelEdit::~CLSkelEdit() { Unload(); } lg_bool CLSkelEdit::SetAnims(lg_dword nCount, SkelAnim* pAnims) { LG_SafeDeleteArray(m_pAnims); m_nNumAnims=0; m_nNumAnims=nCount; m_pAnims=new SkelAnim[m_nNumAnims]; if(!m_pAnims) { m_nNumAnims=0; return LG_FALSE; } lg_dword i=0; for(i=0; i<nCount; i++) { m_pAnims[i]=pAnims[i]; } return LG_TRUE; } //CalculateAABBs simply finds the minimum and maximum //joint locations for each frame, the fExtent perameter //will extend the AABB that far (to account for the //fact that models are typically a little bigger than the //skeleton. lg_bool CLSkelEdit::CalculateAABBs(float fExtent) { //To calculate the AABBs we need to calculate the extremes //of each frame. lg_dword i,j; for(i=0; i<m_nNumKeyFrames; i++) { SetupFrame(i+1, i+1, 0.0f); m_pFrames[i].aabbBox.v3Min.x=m_pSkel[0].x; m_pFrames[i].aabbBox.v3Min.y=m_pSkel[0].y; m_pFrames[i].aabbBox.v3Min.z=m_pSkel[0].z; m_pFrames[i].aabbBox.v3Max.x=m_pSkel[0].x; m_pFrames[i].aabbBox.v3Max.y=m_pSkel[0].y; m_pFrames[i].aabbBox.v3Max.z=m_pSkel[0].z; for(j=0; j<m_nNumJoints; j++) { m_pFrames[i].aabbBox.v3Min.x=LG_Min(m_pSkel[j].x, m_pFrames[i].aabbBox.v3Min.x); m_pFrames[i].aabbBox.v3Min.y=LG_Min(m_pSkel[j].y, m_pFrames[i].aabbBox.v3Min.y); m_pFrames[i].aabbBox.v3Min.z=LG_Min(m_pSkel[j].z, m_pFrames[i].aabbBox.v3Min.z); m_pFrames[i].aabbBox.v3Max.x=LG_Max(m_pSkel[j].x, m_pFrames[i].aabbBox.v3Max.x); m_pFrames[i].aabbBox.v3Max.y=LG_Max(m_pSkel[j].y, m_pFrames[i].aabbBox.v3Max.y); m_pFrames[i].aabbBox.v3Max.z=LG_Max(m_pSkel[j].z, m_pFrames[i].aabbBox.v3Max.z); } //Adjust the AABB by the extent. m_pFrames[i].aabbBox.v3Min.x-=fExtent; m_pFrames[i].aabbBox.v3Min.y-=fExtent; m_pFrames[i].aabbBox.v3Min.z-=fExtent; m_pFrames[i].aabbBox.v3Max.x+=fExtent; m_pFrames[i].aabbBox.v3Max.y+=fExtent; m_pFrames[i].aabbBox.v3Max.z+=fExtent; } return LG_TRUE; } lg_bool CLSkelEdit::ImportFrames(CLSkelEdit* pSkel) { CString szTemp; lg_dword i=0, j=0, nNumJoints=0; //Start by allocating enough memory to temporarility store joint information. #ifdef IMPORT_ENTIRESKEL //Generate a list of names with each of the bones LMESH_NAME szList1[1024]; //List of all the joints. lg_dword nIndex[1024]; //Holds a list of joint reference to any imported joints (either points to an old joint, or points to a new one). for(i=0; i<m_nNumJoints; i++) { L_strncpy(szList1[i], m_pBaseSkeleton[i].szName, LMESH_MAX_NAME_LENGTH); } //Generate a list with all the unique joints. for(i=0, nNumJoints=this->m_nNumJoints; i<pSkel->m_nNumJoints; i++) { lg_bool bFound=LG_FALSE; for(j=0; j<this->m_nNumJoints; j++) { if(L_strnicmp(szList1[j], pSkel->m_pBaseSkeleton[i].szName, 0)) { bFound=LG_TRUE; nIndex[i]=j; break; } } if(!bFound) { L_strncpy(szList1[nNumJoints], pSkel->m_pBaseSkeleton[i].szName, LMESH_MAX_NAME_LENGTH); nIndex[i]=nNumJoints; nNumJoints++; } } szTemp="The joints:\n"; for(i=0; i<nNumJoints; i++) { szTemp.AppendFormat("%s, ", szList1[i]); } AfxMessageBox(szTemp); //Allocate some memory for the joints. LMESH_JOINTEX* pNewSkel=new LMESH_JOINTEX[nNumJoints]; if(!pNewSkel) return LG_FALSE; /* for(i=0; i<nNumJoints; i++) { memset(&pNewSkel[i], 0, sizeof(LMESH_JOINTEX)); szTemp.Format("Bone %i", i); L_strncpy(pNewSkel[i].szName, szTemp, LMESH_MAX_NAME_LENGTH); pNewSkel[i].szParentBone[0]=0; pNewSkel[i].nParentBone=0; pNewSkel[i].position[0]=0.0f; pNewSkel[i].position[1]=0.0f; pNewSkel[i].position[2]=0.0f; pNewSkel[i].rotation[0]=0.0f; pNewSkel[i].rotation[1]=0.0f; pNewSkel[i].rotation[2]=0.0f; if(i<m_nNumJoints) pNewSkel[i]=m_pBaseSkeleton[i]; } */ //Copy original skeleton stuff: for(i=0; i<nNumJoints; i++) { //Find the bone with the same name. lg_bool bFound=LG_FALSE; pNewSkel[i]=m_pBaseSkeleton[0]; for(j=0; j<m_nNumJoints; j++) { if(L_strnicmp(szList1[i], m_pBaseSkeleton[j].szName, 0)) { bFound=LG_TRUE; pNewSkel[i]=m_pBaseSkeleton[j]; break; } } if(!bFound) { for(j=0; j<pSkel->m_nNumJoints; j++) { if(L_strnicmp(szList1[i+m_nNumJoints], pSkel->m_pBaseSkeleton[j].szName, 0)) { bFound=LG_TRUE; pNewSkel[i]=pSkel->m_pBaseSkeleton[j]; pNewSkel[i].nJointRef=i; break; } } } } //Now make sure all the parent bone refs are correct. for(i=0; i<nNumJoints; i++) { for(j=0; j<nNumJoints; j++) { if(L_strnicmp(pNewSkel[i].szParentBone, pNewSkel[j].szName, 0)) { pNewSkel[i].nParentBone=j+1; } } } m_nNumJoints=nNumJoints; delete[]m_pBaseSkeleton; m_pBaseSkeleton=pNewSkel; #endif IMPORT_ENTIRESKEL //Copy the new joints //Allocate some memory for those frames //The process of importing frames, means that we import any //keyframe information for any joints that have the same //name, probably should check to make sure that there //is at least one matching frame before importing. lg_dword nKeyFrames=m_nNumKeyFrames+pSkel->GetNumKeyFrames(); SkelFrame* pTempPositions=new SkelFrame[nKeyFrames]; if(!pTempPositions) return LG_FALSE; for(i=0; i<nKeyFrames; i++) pTempPositions[i].Initialize(m_nNumJoints); //Copy the original positions: for(i=0; i<m_nNumJoints; i++) { for(j=0; j<nKeyFrames; j++) { if(j<m_nNumKeyFrames) { pTempPositions[j].LocalPos[i]=m_pFrames[j].LocalPos[i]; } else { //Set non original frames to identity. memset(&pTempPositions[j].LocalPos[i], 0, sizeof(SkelJointPos)); } } } //Copy the original AABBs for(i=0; i<m_nNumKeyFrames; i++) { pTempPositions[i].aabbBox=m_pFrames[i].aabbBox; } //Copy the imported AABBs for(i=0; i<pSkel->GetNumFrames(); i++) { pTempPositions[i+m_nNumKeyFrames].aabbBox=pSkel->m_pFrames[i].aabbBox; } //For the skeleton we are importing we find out if there are //compatible bones and for each compatible bone we copy the //keyframe information. for(i=0; i<pSkel->GetNumJoints(); i++) { //Compare the joint with each of the frames. for(j=0; j<m_nNumJoints; j++) { if(stricmp(pSkel->m_pBaseSkeleton[i].szName, m_pBaseSkeleton[j].szName)==0) { //We found a compatible bone... //Now copy in the animation stuff. lg_dword nCmpFrame=j; for(j=0; j<pSkel->GetNumFrames(); j++) { pTempPositions[j+m_nNumKeyFrames].LocalPos[nCmpFrame]=pSkel->m_pFrames[j].LocalPos[nCmpFrame]; } break; } } } lg_dword nOffset=m_nNumKeyFrames; m_nNumKeyFrames=nKeyFrames; delete[]m_pFrames; m_pFrames=pTempPositions; //We also want to import the animation information, //we need to set off the start frame. lg_dword nNumAnims=m_nNumAnims+pSkel->m_nNumAnims; SkelAnim* pAnims=new SkelAnim[nNumAnims]; if(!pAnims) { AfxMessageBox("Could not import animation information!"); CalcExData(); return LG_TRUE; } //Copy the original anims, and copy the new anims; for(i=0; i<nNumAnims; i++) { if(i<m_nNumAnims) pAnims[i]=m_pAnims[i]; else { pAnims[i]=pSkel->m_pAnims[i-m_nNumAnims]; pAnims[i].nFirstFrame+=nOffset; } } m_nNumAnims=nNumAnims; delete[]m_pAnims; m_pAnims=pAnims; //Since the skeleton has significantly changed we need to //calculate the extra data again. CalcExData(); return LG_TRUE; } lg_bool CLSkelEdit::Load(LMPath szFile) { Unload(); CFile fin; if(!fin.Open(szFile, fin.modeRead)) return LG_FALSE; lg_bool bResult=Serialize((lg_void*)&fin, CLMeshEdit::ReadFn, RW_READ); fin.Close(); m_nFlags=bResult?LM_FLAG_LOADED:0; if(bResult) { //Since information gets edited we're going to have //to allocate memory in a special way, we can't //use the information supplied by Serialize. //Need direct3d stuff m_pSkel=new JointVertex[m_nNumJoints]; SetupFrame(0, 0, 0.0f); //We also need the ex data. CalcExData(); } return bResult; } lg_bool CLSkelEdit::Save(LMPath szFile) { if(!IsLoaded()) return LG_FALSE; CFile fin; if(!fin.Open(szFile, fin.modeWrite|fin.modeCreate)) return LG_FALSE; lg_bool bResult=Serialize((lg_void*)&fin, CLMeshEdit::WriteFn, RW_WRITE); fin.Close(); return bResult; } lg_void CLSkelEdit::Unload() { //Do the actual delete: //To come... //Base unload: CLSkel2::Unload(); //Get rid of any extra data. LG_SafeDeleteArray(m_pSkel); } lg_void CLSkelEdit::SetupFrame(lg_dword nAnim, lg_float fTime) { // The range could easily be changed by modifying this //value, 100.0f seemed to be a good range to me. #define PREP_MAX_RANGE 100.0f if(m_nNumAnims<1) return; nAnim=LG_Clamp(nAnim, 0, m_nNumAnims-1); fTime=LG_Clamp(fTime, 0.0f, PREP_MAX_RANGE); float fFrame; lg_dword nFrame1=0, nFrame2=0; //Get the animation we are dealing with. const SkelAnim* pAnim=GetAnim(nAnim); if(LG_CheckFlag(pAnim->nFlags, pAnim->ANIM_FLAG_LOOPBACK)) { if(fTime>=50.0f) fTime=100.0f-fTime; fFrame=pAnim->nFirstFrame+((float)pAnim->nNumFrames-1-0.000001f)*fTime/(PREP_MAX_RANGE*0.5f); } else { fFrame=pAnim->nFirstFrame+((float)pAnim->nNumFrames-0.000001f)*fTime/PREP_MAX_RANGE; } nFrame1=(lg_dword)fFrame; nFrame2=nFrame1>=(pAnim->nFirstFrame+pAnim->nNumFrames-1)?pAnim->nFirstFrame:nFrame1+1; //To get the interpolation value we need only find the fraction portion of fFrame fFrame-nFrame1. SetupFrame(nFrame1, nFrame2, fFrame-nFrame1); } lg_void CLSkelEdit::SetupFrame(lg_dword nFrame1, lg_dword nFrame2, lg_float t) { lg_dword i=0; if(!LG_CheckFlag(m_nFlags, LM_FLAG_LOADED)) return; lg_dword nNumJoints=this->m_nNumJoints; for(i=0; i<nNumJoints; i++) { ML_MAT Trans; GenerateJointTransform(&Trans, i, nFrame1, nFrame2, t); ML_MatMultiply( &Trans, GetBaseTransform(i), &Trans); //To find the final location of a joint we need to (1) find the //relative location of the joint. (2) multiply that by all of //it parent/grandparent's/etc transformation matrices. //(1) m_pSkel[i].x=0.0f; m_pSkel[i].y=0.0f; m_pSkel[i].z=0.0f; m_pSkel[i].psize=4.0f; m_pSkel[i].color=m_nColor; //(2) ML_Vec3TransformCoord((ML_VEC3*)&m_pSkel[i].x, (ML_VEC3*)&m_pSkel[i].x, &Trans);//pJointTrans[i]); } //ML_AABB aabb; GenerateAABB(&m_aabb, nFrame1, nFrame2, t); } lg_void CLSkelEdit::Render() { //We now want to render the skelton for testing purposes. lg_dword i=0; //If there are no joints just return true cause there is nothing //to render. if(!m_nNumJoints) return; BoneVertex Line[2]; //We want to render the bones first, this //is simply a line from the bone to it's parent. //If it has no parent nothing gets rendered. CLMeshEdit::s_pDevice->SetRenderState(D3DRS_ZENABLE, FALSE); CLMeshEdit::s_pDevice->SetTexture(0, LG_NULL); CLMeshEdit::s_pDevice->SetFVF(BONE_VERTEX_FORMAT); for(i=0; i<GetNumJoints(); i++) { memcpy(&Line[0].x, &m_pSkel[i].x, 12); Line[0].color=m_pSkel[i].color; lg_dword nBone=GetParentBoneRef(i); if(nBone) { memcpy(&Line[1].x, &m_pSkel[nBone-1].x, 12); Line[1].color=m_pSkel[nBone-1].color; CLMeshEdit::s_pDevice->DrawPrimitiveUP(D3DPT_LINELIST, 1, &Line, sizeof(BoneVertex)); } } //We can render all the joints at once since they are just points. CLMeshEdit::s_pDevice->SetFVF(JOINT_VERTEX_FORMAT); CLMeshEdit::s_pDevice->DrawPrimitiveUP(D3DPT_POINTLIST, GetNumJoints(), m_pSkel, sizeof(JointVertex)); //Render the AABB. CLMeshEdit::s_pDevice->SetRenderState(D3DRS_ZENABLE, TRUE); RenderAABB(); } lg_void CLSkelEdit::RenderAABB() { //ML_AABB aabb; //GenerateAABB(&aabb, nFrame1, nFrame2, t); ML_MAT matTmp; CLMeshEdit::s_pDevice->GetTransform(D3DTS_WORLD, (D3DMATRIX*)&matTmp); //ML_AABB aabb=m_aabb; ML_AABB aabbTrans; ML_AABBTransform(&aabbTrans, &m_aabb, &matTmp); ML_MAT matIdent; ML_MatIdentity(&matIdent); for(lg_dword i=0; i<16; i++) { m_vAABB[i].color=0xFFFFFF90; } ML_VEC3 vTmp; memcpy(&m_vAABB[0], ML_AABBCorner(&vTmp, &aabbTrans, ML_AABB_BLF), 12); memcpy(&m_vAABB[1], ML_AABBCorner(&vTmp, &aabbTrans, ML_AABB_TLF), 12); m_vAABB[2].x=aabbTrans.v3Min.x; m_vAABB[2].y=aabbTrans.v3Max.y; m_vAABB[2].z=aabbTrans.v3Max.z; m_vAABB[3].x=aabbTrans.v3Max.x; m_vAABB[3].y=aabbTrans.v3Max.y; m_vAABB[3].z=aabbTrans.v3Max.z; m_vAABB[4].x=aabbTrans.v3Max.x; m_vAABB[4].y=aabbTrans.v3Max.y; m_vAABB[4].z=aabbTrans.v3Min.z; m_vAABB[5].x=aabbTrans.v3Max.x; m_vAABB[5].y=aabbTrans.v3Min.y; m_vAABB[5].z=aabbTrans.v3Min.z; m_vAABB[6].x=aabbTrans.v3Max.x; m_vAABB[6].y=aabbTrans.v3Min.y; m_vAABB[6].z=aabbTrans.v3Max.z; m_vAABB[7].x=aabbTrans.v3Min.x; m_vAABB[7].y=aabbTrans.v3Min.y; m_vAABB[7].z=aabbTrans.v3Max.z; m_vAABB[8].x=aabbTrans.v3Min.x; m_vAABB[8].y=aabbTrans.v3Min.y; m_vAABB[8].z=aabbTrans.v3Min.z; m_vAABB[9].x=aabbTrans.v3Max.x; m_vAABB[9].y=aabbTrans.v3Min.y; m_vAABB[9].z=aabbTrans.v3Min.z; m_vAABB[10].x=aabbTrans.v3Max.x; m_vAABB[10].y=aabbTrans.v3Min.y; m_vAABB[10].z=aabbTrans.v3Max.z; m_vAABB[11].x=aabbTrans.v3Max.x; m_vAABB[11].y=aabbTrans.v3Max.y; m_vAABB[11].z=aabbTrans.v3Max.z; m_vAABB[12].x=aabbTrans.v3Max.x; m_vAABB[12].y=aabbTrans.v3Max.y; m_vAABB[12].z=aabbTrans.v3Min.z; m_vAABB[13].x=aabbTrans.v3Min.x; m_vAABB[13].y=aabbTrans.v3Max.y; m_vAABB[13].z=aabbTrans.v3Min.z; m_vAABB[14].x=aabbTrans.v3Min.x; m_vAABB[14].y=aabbTrans.v3Max.y; m_vAABB[14].z=aabbTrans.v3Max.z; m_vAABB[15].x=aabbTrans.v3Min.x; m_vAABB[15].y=aabbTrans.v3Min.y; m_vAABB[15].z=aabbTrans.v3Max.z; for(lg_dword i=0; i<16; i++) { if(m_vAABB[i].z==aabbTrans.v3Max.z) m_vAABB[i].color=0xFF870178; else m_vAABB[i].color=0xffff7df1; } //Render the AABB. CLMeshEdit::s_pDevice->SetTransform(D3DTS_WORLD, (D3DMATRIX*)&matIdent); CLMeshEdit::s_pDevice->SetFVF(BONE_VERTEX_FORMAT); CLMeshEdit::s_pDevice->DrawPrimitiveUP(D3DPT_LINESTRIP, 15, &m_vAABB, sizeof(BoneVertex)); CLMeshEdit::s_pDevice->SetTransform(D3DTS_WORLD, (D3DMATRIX*)&matTmp); /* BONEVERTEX Test[16]; ML_VEC3 Corners[8]; ML_AABB aabbTemp; for(lg_dword i=0; i<8; i++) { ML_AABBCorner(&Corners[i], &m_aabb, (ML_AABB_CORNER)i); ML_Vec3TransformCoord(&Corners[i], &Corners[i], &matTmp); } ML_AABBFromVec3s(&aabbTemp, Corners, 8); for(lg_dword i=0; i<16; i++) { Test[i].color=0xFFFFFF00; } memcpy(&Test[0], ML_AABBCorner(&vTmp, &aabbTemp, ML_AABB_BLF), 12); memcpy(&Test[1], ML_AABBCorner(&vTmp, &aabbTemp, ML_AABB_TLF), 12); Test[2].x=aabbTemp.v3Min.x; Test[2].y=aabbTemp.v3Max.y; Test[2].z=aabbTemp.v3Max.z; Test[3].x=aabbTemp.v3Max.x; Test[3].y=aabbTemp.v3Max.y; Test[3].z=aabbTemp.v3Max.z; Test[4].x=aabbTemp.v3Max.x; Test[4].y=aabbTemp.v3Max.y; Test[4].z=aabbTemp.v3Min.z; Test[5].x=aabbTemp.v3Max.x; Test[5].y=aabbTemp.v3Min.y; Test[5].z=aabbTemp.v3Min.z; Test[6].x=aabbTemp.v3Max.x; Test[6].y=aabbTemp.v3Min.y; Test[6].z=aabbTemp.v3Max.z; Test[7].x=aabbTemp.v3Min.x; Test[7].y=aabbTemp.v3Min.y; Test[7].z=aabbTemp.v3Max.z; Test[8].x=aabbTemp.v3Min.x; Test[8].y=aabbTemp.v3Min.y; Test[8].z=aabbTemp.v3Min.z; Test[9].x=aabbTemp.v3Max.x; Test[9].y=aabbTemp.v3Min.y; Test[9].z=aabbTemp.v3Min.z; Test[10].x=aabbTemp.v3Max.x; Test[10].y=aabbTemp.v3Min.y; Test[10].z=aabbTemp.v3Max.z; Test[11].x=aabbTemp.v3Max.x; Test[11].y=aabbTemp.v3Max.y; Test[11].z=aabbTemp.v3Max.z; Test[12].x=aabbTemp.v3Max.x; Test[12].y=aabbTemp.v3Max.y; Test[12].z=aabbTemp.v3Min.z; Test[13].x=aabbTemp.v3Min.x; Test[13].y=aabbTemp.v3Max.y; Test[13].z=aabbTemp.v3Min.z; Test[14].x=aabbTemp.v3Min.x; Test[14].y=aabbTemp.v3Max.y; Test[14].z=aabbTemp.v3Max.z; Test[15].x=aabbTemp.v3Min.x; Test[15].y=aabbTemp.v3Min.y; Test[15].z=aabbTemp.v3Max.z; //Render the AABB. CLMeshEdit::s_pDevice->SetTransform(D3DTS_WORLD, (D3DMATRIX*)&matIdent); CLMeshEdit::s_pDevice->SetFVF(BONEVERTEX_FVF); CLMeshEdit::s_pDevice->DrawPrimitiveUP(D3DPT_LINESTRIP, 15, &Test, sizeof(BONEVERTEX)); CLMeshEdit::s_pDevice->SetTransform(D3DTS_WORLD, (D3DMATRIX*)&matTmp); */ } <file_sep>/tools/CornerBin/CornerBin/IconDlg/IconDlg.h /* Module : ICONDLG.H Purpose: Interface for an MFC class for an Icon Picker dialog similar to the version found in Internet Explorer 4 PP2 Created: PJN / ICONDLG/1 / 25-07-1997 History: None Copyright (c) 1997 by <NAME>. All rights reserved. */ ////////////////////////////////// Macros /////////////////////////// #ifndef __ICONDLG_H__ #define __ICONDLG_H__ ///////////////////////////////// Includes ////////////////////////////////// #include "resource.h" ///////////////////////////////// Classes //////////////////////////////////// class CIconDialog : public CDialog { public: CIconDialog(CWnd* pParent = NULL); BOOL SetIcon(const CString& sFilename, int nIndex); void GetIcon(CString& sFilename, int& nIconIndex); protected: //{{AFX_VIRTUAL(CIconDialog) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL //{{AFX_DATA(CIconDialog) enum { IDD = IDD_CHOOSE_ICON }; CListBox m_ctrlIconList; CString m_sFilename; int m_nIconIndex; //}}AFX_DATA //{{AFX_MSG(CIconDialog) afx_msg void OnBrowse(); afx_msg void OnMeasureItem(int nIDCtl, LPMEASUREITEMSTRUCT lpMeasureItemStruct); afx_msg void OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct); afx_msg void OnDestroy(); virtual void OnOK(); afx_msg void OnDblclkIconlist(); virtual BOOL OnInitDialog(); //}}AFX_MSG DECLARE_MESSAGE_MAP() void UpdateIconList(); }; #endif //__ICONDLG_H__ <file_sep>/tools/CornerBin/CornerBin/CBSettings.cpp #include "StdAfx.h" #include "CBSettings.h" CCBSettings::CCBSettings(void) { } CCBSettings::~CCBSettings(void) { } BOOL CCBSettings::LoadSettings(void) { CRegKey rSoftware, rBeem, rCB; rSoftware.Open(HKEY_CURRENT_USER, _T("Software")); rBeem.Create(rSoftware, _T("Beem Software")); rCB.Create(rBeem, _T("CornerBin")); //Attempt to load settings, and create defaults if they aren't already set. LoadARegString(m_Settings.m_strEmptyIcon, &rCB, _T("EmptyIcon"), _T("")); LoadARegString(m_Settings.m_strFullIcon, &rCB, _T("FullIcon"), _T("")); LoadARegString(m_Settings.m_strToolTip, &rCB, _T("ToolTip"), _T("Recycle Bin")); LoadARegDword(m_Settings.m_bEmptyPrompt, &rCB, _T("PromptBeforeEmpty"), 1); LoadARegDword(m_Settings.m_bOpenRBOnDblClk, &rCB, _T("OpenRBOnDblClk"), 1); LoadARegDword(m_Settings.m_nUpdateFreq, &rCB, _T("UpdateFrequency"), 1000); LoadARegDword(m_Settings.m_bSimpleMenu, &rCB, _T("SimpleMenu"), 0); rCB.Close(); rBeem.Close(); rSoftware.Close(); return TRUE; } BOOL CCBSettings::SaveSettings(void) { CRegKey rSoftware, rBeem, rCB; rSoftware.Open(HKEY_CURRENT_USER, _T("Software")); rBeem.Create(rSoftware, _T("Beem Software")); rCB.Create(rBeem, _T("CornerBin")); rCB.SetStringValue(_T("EmptyIcon"), m_Settings.m_strEmptyIcon); rCB.SetStringValue(_T("FullIcon"), m_Settings.m_strFullIcon); rCB.SetStringValue(_T("ToolTip"), m_Settings.m_strToolTip); rCB.SetDWORDValue(_T("PromptBeforeEmpty"), m_Settings.m_bEmptyPrompt); rCB.SetDWORDValue(_T("OpenRBOnDblClk"), m_Settings.m_bOpenRBOnDblClk); rCB.SetDWORDValue(_T("UpdateFrequency"), m_Settings.m_nUpdateFreq); rCB.SetDWORDValue(_T("SimpleMenu"), m_Settings.m_bSimpleMenu); rCB.Close(); rBeem.Close(); rSoftware.Close(); return 0; } LPCTSTR CCBSettings::GetFullIcon(void) { return m_Settings.m_strFullIcon; } LPCTSTR CCBSettings::GetEmptyIcon(void) { return m_Settings.m_strEmptyIcon; } BOOL CCBSettings::GetEmptyPrompt(void) { return m_Settings.m_bEmptyPrompt != 0; } BOOL CCBSettings::GetOpenOnDblClk(void) { return m_Settings.m_bOpenRBOnDblClk != 0; } void CCBSettings::SetSettings(const SSettings* pSettings) { m_Settings = *pSettings; SaveSettings(); } LPCTSTR CCBSettings::GetTooTip(void) { return m_Settings.m_strToolTip; } DWORD CCBSettings::GetUpdateFreq(void) { return m_Settings.m_nUpdateFreq; } BOOL CCBSettings::GetSimpleMenu(void) { return m_Settings.m_bSimpleMenu != 0; } void CCBSettings::LoadARegString(CString& strOut, CRegKey* pKey, LPCTSTR strName, LPCTSTR strDefault) { TCHAR strTemp[1024]; DWORD nChars = 1023; strOut = strDefault; if(ERROR_SUCCESS == pKey->QueryStringValue(strName, strTemp, &nChars)) { strOut = strTemp; } else { pKey->SetStringValue(strName, strOut); } } void CCBSettings::LoadARegDword(DWORD& nOut, CRegKey* pKey, LPCTSTR strName, DWORD nDefault) { nOut = nDefault; pKey->QueryDWORDValue(strName, nOut); } void CCBSettings::GetSettings(SSettings* pSettingsOut) { *pSettingsOut = m_Settings; } <file_sep>/games/Explor2002/Source_Old/Beta 2/Readme.txt Readme for Explor(tm): A New World by <NAME> Explor Play Game Files: Explor.exe - The game of Explor(still in development) images\*.img - The images used in the game Explor *.map - Maps used by the game Explor explor.ico - Icon developed for the explor game credit.txt - credits for the game credit.exe - scrolls credits.txt up the screen needs further development Explor Development Files: Genwall.exe - Generates the images used as walls in explor binread.exe - dumps a copy of integer binary in a file *.bas - source code used for explor development Explor, ExplorED, ExplorSCIPT, Beem Software and their respective logos are property of Blaine Myers. Explor, ExplorED, ExplorSCRIPT, and Beem Software are copyright (c), 2001 by <NAME>. ======================================================== === Version History === === for Explor: A New World === ======================================================== vX.XX Developing stages of Exlor Beta 2 v0.04b (August 6, 2000) Added automap. Made it so automap can be turned off if the value is false. v0.03b (August 6, 2000) Now there is only one load () function. Fixed a bug that appeared while facing north v0.02b The Beta release of this software title. v0.00c A 2D version of the game before it was rendered 3D.<file_sep>/tools/fs_sys2/fs_fs2.h #ifndef __FS_FS2_H__ #define __FS_FS2_H__ #include "fs_sys2.h" #include "fs_file.h" #include "fs_list_stack.h" #include "fs_internal.h" template<class T> static void FS_SAFE_DELETE_ARRAY(T*& p, LF_ALLOC_REASON reason){ if(p){FS_Free(p, reason); p=FS_NULL;} } template<class T> static void FS_SAFE_DELETE(T*& p, LF_ALLOC_REASON reason){ if(p){FS_Free(p, reason); p=FS_NULL;} } template<class T> static T FS_max(T v1, T v2){return ((v1)>(v2))?(v1):(v2); } template<class T> static T FS_min(T v1, T v2){return ((v1)<(v2))?(v1):(v2); } template<class T> static T FS_clamp(T v1, T min, T max){ return ( (v1)>(max)?(max):(v1)<(min)?(min):(v1) ); } class FS_SYS2_EXPORTS CLFileSystem: public IFsMemObj { public: CLFileSystem(); ~CLFileSystem(); fs_dword MountBaseA(fs_cstr8 szOSPath); fs_dword MountBaseW(fs_cstr16 szOSPath); fs_dword MountA(fs_cstr8 szOSPath, fs_cstr8 szMountPath, fs_dword Flags); fs_dword MountW(fs_cstr16 szOSPath, fs_cstr16 szMountPath, fs_dword Flags); fs_dword MountLPKA(fs_cstr8 szMountedFile, fs_dword Flags); fs_dword MountLPKW(fs_cstr16 szMountedFile, fs_dword Flags); fs_bool UnMountAll(); fs_bool ExistsA(fs_cstr8 szFilename); fs_bool ExistsW(fs_cstr16 szFilename); CLFile* OpenFileA(fs_cstr8 szFilename, fs_dword Access, fs_dword CreateMode); CLFile* OpenFileW(fs_cstr16 szFilename, fs_dword Access, fs_dword CreateMode); fs_bool CloseFile(CLFile* pFile); void EnumerateFilesOfTypeA( fs_cstr8 Ext , FS_ENUMERATE_FUNCA EnumerateFunc , void* Data ); void EnumerateFilesOfTypeW( fs_cstr16 Ext , FS_ENUMERATE_FUNCW EnumerateFunc , void* Data ); void PrintMountInfo(FS_PRINT_MOUNT_INFO_TYPE Type); private: static const fs_dword PART_TABLE_SIZE = 256; //Data containing information about a mounted file: struct MOUNT_FILE { fs_pathW szMountFileW; fs_pathW szOSFileW; fs_dword ExtOffset; fs_dword Flags; fs_dword nSize; fs_dword nCmpSize; fs_dword nOffset; static const fs_dword MOUNT_FILE_ARCHIVED =(1<<0); //This file is archived. static const fs_dword MOUNT_FILE_READONLY =(1<<1); //The file is read only. static const fs_dword MOUNT_FILE_ZLIBCMP =(1<<2); //The file is compressed with zlib compression. static const fs_dword MOUNT_FILE_DIRECTORY=(1<<3); //The mount file is a directory. static const fs_dword MOUNT_FILE_EMPTY =(1<<4); //This partition table entry is empty and can be mounted over. }; //The partition table is used to store all the mounted file information. //It stores an array of MOUNT_FILEs in a hash table and uses hash values //to lookup information. class FS_SYS2_EXPORTS CPartTable: public IFsMemObj { private: static const fs_dword HASH_SIZE = 1024; struct MOUNT_FILE_EX: public MOUNT_FILE, CLfListStack::LSItem { fs_dword nHashValue; MOUNT_FILE_EX* pNext; }; MOUNT_FILE_EX* m_HashList[HASH_SIZE]; const fs_dword m_nMaxFiles; MOUNT_FILE_EX* m_pMasterList; CLfListStack m_UnusedFiles; CPartTable*const m_Next; public: CPartTable( CPartTable* Next , fs_dword nMaxFiles ); ~CPartTable(); void Clear(); fs_bool IsFull()const; CPartTable* GetNext()const{ return m_Next; } //The MountFile function mounts the specified MOUNT_FILE data. //The only flag that is meaningful here is MOUNT_FILE_OVERWRITE //and MOUNT_FILE_OVERWRITELPKONLY. //which, when specified, will cause a duplicate mount file to //overwrite a previous mount file. If not specifed the duplicate //will not be overwritten. The LPK only will only overwrite a file //if the previous file is archived. If the file is a disk file it //will not be overwritten. This is useful so that new lpk files //will take priority over old ones, but disk files still have //the highest priority. fs_bool MountFile(MOUNT_FILE* pFile, fs_dword Flags); CLFileSystem::MOUNT_FILE* FindFile(fs_cstr16 szFile); void PrintMountInfo(FS_PRINT_MOUNT_INFO_TYPE Type); static void PrintFileInfo(MOUNT_FILE_EX* pFile); void EnumerateFilesOfTypeA( fs_cstr8 Ext , FS_ENUMERATE_FUNCA EnumerateFunc , void* Data ); void EnumerateFilesOfTypeW( fs_cstr16 Ext , FS_ENUMERATE_FUNCW EnumerateFunc , void* Data ); private: static fs_dword GetHashValue1024(fs_cstr16 szString); }; private: CPartTable* m_PrtTableList; fs_bool m_bBaseMounted; fs_pathW m_szBasePath; fs_dword MountDirW(fs_cstr16 szOSPath, fs_cstr16 szMountPath, fs_dword Flags); fs_dword MountDirA(fs_cstr8 szOSPath, fs_cstr8 szMountPath, fs_dword Flags); fs_bool MountFile(MOUNT_FILE* pFile, fs_dword Flags); MOUNT_FILE* GetFileInfoW( fs_cstr16 szMountPath , CPartTable** OwnerTable ); MOUNT_FILE* GetFileInfoA( fs_cstr8 szMountPath , CPartTable** OwnerTable ); CLFile* OpenExistingFile(const MOUNT_FILE* pMountInfo, BDIO_FILE File, fs_dword Access, fs_bool bNew); }; #endif __FS_FS2_H__<file_sep>/games/Legacy-Engine/Source/lf_sys2/lf_c_interface.cpp //lf_c_interface.cpp - Code for the C interface for the file system. #include "lf_fs2.h" //#define FS_ON_STACK #ifdef FS_ON_STACK CLFileSystem g_FS; CLFileSystem* g_pFS=&g_FS; #else !FS_ON_STACK CLFileSystem* g_pFS=LF_NULL; #endif FS_ON_STACK //A testing function, this will not be the final directory listing function extern "C" void FS_PrintMountInfo() { g_pFS->PrintMountInfo(); } //File system function (c-interface). extern "C" lf_bool FS_Initialize(lf_dword nMaxFiles, LF_ALLOC_FUNC pAlloc, LF_FREE_FUNC pFree) { if(pAlloc && pFree) LF_SetMemFuncs(pAlloc, pFree); #ifndef FS_ON_STACK g_pFS=new CLFileSystem(nMaxFiles); if(!g_pFS) { LF_ErrPrintW(L"FS_Initalize Error: Not enough memory.", ERR_LEVEL_ERROR); return LF_FALSE; } #endif return LF_TRUE; } extern "C" lf_bool FS_Shutdown() { lf_bool bResult=g_pFS->UnMountAll(); #ifndef FS_ON_STACK delete g_pFS; #endif FS_ON_STACK return bResult; } extern "C" lf_dword FS_MountBaseA(lf_cstr szOSPath) { return g_pFS->MountBaseA(szOSPath); } extern "C" lf_dword FS_MountBaseW(lf_cwstr szOSPath) { return g_pFS->MountBaseW(szOSPath); } extern "C" lf_dword FS_MountA(lf_cstr szOSPath, lf_cstr szMountPath, lf_dword Flags) { return g_pFS->MountA(szOSPath, szMountPath, Flags); } extern "C" lf_dword FS_MountW(lf_cwstr szOSPath, lf_cwstr szMountPath, lf_dword Flags) { return g_pFS->MountW(szOSPath, szMountPath, Flags); } extern "C" lf_dword FS_MountLPKA(lf_cstr szMountedFile, lf_dword Flags) { return g_pFS->MountLPKA(szMountedFile, Flags); } extern "C" lf_dword FS_MountLPKW(lf_cwstr szMountedFile, lf_dword Flags) { return g_pFS->MountLPKW(szMountedFile, Flags); } extern "C" lf_bool FS_UnMountAll() { return g_pFS->UnMountAll(); } //File access functions c-interface. extern "C" LF_FILE3 LF_OpenA(lf_cstr szFilename, lf_dword Access, lf_dword CreateMode) { return g_pFS->OpenFileA(szFilename, Access, CreateMode); } extern "C" LF_FILE3 LF_OpenW(lf_cwstr szFilename, lf_dword Access, lf_dword CreateMode) { return g_pFS->OpenFileW(szFilename, Access, CreateMode); } extern "C" lf_bool LF_Close(LF_FILE3 File) { return g_pFS->CloseFile((CLFile*)File); } extern "C" lf_dword LF_Read(LF_FILE3 File, lf_void* pOutBuffer, lf_dword nSize) { CLFile* pFile=(CLFile*)File; return pFile->Read(pOutBuffer, nSize); } extern "C" lf_dword LF_Write(LF_FILE3 File, lf_void* pInBuffer, lf_dword nSize) { CLFile* pFile=(CLFile*)File; return pFile->Write(pInBuffer, nSize); } extern "C" lf_dword LF_Tell(LF_FILE3 File) { CLFile* pFile=(CLFile*)File; return pFile->Tell(); } extern "C" lf_dword LF_Seek(LF_FILE3 File, LF_SEEK_TYPE nMode, lf_long nOffset) { CLFile* pFile=(CLFile*)File; return pFile->Seek(nMode, nOffset); } extern "C" lf_dword LF_GetSize(LF_FILE3 File) { CLFile* pFile=(CLFile*)File; return pFile->GetSize(); } extern "C" lf_pcvoid LF_GetMemPointer(LF_FILE3 File) { CLFile* pFile=(CLFile*)File; return pFile->GetMemPointer(); } extern "C" lf_bool LF_IsEOF(LF_FILE3 File) { CLFile* pFile=(CLFile*)File; return pFile->IsEOF(); }<file_sep>/games/Legacy-Engine/Scrapped/old/old_test_code.cpp //Obsolete test stuff... #define LVTVERTEX_TYPE (D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_DIFFUSE|D3DFVF_TEX2) typedef struct _LVTVERTEX{ float x, y, z; float nx, ny, nz; lg_dword diffuse; float tu, tv; float tcu, tcv; }LVTVERTEX; class CLExplorMap { private: lf_bool m_bOpen; lg_word m_nWidth; lg_word m_nHeight; lg_word* m_pTiles; IDirect3DDevice9* m_pDevice; IDirect3DTexture9* m_pWallTex; IDirect3DTexture9* m_pDoorTex; IDirect3DVertexBuffer9* m_pVB; public: CLExplorMap(); ~CLExplorMap(); void Open(IDirect3DDevice9* pDevice, lf_path szFilename); void Validate(); void Invalidate(); void Render(); void Close(); }; CLExplorMap::CLExplorMap(): m_bOpen(LG_FALSE), m_nWidth(0), m_nHeight(0), m_pTiles(LG_NULL), m_pWallTex(LG_NULL), m_pDoorTex(LG_NULL) { } CLExplorMap::~CLExplorMap() { Close(); } void CLExplorMap::Open(IDirect3DDevice9* pDevice, lf_path szFilename) { Close(); LF_FILE3 fileMap=LF_Open(szFilename, LF_ACCESS_READ, LF_OPEN_EXISTING); if(!fileMap) return; lg_word nWord1, nWord2; LF_Read(fileMap, &nWord1, 2); LF_Read(fileMap, &nWord2, 2); if(nWord1!=*(lg_word*)"EM" || nWord2!=3) { LF_Close(fileMap); return; } //Really the only information needed //is the width and height, the rest of the information //isn't even used (or necessary). LF_Seek(fileMap, LF_SEEK_CURRENT, 8); LF_Read(fileMap, &m_nWidth, 2); LF_Read(fileMap, &m_nHeight, 2); LF_Seek(fileMap, LF_SEEK_CURRENT, 14); m_pTiles=new lg_word[m_nWidth*m_nHeight]; LF_Read(fileMap, m_pTiles, m_nWidth*m_nHeight*sizeof(lg_word)); LF_Close(fileMap); //We now have the map all read, so we should prepare the rendering features. m_pDevice=pDevice; Validate(); m_bOpen=LG_TRUE; } void CLExplorMap::Validate() { if(!m_pWallTex) m_pWallTex=Tex_Load2("/dbase/Explor Test/explor_wall.tga"); if(!m_pDoorTex) m_pDoorTex=Tex_Load2("/dbase/Explor Test/explor_door.tga"); } void CLExplorMap::Invalidate() { L_safe_release(m_pWallTex); L_safe_release(m_pDoorTex); } void CLExplorMap::Render() { if(!m_bOpen) return; LVTVERTEX verts[10]; ML_MAT matTrans; ML_MatIdentity(&matTrans); m_pDevice->SetTransform(D3DTS_WORLD, (D3DMATRIX*)&matTrans); m_pDevice->SetFVF(D3DFVF_XYZ|D3DFVF_TEX2); IDirect3DDevice9_SetRenderState(m_pDevice, D3DRS_ALPHABLENDENABLE, FALSE); for(lg_short nx=-1; nx<m_nWidth+1; nx++) { for(lg_short ny=-1; ny<m_nHeight+1; ny++) { #define EMAP_SCALE 2.0f float fx=nx*EMAP_SCALE, fy=ny*EMAP_SCALE; if(ny<0 || nx<0 || nx>=m_nWidth || ny>=m_nHeight) { m_pDevice->SetTexture(0, m_pWallTex); goto Rasterize; } switch(m_pTiles[nx+m_nWidth*ny]) { case 10: m_pDevice->SetTexture(0, m_pWallTex); break; case 20: m_pDevice->SetTexture(0, m_pDoorTex); break; case 0: default: m_pDevice->SetTexture(0, m_pWallTex); verts[0].x=fx; verts[0].y=0.0f; verts[0].z=fy; verts[0].nx=0.0f; verts[0].ny=1.0f; verts[1].x=fx; verts[1].y=0.0f; verts[1].z=fy+EMAP_SCALE; verts[1].nx=0.0f; verts[1].ny=0.0f; verts[3].x=fx+EMAP_SCALE; verts[3].y=0.0f; verts[3].z=fy+EMAP_SCALE; verts[3].nx=1.0f; verts[3].ny=0.0f; verts[2].x=fx+EMAP_SCALE; verts[2].y=0.0f; verts[2].z=fy; verts[2].nx=1.0f; verts[2].ny=1.0f; m_pDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, verts, sizeof(LVTVERTEX)); continue; break; } Rasterize: //Render the square... verts[0].x=fx; verts[0].y=0.0f; verts[0].z=fy; verts[0].nx=0.0f; verts[0].ny=1.0f; verts[1].x=fx; verts[1].y=EMAP_SCALE; verts[1].z=fy; verts[1].nx=0.0f; verts[1].ny=0.0f; verts[2].x=fx+EMAP_SCALE; verts[2].y=0.0f; verts[2].z=fy; verts[2].nx=1.0f; verts[2].ny=1.0f; verts[3].x=fx+EMAP_SCALE; verts[3].y=EMAP_SCALE; verts[3].z=fy; verts[3].nx=1.0f; verts[3].ny=0.0f; verts[4].x=fx+EMAP_SCALE; verts[4].y=0.0f; verts[4].z=fy+EMAP_SCALE; verts[4].nx=0.0f; verts[4].ny=1.0f; verts[5].x=fx+EMAP_SCALE; verts[5].y=EMAP_SCALE; verts[5].z=fy+EMAP_SCALE; verts[5].nx=0.0f; verts[5].ny=0.0f; verts[6].x=fx; verts[6].y=0.0f; verts[6].z=fy+EMAP_SCALE; verts[6].nx=1.0f; verts[6].ny=1.0f; verts[7].x=fx; verts[7].y=EMAP_SCALE; verts[7].z=fy+EMAP_SCALE; verts[7].nx=1.0f; verts[7].ny=0.0f; verts[8].x=fx; verts[8].y=0.0f; verts[8].z=fy; verts[8].nx=0.0f; verts[8].ny=1.0f; verts[9].x=fx; verts[9].y=EMAP_SCALE; verts[9].z=fy; verts[9].nx=0.0f; verts[9].ny=0.0f; m_pDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 8, verts, sizeof(LVTVERTEX)); verts[0].x=fx; verts[0].y=EMAP_SCALE; verts[0].z=fy; verts[1].x=fx; verts[1].y=EMAP_SCALE; verts[1].z=fy+EMAP_SCALE; verts[3].x=fx+EMAP_SCALE; verts[3].y=EMAP_SCALE; verts[3].z=fy+EMAP_SCALE; verts[2].x=fx+EMAP_SCALE; verts[2].y=EMAP_SCALE; verts[2].z=fy; m_pDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, verts, sizeof(LVTVERTEX)); } } } void CLExplorMap::Close() { if(!m_bOpen) return; L_safe_delete_array(m_pTiles); Invalidate(); m_bOpen=LG_FALSE; } void CLVTObj::RenderTestWall() { ML_MAT matTrans; ML_MatIdentity(&matTrans); IDirect3DDevice9_SetFVF(m_pDevice, LVTVERTEX_TYPE); IDirect3DDevice9_SetStreamSource(m_pDevice,0,m_lpVB,0,sizeof(LVTVERTEX)); ML_MatIdentity(&matTrans); //matTrans._43=50.0f; //matTrans._42=0.0f; //m_pDevice->SetTransform(D3DTS_VIEW, (D3DMATRIX*)&matTrans); //ML_MatRotationY(&matTrans, LT_GetTimeMS()/-3000.0f); //ML_MatIdentity(&matTrans); ML_MAT matSize; #define SCALE 0.10f D3DXMatrixScaling((D3DXMATRIX*)&matSize, SCALE, SCALE, SCALE); ML_MatMultiply(&matTrans, &matTrans, &matSize); matTrans._43=0.0f; m_pDevice->SetTransform(D3DTS_WORLD, (D3DMATRIX*)&matTrans); m_pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); #define MULTIPASS #ifdef MULTIPASS IDirect3DDevice9_SetTexture(m_pDevice,0,m_lpTex); IDirect3DDevice9_SetRenderState(m_pDevice, D3DRS_ALPHABLENDENABLE, TRUE); IDirect3DDevice9_DrawPrimitive(m_pDevice,D3DPT_TRIANGLELIST, 0, 200); IDirect3DDevice9_SetRenderState(m_pDevice, D3DRS_ALPHABLENDENABLE, TRUE); IDirect3DDevice9_SetTexture(m_pDevice,0,m_lpLM); IDirect3DDevice9_SetTextureStageState(m_pDevice, 0, D3DTSS_TEXCOORDINDEX, 1); IDirect3DDevice9_SetRenderState(m_pDevice, D3DRS_SRCBLEND, D3DBLEND_ZERO); IDirect3DDevice9_SetRenderState(m_pDevice, D3DRS_DESTBLEND, D3DBLEND_SRCCOLOR); IDirect3DDevice9_DrawPrimitive(m_pDevice,D3DPT_TRIANGLELIST, 0, 200); IDirect3DDevice9_SetTextureStageState(m_pDevice, 0, D3DTSS_TEXCOORDINDEX, 0); #else m_pDevice->SetTexture(0,m_lpTex); m_pDevice->SetTexture(1,m_lpLM); m_pDevice->SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, 0); m_pDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE); m_pDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1); m_pDevice->SetTextureStageState(1, D3DTSS_TEXCOORDINDEX, 1); m_pDevice->SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_TEXTURE); m_pDevice->SetTextureStageState(1, D3DTSS_COLORARG2, D3DTA_CURRENT); m_pDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_MODULATE); m_pDevice->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 200); m_pDevice->SetTexture(1, LG_NULL); #endif IDirect3DDevice9_SetRenderState(m_pDevice, D3DRS_CULLMODE, D3DCULL_CCW); } void CLVTObj::ValidateTestWall() { // Stuff for the test wall. LVTVERTEX lpVerts[600]; int x=0, y=0, i=0; lg_result nResult=0; void* lpBuffer=LG_NULL; //Code for test wall. m_lpTex=Tex_Load2("/dbase/textures/graybrick.tga"); m_lpLM=Tex_Load2("/dbase/textures/misc/spotdown01lm.tga"); for(x=0, i=0; x<10; x++) { for(y=0; y<10; y++, i+=6) { lg_bool bExtY=LG_FALSE; lg_bool bExtX=LG_FALSE; float fTop=0.0f; float fBottom=1.0f; float fLeft=0.0f; float fRight=1.0f; if(!(x%2)) { fLeft=0.0f; fRight=0.5f; } else { fLeft=0.5f; fRight=1.0f; } if(!(y%2)) { fTop=0.0f; fBottom=0.5f; } else { fTop=0.5f; fBottom=1.0f; } lpVerts[i].x=x*10.0f-50.0f; lpVerts[i].y=0.0f; lpVerts[i].z=y*10.0f-50.0f; lpVerts[i].nx=0.0f; lpVerts[i].nz=0.0f; lpVerts[i].ny=1.0f; lpVerts[i].diffuse=0xFFFFFFFF; lpVerts[i].tu=0.0f; lpVerts[i].tv=1.0f; lpVerts[i].tcu=fLeft; lpVerts[i].tcv=fBottom; lpVerts[i+1].x=x*10.0f+10.0f-50.0f; lpVerts[i+1].y=0.0f; lpVerts[i+1].z=y*10.0f+10.0f-50.0f; lpVerts[i+1].nx=0.0f; lpVerts[i+1].nz=0.0f; lpVerts[i+1].ny=1.0f; lpVerts[i+1].diffuse=0xFFFFFFFF; lpVerts[i+1].tu=1.0f; lpVerts[i+1].tv=0.0f; lpVerts[i+1].tcu=fRight; lpVerts[i+1].tcv=fTop;; lpVerts[i+2].x=x*10.0f+10.0f-50.0f; lpVerts[i+2].y=0.0f; lpVerts[i+2].z=y*10.0f-50.0f; lpVerts[i+2].nx=0.0f; lpVerts[i+2].nz=0.0f; lpVerts[i+2].ny=1.0f; lpVerts[i+2].diffuse=0xFFFFFFFF; lpVerts[i+2].tu=1.0f; lpVerts[i+2].tv=1.0f; lpVerts[i+2].tcu=fRight; lpVerts[i+2].tcv=fBottom; memcpy(&lpVerts[i+3], &lpVerts[i+1], sizeof(lpVerts[0])); memcpy(&lpVerts[i+4], &lpVerts[i], sizeof(lpVerts[0])); lpVerts[i+5].x=x*10.0f-50.0f; lpVerts[i+5].y=0.0f; lpVerts[i+5].z=y*10.0f+10.0f-50.0f; lpVerts[i+5].nx=0.0f; lpVerts[i+5].nz=0.0f; lpVerts[i+5].ny=1.0f; lpVerts[i+5].diffuse=0x00FFFFFF; lpVerts[i+5].tu=0.0f; lpVerts[i+5].tv=0.0f; lpVerts[i+5].tcu=fLeft; lpVerts[i+5].tcv=fTop; } } nResult=IDirect3DDevice9_CreateVertexBuffer( m_pDevice, sizeof(LVTVERTEX)*600, 0, LVTVERTEX_TYPE, D3DPOOL_MANAGED, &m_lpVB, LG_NULL); if(LG_FAILED(nResult)) { Err_PrintDX("IDirect3DDevice9::CreateVertexBuffer", nResult); L_safe_release(m_lpLM); L_safe_release(m_lpTex); return; } nResult=IDirect3DVertexBuffer9_Lock(m_lpVB, 0, sizeof(LVTVERTEX)*600, &lpBuffer, 0); if(lpBuffer) memcpy(lpBuffer, &lpVerts, sizeof(LVTVERTEX)*600); IDirect3DVertexBuffer9_Unlock(m_lpVB); } <file_sep>/tools/CornerBin/CornerBin/CBTrayIcon.cpp #include "StdAfx.h" #include "Resource.h" #include "CBTrayIcon.h" const DWORD CCBTrayIcon::s_nUEID = 0xACE48A8F; #ifdef _DEBUG const GUID CCBTrayIcon::s_GUID = { 0xbc1e76d3, 0x6229, 0x4f4c, { 0xb9, 0x7f, 0xd3, 0x78, 0xb8, 0xb9, 0x68, 0xbe } }; #else const GUID CCBTrayIcon::s_GUID = { 0x3479e298, 0x417e, 0x4938, { 0x95, 0x1b, 0x13, 0xf, 0xa1, 0xf7, 0x21, 0x7 } }; #endif #define NIF_USING_GUID 0//NIF_GUID CCBTrayIcon::CCBTrayIcon(void) : m_pSettings(NULL) , m_bIsFull(FALSE) , m_IcoEmpty(NULL) , m_IcoFull(NULL) { } CCBTrayIcon::~CCBTrayIcon(void) { } BOOL CCBTrayIcon::Init(HINSTANCE hInst, HWND hwndParent, CCBSettings* pSettings) { m_pSettings = pSettings; m_hwndParent = hwndParent; LoadIcons(); NOTIFYICONDATA NoteData; memset(&NoteData, 0, sizeof(NoteData)); NoteData.cbSize = NOTIFYICONDATA_V3_SIZE; NoteData.uVersion = s_nVERSION; NoteData.hWnd = hwndParent; NoteData.uID = s_nUEID; NoteData.uFlags = NIF_ICON|NIF_MESSAGE|NIF_TIP|NIF_USING_GUID; NoteData.hIcon = IsRBFull()?m_IcoFull:m_IcoEmpty; NoteData.guidItem = s_GUID; NoteData.uCallbackMessage = WM_SYSTRAYNOTIFY; _tcscpy_s(NoteData.szTip, 63, m_pSettings->GetTooTip()); BOOL bRes = Shell_NotifyIcon(NIM_ADD, &NoteData); if(!bRes) AfxMessageBox(TEXT("Could not init tray icon.")); Update(); return bRes; } void CCBTrayIcon::UnInit(void) { NOTIFYICONDATA NoteData; memset(&NoteData, 0, sizeof(NoteData)); NoteData.cbSize = NOTIFYICONDATA_V3_SIZE; NoteData.uVersion = s_nVERSION; NoteData.hWnd = m_hwndParent; NoteData.uFlags = NIF_USING_GUID; NoteData.uID = s_nUEID; NoteData.guidItem = s_GUID; Shell_NotifyIcon(NIM_DELETE, &NoteData); //Make sure any currently loaded icons are destroyed: ::DestroyIcon(m_IcoFull); ::DestroyIcon(m_IcoEmpty); m_IcoFull = NULL; m_IcoEmpty = NULL; } void CCBTrayIcon::Update(void) { //Update is called as often as the application wishes. //It checks the status of the RB and changes the icon if necessary. BOOL bIsFull = IsRBFull(); if(m_bIsFull != bIsFull) { //The status is changed, so we should change the state and icon. m_bIsFull = bIsFull; //And set the chosen icon: NOTIFYICONDATA NoteData; memset(&NoteData, 0, sizeof(NoteData)); NoteData.cbSize = NOTIFYICONDATA_V3_SIZE; NoteData.uVersion = s_nVERSION; NoteData.hWnd = m_hwndParent; NoteData.uFlags = NIF_ICON|NIF_USING_GUID; NoteData.uID = s_nUEID; NoteData.guidItem = s_GUID; NoteData.hIcon = m_bIsFull?m_IcoFull:m_IcoEmpty; Shell_NotifyIcon(NIM_MODIFY, &NoteData); } } BOOL CCBTrayIcon::IsRBFull(void) { ::SHQUERYRBINFO RBInfo; memset(&RBInfo, 0, sizeof(RBInfo)); RBInfo.cbSize = sizeof(RBInfo); ::SHQueryRecycleBin(NULL, &RBInfo); return (RBInfo.i64NumItems != 0); } HICON CCBTrayIcon::LoadIcon2(LPCTSTR strIcon) { //This function loads an icon based upon the string specification, or returns NULL if it couldn't. //The string specification is as follows //("(iconpath)"(:(resourcenumber))?) //That is, a path is always specified, and a resource number is specified if the path was a dll or other library. CString strIconC = strIcon; DWORD nResID = 0; int nToken=0; CString strPath = strIconC.Tokenize(_T("|"), nToken); if(-1 == nToken) return NULL; CString strResID = strIconC.Tokenize(_T("|"), nToken); nResID = (nToken != -1)?_ttoi(strResID):0xFFFFFFFF; ///CString strMsg; ///strMsg.Format(_T("The path is \"%s\" the res id is %d"), strPath, nResID); ///::AfxMessageBox(strMsg); //If no resource id was specified, the icon should just be a file: HICON hIcon[1] = {NULL}; if(0xFFFFFFFF == nResID) { hIcon[0] = ::LoadIcon(NULL, strPath); } else { ::ExtractIconEx(strPath, nResID, NULL, hIcon, 1); } return hIcon[0]; } void CCBTrayIcon::LoadIcons(void) { //Make sure any currently loaded icons are destroyed: ::DestroyIcon(m_IcoFull); ::DestroyIcon(m_IcoEmpty); m_IcoFull = NULL; m_IcoEmpty = NULL; m_IcoFull = this->LoadIcon2(m_pSettings->GetFullIcon()); m_IcoEmpty = this->LoadIcon2(m_pSettings->GetEmptyIcon()); //If no icon was loaded, we load the default icons. if(NULL == m_IcoFull) m_IcoFull = (HICON)::LoadImage(::AfxGetInstanceHandle(), MAKEINTRESOURCE(IDI_DEFF), IMAGE_ICON, 16, 16, 0); if(NULL == m_IcoEmpty) m_IcoEmpty = (HICON)::LoadImage(::AfxGetInstanceHandle(), MAKEINTRESOURCE(IDI_DEFE), IMAGE_ICON, 16, 16, 0); } <file_sep>/Misc/DBXExporter/DBXExporter/DBXExporter.cpp #include <stdio.h> #include <conio.h> #include "oedbx/examples/ex1.h" int main( int argc , char* argv[] ) { printf( "DBX Exporter (c) 2016 <NAME>\n" ); ExtractAllMessages( "../Might and Magic.dbx" , "../extraction.log" ); printf( "Done.\n" ); #if defined( _DEBUG ) _getch(); #endif return 0; }<file_sep>/tools/fs_sys2/fs_bdio.h #ifndef _FS_BDIO_H__ #define _FS_BDIO_H__ #include "fs_sys2.h" #ifdef __cplusplus extern "C"{ #endif __cplusplus /* Basic DIO stuff, should only be used internally only. */ static fs_bool FS_CheckFlag(fs_dword flag, fs_dword var){ return ((flag&var) != 0); } static const fs_dword LF_ACCESS_BDIO_TEMP = (1 << 5); typedef fs_intptr_t BDIO_FILE; BDIO_FILE BDIO_OpenA(fs_cstr8 szFilename, LF_CREATE_MODE nMode, fs_dword nAccess); BDIO_FILE BDIO_OpenW(fs_cstr16 szFilename, LF_CREATE_MODE nMode, fs_dword nAccess); fs_bool BDIO_Close(BDIO_FILE File); fs_dword BDIO_Read(BDIO_FILE File, fs_dword nSize, void* pOutBuffer); fs_dword BDIO_Write(BDIO_FILE File, fs_dword nSize, const void* pInBuffer); fs_dword BDIO_Tell(BDIO_FILE File); fs_dword BDIO_Seek(BDIO_FILE File, fs_long nOffset, LF_SEEK_TYPE nOrigin); fs_dword BDIO_GetSize(BDIO_FILE File); fs_dword BDIO_WriteCompressed(BDIO_FILE File, fs_dword nSize, void* pInBuffer); fs_dword BDIO_ReadCompressed(BDIO_FILE File, fs_dword nSize, void* pOutBuffer); fs_bool BDIO_ChangeDirA(fs_cstr8 szDir); fs_bool BDIO_ChangeDirW(fs_cstr16 szDir); fs_dword BDIO_GetCurrentDirA(fs_str8 szDir, fs_dword nSize); fs_dword BDIO_GetCurrentDirW(fs_str16 szDir, fs_dword nSize); BDIO_FILE BDIO_OpenTempFileA(LF_CREATE_MODE nMode, fs_dword nAccess); BDIO_FILE BDIO_OpenTempFileW(LF_CREATE_MODE nMode, fs_dword nAccess); fs_dword BDIO_CopyData(BDIO_FILE DestFile, BDIO_FILE SourceFile, fs_dword nSize); fs_dword BDIO_GetFullPathNameW(fs_pathW szPath, const fs_pathW szFilename); fs_dword BDIO_GetFullPathNameA(fs_pathA szPath, const fs_pathA szFilename); typedef void* BDIO_FIND; typedef struct _BDIO_FIND_DATAW{ fs_bool bDirectory; fs_bool bReadOnly; fs_bool bHidden; fs_bool bNormal; fs_large_integer nFileSize; fs_pathW szFilename; }BDIO_FIND_DATAW; typedef struct _BDIO_FIND_DATAA{ fs_bool bDirectory; fs_bool bReadOnly; fs_bool bHidden; fs_bool bNormal; fs_large_integer nFileSize; fs_pathA szFilename; }BDIO_FIND_DATAA; BDIO_FIND BDIO_FindFirstFileW(fs_cstr16 szFilename, BDIO_FIND_DATAW* pFindData); fs_bool BDIO_FindNextFileW(BDIO_FIND hFindFile, BDIO_FIND_DATAW* pFindData); BDIO_FIND BDIO_FindFirstFileA(fs_cstr8 szFilename, BDIO_FIND_DATAA* pFindData); fs_bool BDIO_FindNextFileA(BDIO_FIND hFindFile, BDIO_FIND_DATAA* pFindData); fs_bool BDIO_FindClose(BDIO_FIND hFindFile); fs_char8 BDIO_GetOsPathSeparator(); #ifdef __cplusplus } #endif __cplusplus #endif _FS_BDIO_H__<file_sep>/games/Legacy-Engine/Scrapped/old/le_test.cpp #include "le_test.h" #include "lg_err.h" #include "lg_sys.h" #include "ld_sys.h" #include "lg_func.h" #include <stdio.h> void CLJack::Initialize(ML_VEC3* v3Pos) { CLBase3DEntity::Initialize(v3Pos); m_fMass=65.0f; m_pWalk=LG_LoadSkel("/dbase/skels/mb/mb_walk.lskl", 0); m_pStand=LG_LoadSkel("/dbase/skels/mb/mb_stand1.lskl", 0); m_pJump=LG_LoadSkel("/dbase/skels/mb/mb_jump.lskl", 0); LoadMesh("/dbase/meshes/jack/jack_lantern.xml", 0.023f, LOADMESH_BB45); if(m_pMeshNodes) { m_pMeshNodes[0].SetAnimation(m_pStand, 0, 2000, 0); } InitPhys(LG_TRUE); } void CLJack::ProcessAI() { //For this entity velocity represents the amount of units the entity //will move in one second. (Since max payne entities are small //the velocity is small.) const float DEFAULT_VEL=2.0f; const float DEFAULT_ROT=ML_PI; m_fVelFwd=0.0f; m_fVelStrafe=0.0f; lg_bool bJump=LG_FALSE; if(s_pCmds[COMMAND_MOVEFORWARD].IsActive()) m_fVelFwd=DEFAULT_VEL; if(s_pCmds[COMMAND_MOVELEFT].IsActive()) m_fVelStrafe=-DEFAULT_VEL; if(s_pCmds[COMMAND_MOVERIGHT].IsActive()) m_fVelStrafe=DEFAULT_VEL; if(s_pCmds[COMMAND_MOVEBACK].IsActive()) m_fVelFwd=-DEFAULT_VEL; if(s_pCmds[COMMAND_TURNRIGHT].IsActive()) m_fYaw+=DEFAULT_ROT*s_Timer.GetFElapsed(); if(s_pCmds[COMMAND_TURNLEFT].IsActive()) m_fYaw-=DEFAULT_ROT*s_Timer.GetFElapsed(); if(s_pCmds[COMMAND_MOVEUP].Activated()) bJump=LG_TRUE; if(s_pCmds[COMMAND_SPEED].IsActive()) { m_fVelFwd*=2.0f; m_fVelStrafe*=2.0f; } m_fPitch+=s_pAxis->nY/100.0f; m_fPitch=LG_Clamp(m_fPitch, -(ML_HALFPI-0.001f), (ML_HALFPI-0.001f)); m_v3PhysRot.y=s_pAxis->nX/2.5f; m_v3PhysVel.x+=m_fVelFwd*ML_sinf(m_fYaw)+m_fVelStrafe*ML_sinf(m_fYaw+ML_PI*0.5f); m_v3PhysVel.z+=m_fVelFwd*ML_cosf(m_fYaw)+m_fVelStrafe*ML_cosf(m_fYaw+ML_PI*0.5f); if(bJump)// && m_nMovementType==MOVEMENT_WALKING) { m_v3PhysVel.y=7.0f; m_nMovementType=MOVEMENT_FALLING; } //Update the mesh times... if(!m_pMeshNodes) return; m_pMeshNodes[0].UpdateTime(s_Timer.GetTime()); //Set animations as necessary... if(0)//m_nMovementType==MOVEMENT_FALLING) m_pMeshNodes[0].SetAnimation(m_pJump, 0, 1000, 1); else if((m_fVelFwd!=0.0f || m_fVelStrafe!=0.0f)) m_pMeshNodes[0].SetAnimation(m_pWalk, 0, (m_fVelFwd<0.0f)?-2000:2000, 250); else m_pMeshNodes[0].SetAnimation(m_pStand, 0, 2000, 250); #if 1 Err_MsgPrintf( "Jack's Position: %s: (%.3f, %.3f, %.3f) Vel: (%f, %f, %f) %s", (m_nNumRegions?s_pWorldMap->m_pRegions[m_nRegions[0]].szName:"NOWHERE"), m_v3Pos.x, m_v3Pos.y, m_v3Pos.z, m_v3PhysVel.x, m_v3PhysVel.y, m_v3PhysVel.z, m_nMovementType==MOVEMENT_WALKING?"ON GROUND":"IN AIR"); #endif } void CLBlaineEnt::Initialize(ML_VEC3* v3Pos) { CLBase3DEntity::Initialize(v3Pos); m_fMass=55.0f; m_pWalk=LG_LoadSkel("/dbase/skels/mb/mb_walk.lskl", 0); m_pStand=LG_LoadSkel("/dbase/skels/mb/mb_stand1.lskl", 0); LoadMesh("/dbase/meshes/blaine/blaine.xml", 0.023f, LOADMESH_BB45); //LoadMesh("/dbase/meshes/jack/jack_lantern.xml", 0.023f, LOADMESH_BB45); if(m_pMeshNodes) { m_pMeshNodes[0].SetAnimation(m_pStand, 0, 2000, 0); } m_nLastAIUpdate=s_Timer.GetTime(); m_fRotation=ML_PI*0.25f; //Setup the sounds alGetError(); alGenBuffers(1, &m_SndBuffer); alGenSources(1, &m_Snd); alSourcei(m_Snd, AL_LOOPING, AL_TRUE); CLSndMgr::LS_LoadSoundIntoBuffer( m_SndBuffer, "/dbase/sounds/speech/MyNameIsBlaine.ogg"); alSourcei(m_Snd, AL_BUFFER, m_SndBuffer); alSourcePlay(m_Snd); //alSourcef(m_Snd, AL_MAX_DISTANCE, 10.0f); //alSourcef(m_Snd, AL_REFERENCE_DISTANCE, 5.0f); alSourcef(m_Snd, AL_ROLLOFF_FACTOR, 1.2f); InitPhys(LG_TRUE); } void CLBlaineEnt::ProcessAI() { //For this entity velocity represents the amount of units the entity //will move in one second. const float DEFAULT_VEL=2.5f; const float DEFAULT_ROT=ML_PI; m_fVelFwd=0.0f; m_fVelStrafe=0.0f; m_v3PhysRot.y=m_fRotation; //m_fYaw+=m_fRotation*s_Timer.GetFElapsed(); m_fVelFwd=DEFAULT_VEL*0.5f; if((s_Timer.GetTime()-m_nLastAIUpdate)>5000) { m_fRotation=LG_RandomFloat(-ML_HALFPI, ML_HALFPI); //m_fRotation=-m_fRotation; m_nLastAIUpdate=s_Timer.GetTime(); } m_v3PhysVel.x+=m_fVelFwd*ML_sinf(m_fYaw)+m_fVelStrafe*ML_sinf(m_fYaw+ML_PI*0.5f); m_v3PhysVel.z+=m_fVelFwd*ML_cosf(m_fYaw)+m_fVelStrafe*ML_cosf(m_fYaw+ML_PI*0.5f); //Update the meshes... if(m_pMeshNodes) { m_pMeshNodes[0].UpdateTime(s_Timer.GetTime()); if((m_fVelFwd!=0.0f || m_fVelStrafe!=0.0f)) m_pMeshNodes[0].SetAnimation(m_pWalk, 0, (m_fVelFwd<0.0f)?-2000:2000, 250); else m_pMeshNodes[0].SetAnimation(m_pStand, 0, 2000, 250); } //alSourcefv(m_Snd, AL_POSITION, (ALfloat*)&m_v3Pos); alSource3f(m_Snd, AL_POSITION, m_v3Pos.x, m_v3Pos.y+1.5f, -m_v3Pos.z); alSource3f(m_Snd, AL_VELOCITY, m_v3PhysVel.x, m_v3PhysVel.y, -m_v3PhysVel.z); } #if 0 void CLMonaEnt::Initialize(ML_VEC3* v3Pos) { CLBase3DEntity::Initialize(v3Pos); m_pSkel=LG_LoadSkel("/dbase/meshes/max payne/p2_walk_stand.lskl", 0); LoadMesh("/dbase/meshes/max payne/hooker.xml", 1.0f, LOADMESH_BB45); if(m_pMeshNodes) { m_pMeshNodes[0].SetAnimation(m_pSkel, 0, 2000, 0); } } void CLMonaEnt::ProcessAI() { //For this entity velocity represents the amount of units the entity //will move in one second. const float DEFAULT_VEL=2.5f; const float DEFAULT_ROT=ML_PI; m_fVelFwd=0.0f; m_fVelStrafe=0.0f; m_fYaw+=(DEFAULT_ROT/4.0f)*s_Timer.GetFElapsed(); m_fVelFwd=DEFAULT_VEL*0.5f; while(m_fYaw>ML_2PI) { m_fYaw-=ML_2PI; } while(m_fYaw<0.0f) { m_fYaw+=ML_2PI; } CalculateVelXZ(); //Update the meshes... if(m_pMeshNodes) { m_pMeshNodes[0].UpdateTime(s_Timer.GetTime()); if((m_fVelFwd!=0.0f || m_fVelStrafe!=0.0f)) m_pMeshNodes[0].SetAnimation(m_pSkel, 1, (m_fVelFwd<0.0f)?-2000:2000, 250); else m_pMeshNodes[0].SetAnimation(m_pSkel, 0, 2000, 250); } } #endif void CLBarrelEnt::Initialize(ML_VEC3* v3Pos) { CLBase3DEntity::Initialize(v3Pos); m_fMass=100.0f; LoadMesh("/dbase/meshes/objects/barrel.xml", 0.13f, 0); InitPhys(LG_FALSE); /* ::NewtonBodySetMaterialGroupID(m_pNewtonBody, MTR_OBJECT); ML_VEC3 v3={ m_aabbBase.v3Min.x+(m_aabbBase.v3Max.x-m_aabbBase.v3Min.x)/2, m_aabbBase.v3Min.y+(m_aabbBase.v3Max.y-m_aabbBase.v3Min.y)/2, m_aabbBase.v3Min.z+(m_aabbBase.v3Max.z-m_aabbBase.v3Min.z)/2}; NewtonBodySetCentreOfMass(m_pNewtonBody, (dFloat*)&v3); */ } void CLBarrelEnt::ProcessAI() { } <file_sep>/tools/MConvert/Source/MConvert.cpp #include <windows.h> #include <math.h> #include <stdlib.h> #include <stdio.h> #include <tchar.h> #include "resource.h" #include "MConvert.h" BOOL CALLBACK MainDialogProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); int UpdateFields(HWND hWnd, WORD wCommand); ExData exdata; int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { HWND hdlg=NULL; MSG msg; if(exdata.GetConversionInfo()!=0){ MessageBox(NULL, TEXT("Error Opening Conversion Table"), TEXT("Notice"), MB_OK|MB_ICONERROR); return 0; } hdlg=CreateDialog( hInstance, "MConvertDlg", NULL, (DLGPROC)MainDialogProc); if(hdlg==NULL) return 0; ShowWindow(hdlg, nShowCmd); while(TRUE){ if(!GetMessage(&msg, NULL, 0, 0)){ return msg.wParam; } if(!IsDialogMessage(hdlg, &msg)){ TranslateMessage(&msg); DispatchMessage(&msg); } } return msg.wParam; } BOOL CALLBACK MainDialogProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { int i=0; switch (uMsg){ case WM_COMMAND: { //If the edit box has changed we update the value. if(LOWORD(wParam)==IDC_EDIT1) UpdateFields(hWnd, LOWORD(wParam)); switch (LOWORD(wParam)) { case IDOK: UpdateFields(hWnd, LOWORD(wParam)); break; } break; } case WM_CLOSE:DestroyWindow(hWnd);break; case WM_DESTROY:PostQuitMessage(0);break; case WM_INITDIALOG: for(i=0; i<=exdata.numentries;i++){ SendDlgItemMessage( hWnd, IDC_COMBO1, CB_ADDSTRING, 0, (LPARAM) exdata.countryName[i]); SendDlgItemMessage( hWnd, IDC_COMBO2, CB_ADDSTRING, 0, (LPARAM)exdata.countryName[i]); } break; default:return FALSE; } return TRUE; } BOOL UpdateFields(HWND hWnd, WORD wCommand) { char srcCountryName[255]; char destCountryName[255]; char srcAmnt[20]; char destAmnt[20]; double dSrcAmnt; double dDestAmount; int DataEntry; int DestEntry; GetDlgItemText(hWnd, IDC_COMBO1, srcCountryName, sizeof(srcCountryName)/sizeof(char)); GetDlgItemText(hWnd, IDC_COMBO2, destCountryName, sizeof(destCountryName)/sizeof(char)); GetDlgItemText(hWnd, IDC_EDIT1, srcAmnt, sizeof(srcAmnt)/sizeof(char)); for(int i=0;i<exdata.numentries;i++){ if(strcmp(srcCountryName, exdata.countryName[i])==0)DataEntry=i; if(strcmp(destCountryName, exdata.countryName[i])==0)DestEntry=i; } if(DataEntry>exdata.numentries||DataEntry<0)return FALSE; if(DestEntry>exdata.numentries||DestEntry<0)return FALSE; dSrcAmnt=atof(srcAmnt); //I beleive this is the correct way to convert dDestAmount=dSrcAmnt*exdata.exchangeRate[DestEntry]/exdata.exchangeRate[DataEntry]; sprintf(destAmnt, "%.2f", dDestAmount); SetDlgItemText(hWnd, IDC_STATIC1, destAmnt); return TRUE; } <file_sep>/games/Legacy-Engine/Source/lf_sys2/lf_fs2.cpp #include <stdlib.h> #include <stdio.h> #include <string.h> #include "lf_fs2.h" #include "lf_bdio.h" #include "lf_lpk.h" //NOTES: The file system is fairly simply, but most of the methods have a //wide character and multibyte method that way the file system is compatible //both with Windows 98 and unicode operating systems. The file system stores //information about all files in a partition table that uses hash indexes to //quickly access information about each of the files. //TODO: Testing on windows 98 //Inusuring complete testing, and better support for the multi-byte methods. //Typical mounting procedure. //1) The first thing that needs to be done is to have the base get mounted. //eg. // MountBase(".\"); //This would mount the current directory. //This will get the base file system mounted. //2) Mount any subdirectories. //eg. // Mount("base", "/base1/", MOUNT_FILE_OVERWRITE|MOUNT_FILE_SUBDIRS); // Mount("expansionbase", "/base2/", MOUNT_FILE_OVERWRITE|MOUNT_FILE_SUBDIRS); // This will get the main folders mounted for the application. Note that // You could do something as follows: // Mount("base", "/base1/", MOUNT_FILE_OVERWRITE|MOUNT_FILE_SUBDIRS); // Mount("expansionbase", "/base1/", MOUNT_FILE_OVERWRITE|MOUNT_FILE_SUBDIRS); // And that all files in the OS folder expansionbase would take precedence over // any files in base, but the same mount path would be used no matter what. //3) Mount any LPK files. //eg. // MountLPK("/base1/pak0.lpk", MOUNT_FILE_OVERWRITELPKONLY); // MountLPK("/base1/pak1.lpk", MOUNT_FILE_OVERWRITELPKONLY); // MountLPK("/base1/pak2.lpk", MOUNT_FILE_OVERWTITELPKONLY); // Note that by specifying MOUNT_FILE_OVERWRITELPKONLY any files // in pak1 would overwrite files in pak0, but not any files that // are directly on the hard drive. //4) Proceed to open, close, read, and write files as necessary. CLFileSystem::CLFileSystem(lf_dword nMaxFiles): m_PrtTable(nMaxFiles), m_nMaxFiles(nMaxFiles), m_bBaseMounted(LF_FALSE) { m_szBasePath[0]=0; } CLFileSystem::~CLFileSystem() { UnMountAll(); } void CLFileSystem::PrintMountInfo() { LF_ErrPrintW(L"Base mounted at \"%s\"", ERR_LEVEL_ALWAYS, this->m_szBasePath); LF_ErrPrintW(L"Mounted Files:", ERR_LEVEL_ALWAYS); m_PrtTable.PrintMountInfo(); } //GetFileInfo retrieves information about a mounted file. const CLFileSystem::MOUNT_FILE* CLFileSystem::GetFileInfoW(lf_cwstr szMountPath) { return m_PrtTable.FindFile(szMountPath); } const CLFileSystem::MOUNT_FILE* CLFileSystem::GetFileInfoA(lf_cstr szMountPath) { lf_pathW szPath; mbstowcs(szPath, szMountPath, LF_MAX_PATH); return m_PrtTable.FindFile(szPath); } //Mount base must be called before any other mounting operations are called. //Mount base basically sets the current directory. From there on out any //calls to mount don't need full path names they only need path names //relative to the OS path that was mounted at the base. When MountBase is //called any files immediately in the base directory are mounted, but not //subdirectories. Note that even if a base is mounted, files outside the //base may still be mounted (for example a CD-ROM drive can be mounted). //The path to the base is always /. Note that any files that are created //are always created relatvie to the base, and not other paths that may //be mounted. I want to change that, however, so that a path can be mounted //to where files should be saved. lf_dword CLFileSystem::MountBaseW(lf_cwstr szOSPath) { if(m_bBaseMounted) { LF_ErrPrintW(L"MountBase Error: The base file system is already mounted. Call UnMountAll before mounting the base.", ERR_LEVEL_ERROR); return 0; } if(!BDIO_ChangeDirW(szOSPath)) { LF_ErrPrintW(L"MountBase Error: Could not mount base file system.", ERR_LEVEL_ERROR); return 0; } BDIO_GetCurrentDirW(m_szBasePath, LF_MAX_PATH); m_bBaseMounted=LF_TRUE; lf_dword nMountCount=MountW(L".", L"/", 0); LF_ErrPrintW(L"Mounted \"%s\" to \"/\"", ERR_LEVEL_DETAIL, m_szBasePath); return nMountCount; } lf_dword CLFileSystem::MountBaseA(lf_cstr szOSPath) { if(m_bBaseMounted) { LF_ErrPrintW(L"MountBase Error: The base file system is already mounted. Call UnMountAll before mounting the base.", ERR_LEVEL_ERROR); return 0; } if(!BDIO_ChangeDirA(szOSPath)) { LF_ErrPrintW(L"MountBase Error: Could not mount base file system.", ERR_LEVEL_ERROR); return 0; } lf_pathA szBasePath; BDIO_GetCurrentDirA(szBasePath, LF_MAX_PATH); mbstowcs(m_szBasePath, szBasePath, LF_MAX_PATH); m_bBaseMounted=LF_TRUE; lf_dword nMountCount=MountA(".", "/", 0); LF_ErrPrintW(L"Mounted \"%s\" to \"/\"", ERR_LEVEL_DETAIL, m_szBasePath); return nMountCount; } //MountLPK mounts a Legacy PaKage file into the file system. Note that before //an LPK can be mounted the actually LPK file must be within the file system. //Then when MountLPK is called the path to the mounted file (e.g. /base1/pak0.lpk) //should be specifed as a parameter, and not the os path (e.g. NOT .\base\pak0.lpk). //This method will expand the archive file into the current directory, so if //a file was stored in the LPK as Credits.txt it would now be /base1/Credits.txt //and Textures/Tex1.tga would be /base1/Textures/Tex1.tga. //Note that for the flags either MOUNT_FILE_OVERWRITE or MOUNT_FILE_OVERWRITELPKONLY //may be specifed. // //MOUNT_FILE_OVERWRITE: If any file with the same mout path as the new file //already exists, then the new file will take precedence over the old file //that is to say that when calls to open a file with the specified name //are made the file most recently mounted file will be opened (it doens't //mean that the OS file will be overwritten, because it won't). // //MOUNT_FILE_OVERWRITELPKONLY: Is similar to the above flag, but a newer file //will only take precedence over other archived files. So fore example if two //LPK files have a file with the same name stored in them, the most recently //mounted LPK file will take precedence, but if there was a file directly on //the hard drive, the hard drive file will take precedence, whether or not //the archive was mounted first or second. // //If neither flag is specified files will never get overwritten and the first //file to be mounted will always take precidence. lf_dword CLFileSystem::MountLPKW(lf_cwstr szMountedFile, lf_dword Flags) { const MOUNT_FILE* pMountFile=GetFileInfoW(szMountedFile); if(!pMountFile) { LF_ErrPrintW(L"MountLPK Error: The archive file \"%s\" has not been mounted.", ERR_LEVEL_ERROR, szMountedFile); return 0; } lf_pathW szMountDir; LF_GetDirFromPathW(szMountDir, szMountedFile); LF_ErrPrintW(L"Expanding \"%s\" to \"%s\"", ERR_LEVEL_NOTICE, szMountedFile, szMountDir); CLArchive lpkFile; if(!lpkFile.OpenW(pMountFile->szOSFileW)) { LF_ErrPrintW(L"Could not mount \"%s\". Possibly not a valid archive.", ERR_LEVEL_ERROR, szMountedFile); return 0; } lf_dword dwMounted=0; for(lf_dword i=0; i<lpkFile.GetNumFiles(); i++) { LPK_FILE_INFO fileInfo; if(!lpkFile.GetFileInfo(i, &fileInfo)) continue; MOUNT_FILE mountFile; swprintf(mountFile.szMountFileW, LF_MAX_PATH, L"%s%s", szMountDir, fileInfo.szFilename); swprintf(mountFile.szOSFileW, LF_MAX_PATH, L"%s", pMountFile->szOSFileW); mountFile.nSize=fileInfo.nSize; mountFile.nCmpSize=fileInfo.nCmpSize; mountFile.nOffset=fileInfo.nOffset; mountFile.Flags=MOUNT_FILE::MOUNT_FILE_ARCHIVED|MOUNT_FILE::MOUNT_FILE_READONLY; if(fileInfo.nType==LPK_FILE_TYPE_ZLIBCMP) mountFile.Flags|=MOUNT_FILE::MOUNT_FILE_ZLIBCMP; if(MountFile(&mountFile, Flags)) dwMounted++; else { LF_ErrPrintW(L"Mount Error: Could not mount \"%s\".", ERR_LEVEL_ERROR, mountFile.szOSFileW); } } return dwMounted; } lf_dword CLFileSystem::MountLPKA(lf_cstr szMountedFile, lf_dword Flags) { lf_pathW szMountedFileW; mbstowcs(szMountedFileW, szMountedFile, LF_MAX_PATH); const MOUNT_FILE* pMountFile=GetFileInfoA(szMountedFile); if(!pMountFile) { LF_ErrPrintW(L"MountLPK Error: The archive file \"%s\" has not been mounted.", ERR_LEVEL_ERROR, szMountedFileW); return 0; } lf_pathW szMountDir; LF_GetDirFromPathW(szMountDir, szMountedFileW); LF_ErrPrintW(L"Expanding \"%s\" to \"%s\"", ERR_LEVEL_NOTICE, szMountedFileW, szMountDir); lf_pathA szOSFileA; wcstombs(szOSFileA, pMountFile->szOSFileW, LF_MAX_PATH); CLArchive lpkFile; if(!lpkFile.OpenA(szOSFileA)) { LF_ErrPrintW(L"Could not mount \"%s\". Possibly not a valid archive.", ERR_LEVEL_ERROR, szMountedFile); return 0; } lf_dword dwMounted=0; for(lf_dword i=0; i<lpkFile.GetNumFiles(); i++) { LPK_FILE_INFO fileInfo; if(!lpkFile.GetFileInfo(i, &fileInfo)) continue; MOUNT_FILE mountFile; swprintf(mountFile.szMountFileW, LF_MAX_PATH, L"%s%s", szMountDir, fileInfo.szFilename); swprintf(mountFile.szOSFileW, LF_MAX_PATH, L"%s", pMountFile->szOSFileW); mountFile.nSize=fileInfo.nSize; mountFile.nCmpSize=fileInfo.nCmpSize; mountFile.nOffset=fileInfo.nOffset; mountFile.Flags=MOUNT_FILE::MOUNT_FILE_ARCHIVED|MOUNT_FILE::MOUNT_FILE_READONLY; if(fileInfo.nType==LPK_FILE_TYPE_ZLIBCMP) mountFile.Flags|=MOUNT_FILE::MOUNT_FILE_ZLIBCMP; if(MountFile(&mountFile, Flags)) dwMounted++; else { LF_ErrPrintW(L"Mount Error: Could not mount \"%s\".", ERR_LEVEL_ERROR, mountFile.szOSFileW); } } return dwMounted; } lf_dword CLFileSystem::MountDirW( lf_cwstr szOSPath, lf_cwstr szMount, lf_dword Flags) { lf_dword nMountCount=0; lf_bool bRes=0; lf_pathW szSearchPath; _snwprintf(szSearchPath, LF_MAX_PATH, L"%s\\*", szOSPath); //Recursivley mount all files... BDIO_FIND_DATAW sData; BDIO_FIND hFind=BDIO_FindFirstFileW(szSearchPath, &sData); if(!hFind) { LF_ErrPrintW( L"Mount Error: Could not mount any files. \"%s\" may not exist.", ERR_LEVEL_ERROR, szOSPath); return 0; } //Mount the directory, itself... MOUNT_FILE mountInfo; mountInfo.nCmpSize=mountInfo.nOffset=mountInfo.nSize=0; mountInfo.Flags=MOUNT_FILE::MOUNT_FILE_DIRECTORY; wcsncpy(mountInfo.szOSFileW, szOSPath, LF_MAX_PATH); wcsncpy(mountInfo.szMountFileW, szMount, LF_MAX_PATH); //Directories take the same overwrite priority, so overwritten //directories will be used when creating new files. bRes=MountFile(&mountInfo, Flags); if(!bRes) { LF_ErrPrintW(L"Mount Error: Could not mount \"%s\".", ERR_LEVEL_ERROR, mountInfo.szOSFileW); BDIO_FindClose(hFind); return nMountCount; } do { //Generate the mounted path and OS path.. MOUNT_FILE sMountFile; _snwprintf(sMountFile.szOSFileW, LF_MAX_PATH, L"%s\\%s", szOSPath, sData.szFilename); _snwprintf(sMountFile.szMountFileW, LF_MAX_PATH, L"%s%s", szMount, sData.szFilename); //If a directory was found mount that directory... if(sData.bDirectory) { //Ignore . and .. directories. if(sData.szFilename[0]=='.') continue; if(LF_CHECK_FLAG(Flags, MOUNT_MOUNT_SUBDIRS)) { wcsncat(sMountFile.szMountFileW, L"/", LF_min(1, LF_MAX_PATH-wcslen(sMountFile.szMountFileW))); nMountCount+=MountDirW(sMountFile.szOSFileW, sMountFile.szMountFileW, Flags); } } else { if(sData.nFileSize.dwHighPart) { LF_ErrPrintW(L"\"%s\" is too large to mount!", ERR_LEVEL_ERROR, sMountFile.szOSFileW); continue; } sMountFile.nSize=sData.nFileSize.dwLowPart; sMountFile.nCmpSize=sMountFile.nSize; sMountFile.nOffset=0; sMountFile.Flags=0; if(sData.bReadOnly) sMountFile.Flags|=MOUNT_FILE::MOUNT_FILE_READONLY; if(MountFile(&sMountFile, Flags)) nMountCount++; else LF_ErrPrintW(L"Mount Error: Could not mount \"%s\".", ERR_LEVEL_ERROR, mountInfo.szOSFileW); } }while(BDIO_FindNextFileW(hFind, &sData)); BDIO_FindClose(hFind); return nMountCount; } lf_dword CLFileSystem::MountDirA( lf_cstr szOSPath, lf_cstr szMount, lf_dword Flags) { lf_dword nMountCount=0; lf_bool bRes=0; lf_pathA szSearchPath; _snprintf(szSearchPath, LF_MAX_PATH, "%s\\*", szOSPath); //Recursivley mount all files... BDIO_FIND_DATAA sData; BDIO_FIND hFind=BDIO_FindFirstFileA(szSearchPath, &sData); if(!hFind) { LF_ErrPrintA( "Mount Error: Could not mount any files. \"%s\" may not exist.", ERR_LEVEL_ERROR, szOSPath); return 0; } //Mount the directory, itself... MOUNT_FILE mountInfo; mountInfo.nCmpSize=mountInfo.nOffset=mountInfo.nSize=0; mountInfo.Flags=MOUNT_FILE::MOUNT_FILE_DIRECTORY; mbstowcs(mountInfo.szOSFileW, szOSPath, LF_MAX_PATH); mbstowcs(mountInfo.szMountFileW, szMount, LF_MAX_PATH); //Directories take the same overwrite priority, so overwritten //directories will be used when creating new files. bRes=MountFile(&mountInfo, Flags); if(!bRes) { LF_ErrPrintW(L"Mount Error: Could not mount \"%s\".", ERR_LEVEL_ERROR, mountInfo.szOSFileW); BDIO_FindClose(hFind); return nMountCount; } do { //Generate the mounted path and OS path.. MOUNT_FILE sMountFile; lf_pathA szOSFileA, szMountFileA; _snprintf(szOSFileA, LF_MAX_PATH, "%s\\%s", szOSPath, sData.szFilename); _snprintf(szMountFileA, LF_MAX_PATH, "%s%s", szMount, sData.szFilename); mbstowcs(sMountFile.szOSFileW, szOSFileA, LF_MAX_PATH); mbstowcs(sMountFile.szMountFileW, szMountFileA, LF_MAX_PATH); //If a directory was found mount that directory... if(sData.bDirectory) { //Ignore . and .. directories. if(sData.szFilename[0]=='.') continue; if(LF_CHECK_FLAG(Flags, MOUNT_MOUNT_SUBDIRS)) { strncat(szMountFileA, "/", LF_min(1, LF_MAX_PATH-strlen(szMountFileA))); nMountCount+=MountDirA(szOSFileA, szMountFileA, Flags); } } else { if(sData.nFileSize.dwHighPart) { LF_ErrPrintW(L"\"%s\" is too large to mount!", ERR_LEVEL_ERROR, sMountFile.szOSFileW); continue; } sMountFile.nSize=sData.nFileSize.dwLowPart; sMountFile.nCmpSize=sMountFile.nSize; sMountFile.nOffset=0; sMountFile.Flags=0; if(sData.bReadOnly) sMountFile.Flags|=MOUNT_FILE::MOUNT_FILE_READONLY; if(MountFile(&sMountFile, Flags)) nMountCount++; else LF_ErrPrintW(L"Mount Error: Could not mount \"%s\".", ERR_LEVEL_ERROR, mountInfo.szOSFileW); } }while(BDIO_FindNextFileA(hFind, &sData)); BDIO_FindClose(hFind); return nMountCount; } //The Mount method mounts a directory to the file //system. If the MOUNT_MOUNT_SUBDIRS flag is specifed //then all subdirectories will be mounted as well. lf_dword CLFileSystem::MountW( lf_cwstr szOSPathToMount, lf_cwstr szMountToPath, lf_dword Flags) { lf_dword nMountCount=0; lf_pathW szMount; lf_pathW szOSPath; //Get the full path to the specified directory... BDIO_GetFullPathNameW(szOSPath, szOSPathToMount); //Insure that the mounting path does not have a / or \. size_t nLast=wcslen(szOSPath)-1; if(szOSPath[nLast]==L'/' || szOSPath[nLast]==L'\\') szOSPath[nLast]=0; if(szMountToPath[0]!='/') { LF_ErrPrintW( L"The path must be mounted at least to the base. Try mount \"%s\" \"/%s\" instead.", ERR_LEVEL_WARNING, szOSPathToMount, szMountToPath); return 0; } //Insure that the mount path has a / at the end of it if(szMountToPath[wcslen(szMountToPath)-1]!=L'/') _snwprintf(szMount, LF_MAX_PATH, L"%s/", szMountToPath); else _snwprintf(szMount, LF_MAX_PATH, L"%s", szMountToPath); LF_ErrPrintW(L"Mounting \"%s\" to \"%s\"...", ERR_LEVEL_NOTICE, szOSPath, szMount); return MountDirW(szOSPath, szMount, Flags); } lf_dword CLFileSystem::MountA( lf_cstr szOSPathToMount, lf_cstr szMountToPath, lf_dword Flags) { lf_dword nMountCount=0; lf_pathA szMount; lf_pathA szOSPath; //Get the full path to the specified directory... BDIO_GetFullPathNameA(szOSPath, szOSPathToMount); //Insure that the mountine path does not have a / or \. size_t nLast=strlen(szOSPath)-1; if(szOSPath[nLast]=='/' || szOSPath[nLast]=='\\') szOSPath[nLast]=0; if(szMountToPath[0]!='/') { LF_ErrPrintW( L"The path must be mounted at least to the base. Try mount \"%s\" \"/%s\" instead.", ERR_LEVEL_WARNING, szOSPathToMount, szMountToPath); return 0; } //Insure that the mount path has a / at the end of it if(szMountToPath[strlen(szMountToPath)-1]!=L'/') _snprintf(szMount, LF_MAX_PATH, "%s/", szMountToPath); else _snprintf(szMount, LF_MAX_PATH, "%s", szMountToPath); lf_pathW szOSPathW, szMountW; mbstowcs(szOSPathW, szOSPath, LF_MAX_PATH); mbstowcs(szMountW, szMount, LF_MAX_PATH); LF_ErrPrintW(L"Mounting \"%s\" to \"%s\"...", ERR_LEVEL_NOTICE, szOSPathW, szMountW); return MountDirA(szOSPath, szMount, Flags); } lf_bool CLFileSystem::UnMountAll() { LF_ErrPrintW(L"Clearing partition table...", ERR_LEVEL_NOTICE); m_PrtTable.Clear(); LF_ErrPrintW(L"Unmounting the base...", ERR_LEVEL_NOTICE); m_bBaseMounted=LF_FALSE; m_szBasePath[0]=0; return LF_TRUE; } lf_bool CLFileSystem::MountFile(MOUNT_FILE* pFile, lf_dword dwFlags) { LF_ErrPrintW(L"Mounting \"%s\"", ERR_LEVEL_SUPERDETAIL, pFile->szMountFileW); return m_PrtTable.MountFile(pFile, dwFlags); } /********************************************************* File opening code, note that files are opened and closed using the file system, but they are accessed (read and written to) using the CLFile class. *********************************************************/ CLFile* CLFileSystem::OpenFileW(lf_cwstr szFilename, lf_dword Access, lf_dword CreateMode) { lf_bool bOpenExisting=LF_TRUE; lf_bool bNew=LF_FALSE; //Check the flags to make sure they are compatible. if(LF_CHECK_FLAG(Access, LF_ACCESS_WRITE) && LF_CHECK_FLAG(Access, LF_ACCESS_MEMORY)) { LF_ErrPrintW(L"OpenFile Error: Cannot open a file with memory access and write access.", ERR_LEVEL_ERROR); return LF_NULL; } //Note that if creating a new file, then we shouldn't end here. const MOUNT_FILE* pMountInfo=GetFileInfoW(szFilename); if(CreateMode==LF_OPEN_EXISTING) { if(!pMountInfo) { LF_ErrPrintW(L"OpenFile Error: \"%s\" could not be found in the file system.", ERR_LEVEL_ERROR, szFilename); return LF_NULL; } bOpenExisting=LF_TRUE; bNew=LF_FALSE; } else if(CreateMode==LF_OPEN_ALWAYS) { bOpenExisting=pMountInfo?LF_TRUE:LF_FALSE; bNew=LF_FALSE; } else if(CreateMode==LF_CREATE_NEW) { if(pMountInfo) { LF_ErrPrintW(L"OpenFile Error: Cannot create \"%s\", it already exists.", ERR_LEVEL_ERROR, szFilename); return LF_NULL; } bOpenExisting=LF_FALSE; bNew=LF_TRUE; } else if(CreateMode==LF_CREATE_ALWAYS) { if(pMountInfo) { bOpenExisting=LF_TRUE; bNew=LF_TRUE; } else { bOpenExisting=LF_FALSE; bNew=LF_TRUE; } } else { LF_ErrPrintW(L"OpenFile Error: Invalid creation mode specifed.", ERR_LEVEL_ERROR); return LF_NULL; } //If the file is mounted then we are opening an existing file. if(bOpenExisting) { if(LF_CHECK_FLAG(pMountInfo->Flags, MOUNT_FILE::MOUNT_FILE_DIRECTORY)) { LF_ErrPrintW(L"OpenFile Error: \"%s\" is a directory, not a file.", ERR_LEVEL_ERROR, pMountInfo->szMountFileW); return LF_NULL; } //If we're trying to create a new file, and the existing file is read //only then we can't. if(LF_CHECK_FLAG(pMountInfo->Flags, MOUNT_FILE::MOUNT_FILE_READONLY) && bNew) { LF_ErrPrintW(L"OpenFile Error: \"%s\" cannot be created, because an existing file is read only.", ERR_LEVEL_ERROR, szFilename); return LF_NULL; } BDIO_FILE bdioFile=BDIO_OpenW(pMountInfo->szOSFileW, bNew?BDIO_CREATE_ALWAYS:BDIO_OPEN_EXISTING, Access); if(!bdioFile) { LF_ErrPrintW(L"Could not open the OS file: \"%s\".", ERR_LEVEL_ERROR, pMountInfo->szOSFileW); return LF_NULL; } return OpenExistingFile(pMountInfo, bdioFile, Access, bNew); } else { //TODO: Should also check to see if it is likely that the //file exists (because some OSs are not case sensitive //in which case the file may exist, but the path specified //may be a mounted file. //If it is necessary to create a new file, then we need to prepare //the mount info for the new file, as well as create an OS file. MOUNT_FILE mountInfo; //Get the specifie directory for the file, //then find the information about that directory in //the partition table. lf_pathW szDir; LF_GetDirFromPathW(szDir, szFilename); //The mount filename will be the same wcsncpy(mountInfo.szMountFileW, szFilename, LF_MAX_PATH); const MOUNT_FILE* pDirInfo=GetFileInfoW(szDir); if(!pDirInfo || !LF_CHECK_FLAG(pDirInfo->Flags, MOUNT_FILE::MOUNT_FILE_DIRECTORY)) { LF_ErrPrintW( L"OpenFile Error: Cannot create the specified file, the directory \"%s\" does not exist.", ERR_LEVEL_ERROR, szDir); return LF_NULL; } //Get just the filename for the file, //this will be used to create the OS file. lf_pathW szFile; LF_GetFileNameFromPathW(szFile, szFilename); //The OS filename is the information from the dir + the filename //Note that the OS separator must be inserted. _snwprintf(mountInfo.szOSFileW, LF_MAX_PATH, L"%s\\%s", pDirInfo->szOSFileW, szFile); //The initial file information is all zeroes. mountInfo.Flags=0; mountInfo.nCmpSize=0; mountInfo.nSize=0; mountInfo.nOffset=0; //Create the OS file. BDIO_FILE bdioFile=BDIO_OpenW(mountInfo.szOSFileW, BDIO_CREATE_NEW, Access); if(!bdioFile) { LF_ErrPrintW( L"OpenFile Error: Could not create new file: \"%s\".", ERR_LEVEL_ERROR, mountInfo.szMountFileW); return LF_NULL; } //If the OS file was created, then we can mount the new file //and open the existing file. MountFile(&mountInfo, MOUNT_FILE_OVERWRITE); return OpenExistingFile(&mountInfo, bdioFile, Access, LF_TRUE); } } CLFile* CLFileSystem::OpenFileA(lf_cstr szFilename, lf_dword Access, lf_dword CreateMode) { lf_bool bOpenExisting=LF_TRUE; lf_bool bNew=LF_FALSE; //lf_pathW szFilenameW; //mbstowcs(szFilenameW, szFilename, LF_MAX_PATH); //Check the flags to make sure they are compatible. if(LF_CHECK_FLAG(Access, LF_ACCESS_WRITE) && LF_CHECK_FLAG(Access, LF_ACCESS_MEMORY)) { LF_ErrPrintA("OpenFile Error: Cannot open a file with memory access and write access.", ERR_LEVEL_ERROR); return LF_NULL; } //Note that if creating a new file, then we shouldn't end here. const MOUNT_FILE* pMountInfo=GetFileInfoA(szFilename); if(CreateMode==LF_OPEN_EXISTING) { if(!pMountInfo) { LF_ErrPrintA("OpenFile Error: \"%s\" could not be found in the file system.", ERR_LEVEL_ERROR, szFilename); return LF_NULL; } bOpenExisting=LF_TRUE; bNew=LF_FALSE; } else if(CreateMode==LF_OPEN_ALWAYS) { bOpenExisting=pMountInfo?LF_TRUE:LF_FALSE; bNew=LF_FALSE; } else if(CreateMode==LF_CREATE_NEW) { if(pMountInfo) { LF_ErrPrintA("OpenFile Error: Cannot create \"%s\", it already exists.", ERR_LEVEL_ERROR, szFilename); return LF_NULL; } bOpenExisting=LF_FALSE; bNew=LF_TRUE; } else if(CreateMode==LF_CREATE_ALWAYS) { if(pMountInfo) { bOpenExisting=LF_TRUE; bNew=LF_TRUE; } else { bOpenExisting=LF_FALSE; bNew=LF_TRUE; } } else { LF_ErrPrintA("OpenFile Error: Invalid creation mode specifed.", ERR_LEVEL_ERROR); return LF_NULL; } //If the file is mounted then we are opening an existing file. if(bOpenExisting) { if(LF_CHECK_FLAG(pMountInfo->Flags, MOUNT_FILE::MOUNT_FILE_DIRECTORY)) { LF_ErrPrintW(L"OpenFile Error: \"%s\" is a directory, not a file.", ERR_LEVEL_ERROR, pMountInfo->szMountFileW); return LF_NULL; } //If we're trying to create a new file, and the existing file is read //only then we can't. if(LF_CHECK_FLAG(pMountInfo->Flags, MOUNT_FILE::MOUNT_FILE_READONLY) && bNew) { LF_ErrPrintA("OpenFile Error: \"%s\" cannot be created, because an existing file is read only.", ERR_LEVEL_ERROR, szFilename); return LF_NULL; } lf_pathA szOSFileA; wcstombs(szOSFileA, pMountInfo->szOSFileW, LF_MAX_PATH); BDIO_FILE bdioFile=BDIO_OpenA(szOSFileA, bNew?BDIO_CREATE_ALWAYS:BDIO_OPEN_EXISTING, Access); if(!bdioFile) { LF_ErrPrintW(L"Could not open the OS file: \"%s\".", ERR_LEVEL_ERROR, pMountInfo->szOSFileW); return LF_NULL; } return OpenExistingFile(pMountInfo, bdioFile, Access, bNew); } else { //Should also check to see if it is likely that the //file exists (because some OSs are not case sensitive //in which case the file may exist, but the path specified //may be a mounted file. //If it is necessary to create a new file, then we need to prepare //the mount info for the new file, as well as create an OS file. MOUNT_FILE mountInfo; //Get the specifie directory for the file, //then find the information about that directory in //the partition table. lf_pathA szDir; LF_GetDirFromPathA(szDir, szFilename); //The mount filename will be the same mbstowcs(mountInfo.szMountFileW, szFilename, LF_MAX_PATH); const MOUNT_FILE* pDirInfo=GetFileInfoA(szDir); if(!pDirInfo || !LF_CHECK_FLAG(pDirInfo->Flags, MOUNT_FILE::MOUNT_FILE_DIRECTORY)) { LF_ErrPrintA( "OpenFile Error: Cannot create the specified file, the directory \"%s\" does not exist.", ERR_LEVEL_ERROR, szDir); return LF_NULL; } //Get just the filename for the file, //this will be used to create the OS file. lf_pathA szFile; lf_pathW szFileW; LF_GetFileNameFromPathA(szFile, szFilename); mbstowcs(szFileW, szFile, LF_MAX_PATH); //The OS filename is the information from the dir + the filename //Note that the OS separator must be inserted. _snwprintf(mountInfo.szOSFileW, LF_MAX_PATH, L"%s\\%s", pDirInfo->szOSFileW, szFileW); //The initial file information is all zeroes. mountInfo.Flags=0; mountInfo.nCmpSize=0; mountInfo.nSize=0; mountInfo.nOffset=0; //Create the OS file. lf_pathA szOSFileA; wcstombs(szOSFileA, mountInfo.szOSFileW, LF_MAX_PATH); BDIO_FILE bdioFile=BDIO_OpenA(szOSFileA, BDIO_CREATE_NEW, Access); if(!bdioFile) { LF_ErrPrintW( L"OpenFile Error: Could not create new file: \"%s\".", ERR_LEVEL_ERROR, mountInfo.szMountFileW); return LF_NULL; } //If the OS file was created, then we can mount the new file //and open the existing file. MountFile(&mountInfo, MOUNT_FILE_OVERWRITE); return OpenExistingFile(&mountInfo, bdioFile, Access, LF_TRUE); } } CLFile* CLFileSystem::OpenExistingFile(const MOUNT_FILE* pMountInfo, BDIO_FILE File, lf_dword Access, lf_bool bNew) { //First thing's first, allocate memory for the file. CLFile* pFile=new CLFile; if(!pFile) { LF_ErrPrintW(L"OpenFile Error: Could not allocate memory for file.", ERR_LEVEL_ERROR); return LF_NULL; } //Initialize the file. pFile->m_BaseFile=File; pFile->m_bEOF=LF_FALSE; pFile->m_nAccess=Access; pFile->m_nBaseFileBegin=pMountInfo->nOffset; pFile->m_nFilePointer=0; //If creating a new file, the size needs to be set to 0. pFile->m_nSize=bNew?0:pMountInfo->nSize; pFile->m_pData=LF_NULL; wcsncpy(pFile->m_szPathW, pMountInfo->szMountFileW, LF_MAX_PATH); if(LF_CHECK_FLAG(pMountInfo->Flags, MOUNT_FILE::MOUNT_FILE_READONLY) && bNew) { LF_ErrPrintW(L"OpenFile Error: \"%s\" cannot be created, because an existing file is read only.", ERR_LEVEL_ERROR, pFile->m_szPathW); BDIO_Close(pFile->m_BaseFile); delete pFile; return LF_NULL; } //Check infor flags again. if(LF_CHECK_FLAG(pFile->m_nAccess, LF_ACCESS_WRITE) && LF_CHECK_FLAG(pMountInfo->Flags, MOUNT_FILE::MOUNT_FILE_READONLY)) { LF_ErrPrintW(L"OpenFile Error: \"%s\" is read only, cannot open for writing.", ERR_LEVEL_ERROR, pFile->m_szPathW); BDIO_Close(pFile->m_BaseFile); delete pFile; return LF_NULL; } LF_ErrPrintW(L"Opening \"%s\"...", ERR_LEVEL_DETAIL, pFile->m_szPathW); //If the file is in an archive and is compressed it needs to be opened as a //memory file. if(LF_CHECK_FLAG(pMountInfo->Flags, MOUNT_FILE::MOUNT_FILE_ARCHIVED) && LF_CHECK_FLAG(pMountInfo->Flags, MOUNT_FILE::MOUNT_FILE_ZLIBCMP)) { pFile->m_nAccess|=LF_ACCESS_MEMORY; } //If the file is a memory file then we just open it, //allocate memory for it, and copy the file data into //the buffer. if(LF_CHECK_FLAG(pFile->m_nAccess, LF_ACCESS_MEMORY)) { //Allocate memory... pFile->m_pData=new lf_byte[pFile->m_nSize]; if(!pFile->m_pData) { LF_ErrPrintW(L"OpenFile Error: Could not allocte memory for \"%s\".", ERR_LEVEL_ERROR, pFile->m_szPathW); BDIO_Close(pFile->m_BaseFile); delete pFile; return LF_NULL; } //Read the file data... lf_dword nRead=0; //Seek to the beginning of the file... BDIO_Seek(pFile->m_BaseFile, pFile->m_nBaseFileBegin, BDIO_SEEK_BEGIN); //Then read either the compress data, or the uncompressed data. if(LF_CHECK_FLAG(pMountInfo->Flags, MOUNT_FILE::MOUNT_FILE_ZLIBCMP)) { LF_ErrPrintW( L"Reading and uncompressing \"%s\"...", ERR_LEVEL_DETAIL, pFile->m_szPathW); nRead=BDIO_ReadCompressed(pFile->m_BaseFile, pFile->m_nSize, pFile->m_pData); } else { LF_ErrPrintW( L"Reading \"%s\"...", ERR_LEVEL_DETAIL, pFile->m_szPathW); nRead=BDIO_Read(pFile->m_BaseFile, pFile->m_nSize, pFile->m_pData); } if(nRead!=pFile->m_nSize) { LF_ErrPrintW( L"OpenFile Warning: Only read %d out of %d bytes in \"%s\".", ERR_LEVEL_WARNING, nRead, pFile->m_nSize, pFile->m_szPathW); pFile->m_nSize=nRead; } //We have the file open in memory so we no longer need to keep the //BDIO file open. BDIO_Close(pFile->m_BaseFile); pFile->m_BaseFile=LF_NULL; } else { //The file is not being opened as a memory file. //So we just leave it as it is and all file //reading/seeking functions will take care of everything. } pFile->m_bEOF=pFile->m_nFilePointer>=pFile->m_nSize; return pFile; } lf_bool CLFileSystem::CloseFile(CLFile* pFile) { lf_dword nSize=0; if(!pFile) return LF_FALSE; LF_ErrPrintW(L"Closing \"%s\"...", ERR_LEVEL_DETAIL, pFile->m_szPathW); if(pFile->m_BaseFile) { nSize=BDIO_GetSize(pFile->m_BaseFile); BDIO_Close(pFile->m_BaseFile); } LF_SAFE_DELETE_ARRAY(pFile->m_pData); //If the file was writeable we need to update the data in the //partition table. if(LF_CHECK_FLAG(pFile->m_nAccess, LF_ACCESS_WRITE)) { const MOUNT_FILE* pMountInfo=GetFileInfoW(pFile->m_szPathW); if(!pMountInfo) { LF_ErrPrintW(L"CloseFile Error: Could not update partition table.", ERR_LEVEL_ERROR); } else { MOUNT_FILE mountInfo=*pMountInfo; mountInfo.nSize=nSize; mountInfo.nCmpSize=nSize; m_PrtTable.MountFile(&mountInfo, MOUNT_FILE_OVERWRITE); } } LF_SAFE_DELETE(pFile); return LF_TRUE; } /******************************************************** *** The Partition Table Code *** A partition table keeps track of mounted files *** the table stores information about each file. *** *** The partition table stores all the file information *** in a hash table with 1024 entries. If a filename *** has a duplicate hash value then the table points *** to a linked list with all the filenames. ********************************************************/ CLFileSystem::CPartitionTable::CPartitionTable(lf_dword nMaxFiles): m_pHashList(LF_NULL), m_nMaxFiles(nMaxFiles), m_pMasterList(LF_NULL) { //The hash table is always 1024 in size, if any dupicate //hashes are generated, then there will be a linked list at the hash entry. m_pHashList=new MOUNT_FILE_EX*[1024]; if(!m_pHashList) return; //Create an initialize the master list m_pMasterList=new MOUNT_FILE_EX[nMaxFiles]; if(!m_pMasterList) { LF_SAFE_DELETE_ARRAY(m_pHashList); return; } m_UnusedFiles.Init(m_pMasterList, nMaxFiles, sizeof(MOUNT_FILE_EX)); for(lf_dword i=0; i<1024; i++) { /* m_pList2[i].Flags=CLFileSystem::MOUNT_FILE::MOUNT_FILE_EMPTY; m_pList2[i].pNext=LF_NULL; //There really isn't any reason to save the hash value, //but we are doing so anyway. m_pList2[i].nHashValue=i; */ m_pHashList[i]=LF_NULL; } } CLFileSystem::CPartitionTable::~CPartitionTable() { Clear(); //Delete the hash table (note that the Clear method has already //deleted any linked lists that may exist, so the array can //safely be deleted without memory leaks. LF_SAFE_DELETE_ARRAY(m_pHashList); LF_SAFE_DELETE_ARRAY(m_pMasterList); } void CLFileSystem::CPartitionTable::Clear() { #if 1 m_UnusedFiles.Init(m_pMasterList, m_nMaxFiles, sizeof(MOUNT_FILE_EX)); for(lf_dword i=0; i<1024; i++) { m_pHashList[i]=LF_NULL; } #else for(lf_dword i=0; i<1024; i++) { if(m_pHashList[i]) { //If there was more than one file with the same hash //proceed to move all files from the linked list //to the unused stack. for(MOUNT_FILE_EX* pItem=m_pHashList[i].pNext; pItem; ) { MOUNT_FILE_EX* pNext=pItem->pNext; //LF_SAFE_DELETE(pItem); m_UnusedList.Push(pItem); pItem=pNext; } //Push the actuall item into the unused stack m_UnusedList.Push(m_pHashList[i]); m_pHashList[i]=LF_NULL; } /* //Set the file to empty. m_pList2[i].Flags=MOUNT_FILE::MOUNT_FILE_EMPTY; //If there was more than one file with the same hash //proceed to delete the linked list. for(MOUNT_FILE_EX* pItem=m_pList2[i].pNext; pItem; ) { MOUNT_FILE_EX* pNext=pItem->pNext; LF_SAFE_DELETE(pItem); pItem=pNext; } //Set the next item to null. m_pList2[i].pNext=LF_NULL; */ } #endif } //FindFile finds a file in the partition table with the specified path. //If not file exists it returns NULL, also note that //this is CASE SENSITIVE so /base1/Tex.tga and /base1/tex.tga are not //the same file. const CLFileSystem::MOUNT_FILE* CLFileSystem::CPartitionTable::FindFile(lf_cwstr szFile) { //To find a file just get the hash value for the specified filename //and check to see if a file is at that hash entry, not that //the linked list should be checked at that hash entry. lf_dword nHash=GetHashValue1024(szFile); //Loop through the linked list (usually 1-3 items long) and find //the filename. for(MOUNT_FILE_EX* pItem=m_pHashList[nHash]; pItem; pItem=pItem->pNext) { //Note that if a file is empty we don't need to worry //about it (we actually NEED to continue, becuase if a file //was mounted in that spot and was then unmounted all the //data is still there, only the Flags value has been changed.) if(pItem->Flags==MOUNT_FILE::MOUNT_FILE_EMPTY) continue; //If the string matches then return the file info. if(pItem->Flags!=MOUNT_FILE::MOUNT_FILE_ARCHIVED && (wcscmp(pItem->szMountFileW, szFile)==0)) return pItem; } return LF_NULL; } lf_bool CLFileSystem::CPartitionTable::MountFile(CLFileSystem::MOUNT_FILE* pFile, lf_dword Flags) { //Get the hash value for the mounted filename //note that we always use the mounted filename for the //hash table and not the OS filename. lf_dword nHash=GetHashValue1024(pFile->szMountFileW); //If the file at that hash entry is empty and there is no //linked list attached we can simply add the file to that spot. if( (m_pHashList[nHash]==LF_NULL)) { //Create a new files; MOUNT_FILE_EX* pNewFile=(MOUNT_FILE_EX*)m_UnusedFiles.Pop(); if(!pNewFile) return LF_FALSE; pNewFile->pNext=LF_NULL; pNewFile->nHashValue=nHash; //Copy over the information for the file: memcpy(pNewFile, pFile, sizeof(MOUNT_FILE)); ////Copy just the MOUNT_FILE data, that way we don't overwrite the pNext value. //memcpy(m_pHashList[nHash], pFile, sizeof(MOUNT_FILE)); m_pHashList[nHash]=pNewFile; return LF_TRUE; } else { //The same filename may already exist. So loop through the table and find //out if it does, if it does either skip the file or overwrite it based on //the flag, if the file doesn't exist add it on the end. for(MOUNT_FILE_EX* pItem=m_pHashList[nHash]; pItem; pItem=pItem->pNext) { if(wcscmp(pItem->szMountFileW, pFile->szMountFileW)==0) { //The same file already exists, check flags and act appropriately. //If we need to overwrite an old file then we just copy the info if(LF_CHECK_FLAG(Flags, MOUNT_FILE_OVERWRITELPKONLY)) { if(LF_CHECK_FLAG(pItem->Flags, MOUNT_FILE::MOUNT_FILE_ARCHIVED)) { LF_ErrPrintW(L"Copying %s over old archive file.", ERR_LEVEL_DETAIL, pFile->szMountFileW); memcpy(pItem, pFile, sizeof(MOUNT_FILE)); return LF_TRUE; } else { LF_ErrPrintW(L"Cannot mount %s. A file with the same name has already been mounted.", ERR_LEVEL_DETAIL, pFile->szMountFileW); return LF_FALSE; } } else if(LF_CHECK_FLAG(Flags, MOUNT_FILE_OVERWRITE)) { LF_ErrPrintW(L"Copying %s over old file.", ERR_LEVEL_DETAIL, pFile->szMountFileW); memcpy(pItem, pFile, sizeof(MOUNT_FILE)); return LF_TRUE; } else { LF_ErrPrintW(L"Cannot mount %s. A file with the same name has already been mounted.", ERR_LEVEL_DETAIL, pFile->szMountFileW); return LF_FALSE; } } if(pItem->pNext==LF_NULL) { //We got to the end of the list and the file wasn't found, //so we proceed to add the new file onto the end of the list. MOUNT_FILE_EX* pNew=(MOUNT_FILE_EX*)m_UnusedFiles.Pop();//new MOUNT_FILE_EX; if(!pNew) return LF_FALSE; memcpy(pNew, pFile, sizeof(MOUNT_FILE)); pNew->nHashValue=nHash; pNew->pNext=LF_NULL; pItem->pNext=pNew; return LF_TRUE; } //^^^...Loop to the next item in the list...^^^ } } //Shoul never actually get here. return LF_FALSE; } lf_dword CLFileSystem::CPartitionTable::GetHashValue1024(lf_cwstr szString) { //This is basically <NAME>' One-At-A-Time-Hash. //http://www.burtleburtle.net/bob/hash/doobs.html lf_dword nLen=wcslen(szString); lf_dword nHash=0; lf_dword i=0; for(i=0; i<nLen; i++) { nHash+=szString[i]; nHash+=(nHash<<10); nHash^=(nHash>>6); } nHash+=(nHash<<3); nHash^=(nHash>>11); nHash+=(nHash<<15); //We'll limit our hash value from 0 to 1023. return nHash&0x000003FF; //Same as nHash%1024 but should be faster. } lf_dword CLFileSystem::CPartitionTable::GetHashValue1024_Short(lf_cwstr szString) { //This is basically <NAME>' One-At-A-Time-Hash. //http://www.burtleburtle.net/bob/hash/doobs.html lf_pathW szKey; lf_dword nLen=0;//wcslen(szKey); lf_dword nHash=0; lf_dword i=0; LF_GetFileNameFromPathW(szKey, szString); nLen=wcslen(szKey); for(i=0; i<nLen; i++) { nHash+=szKey[i]; nHash+=(nHash<<10); nHash^=(nHash>>6); } nHash+=(nHash<<3); nHash^=(nHash>>11); nHash+=(nHash<<15); //We'll limit our hash value from 0 to 1023. return nHash&0x000003FF; //Same as nHash%1024 but should be faster. } void CLFileSystem::CPartitionTable::PrintMountInfo() { //Loop through all hash indexes and if the file exists //then print out the information about it. LF_ErrPrint("FLAGS SIZE PACKED PATH", ERR_LEVEL_ALWAYS); LF_ErrPrint("----- ---- ------ ----", ERR_LEVEL_ALWAYS); lf_dword nFiles=0; for(lf_dword i=0; i<1024; i++) { for(MOUNT_FILE_EX* pItem=m_pHashList[i]; pItem; pItem=pItem->pNext) { nFiles++; PrintFileInfo(pItem); } } LF_ErrPrint("Totals: %d files", ERR_LEVEL_ALWAYS, nFiles); } void CLFileSystem::CPartitionTable::PrintFileInfo(MOUNT_FILE_EX* pFile) { //If there was not file in that table position we'll simply return. if(pFile->Flags==MOUNT_FILE::MOUNT_FILE_EMPTY) return; lf_wchar_t szOutput[29+LF_MAX_PATH]; szOutput[5]=' '; //First thing print all the file flags. if(LF_CHECK_FLAG(pFile->Flags, MOUNT_FILE::MOUNT_FILE_DIRECTORY)) szOutput[0]=('d'); else szOutput[0]=('-'); if(LF_CHECK_FLAG(pFile->Flags, MOUNT_FILE::MOUNT_FILE_ARCHIVED)) szOutput[1]=('a'); else szOutput[1]=('-'); if(LF_CHECK_FLAG(pFile->Flags, MOUNT_FILE::MOUNT_FILE_READONLY)) { szOutput[2]=('r'); szOutput[3]=('-'); } else { szOutput[2]=('r'); szOutput[3]=('w'); } if(LF_CHECK_FLAG(pFile->Flags, MOUNT_FILE::MOUNT_FILE_ZLIBCMP)) szOutput[4]=('z'); else szOutput[4]=('-'); _snwprintf(&szOutput[6], 10, L"%10u", pFile->nSize); szOutput[16]=' '; _snwprintf(&szOutput[17], 10, L"%10u", pFile->nCmpSize); szOutput[27]=' '; _snwprintf(&szOutput[28], LF_MAX_PATH, L"%s", pFile->szMountFileW); szOutput[28+LF_MAX_PATH]=0; LF_ErrPrintW(szOutput, ERR_LEVEL_ALWAYS); _snwprintf(szOutput, LF_MAX_PATH+27, L"%4u: %10u (%s)", pFile->nHashValue, pFile->nOffset, pFile->szOSFileW); LF_ErrPrintW(szOutput, ERR_LEVEL_DETAIL); #if 0 LF_ErrPrintW(L"%s", ERR_LEVEL_ALWAYS, pFile->szMountFileW); LF_ErrPrintW(L"(%s).%d", ERR_LEVEL_ALWAYS, pFile->szOSFileW, pFile->nOffset); LF_ErrPrintW(L"Size: %d Compressed Size: %d Hash Value: %d", ERR_LEVEL_ALWAYS, pFile->nSize, pFile->nCmpSize, pFile->nHashValue); LF_ErrPrintW(L"Flags: ", ERR_LEVEL_ALWAYS); lf_wchar_t szFlags[6]; szFlags[5]=0; if(LF_CHECK_FLAG(pFile->Flags, MOUNT_FILE::MOUNT_FILE_DIRECTORY)) szFlags[0]=('D'); else szFlags[0]=('-'); if(LF_CHECK_FLAG(pFile->Flags, MOUNT_FILE::MOUNT_FILE_ARCHIVED)) szFlags[1]=('A'); else szFlags[1]=('-'); if(LF_CHECK_FLAG(pFile->Flags, MOUNT_FILE::MOUNT_FILE_READONLY)) { szFlags[2]=('R'); szFlags[3]=('-'); } else { szFlags[2]=('R'); szFlags[3]=('W'); } if(LF_CHECK_FLAG(pFile->Flags, MOUNT_FILE::MOUNT_FILE_ZLIBCMP)) szFlags[4]=('Z'); else szFlags[4]=('-'); LF_ErrPrintW(szFlags, ERR_LEVEL_ALWAYS); #endif } <file_sep>/tools/img_lib/img_lib2/img_lib/img_jpg.c #include <setjmp.h> #include "img_private.h" #include "jpeg-6b\jinclude.h" #include "jpeg-6b\jpeglib.h" /* The exception handling code, see also jerror.h. */ jmp_buf g_mark; void img_error_exit (j_common_ptr cinfo) { /* Let the memory manager delete any temp files before we die */ jpeg_destroy(cinfo); /* Do a long jump back to the caller and send the exit code.*/ longjmp(g_mark, 1); //exit(0); } HIMG IMG_LoadJPGCallbacks(img_void* stream, IMG_CALLBACKS* lpCB) { struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; IMAGE_S* pImage=IMG_NULL; img_dword i=0; unsigned char* buf=IMG_NULL; //Seek to the beginning of the file. lpCB->seek(stream, 0, IMG_SEEK_SET); /* Exception handling code, if set jump is not 0 it means that the jpeg6b library failed.*/ if(setjmp(g_mark)) { if(pImage) { if(pImage->pImage) free(pImage); if(buf) free(buf); free(pImage); } return IMG_NULL; } pImage=(IMAGE_S*)malloc(sizeof(IMAGE_S)); if(!pImage) { return IMG_NULL; } /* Make sure we zero out the structure, that way if jpeg6b fails we won't try to deallocate memory that hasn't been allocated.*/ memset(pImage, 0, sizeof(IMAGE_S)); //try... cinfo.err = jpeg_std_error(&jerr); jpeg_create_decompress(&cinfo); jpeg_stdio_src(&cinfo, stream, lpCB->read); jpeg_read_header(&cinfo, TRUE); memset(pImage, 0, sizeof(IMAGE_S)); pImage->nBitDepth=24; pImage->nDataFmt=IMGFMT_B8G8R8; //The RGB image format for JPEGS is backwards it is B8G8R8 in the img_lib format. pImage->nWidth=cinfo.image_width; pImage->nHeight=cinfo.image_height; pImage->nDataSize=pImage->nWidth*pImage->nHeight*3; pImage->nOrient=IMGORIENT_TOPLEFT; pImage->pImage=malloc(pImage->nDataSize); if(!pImage->pImage) { free(pImage); jpeg_abort_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); return IMG_NULL; } cinfo.out_color_space=JCS_RGB; jpeg_start_decompress(&cinfo); //We can simply read the scanlines into the last scanline of the img_lib file //that way we don't need a temporary buffer to read scanlines. buf=(img_byte*)pImage->pImage+pImage->nWidth*(pImage->nHeight-1)*3; for(i=0; jpeg_read_scanlines(&cinfo, &buf, 1); i++) { memcpy((img_byte*)pImage->pImage+i*pImage->nWidth*3, buf, pImage->nWidth*3); } jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); //ending try block... (goes to setjmp if it fails). return pImage; }<file_sep>/games/Legacy-Engine/Source/3rdParty/ML_lib/ML_misc_F.c #include "ML_lib.h" #include <math.h> #pragma warning(disable:4716) //Disable the "must return a value" warning. ml_dword ML_FUNC ML_NextPow2(const ml_dword n) { ml_dword nRes; if(n>0x80000000) return n; nRes=0x00000001; while(nRes<n) { nRes<<=1; } return nRes; } ml_dword ML_FUNC ML_Pow2(const ml_byte n) { return 0x00000001<<n; } ml_float ML_FUNC ML_sqrtf(const ml_float f) { return sqrtf( f ); } ml_float ML_FUNC ML_cosf(const ml_float f) { return cosf(f); } ml_float ML_FUNC ML_sinf(const ml_float f) { return sinf(f); } ml_float ML_FUNC ML_tanf(const ml_float f) { return ML_sinf(f)/ML_cosf(f); } ml_float ML_FUNC ML_acosf(const ml_float f) { return acosf( f ); } ml_float ML_FUNC ML_asinf(const ml_float f) { return asinf( f ); } ml_float ML_FUNC ML_sincosf(const ml_float f, ml_float *cos) { *cos = cosf( f ); return sinf( f ); } ml_long ML_FUNC ML_absl(ml_long l) { return abs( l ); } ml_float ML_FUNC ML_absf(ml_float f) { return fabsf( f ); } <file_sep>/games/Bomb/Readme.txt Bomb v1.03 Copyright (C) 2000, <NAME> for Beem Software This folder includes: Bomb.exe - The executable of Bomb. Bomb.bas - The Qbasic source code for Bomb. Readme.txt - This file. Instructions: At the beginning you will be prompted as to the speed you wish to run it. 1 works well for 75Mhz 20 for 450Mhz anything else you'll have to guess. Then you will be prompted to name your enemy, do so. After that you will see your enemy running across the sceen. Press space and you will hit it. ======================================================= === Version history === === for Bomb === ======================================================= v1.04 (August 4, 2001) Simply made it so the guy moves across the entire screen. Rather than just part of it. v1.03 (July 10, 2000) Improved some of the code. Added speed adjustment support. v1.01 Renamed Bomb 3.0. Added the ability to name the enemy. v1.00 First release. A very limited version you were not allowed to name your enemy.<file_sep>/Misc/DBXExporter/DBXExporter/oedbx/library/oedbx/dbxMessageInfo.h //*************************************************************************************** #ifndef dbxMessageInfoH #define dbxMessageInfoH //*************************************************************************************** #include <oedbx/dbxIndexedInfo.h> //*************************************************************************************** const int1 miiIndex = 0x00, miiFlags = 0x01, miiMessageAddress = 0x04, miiSubject = 0x08; class AS_EXPORT DbxMessageInfo : public DbxIndexedInfo { public : DbxMessageInfo(InStream ins, int4 address) : DbxIndexedInfo(ins, address) { } const char * GetIndexText (int1 index) const; IndexedInfoDataType GetIndexDataType(int1 index) const; }; //*********************************************** #endif dbxMessageInfoH <file_sep>/Misc/DBXExporter/DBXExporter/oedbx/library/oedbx/dbxCommon.h //*************************************************************************************** #ifndef dbxCommonH #define dbxCommonH //*************************************************************************************** #include <string> #include <fstream> #include <iomanip> //*************************************************************************************** #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) #define AS_WIN32 #else #error "This code is made for windows." #endif //#define AS_OEDBX_DLL #if defined(AS_WIN32) && defined(AS_OEDBX_DLL) #if defined(AS_OE_IMPLEMENTATION) #define AS_EXPORT __declspec(dllexport) #else #define AS_EXPORT __declspec(dllimport) #endif #else #define AS_EXPORT #endif typedef unsigned char int1; typedef unsigned short int2; typedef unsigned long int4; typedef std::istream & InStream; typedef std::ostream & OutStream; class AS_EXPORT DbxException { public : DbxException(const std::string text) { Error = text; } const char * what() const { return Error.c_str(); } private : std::string Error; }; std::string AS_EXPORT FileTime2String(int1 * str); OutStream AS_EXPORT rows2File(OutStream out,int4 address, int1 * values, int4 length); //*********************************************** #endif dbxCommonH <file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/lv_test.h #ifndef __LV_TEST_H__ #define __LV_TEST_H__ #include <d3d9.h> /* typedef struct _L3DMVERTEX{ float x, y, z; float tu, tv; }L3DMVERTEX; #define L3DMVERTEX_TYPE (D3DFVF_XYZ|D3DFVF_TEX1) typedef struct _L3DM_MODEL{ L_dword dwTriangleCount; L3DMVERTEX* pVertices; IDirect3DVertexBuffer9* lpVB; IDirect3DTexture9* lpSkin; }L3DM_MODEL; */ typedef struct _LVT_OBJ{ IDirect3DVertexBuffer9* lpVB; IDirect3DTexture9* lpTex; IDirect3DTexture9* lpLM; //L3DM_MODEL l3dmTest; }LVT_OBJ; #ifdef __cplusplus #define LVT_EXPORT extern "C" #else #define LVT_EXPORT #endif LVT_EXPORT int LVT_Delete(LVT_OBJ* lpObj); LVT_EXPORT void LVT_Render(LVT_OBJ* lpObj, IDirect3DDevice9* lpDevice); LVT_EXPORT int LVT_ValidateInvalidate(LVT_OBJ* lpObj, IDirect3DDevice9* lpDevice, L_bool bValidate); LVT_EXPORT LVT_OBJ* LVT_CreateTest(IDirect3DDevice9* lpDevice); LVT_EXPORT void LVT_LoadModel(char* szFilename); #endif __LV_TEST_H__<file_sep>/games/Legacy-Engine/Scrapped/libs/ML_lib2008April/ML_vec3.h #ifndef __ML_VEC3_H__ #define __ML_VEC3_H__ #include "ML_lib.h" #ifdef __cplusplus extern "C"{ #endif __cplusplus /************************************* ML_VEC3 function implimentations: *************************************/ ML_VEC3* ML_FUNC ML_Vec3Add_F(ML_VEC3* pOut, const ML_VEC3* pV1, const ML_VEC3* pV2); ML_VEC3* ML_FUNC ML_Vec3Add_SSE(ML_VEC3* pOut, const ML_VEC3* pV1, const ML_VEC3* pV2); ML_VEC3* ML_FUNC ML_Vec3Add_3DNOW(ML_VEC3* pOut, const ML_VEC3* pV1, const ML_VEC3* pV2); ML_VEC3* ML_FUNC ML_Vec3Cross_F(ML_VEC3* pOut, const ML_VEC3* pV1, const ML_VEC3* pV2); ML_VEC3* ML_FUNC ML_Vec3Cross_SSE(ML_VEC3* pOut, const ML_VEC3* pV1, const ML_VEC3* pV2); ML_VEC3* ML_FUNC ML_Vec3Cross_3DNOW(ML_VEC3* pOut, const ML_VEC3* pV1, const ML_VEC3* pV2); float ML_FUNC ML_Vec3Dot_F(const ML_VEC3* pV1, const ML_VEC3* pV2); float ML_FUNC ML_Vec3Dot_SSE3(const ML_VEC3* pV1, const ML_VEC3* pV2); float ML_FUNC ML_Vec3Dot_SSE(const ML_VEC3* pV1, const ML_VEC3* pV2); float ML_FUNC ML_Vec3Dot_3DNOW(const ML_VEC3* pV1, const ML_VEC3* pV2); float ML_FUNC ML_Vec3Length_F(const ML_VEC3* pV); float ML_FUNC ML_Vec3Length_SSE3(const ML_VEC3* pV); float ML_FUNC ML_Vec3Length_SSE(const ML_VEC3* pV); float ML_FUNC ML_Vec3Length_3DNOW(const ML_VEC3* pV); float ML_FUNC ML_Vec3LengthSq_F(const ML_VEC3* pV); float ML_FUNC ML_Vec3LengthSq_SSE3(const ML_VEC3* pV); float ML_FUNC ML_Vec3LengthSq_SSE(const ML_VEC3* pV); float ML_FUNC ML_Vec3LengthSq_3DNOW(const ML_VEC3* pV); ML_VEC3* ML_FUNC ML_Vec3Normalize_F(ML_VEC3* pOut, const ML_VEC3* pV); ML_VEC3* ML_FUNC ML_Vec3Normalize_SSE3(ML_VEC3* pOut, const ML_VEC3* pV); ML_VEC3* ML_FUNC ML_Vec3Normalize_SSE(ML_VEC3* pOut, const ML_VEC3* pV); ML_VEC3* ML_FUNC ML_Vec3Normalize_3DNOW(ML_VEC3* pOut, const ML_VEC3* pV); ML_VEC3* ML_FUNC ML_Vec3Scale_F(ML_VEC3* pOut, const ML_VEC3* pV, float s); ML_VEC3* ML_FUNC ML_Vec3Scale_SSE(ML_VEC3* pOut, const ML_VEC3* pV, float s); ML_VEC3* ML_FUNC ML_Vec3Scale_3DNOW(ML_VEC3* pOut, const ML_VEC3* pV, float s); ML_VEC3* ML_FUNC ML_Vec3Subtract_F(ML_VEC3* pOut, const ML_VEC3* pV1, const ML_VEC3* pV2); ML_VEC3* ML_FUNC ML_Vec3Subtract_SSE(ML_VEC3* pOut, const ML_VEC3* pV1, const ML_VEC3* pV2); ML_VEC3* ML_FUNC ML_Vec3Subtract_3DNOW(ML_VEC3* pOut, const ML_VEC3* pV1, const ML_VEC3* pV2); float ML_FUNC ML_Vec3Distance_F(const ML_VEC3* pV1, const ML_VEC3* pV2); float ML_FUNC ML_Vec3Distance_SSE3(const ML_VEC3* pV1, const ML_VEC3* pV2); float ML_FUNC ML_Vec3Distance_SSE(const ML_VEC3* pV1, const ML_VEC3* pV2); float ML_FUNC ML_Vec3Distance_3DNOW(const ML_VEC3* pV1, const ML_VEC3* pV2); ML_VEC4* ML_FUNC ML_Vec3Transform_F(ML_VEC4* pOut, const ML_VEC3* pV, const ML_MAT* pM); ML_VEC4* ML_FUNC ML_Vec3Transform_SSE(ML_VEC4* pOut, const ML_VEC3* pV, const ML_MAT* pM); ML_VEC4* ML_FUNC ML_Vec3Transform_3DNOW(ML_VEC4* pOut, const ML_VEC3* pV, const ML_MAT* pM); ML_VEC3* ML_FUNC ML_Vec3TransformCoord_F(ML_VEC3* pOut, const ML_VEC3* pV, const ML_MAT* pM); ML_VEC3* ML_FUNC ML_Vec3TransformCoord_SSE(ML_VEC3* pOut, const ML_VEC3* pV, const ML_MAT* pM); ML_VEC3* ML_FUNC ML_Vec3TransformCoord_3DNOW(ML_VEC3* pOut, const ML_VEC3* pV, const ML_MAT* pM); ML_VEC3* ML_FUNC ML_Vec3TransformNormal_F(ML_VEC3* pOut, const ML_VEC3* pV, const ML_MAT* pM); ML_VEC3* ML_FUNC ML_Vec3TransformNormal_SSE(ML_VEC3* pOut, const ML_VEC3* pV, const ML_MAT* pM); ML_VEC3* ML_FUNC ML_Vec3TransformNormal_3DNOW(ML_VEC3* pOut, const ML_VEC3* pV, const ML_MAT* pM); #ifdef __cplusplus } /* extern "C" */ #endif __cplusplus #endif __ML_VEC3_H__<file_sep>/tools/fs_sys2/fs_misc.c #include <string.h> #include <ctype.h> #include "fs_sys2.h" /*************************************************** Pathname getting functions, retrieve filename path, or short filename from a full path ***************************************************/ fs_str8 FS_GetFileNameFromPathA(fs_str8 szFileName, fs_cstr8 szFullPath) { fs_dword dwLen=strlen(szFullPath); fs_dword i=0, j=0; for(i=dwLen; i>0; i--) { if(szFullPath[i]=='\\' || szFullPath[i]=='/') { i++; break; } } for(j=0 ;i<dwLen+1; i++, j++) { szFileName[j]=szFullPath[i]; } return szFileName; } fs_str16 FS_GetFileNameFromPathW(fs_str16 szFileName, fs_cstr16 szFullPath) { fs_dword dwLen=wcslen(szFullPath); fs_dword i=0, j=0; for(i=dwLen; i>0; i--) { if(szFullPath[i]=='\\' || szFullPath[i]=='/') { i++; break; } } for(j=0 ;i<dwLen+1; i++, j++) { szFileName[j]=szFullPath[i]; } return szFileName; } fs_str8 FS_GetDirFromPathA(fs_str8 szDir, fs_cstr8 szFullPath) { fs_dword dwLen=strlen(szFullPath); fs_long i=0; for(i=(fs_long)dwLen-1; i>=0; i--) { if(szFullPath[i]=='\\' || szFullPath[i]=='/') break; } strncpy(szDir, szFullPath, i+1); szDir[i+1]=0; return szDir; } fs_str16 FS_GetDirFromPathW(fs_str16 szDir, fs_cstr16 szFullPath) { fs_dword dwLen=wcslen(szFullPath); fs_long i=0; for(i=(fs_long)dwLen-1; i>=0; i--) { if(szFullPath[i]=='\\' || szFullPath[i]=='/') break; } wcsncpy(szDir, szFullPath, i+1); szDir[i+1]=0; return szDir; } void FS_SYS2_EXPORTS FS_FixCaseA(fs_pathA szOut, fs_cstr8 szFullPath) { fs_long i = 0; for(i=0; i<FS_MAX_PATH; i++) { szOut[i] = tolower(szFullPath[i]); if(0 == szOut[i])break; } szOut[FS_MAX_PATH] = 0; } void FS_SYS2_EXPORTS FS_FixCaseW(fs_pathW szOut, fs_cstr16 szFullPath) { fs_long i = 0; for(i=0; i<FS_MAX_PATH; i++) { szOut[i] = tolower(szFullPath[i]); if(0 == szOut[i])break; } szOut[FS_MAX_PATH] = 0; }<file_sep>/games/Legacy-Engine/Source/3rdParty/ML_lib/ML_quat.c /* ML_quat.c - Code for quaternion computations. Copyrgiht (C) 2006, <NAME>. Note the quaternion stuff is the only stuff that isn't written in assembly (mostly because it is so complicated and it will probably take me a while to write the assembly). */ #include "ML_lib.h" ml_quat* ML_FUNC ML_QuatSlerp(ml_quat* pOut, const ml_quat* pQ1, const ml_quat* pQ2, float t) { float sine, cosine; float beta = 1.0f - t; float quat[4]; quat[0] = pQ2->x; quat[1] = pQ2->y; quat[2] = pQ2->z; quat[3] = pQ2->w; // Smelling of SIMD... cosine = (pQ1->x*pQ2->x) + (pQ1->y*pQ2->y) + (pQ1->z*pQ2->z) + (pQ1->w*pQ2->w); // If negative cosine, invert to stay in 0 to Pi range if(cosine < 0.0f) { quat[0] = -quat[0]; quat[1] = -quat[1]; quat[2] = -quat[2]; quat[3] = -quat[3]; cosine = -cosine; } // if cosine of angle between them is not 0.0 if(1.0f - cosine > 0.0001f) { // get the angle between them cosine = ML_acosf(cosine); // Find the reciprocal of the sin(angle) sine = 1.0f / ML_sinf(cosine); // recalculate weights beta = ML_sinf(cosine * beta) * sine; t = ML_sinf(cosine * t) * sine; } // TODO: This smells of SIMD parallelism... pOut->x = (beta * pQ1->x) + (t * quat[0]); pOut->y = (beta * pQ1->y) + (t * quat[1]); pOut->z = (beta * pQ1->z) + (t * quat[2]); pOut->w = (beta * pQ1->w) + (t * quat[3]); return pOut; } ml_quat* ML_FUNC ML_QuatRotationMat(ml_quat* pOut, const ml_mat* pM) { float fTrace=pM->_11+pM->_22+pM->_33+1.0f; if(fTrace > 0.00000001f) { pOut->w=ML_sqrtf(fTrace)*0.5f; fTrace=0.25f/pOut->w; pOut->x=(pM->_23-pM->_32)*fTrace; pOut->y=(pM->_31-pM->_13)*fTrace; pOut->z=(pM->_12-pM->_21)*fTrace; return pOut; } if( (pM->_11>pM->_22) && (pM->_11>pM->_33)) { fTrace=pM->_11-pM->_22-pM->_33+1.0f; pOut->x=ML_sqrtf(fTrace)*0.5f; fTrace=0.25f/pOut->x; pOut->w=(pM->_23-pM->_32)*fTrace; pOut->y=(pM->_12+pM->_21)*fTrace; pOut->z=(pM->_31+pM->_13)*fTrace; return pOut; } else if(pM->_22>pM->_33) { //MessageBox(0, "Y", 0, 0); fTrace=pM->_22-pM->_11-pM->_33+1.0f; pOut->y=ML_sqrtf(fTrace)*0.5f; fTrace=0.25f/pOut->y; pOut->w=(pM->_31-pM->_13)*fTrace; pOut->x=(pM->_12+pM->_21)*fTrace; pOut->z=(pM->_23+pM->_32)*fTrace; return pOut; } else { //MessageBox(0, "Z", 0, 0); fTrace=pM->_33-pM->_11-pM->_22+1.0f; pOut->z=ML_sqrtf(fTrace)*0.5f; fTrace=0.25f/pOut->z; pOut->w=(pM->_12-pM->_21)*fTrace; pOut->x=(pM->_31+pM->_13)*fTrace; pOut->y=(pM->_23+pM->_32)*fTrace; return pOut; } }<file_sep>/tools/PodSyncPrep/src/podsyncp/DLPanel.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package podsyncp; import javax.swing.JTextArea; /** * * @author beemfx */ public class DLPanel extends javax.swing.JPanel { public DLPanel() { String strFeed = "http://www.keithandthegirl.com/rss/"; //strFeed = "http://www.pcgamer.com/feed/"; boolean bTest = false; if(bTest) { PodcastRSS rss = new PodcastRSS(strFeed); JTextArea t = new JTextArea(rss.toString());//ReadFeed(strFeed)); this.add(t); } } } <file_sep>/games/Legacy-Engine/Source/engine/lg_video.cpp #include "common.h" #include "lg_sys.h" #include "lg_err.h" #include "lg_cvars.h" #include "lg_err_ex.h" /**************************************************************** LV_ValidateGraphics() & LV_InvalidateGraphics () These functions are called whenever the graphics in the game have to be reset, so any graphics that need to be loaded should be validated and invalidated here. Invalidating means removing the object as a Direct3D resource. D3DPOOL_MANAGED resources usually don't need to be invalidated or revalidated. Any object invalidated in LV_InvalidateGraphics, should be revalidated in LV_ValidateGraphics. *****************************************************************/ void CLGame::LV_ValidateGraphics() { Err_Printf("Validating Direct3D objects..."); //This will set the texture load modes... //LV_InitTexLoad(); Err_Printf("Validating graphical console..."); m_VCon.Validate(); #ifdef OLD_WORLD Err_Printf("Validating meshes..."); m_pMeshMgr->ValidateMeshes(); Err_Printf("Validating world..."); m_pWorld->Validate(); #endif ValidateMgrs(); //m_pMMgr->ValidateMeshes(); m_WorldCln.Validate(); /* Reset the states. */ Err_Printf("Calling SetStates..."); if(!m_Video.SetStates()) Err_Printf("An error occured while setting sampler and render states."); //m_pTMgr->Validate(); //m_pFxMgr->Validate(); } void CLGame::LV_InvalidateGraphics() { Err_Printf("Invalidating Direct3D objects..."); Err_Printf("Invalidating World..."); #ifdef OLD_WORLD m_pWorld->Invalidate(); #endif Err_Printf("Invalidating graphical console..."); m_VCon.Invalidate(); //m_pMMgr->InvalidateMeshes(); #ifdef OLD_WORLD Err_Printf("Invalidating meshes..."); m_pMeshMgr->InvalidateMeshes(); #endif OLD_WORLD m_WorldCln.Invalidate(); Err_Printf("Purging textures..."); //m_pTMgr->Invalidate(); //m_pFxMgr->Invalidate(); InvalidateMgrs(); } #if 0 void CLGame::LV_InitTexLoad() { Err_Printf("Initializing texture management..."); lg_dword TexLdFlags=0; if(CV_Get(CVAR_v_UseMipMaps)->nValue) TexLdFlags|=TEXLOAD_GENMIPMAP; if(CV_Get(CVAR_v_HWMipMaps)->nValue) TexLdFlags|=TEXLOAD_HWMIPMAP; if(CV_Get(CVAR_v_MipGenFilter)->nValue>=FILTER_LINEAR) TexLdFlags|=TEXLOAD_LINEARMIPFILTER; if(CV_Get(CVAR_v_Force16BitTextures)->nValue) TexLdFlags|=TEXLOAD_FORCE16BIT; if(CV_Get(CVAR_v_16BitTextureAlpha)->nValue) TexLdFlags|=TEXLOAD_16BITALPHA; lg_uint nSizeLimit=(lg_uint)CV_Get(CVAR_v_TextureSizeLimit)->nValue; //CLTexMgr::Init calls Tex_SetLoadOptionsFlag. #if 0 m_cTexMgr.Init( s_pDevice, CV_Get(CVAR_v_szDefaultTexture)->szValue, TexLdFlags, nSizeLimit); #endif /* Tex_SetLoadOptions( (lg_bool)CVar_GetValue(s_cvars, CVAR_v_UseMipMaps, LG_NULL), (lg_bool)CVar_GetValue(s_cvars, CVAR_v_HWMipMaps, LG_NULL), (TEXFILTER_MODE)(lg_int)CVar_GetValue(s_cvars, CVAR_v_MipGenFilter, LG_NULL), (lg_uint)CVar_GetValue(s_cvars, CVAR_v_TextureSizeLimit, LG_NULL), (lg_bool)CVar_GetValue(s_cvars, CVAR_v_Force16BitTextures, LG_NULL), (lg_bool)CVar_GetValue(s_cvars, CVAR_v_16BitTextureAlpha, LG_NULL)); */ } #endif /******************************************************************* LV_Restart() Resets the video with the present parameters located in the cvar list. This is called from LV_ValidateDevice() when the device gets reset, or when the user sends the VRESTART command to the console. ********************************************************************/ lg_result CLGame::LV_Restart() { /* Invalidate all graphics. */ LV_InvalidateGraphics(); /* Reset the device. */ if(m_Video.Restart()) { LV_ValidateGraphics(); return LG_OK; } else return LVERR_CANTRECOVER; } /******************************************************************************* LV_ValidateDevice() Called to make sure that the device is valid for rendering. This is called every frame before anything is rendered. If this funciton fails it means the device can't render right now, and in some cases it means the app should shut down. If it succeeds it means it is okay for the device to draw. Should only be called if TestCooperativeLevel fails in Render methods. ********************************************************************************/ lg_result CLGame::LV_ValidateDevice() { lg_result nResult=0; lg_bool bGetBackSurface=LG_FALSE; if(!s_pDevice) { Err_Printf("No device to check validation on."); //CVar_Set(s_cvars, CVAR_lg_ShouldQuit, DEF_TRUE); CV_Set(CV_Get(CVAR_lg_ShouldQuit), DEF_TRUE); return LG_FAIL; } if(LG_SUCCEEDED(nResult=s_pDevice->TestCooperativeLevel())) return LG_OK; switch(nResult) { case D3DERR_DEVICELOST: /* We can't do anything if the device is lost, we have to wait for it to recover. */ return LG_V_OR_S_DISABLED; case D3DERR_DEVICENOTRESET: { D3DPRESENT_PARAMETERS pp; memset(&pp, 0, sizeof(pp)); /* If the device is not reset it means that windows is giving control of the application back to us and we need to reset it. */ if(LG_FAILED(LV_Restart())) { Err_Printf("Could not restart device."); return LG_V_OR_S_DISABLED; } else return LG_OK; } default: return LG_SHUTDOWN; } return LG_SHUTDOWN; }<file_sep>/Misc/DBXExporter/DBXExporter/oedbx/library/dbxFileInfo.cpp //*************************************************************************************** #define AS_OE_IMPLEMENTATION #include <oedbx/dbxFileInfo.h> //*************************************************************************************** DbxFileInfo::DbxFileInfo(InStream ins, int4 address, int4 length) { init(); Address = address; Length = length; try { if(Length) readFileInfo(ins); } catch(const DbxException & E) { delete[] buffer; throw; } } DbxFileInfo::~DbxFileInfo() { delete[] buffer; } void DbxFileInfo::init() { Address = Length = 0; buffer = 0; } //*************************************************************************************** void DbxFileInfo::readFileInfo(InStream ins) { buffer = new int1[Length]; ins.seekg(Address); ins.read((char *)buffer, Length); if(!ins) throw DbxException("Error reading object from input stream !"); } //*************************************************************************************** const char * DbxFileInfo::GetFolderName() const { if(buffer && Length==0x618) return (char *)(buffer+0x105); return 0; } std::string DbxFileInfo::GetFileInfoTime() const { if(buffer && Length==0x108) return FileTime2String(buffer); return ""; } //*************************************************************************************** void DbxFileInfo::ShowResults(OutStream outs) const { outs << std::endl << "File info : " << std::endl << " Address : 0x" << std::hex << Address << std::endl << " Length : 0x" << std::hex << Length << std::endl; if(buffer) if(Length==0x618) outs << " Folder name : " << GetFolderName() << std::endl; else if(Length==0x108) outs << " File time : " << GetFileInfoTime() << std::endl; rows2File(outs,0,buffer,Length); } <file_sep>/games/Night2/Readme.txt Night Killers 2 v1.00 Copyright (C) 1998, <NAME> for Beem Software The folder includes: Night2.exe - The executable for Night Killers 2 Readme.txt - This file. Note: This is just a video. It's really stupid. Originally it said Starcraft 2 not Night killers 2.<file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/ls_init.c /* ls_init.c - Legacy engine audio initialization. */ #include "common.h" #include <dsound.h> #include "ls_init.h" #include "ls_load.h" L_bool LS_SetFormatFromCVars(IDirectSoundBuffer* lpBuffer, HCVARLIST cvarlist) { L_result nResult=0; WAVEFORMATEX wf; memset(&wf, 0, sizeof(WAVEFORMATEX)); wf.cbSize=0; wf.wFormatTag=WAVE_FORMAT_PCM; wf.nChannels=(L_word)CVar_GetValue(cvarlist, "s_Channels", L_null); wf.wBitsPerSample=(L_word)CVar_GetValue(cvarlist, "s_BitsPerSample", L_null); wf.nSamplesPerSec=(L_dword)CVar_GetValue(cvarlist, "s_Frequency", L_null); wf.nBlockAlign=wf.nChannels*(wf.wBitsPerSample/8); wf.nAvgBytesPerSec=wf.nSamplesPerSec*wf.nBlockAlign; Err_Printf( "Setting output format to: %i channels, %i bits per sample at %iHz...", wf.nChannels, wf.wBitsPerSample, wf.nSamplesPerSec); nResult=lpBuffer->lpVtbl->SetFormat(lpBuffer, &wf); Err_PrintDX("IDirectSoundBuffer::SetFormat", nResult); if(L_succeeded(nResult)) return L_true; else return L_false; } L_result LS_Init(L3DGame* lpGame) { WAVEFORMATEX wf; DSBUFFERDESC dsdesc; L_result nResult=0; if(!lpGame) return LG_ERR; memset(&lpGame->s, 0, sizeof(lpGame->s)); /* Create the IDirectSound8 inteface. */ Err_Printf("Creating IDirectSound8 interface..."); nResult=DirectSoundCreate8(&DSDEVID_DefaultPlayback, &lpGame->s.m_lpDS, L_null); Err_PrintDX("DirectSoundCreate8", nResult); if(L_failed(nResult)) { Err_Printf("Failed to create IDirectSound8 interface, audio not available."); lpGame->s.m_lpDS=L_null; lpGame->s.m_bAvailable=L_false; return LG_ERR; } else Err_Printf("IDirectSound8 interface created at 0x%08X.", lpGame->s.m_lpDS); /* Set the cooperative level, for a game we want priority. */ Err_Printf("Setting audio cooperative level to priority..."); nResult=lpGame->s.m_lpDS->lpVtbl->SetCooperativeLevel( lpGame->s.m_lpDS, lpGame->m_hwnd, DSSCL_PRIORITY); Err_PrintDX("IDirectSound8::SetCooperativeLevel", nResult); if(L_failed(nResult)) { Err_Printf("Could not set cooperative level, audio not available."); L_safe_release(lpGame->s.m_lpDS); lpGame->s.m_bAvailable=L_false; return LG_ERR; } /* Get the primary sound buffer. */ memset(&dsdesc, 0, sizeof(dsdesc)); Err_Printf("Creating primary sound buffer..."); dsdesc.dwSize=sizeof(dsdesc); dsdesc.dwFlags=DSBCAPS_PRIMARYBUFFER|DSBCAPS_CTRL3D; nResult=lpGame->s.m_lpDS->lpVtbl->CreateSoundBuffer( lpGame->s.m_lpDS, &dsdesc, &lpGame->s.m_lpPrimaryBuffer, L_null); Err_PrintDX("IDirectSound8::CreateSoundBuffer", nResult); if(L_failed(nResult)) { Err_Printf("Failed to create primary sound buffer, audio not available."); L_safe_release(lpGame->s.m_lpDS); lpGame->s.m_bAvailable=L_false; return LG_ERR; } Err_Printf("Created primary sound buffer at 0x%08X.", lpGame->s.m_lpPrimaryBuffer); /* Set the format of the primary buffer, this really only matters for older hardware. We set the output format from the cvars.*/ Err_Printf("Setting primary sound buffer format..."); memset(&wf, 0, sizeof(wf)); /* wf.cbSize=0; wf.wFormatTag=WAVE_FORMAT_PCM; wf.nChannels=(L_word)CVar_GetValue(lpGame->m_cvars, "s_Channels", L_null); wf.wBitsPerSample=(L_word)CVar_GetValue(lpGame->m_cvars, "s_BitsPerSample", L_null); wf.nSamplesPerSec=(L_dword)CVar_GetValue(lpGame->m_cvars, "s_Frequency", L_null); wf.nBlockAlign=wf.nChannels*(wf.wBitsPerSample/8); wf.nAvgBytesPerSec=wf.nSamplesPerSec*wf.nBlockAlign; */ if(!LS_SetFormatFromCVars(lpGame->s.m_lpPrimaryBuffer, lpGame->m_cvars)) { CVar_Set(lpGame->m_cvars, "s_Channels", "2"); if(!LS_SetFormatFromCVars(lpGame->s.m_lpPrimaryBuffer, lpGame->m_cvars)) { CVar_Set(lpGame->m_cvars, "s_Channels", "1"); if(!LS_SetFormatFromCVars(lpGame->s.m_lpPrimaryBuffer, lpGame->m_cvars)) { Err_Printf("Could not initialize audio format."); L_safe_release(lpGame->s.m_lpPrimaryBuffer); L_safe_release(lpGame->s.m_lpDS); lpGame->s.m_bAvailable=L_false; return LG_ERR; } } } /* Play the primary buffer, most drivers will play the primary buffer anyway, but just to be safe we call the Play method anyway. */ Err_Printf("Playing the primary sound buffer for sound output."); nResult=lpGame->s.m_lpPrimaryBuffer->lpVtbl->Play(lpGame->s.m_lpPrimaryBuffer, 0, 0, DSBPLAY_LOOPING); Err_PrintDX("DirectSoundBuffer::Play", nResult); /* Tell the game that sound is enalbled.*/ lpGame->s.m_bAvailable=L_true; /* Some test stuff. */ LS_LoadSound( lpGame->s.m_lpDS, &lpGame->s.m_lpTestSound, 0, "music\\m2theme.ogg"); //"test\\jungle_loop_02.ogg"); if(lpGame->s.m_lpTestSound) lpGame->s.m_lpTestSound->lpVtbl->Play(lpGame->s.m_lpTestSound, 0, 0, DSBPLAY_LOOPING); return LG_OK; } L_result LS_Shutdown(L3DGame* lpGame) { L_long nCount=0; /* Make sure the audio was initialized, because if it hasn't been there is no point in shutting it donw. */ if(!lpGame->s.m_bAvailable) { Err_Printf("Audio was not initialized, nothing to shut down."); return LG_OK; } L_safe_release(lpGame->s.m_lpTestSound); /* Release Primary sound buffer. */ Err_Printf("Releasing primary sound buffer..."); if(lpGame->s.m_lpPrimaryBuffer) nCount=lpGame->s.m_lpPrimaryBuffer->lpVtbl->Release(lpGame->s.m_lpPrimaryBuffer); Err_Printf( "Released IDirectSoundBuffer interface at 0x%08X with %i references left.", lpGame->s.m_lpPrimaryBuffer, nCount); lpGame->s.m_lpPrimaryBuffer=L_null; /* Release DirectSound8 interface. */ Err_Printf("Releasing IDirectSound8 interface..."); if(lpGame->s.m_lpDS) nCount=lpGame->s.m_lpDS->lpVtbl->Release(lpGame->s.m_lpDS); Err_Printf( "Released IDirectSound8 interface at 0x%08X with %i references left.", lpGame->s.m_lpDS, nCount); lpGame->s.m_lpDS=L_null; return LG_OK; }<file_sep>/games/Legacy-Engine/Scrapped/tools/warchiver/la_win.c #include <windows.h> #include <shlobj.h> #include <process.h> #include <stdio.h> #include "resource.h" #include "..\\filesys\\lf_sys.h" #define ARCHIVE_COMPRESS 0x00000010 #pragma comment(lib, "winmm.lib") #ifdef _DEBUG #define LIBA_PATH "..\\filesys\\debug\\lf_sys_d.dll" #else #define LIBA_PATH "lf_sys.dll" #endif static char g_szAppName[]="WinArchiver v1.01"; #define WM_USER_DONEARCHIVING (WM_USER+1) int (*pArc_Archive)(char*, char*, unsigned long, int (*)(void*, unsigned int, char*)); int SetPos(void* extra, unsigned int nPercentage, char* szOutput) { static HWND hwnd=NULL; static HWND hwndt=NULL; if(extra) { hwnd=extra; SendMessage(hwnd, PBM_SETRANGE, 0, MAKELPARAM(0, 100)); SendMessage(hwnd, PBM_SETPOS, nPercentage, 0); return 1; } else { HWND hwndp=GetParent(hwnd); char szTemp[280]; if(nPercentage>100) nPercentage=100; if(hwnd) SendMessage(hwnd, PBM_SETPOS, nPercentage, 0); _snprintf(szTemp, 279, "Archiving \"%s\"...", szOutput); SetDlgItemText(hwndp, IDC_ARCHFILE, szTemp); return 1; } } typedef struct _APARAMS{ HWND hwnd; char szOutput[MAX_PATH]; int bCompress; }APARAMS, *PAPARAMS; typedef struct _AWPARAMS{ int bCompress; char szSaveFile[MAX_PATH]; }AWPARAMS; void ArchiveProc(void* pvoid) { unsigned long dwFlags=0; APARAMS* pparams=(APARAMS*)pvoid; if(pparams->bCompress) dwFlags|=ARCHIVE_COMPRESS; if(!pArc_Archive(pparams->szOutput, ".", dwFlags, SetPos)) MessageBox( NULL, "An error occured while attempting to archive the files.", g_szAppName, MB_OK|MB_ICONINFORMATION); PostMessage(pparams->hwnd, WM_USER_DONEARCHIVING, 0, 0); _endthread(); } BOOL CALLBACK ArcWait(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { static char szOutput[MAX_PATH]; static APARAMS params; static HFONT hfont=L_null; unsigned long hThreadID=0; switch(uMsg) { case WM_INITDIALOG: { DWORD dwID=0; HWND hwndt=GetDlgItem(hwnd, IDC_ARCHFILE); strncpy(params.szOutput, (char*)((AWPARAMS*)lParam)->szSaveFile, MAX_PATH-1); params.bCompress=((AWPARAMS*)lParam)->bCompress; params.hwnd=hwnd; SetPos(GetDlgItem(hwnd, IDC_ARCPROG), 0, ""); hThreadID=_beginthread(ArchiveProc, 0, &params); hfont=CreateFont( 12, 0, 0, 0, FW_THIN, 0, 0, 0, ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH, "MS Sans Serif"); SendMessage(hwndt, WM_SETFONT, (WPARAM)hfont, 0); SendMessage(hwndt, WM_SETTEXT, 0, (LPARAM)"Preparing to archive..."); /* GetWindowRect(GetParent(hwnd), &rc); MoveWindow(hwnd, (rc.right-rc.left)/2-100, (rc.bottom-rc.top)/2-50, 200, 100, TRUE); */ return FALSE; } case WM_DESTROY: DeleteObject(hfont); hfont=L_null; break; case WM_USER_DONEARCHIVING: PlaySound(TEXT("SystemAsterisk"), NULL, SND_ASYNC|SND_ALIAS); EndDialog(hwnd, 0); break; default: return FALSE; } return TRUE; } BOOL CommandProc(HWND hwnd, WORD wNotifyCode, WORD wID, HWND hwndCtl) { static AWPARAMS awParams={0, 0}; switch(wID) { case IDC_QUIT: SendMessage(hwnd, WM_CLOSE, 0, 0); break; case IDC_ARCHIVEIT: { char szTree[MAX_PATH]; char szSaveFile[MAX_PATH]; char szOldDir[MAX_PATH]; szTree[0]=0; szSaveFile[0]=0; GetDlgItemText(hwnd, IDC_OUTPUT, szSaveFile, MAX_PATH-1); GetDlgItemText(hwnd, IDC_TREE, szTree, MAX_PATH-1); if(strlen(szSaveFile)<2 || strlen(szTree)<2) { MessageBox(hwnd, "A specified path is too short.", g_szAppName, MB_OK|MB_ICONINFORMATION); break; } //Change the current directory to the directory we want to archive. GetCurrentDirectory(MAX_PATH-1, szOldDir); if(!SetCurrentDirectory(szTree)) { MessageBox(hwnd, "The specified tree for archiving is not valid.", g_szAppName, MB_OK|MB_ICONINFORMATION); break; } if(IsDlgButtonChecked(hwnd, IDC_COMPRESS)) awParams.bCompress=1; else awParams.bCompress=0; strcpy(awParams.szSaveFile, szSaveFile); DialogBoxParam(GetModuleHandle(NULL), "ARCHIVING", hwnd, ArcWait, (LPARAM)&awParams); //Restore the old working directory. SetCurrentDirectory(szOldDir); break; } case IDC_BROWSEOUTPUT: { OPENFILENAMEA of; char szOutput[MAX_PATH]; memset(&of, 0, sizeof(OPENFILENAMEA)); szOutput[0]=0; of.lStructSize=sizeof(OPENFILENAMEA); of.hwndOwner=hwnd; of.hInstance=0; of.lpstrFilter="Legacy Archive (*.lpk)\0*.lpk\0All Filess (*.*)\0*.*\0"; of.lpstrCustomFilter=NULL; of.nMaxCustFilter=0; of.nFilterIndex=0; of.lpstrFile=szOutput; of.nMaxFile=MAX_PATH; of.lpstrFileTitle=NULL; of.nMaxFileTitle=0; of.lpstrInitialDir=NULL; of.lpstrTitle="Archive Directory To:"; of.Flags=OFN_NOCHANGEDIR|OFN_OVERWRITEPROMPT|OFN_HIDEREADONLY|OFN_NONETWORKBUTTON; of.nFileOffset=0; of.nFileExtension=0; of.lpstrDefExt="lpk"; of.lCustData=0; of.lpfnHook=NULL; of.lpTemplateName=NULL; if(GetSaveFileNameA(&of)) SetDlgItemText(hwnd, IDC_OUTPUT, szOutput); break; } case IDC_BROWSETREE: { BROWSEINFO bi; LPITEMIDLIST lpid=NULL; IMalloc* imalloc=NULL; char szOutput[MAX_PATH]; memset(&bi, 0, sizeof(bi)); bi.hwndOwner=hwnd; bi.pidlRoot=NULL; bi.pszDisplayName=szOutput; bi.lpszTitle="Select a directory tree for archiving."; bi.ulFlags=BIF_NONEWFOLDERBUTTON; bi.lpfn=NULL; bi.lParam=0; bi.iImage=0; if(lpid=SHBrowseForFolder(&bi)) { SHGetPathFromIDList(lpid, szOutput); SetDlgItemText(hwnd, IDC_TREE, szOutput); if(SUCCEEDED(SHGetMalloc(&imalloc))) { imalloc->lpVtbl->Free(imalloc, lpid); imalloc->lpVtbl->Release(imalloc); } } break; } default: return FALSE; } return TRUE; } BOOL CALLBACK ArcDlgProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { static HANDLE hIcon=NULL; switch(uMsg) { case WM_INITDIALOG: { RECT rc1, rc2; SetWindowText(hwnd, g_szAppName); GetWindowRect(GetDesktopWindow(), &rc1); GetWindowRect(hwnd, &rc2); MoveWindow( hwnd, rc1.right/2-(rc2.right-rc2.left)/2, rc1.bottom/2-(rc2.bottom-rc2.top), rc2.right-rc2.left, rc2.bottom-rc2.top, TRUE); CheckDlgButton(hwnd, IDC_COMPRESS, BST_CHECKED); hIcon=LoadImage(GetModuleHandle(NULL), "WARCICON2", IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR); SendMessage(hwnd, WM_SETICON, ICON_BIG, (LPARAM)hIcon); return TRUE; } case WM_CLOSE: EndDialog(hwnd, 0); DestroyIcon(hIcon); PostQuitMessage(0); break; case WM_COMMAND: CommandProc(hwnd, HIWORD(wParam), LOWORD(wParam), (HWND)lParam); break; default: return FALSE; } return TRUE; } int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpCmdLine, int nShowCmd) { HMODULE hDll=NULL; HWND hwnd=NULL; MSG msg; memset(&msg, 0, sizeof(msg)); hDll=LoadLibrary(LIBA_PATH); pArc_Archive=(void*)GetProcAddress(hDll, "Arc_Archive"); if(pArc_Archive==NULL) { MessageBox(NULL, "Could not find Arc_Archive process \""LIBA_PATH"\" required.", g_szAppName, MB_OK|MB_ICONERROR); return 0; } hwnd=CreateDialog(hInst, "WARCHIVEDLG", NULL, ArcDlgProc); ShowWindow(hwnd, nShowCmd); UpdateWindow(hwnd); while(GetMessage(&msg, NULL, 0, 0)) { if(!IsDialogMessage(hwnd, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } FreeLibrary(hDll); return msg.wParam; }<file_sep>/tools/img_lib/img_lib2/img_lib/img_png.c #include <setjmp.h> #include <malloc.h> #include "libpng-1.2.16\png.h" #include "img_private.h" typedef struct _png_io { img_void* file; IMG_CALLBACKS* pCB; }png_io, *png_io_ptr; void user_error_fn(png_structp png_ptr, png_const_charp error_msg) { //OutputDebugStringA(error_msg); //OutputDebugStringA("\n"); } void user_warning_fn(png_structp png_ptr, png_const_charp warning_msg) { //We don't care... } void user_read_data(png_structp png_ptr, png_bytep data, png_size_t length) { png_io_ptr pio=png_get_io_ptr(png_ptr); if(!pio) return; pio->pCB->read((img_void*)data, 1, (img_uint)length, pio->file); } HIMG IMG_LoadPNGCallbacks(img_void* stream, IMG_CALLBACKS* lpCB) { png_structp png_ptr=IMG_NULL; png_infop info_ptr=IMG_NULL; png_infop end_info=IMG_NULL; png_io io_ptr={IMG_NULL, IMG_NULL}; img_dword i=0; //The img_lib stuff; IMAGE_S* pImage=IMG_NULL; lpCB->seek(stream, 0, IMG_SEEK_SET); //Create the png_struct. png_ptr = png_create_read_struct( PNG_LIBPNG_VER_STRING, IMG_NULL,//(png_voidp)user_error_ptr, user_error_fn, user_warning_fn); if (!png_ptr) return IMG_NULL; info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct( &png_ptr, (png_infopp)NULL, (png_infopp)NULL); IMG_SAFE_FREE(pImage); return IMG_NULL; } //If the png reading functions fail at //some point we have this error catching. if(setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct( &png_ptr, &info_ptr, &end_info); //If the image has been allocated, we'll free any memory. if(pImage) { IMG_SAFE_FREE(pImage->pImage); IMG_SAFE_FREE(pImage); } return IMG_NULL; } io_ptr.file=stream; io_ptr.pCB=lpCB; //Set up the reading callbacks... png_set_read_fn(png_ptr, &io_ptr, user_read_data); //png_set_read_user_chunk_fn(png_ptr, &io_ptr, user_read_data); //png_set_sig_bytes(png_ptr, 0); //Get the image dimensions: //Start reading the image: //png_read_info(png_ptr, info_ptr); //We won't support 64 bit images and we'll revers the color components. //We also make sure we don't get a paletted image. png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_STRIP_16|PNG_TRANSFORM_BGR|PNG_TRANSFORM_EXPAND, png_voidp_NULL); //Allocate memory for the image: pImage=malloc(sizeof(IMAGE_S)); if(!pImage) longjmp(png_jmpbuf(png_ptr), 1); memset(pImage, 0, sizeof(IMAGE_S)); pImage->nWidth=(img_word)png_get_image_width(png_ptr, info_ptr); pImage->nHeight=(img_word)png_get_image_height(png_ptr, info_ptr); pImage->nBitDepth=(img_byte)png_get_bit_depth(png_ptr, info_ptr)*png_get_channels(png_ptr, info_ptr); pImage->nDataFmt=pImage->nBitDepth==32?IMGFMT_A8R8G8B8:IMGFMT_R8G8B8; pImage->nDataSize=pImage->nWidth*pImage->nHeight*pImage->nBitDepth/8; pImage->nOrient=IMGORIENT_TOPLEFT; pImage->pImage=malloc(pImage->nDataSize); if(!pImage->pImage) longjmp(png_jmpbuf(png_ptr), 1); { png_bytepp row_pointers=png_get_rows(png_ptr, info_ptr); img_dword row_length=pImage->nWidth*pImage->nBitDepth/8; for(i=0; i<pImage->nHeight; i++) { memcpy((img_byte*)pImage->pImage+i*row_length, row_pointers[i], row_length); } } png_destroy_read_struct( &png_ptr, &info_ptr, &end_info); return pImage; }<file_sep>/samples/D3DDemo/code/MD3Base/MD3Data.c #include <stdio.h> #include "MD3File.h" BOOL DumpMD3MeshDebugData(FILE * fout, LPMD3MESH lpMesh, DWORD dwDumpFlags); BOOL DumpMD3MeshDebugData(FILE * fout, LPMD3MESH lpMesh, DWORD dwDumpFlags){ LONG i=0; if(!fout)return FALSE; fprintf(fout, "\n\n--- MD3 Mesh Header ---\n\n"); fprintf(fout, "ID: %i\n", lpMesh->md3MeshHeader.dwID); fprintf(fout, "Name: %s\n", lpMesh->md3MeshHeader.szMeshName); fprintf(fout, "Flags: %i\n", lpMesh->md3MeshHeader.lFlags); fprintf(fout, "Num Frames: %i\n", lpMesh->md3MeshHeader.lNumFrames); fprintf(fout, "Num Shaders: %i\n", lpMesh->md3MeshHeader.lNumShaders); fprintf(fout, "Num Vertices: %i\n", lpMesh->md3MeshHeader.lNumVertices); fprintf(fout, "Num Triangles: %i\n", lpMesh->md3MeshHeader.lNumTriangles); fprintf(fout, "Triangle Offset: %i\n", lpMesh->md3MeshHeader.lTriangleOffset); fprintf(fout, "Shader offset: %i\n", lpMesh->md3MeshHeader.lShaderOffset); fprintf(fout, "Tex Coord Offset: %i\n", lpMesh->md3MeshHeader.lTexCoordOffset); fprintf(fout, "Vertex Offset: %i\n", lpMesh->md3MeshHeader.lVertexOffset); fprintf(fout, "Surface End: %i\n", lpMesh->md3MeshHeader.lMeshDataSize); fprintf(fout, "\n"); if( (dwDumpFlags&MD3DUMP_MESHSHADER)==MD3DUMP_MESHSHADER){ fprintf(fout, "- Shader Data -\n\n"); for(i=0; i<lpMesh->md3MeshHeader.lNumShaders; i++){ fprintf(fout, "Shader %i\n", i+1); fprintf(fout, "Shader #: %i\n", lpMesh->md3Shader[i].lShaderNum); fprintf(fout, "Shader name: %s\n", lpMesh->md3Shader[i].szShaderName); } } if( (dwDumpFlags&MD3DUMP_MESHTRI)==MD3DUMP_MESHTRI){ fprintf(fout, "\n\n- Triangle Data -\n\n"); for(i=0; i<lpMesh->md3MeshHeader.lNumTriangles; i++){ fprintf(fout, "Triangle %i\n", i+1); fprintf(fout, "Indexes: (%i, %i, %i)\n", lpMesh->md3Triangle[i].nIndexes[0], lpMesh->md3Triangle[i].nIndexes[1], lpMesh->md3Triangle[i].nIndexes[2]); fprintf(fout, "\n"); } } if( (dwDumpFlags&MD3DUMP_MESHTEXCOORD)==MD3DUMP_MESHTEXCOORD){ fprintf(fout, "\n\n- Texture Coordinates -\n\n"); for(i=0; i<lpMesh->md3MeshHeader.lNumVertices; i++){ fprintf(fout, "TexCoord %i\n", i+1); fprintf(fout, "Coordinates: (%f, %f)\n", lpMesh->md3TexCoords[i].tu, lpMesh->md3TexCoords[i].tv); fprintf(fout, "\n"); } } if( (dwDumpFlags&MD3DUMP_MESHVERTEX)==MD3DUMP_MESHVERTEX){ fprintf(fout, "\n\n- Vertices -\n\n"); for(i=0; i<lpMesh->md3MeshHeader.lNumVertices*lpMesh->md3MeshHeader.lNumFrames; i++){ fprintf(fout, "Vertex %i: ", i+1); fprintf(fout, "(%i, %i, %i, %i)\n", lpMesh->md3Vertex[i].x, lpMesh->md3Vertex[i].y,lpMesh->md3Vertex[i].z, lpMesh->md3Vertex[i].nNormal); } } return TRUE; } BOOL DumpMD3DebugData(LPVOID fout, LPMD3FILE lpFile, DWORD dwDumpFlags){ LONG i=0; /* Write the header data. */ fprintf(fout, "--- MD3 Header ---\n\n"); fprintf(fout, "MD3 ID: %i\n", lpFile->md3Header.dwID); fprintf(fout, "MD3 Version: %i\n", lpFile->md3Header.lVersion); fprintf(fout, "MD3 Filename: %s\n", lpFile->md3Header.szFileName); fprintf(fout, "Flags: %i\n", lpFile->md3Header.lFlags); fprintf(fout, "Number of frames: %i\n", lpFile->md3Header.lNumFrames); fprintf(fout, "Number of tags: %i\n", lpFile->md3Header.lNumTags); fprintf(fout, "Number of meshes: %i\n",lpFile->md3Header.lNumMeshes); fprintf(fout, "Number of skins: %i\n", lpFile->md3Header.lNumSkins); fprintf(fout, "Frame Offset: %i\n", lpFile->md3Header.lFrameOffset); fprintf(fout, "Tag Offset: %i\n", lpFile->md3Header.lTagOffset); fprintf(fout, "Mesh Offset: %i\n", lpFile->md3Header.lMeshOffset); fprintf(fout, "MD3 File Size: %i bytes\n", lpFile->md3Header.lFileSize); fprintf(fout, "\n"); /* Write the frame data. */ if( (dwDumpFlags&MD3DUMP_BONEFRAME)==MD3DUMP_BONEFRAME){ fprintf(fout, "\n\n\n--- Frame Data ---\n\n"); for(i=0; i<lpFile->md3Header.lNumFrames; i++){ fprintf(fout, "- Frame %i -\n", (i+1)); fprintf(fout, "Min Bounds: (%f, %f, %f)\n", lpFile->md3Frame[i].vMin.x, lpFile->md3Frame[i].vMin.y, lpFile->md3Frame[i].vMin.z); fprintf(fout, "Max Bounds: (%f, %f, %f)\n", lpFile->md3Frame[i].vMax.x, lpFile->md3Frame[i].vMax.y, lpFile->md3Frame[i].vMax.z); fprintf(fout, "Local Origin: (%f, %f, %f)\n", lpFile->md3Frame[i].vOrigin.x, lpFile->md3Frame[i].vOrigin.y, lpFile->md3Frame[i].vOrigin.z); fprintf(fout, "Boudning Radius: %f\n", lpFile->md3Frame[i].fRadius); fprintf(fout, "Name: %s\n", lpFile->md3Frame[i].szName); fprintf(fout, "\n"); } } /* Write the tag data. */ if( (dwDumpFlags&MD3DUMP_TAG)==MD3DUMP_TAG){ fprintf(fout, "\n\n\n--- Tag Data ---\n\n"); for(i=0; i<lpFile->md3Header.lNumTags*lpFile->md3Header.lNumFrames; i++){ fprintf(fout, "- Tag %i -\n", (i+1)); fprintf(fout, "Name: %s\n", lpFile->md3Tag[i].szName); fprintf(fout, "Origin: (%f, %f, %f)\n", lpFile->md3Tag[i].vPosition.x, lpFile->md3Tag[i].vPosition.y, lpFile->md3Tag[i].vPosition.z); fprintf(fout, "1st Axis: (%f, %f, %f)\n", lpFile->md3Tag[i].vAxis[0].x, lpFile->md3Tag[i].vAxis[0].y, lpFile->md3Tag[i].vAxis[0].z); fprintf(fout, "2nd Axis: (%f, %f, %f)\n", lpFile->md3Tag[i].vAxis[1].x, lpFile->md3Tag[i].vAxis[1].y, lpFile->md3Tag[i].vAxis[1].z); fprintf(fout, "3rd Axis: (%f, %f, %f)\n", lpFile->md3Tag[i].vAxis[2].x, lpFile->md3Tag[i].vAxis[2].y, lpFile->md3Tag[i].vAxis[2].z); fprintf(fout, "\n"); } } /* Write the Mesh data. */ if( (dwDumpFlags&MD3DUMP_MESH)==MD3DUMP_MESH){ for(i=0; i<lpFile->md3Header.lNumMeshes; i++){ fprintf(fout, "\n=== Mesh %i ===\n", i+1); DumpMD3MeshDebugData(fout, &(lpFile->md3Mesh[i]), dwDumpFlags); } } return TRUE; }<file_sep>/games/Legacy-Engine/Scrapped/tools/warchiver/resource.h //{{NO_DEPENDENCIES}} // Microsoft Developer Studio generated include file. // Used by resource.rc // #define IDC_QUIT 1000 #define IDC_TREE 1002 #define IDC_OUTPUT 1003 #define IDC_ARCHIVEIT 1004 #define IDC_BROWSETREE 1005 #define IDC_BROWSEOUTPUT 1006 #define IDC_TEXT 1007 #define IDC_ARCPROG 1009 #define IDC_FILENAME 1010 #define IDC_COMPRESS 1011 #define IDC_ARCHFILE 1012 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 107 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1013 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif <file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/lv_con.c #include "common.h" #include <stdio.h> #include "lv_con.h" #include "lg_sys.h" #include <lf_sys.h> #define CONSOLE_WIDTH 640.0f #define CONSOLE_HEIGHT 480.0f L_bool VCon_UpdatePos(LVCON* lpVCon) { float fElapsedTime=0; float fScrollDist=0.0f; if(!lpVCon) return L_false; if(!lpVCon->bActive) return L_false; if((timeGetTime()-lpVCon->dwLastCaretChange)>GetCaretBlinkTime()) { lpVCon->bCaretOn=!lpVCon->bCaretOn; lpVCon->dwLastCaretChange=timeGetTime(); } /* In case the console is cleared we make sure teh current console position is allowed. */ if(lpVCon->nScrollPos>(L_long)Con_GetNumEntries(lpVCon->hConsole)) lpVCon->nScrollPos=0; fElapsedTime=(float)(timeGetTime()-lpVCon->dwLastUpdate); fScrollDist=fElapsedTime/1.5f; if(lpVCon->bDeactivating) { if(lpVCon->fPosition<=0.0f) { lpVCon->fPosition=0.0f; lpVCon->bActive=L_false; return L_true; } lpVCon->fPosition-=fScrollDist; } else { lpVCon->fPosition+=fScrollDist; if(lpVCon->fPosition>(CONSOLE_HEIGHT/(2-lpVCon->bFullMode))) lpVCon->fPosition=(CONSOLE_HEIGHT/(2-lpVCon->bFullMode)); } return L_true; } __inline void VCon_FontStringToSize(L_dword* pHeight, L_dword* pWidth, L_pstr szString) { L_dword dwLen=L_strlen(szString); L_bool bFoundHeight=L_false; char szHeight[32]; L_pstr szWidth=L_null; L_dword i=0; if(dwLen<1) { *pWidth=0; *pHeight=16; } for(i=0; i<dwLen; i++) { if(!bFoundHeight) { if(szString[i]=='X' || szString[i]=='x') { bFoundHeight=L_true; szHeight[i]=0; szWidth=&szString[i+1]; break; } szHeight[i]=szString[i]; } } *pHeight=L_atol(szHeight); *pWidth=L_atol(szWidth); return; } LVCON* VCon_Create( HLCONSOLE hConsole, HCVARLIST cvars, IDirect3DDevice9* lpDevice) { LVCON* lpNewCon=L_null; D3DVIEWPORT9 ViewPort; //L_byte dwFontSize=(L_byte)CVar_GetValue(cvars, "lc_FontSize", L_null); L_pstr szBGTexture=CVar_Get(cvars, "lc_BG", L_null); //L_pstr szFontSize=L_null; L_dword dwFontWidth=0, dwFontHeight=0; //szFontSize=CVar_Get(cvars, "lc_FontSize", L_null); /*We need to get the font size and convert it to a componet size.*/ VCon_FontStringToSize(&dwFontHeight, &dwFontWidth, CVar_Get(cvars, "lc_FontSize", L_null)); /* Allocate memory for the graphic console. */ lpNewCon=malloc(sizeof(LVCON)); if(!lpNewCon) { Err_Printf("Could not allocate memory for graphic console."); return L_null; } memset(lpNewCon, 0, sizeof(LVCON)); lpDevice->lpVtbl->GetViewport(lpDevice, &ViewPort); lpNewCon->dwViewHeight=ViewPort.Height; lpNewCon->dwFontHeight=dwFontHeight; /* { char szTemp[100]; sprintf(szTemp, "Width: %i Height: %i", dwFontWidth, dwFontHeight); MessageBox(0, szTemp, 0, 0); } */ /* Attempt to laod the background. */ lpNewCon->lpBackground=L2DI_CreateFromFile( lpDevice, szBGTexture, L_null, (L_dword)CONSOLE_WIDTH, (L_dword)CONSOLE_HEIGHT, 0x00000000); /* If we can't create a background from a texture, we attempt to do it from a color. */ if(!lpNewCon->lpBackground) { Err_Printf("Could not load texture from \"%s\" for console background, using color.", szBGTexture); lpNewCon->lpBackground=L2DI_CreateFromColor( lpDevice, (L_dword)CONSOLE_WIDTH, (L_dword)CONSOLE_HEIGHT, 0xFF8080FF); } if(!lpNewCon->lpBackground) { Err_Printf("Could not load console background, failing."); L_safe_free(lpNewCon); return L_null; } /* Attemp to load a font for the console. */ if(CVar_GetValue(cvars, "lc_UseLegacyFont", L_null) || CVar_GetValue(cvars, "v_Force16BitTextures", L_null)) { L_dword dwWidthInFile=0, dwHeightInFile=0; VCon_FontStringToSize(&dwHeightInFile, &dwWidthInFile, CVar_Get(cvars, "lc_LegacyFontSizeInFile", L_null)); if(!dwFontWidth) dwFontWidth=dwFontHeight/2; lpNewCon->lpFont=Font_Create2( lpDevice, CVar_Get(cvars, "lc_LegacyFont", L_null), (L_byte)dwFontWidth, (L_byte)dwFontHeight, L_false, (L_byte)dwWidthInFile, (L_byte)dwHeightInFile, 0); } else { lpNewCon->lpFont=Font_Create2( lpDevice, CVar_Get(cvars, "lc_Font", L_null), (L_byte)dwFontWidth, (L_byte)dwFontHeight, L_true, 0, 0, (0xFF<<24)|(L_dword)CVar_GetValue(cvars, "lc_FontColor", L_null)); } if(!lpNewCon->lpFont) { Err_Printf("Could not load font for console, failing."); L2DI_Delete(lpNewCon->lpBackground); L_safe_free(lpNewCon); return L_null; } /* Attach the console */ lpNewCon->hConsole=hConsole; /* Set the last time the console was updated to now. */ lpNewCon->dwLastUpdate=timeGetTime(); /* We need to set a few starting values for the console. */ lpNewCon->bCaretOn=L_true; lpNewCon->dwLastCaretChange=timeGetTime(); lpNewCon->bActive=L_false; lpNewCon->bDeactivating=L_true; lpNewCon->fPosition=0; lpNewCon->bFullMode=L_false; return lpNewCon; } L_bool VCon_Delete( LVCON* lpVCon) { if(!lpVCon) return L_false; /* Delete the bg and the font. */ L2DI_Delete(lpVCon->lpBackground); Font_Delete2(lpVCon->lpFont); /* Delete the console itself. */ L_safe_free(lpVCon); return L_true; } L_bool VCon_Render( LVCON* lpVCon, IDirect3DDevice9* lpDevice) { float fRenderPos=0; L_dword i=0; L_long nStart=0; L_long nCharHeight=0; LVFONT_DIMS fontdims; if(!lpVCon) return L_false; /* Update the position, and activity of the console. */ VCon_UpdatePos(lpVCon); lpVCon->dwLastUpdate=timeGetTime(); if(!lpVCon->bActive) return L_true; nCharHeight=lpVCon->dwFontHeight;//16;//lpVCon->lpFont->m_dwFontHeight; /* Render the background at the position. */ L2DI_StartStopDrawing(lpDevice, (L_long)CONSOLE_WIDTH, (L_long)CONSOLE_HEIGHT, L_true); L2DI_Render(lpVCon->lpBackground, lpDevice, 0.0f, lpVCon->fPosition-CONSOLE_HEIGHT); L2DI_StartStopDrawing(lpDevice, 0, 0, L_false); /* Now render all visible text. */ /* First we render the active entry. */ Font_GetDims(lpVCon->lpFont, &fontdims); if(fontdims.bD3DXFont) fRenderPos=lpVCon->fPosition*lpVCon->dwViewHeight/CONSOLE_HEIGHT-nCharHeight-8;//800.0f-nCharHeight;//lpVCon->fPosition*800.0f/CONSOLE_HEIGHT; else fRenderPos=lpVCon->fPosition-nCharHeight-8;//CONSOLE_HEIGHT/2-nCharHeight-8; //fRenderPos-=(nCharHeight*nStart)-8.0f; Font_Begin2(lpVCon->lpFont); { char szTemp[1024]; _snprintf(szTemp, 1022, "]%s", Con_GetEntry(lpVCon->hConsole, 1, L_null)); if(lpVCon->bCaretOn) strncat(szTemp, "_", 1); Font_DrawString2( lpVCon->lpFont, szTemp, 8, (L_long)fRenderPos); } fRenderPos-=nCharHeight; if(lpVCon->nScrollPos) { Font_DrawString2( lpVCon->lpFont, "^ ^ ^ ^", 8, (L_long)fRenderPos); nStart=3; fRenderPos-=nCharHeight; } else nStart=2; for(i=nStart+lpVCon->nScrollPos; fRenderPos>=(-nCharHeight); fRenderPos-=nCharHeight, i++) { if(!Font_DrawString2( lpVCon->lpFont, Con_GetEntry(lpVCon->hConsole, i, L_null), 8, (L_long)fRenderPos)) break; } Font_End2(lpVCon->lpFont); return L_true; } L_bool VCon_Validate( LVCON* lpVCon, IDirect3DDevice9* lpDevice) { D3DVIEWPORT9 ViewPort; if(!lpVCon || !lpDevice) return L_false; L2DI_Validate(lpVCon->lpBackground, lpDevice, L_null); Font_Validate2(lpVCon->lpFont); lpDevice->lpVtbl->GetViewport(lpDevice, &ViewPort); lpVCon->dwViewHeight=ViewPort.Height; return L_true; } L_bool VCon_Invalidate( LVCON* lpVCon) { if(!lpVCon) return L_false; L2DI_Invalidate(lpVCon->lpBackground); Font_Invalidate2(lpVCon->lpFont); return L_true; } /* VCon_OnChar - processes input through the graphical console, it checks to see if it should activate/deactive and then it checks to see if it is active. If it isn't active it won't do anything, if it is, it can scoll up the entry list, and it will pass any other data to the actual console. */ L_bool VCon_OnChar( LVCON* lpVCon, char c) { if(!lpVCon) return L_false; if(c=='`' || c=='~') { lpVCon->bDeactivating=!lpVCon->bDeactivating; if(!lpVCon->bDeactivating) lpVCon->bActive=L_true; return L_true; } if(!lpVCon->bActive) return L_false; /* There are two special coes, LK_PAGEUP and LK_PAGEDOWN that are passed from win_sys.c when the pageup and pagedown keys are pressed, that way the console can know if it should scroll up or down. */ switch(c) { case LK_PAGEUP: lpVCon->nScrollPos++; if(lpVCon->nScrollPos>=((L_long)Con_GetNumEntries(lpVCon->hConsole)-2)) lpVCon->nScrollPos=Con_GetNumEntries(lpVCon->hConsole)-2; break; case LK_PAGEDOWN: lpVCon->nScrollPos--; if(lpVCon->nScrollPos<0) lpVCon->nScrollPos=0; break; case LK_END: lpVCon->nScrollPos=0; break; default: return Con_OnChar(lpVCon->hConsole, c); } return L_true; }<file_sep>/games/Legacy-Engine/Source/common/lg_string.c #include <string.h> #include "lg_string.h" lg_int LG_StrNcCmpA(const lg_char* s1, const lg_char* s2, lg_long n) { lg_char c1, c2; #if 1 if(!s1) { return s2?-1:0; } else if(!s2) return 1; #endif do { c1=*s1++; c2=*s2++; if(!n--) return 0; if(c1!=c2) { if((c1>='a') && (c1<='z')) c1-=('a'-'A'); if((c2>='a') && (c2<='z')) c2-=('a'-'A'); if(c1!=c2) return c1>c2?1:-1; } }while(c1); return 0; } lg_int LG_StrNcCmpW(const lg_wchar* s1, const lg_wchar* s2, lg_long n) { lg_wchar c1, c2; #if 1 if(!s1) { return s2?-1:0; } else if(!s2) return 1; #endif do { c1=*s1++; c2=*s2++; if(!n--) return 0; if(c1!=c2) { if((c1>='a') && (c1<='z')) c1-=('a'-'A'); if((c2>='a') && (c2<='z')) c2-=('a'-'A'); if(c1!=c2) return c1>c2?1:-1; } }while(c1); return 0; } lg_dword LG_StrLenA(const lg_char* s) { lg_dword count=0; while(s[count]) count++; return count; } lg_dword LG_StrLenW(const lg_wchar* s) { lg_dword count=0; while(s[count]) count++; return count; } lg_char* LG_StrCopySafeA(lg_char* dest, const lg_char* src, lg_dword destsize) { strncpy(dest,src, destsize-1); dest[destsize-1] = 0; return dest; } lg_wchar* LG_StrCopySafeW(lg_wchar* dest, const lg_wchar* src, lg_dword destsize) { wcsncpy(dest,src, destsize-1); dest[destsize-1] = 0; return dest; }<file_sep>/samples/D3DDemo/code/MD3Base/MD3Mesh.cpp #define D3D_MD3 #include <d3dx9.h> #include <stdio.h> #include "defines.h" #include "Functions.h" #include "MD3.h" /////////////////////////////////// /// Constructor and Destructor /// /////////////////////////////////// CMD3Mesh::CMD3Mesh() { m_md3File.md3Mesh=NULL; m_md3File.md3Frame=NULL; m_md3File.md3Tag=NULL; ZeroMemory(&m_md3File.md3Header, sizeof(MD3HEADER)); m_lppIB=NULL; m_lppVB=NULL; m_lpVertices=NULL; m_bMD3Loaded=FALSE; m_bValid=FALSE; m_dwNumSkins=0; m_lppNormals=NULL; m_Pool=D3DPOOL_DEFAULT; m_lpDevice=NULL; } CMD3Mesh::~CMD3Mesh() { ClearMD3(); } /////////////////////////////// /// Public member methods /// /////////////////////////////// HRESULT CMD3Mesh::GetNumTags( LONG * lpNumTags) { if(m_bMD3Loaded){ *lpNumTags=m_md3File.md3Header.lNumTags; return S_OK; }else{ *lpNumTags=0; return E_FAIL; } } HRESULT CMD3Mesh::GetTagName( LONG lRef, char szTagName[MAX_QPATH]) { if(m_bMD3Loaded && (lRef>0) && (lRef<=m_md3File.md3Header.lNumTags)){ strcpy(szTagName, m_md3File.md3Tag[lRef-1].szName); return S_OK; }else{ strcpy(szTagName, ""); return E_FAIL; } } HRESULT CMD3Mesh::GetTagTranslation( DWORD dwTagRef, FLOAT fTime, LONG dwFirstFrame, LONG dwSecondFrame, D3DMATRIX * Translation) { D3DXMATRIX FirstFrame, SecondFrame, Final; D3DXQUATERNION FirstQuat, SecondQuat, FinalQuat; LONG lTagRefFirst=0, lTagRefSecond=0; FLOAT x=0.0f, y=0.0f, z=0.0f; lTagRefFirst=dwFirstFrame*m_md3File.md3Header.lNumTags+dwTagRef-1; lTagRefSecond=dwSecondFrame*m_md3File.md3Header.lNumTags+dwTagRef-1; D3DXMatrixIdentity((D3DXMATRIX*)Translation); if( (dwTagRef<1) || (((LONG)dwTagRef) > m_md3File.md3Header.lNumTags)) return E_FAIL; if( (dwFirstFrame < 0) || (dwSecondFrame < 0) || (dwFirstFrame >= m_md3File.md3Header.lNumFrames) || (dwSecondFrame >= m_md3File.md3Header.lNumFrames)) return E_FAIL; FirstFrame._11=m_md3File.md3Tag[lTagRefFirst].vAxis[0].x; FirstFrame._12=m_md3File.md3Tag[lTagRefFirst].vAxis[0].y; FirstFrame._13=m_md3File.md3Tag[lTagRefFirst].vAxis[0].z; FirstFrame._14=0; FirstFrame._21=m_md3File.md3Tag[lTagRefFirst].vAxis[1].x; FirstFrame._22=m_md3File.md3Tag[lTagRefFirst].vAxis[1].y; FirstFrame._23=m_md3File.md3Tag[lTagRefFirst].vAxis[1].z; FirstFrame._24=0; FirstFrame._31=m_md3File.md3Tag[lTagRefFirst].vAxis[2].x; FirstFrame._32=m_md3File.md3Tag[lTagRefFirst].vAxis[2].y; FirstFrame._33=m_md3File.md3Tag[lTagRefFirst].vAxis[2].z; FirstFrame._34=0; FirstFrame._41=0; FirstFrame._42=0; FirstFrame._43=0; FirstFrame._44=1; //If both frames are the same this is a much simpler proccess SecondFrame._11=m_md3File.md3Tag[lTagRefSecond].vAxis[0].x; SecondFrame._12=m_md3File.md3Tag[lTagRefSecond].vAxis[0].y; SecondFrame._13=m_md3File.md3Tag[lTagRefSecond].vAxis[0].z; SecondFrame._14=0; SecondFrame._21=m_md3File.md3Tag[lTagRefSecond].vAxis[1].x; SecondFrame._22=m_md3File.md3Tag[lTagRefSecond].vAxis[1].y; SecondFrame._23=m_md3File.md3Tag[lTagRefSecond].vAxis[1].z; SecondFrame._24=0; SecondFrame._31=m_md3File.md3Tag[lTagRefSecond].vAxis[2].x; SecondFrame._32=m_md3File.md3Tag[lTagRefSecond].vAxis[2].y; SecondFrame._33=m_md3File.md3Tag[lTagRefSecond].vAxis[2].z; SecondFrame._34=0; SecondFrame._41=0; SecondFrame._42=0; SecondFrame._43=0; SecondFrame._44=1; D3DXQuaternionRotationMatrix(&FirstQuat, &FirstFrame); D3DXQuaternionRotationMatrix(&SecondQuat, &SecondFrame); D3DXQuaternionSlerp(&FinalQuat, &FirstQuat, &SecondQuat, fTime); D3DXMatrixRotationQuaternion(&Final, &FinalQuat); //Interpolate translation vector and stick it in the final matrix. x = m_md3File.md3Tag[lTagRefFirst].vPosition.x + fTime * ( m_md3File.md3Tag[lTagRefSecond].vPosition.x - m_md3File.md3Tag[lTagRefFirst].vPosition.x); y = m_md3File.md3Tag[lTagRefFirst].vPosition.y + fTime * ( m_md3File.md3Tag[lTagRefSecond].vPosition.y - m_md3File.md3Tag[lTagRefFirst].vPosition.y); z = m_md3File.md3Tag[lTagRefFirst].vPosition.z + fTime * ( m_md3File.md3Tag[lTagRefSecond].vPosition.z - m_md3File.md3Tag[lTagRefFirst].vPosition.z); Final._41=x; Final._42=y; Final._43=z; Final._44=1; *Translation=Final; return S_OK; } HRESULT CMD3Mesh::LoadMD3A( char szFilename[MAX_PATH], LPDWORD lpBytesRead, LPDIRECT3DDEVICE9 lpDevice, D3DPOOL Pool) { DWORD dwBytesRead=0; HANDLE hFile=NULL; HRESULT hr=0; // Clear any MD3 that might exist. ClearMD3(); // Load the file. hFile=CreateFileA( szFilename, GENERIC_READ, FILE_SHARE_READ, (LPSECURITY_ATTRIBUTES)NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, (HANDLE)NULL); //If the file failed to load we return the last error. if(hFile==INVALID_HANDLE_VALUE) return E_FAIL; //Read the MD3 File, insuring that it really is an MD3 file. if(!ReadMD3File(hFile, &m_md3File, &dwBytesRead, NULL)){ CloseHandle(hFile); return E_FAIL; } //We have the data so we can close the file, and set the number //of bytes read. CloseHandle(hFile); if(lpBytesRead) *lpBytesRead=dwBytesRead; m_Pool=Pool; m_lpDevice=lpDevice; m_lpDevice->AddRef(); hr=CreateModel(); if(SUCCEEDED(hr)){ m_bMD3Loaded=TRUE; } else { SAFE_RELEASE(m_lpDevice); } return hr; } HRESULT CMD3Mesh::LoadMD3W( WCHAR szFilename[MAX_PATH], LPDWORD lpBytesRead, LPDIRECT3DDEVICE9 lpDevice, D3DPOOL Pool) { DWORD dwBytesRead=0; HANDLE hFile=NULL; HRESULT hr=0; // Clear any MD3 that might exist. ClearMD3(); // Load the file. hFile=CreateFileW( szFilename, GENERIC_READ, FILE_SHARE_READ, (LPSECURITY_ATTRIBUTES)NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, (HANDLE)NULL); //If the file failed to load we return the last error. if(hFile==INVALID_HANDLE_VALUE) return E_FAIL; //Read the MD3 File, insuring that it really is an MD3 file. if(!ReadMD3File(hFile, &m_md3File, &dwBytesRead, NULL)){ CloseHandle(hFile); return E_FAIL; } //We have the data so we can close the file, and set the number //of bytes read. CloseHandle(hFile); if(lpBytesRead) *lpBytesRead=dwBytesRead; m_Pool=Pool; m_lpDevice=lpDevice; m_lpDevice->AddRef(); hr=CreateModel(); if(SUCCEEDED(hr)){ m_bMD3Loaded=TRUE; } else { SAFE_RELEASE(m_lpDevice); } return hr; } HRESULT CMD3Mesh::ClearMD3() { //If an MD3 is loaded delete the model and the file. if(m_bMD3Loaded){ DeleteModel(); DeleteMD3File(&m_md3File); SAFE_RELEASE(m_lpDevice); } //Set loaded to false. m_bMD3Loaded=FALSE; return S_OK; } HRESULT CMD3Mesh::RenderWithTexture( LPDIRECT3DTEXTURE9 lpTexture, LONG lMesh, FLOAT fTime, LONG lFirstFrame, LONG lNextFrame, DWORD dwFlags) { LONG lNumVertices=0; LONG i=0, j=0; FLOAT fFirstX=0.0f, fFirstY=0.0f, fFirstZ=0.0f; FLOAT fNextX=0.0f, fNextY=0.0f, fNextZ=0.0f; LPVOID lpBuffer=NULL; //D3D data that should be restored after the render. DWORD dwPrevCullMode=0; LPDIRECT3DTEXTURE9 lpPrevTexture=NULL; if(!m_lpDevice) return E_FAIL; if( (lMesh < 1) || (lMesh>m_md3File.md3Header.lNumMeshes) ) return E_FAIL; //Make sure the frames are within the appropriate range. if((lFirstFrame < 0) || (lFirstFrame>=m_md3File.md3Header.lNumFrames)) return S_FALSE; if((lNextFrame < 0) || (lNextFrame>=m_md3File.md3Header.lNumFrames)) return S_FALSE; //Get the D3D data that should be restored. m_lpDevice->GetRenderState(D3DRS_CULLMODE, &dwPrevCullMode); m_lpDevice->GetTexture(0, (IDirect3DBaseTexture9**)&lpPrevTexture); if(MD3TEXRENDER_NOCULL==(MD3TEXRENDER_NOCULL&dwFlags)) m_lpDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); else m_lpDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CW); lNumVertices=m_md3File.md3Mesh[lMesh-1].md3MeshHeader.lNumVertices; for(i=0; i<lNumVertices; i++){ fFirstX=m_md3File.md3Mesh[lMesh-1].md3Vertex[i+lFirstFrame*lNumVertices].x*MD3_XYZ_SCALE; fFirstY=m_md3File.md3Mesh[lMesh-1].md3Vertex[i+lFirstFrame*lNumVertices].y*MD3_XYZ_SCALE; fFirstZ=m_md3File.md3Mesh[lMesh-1].md3Vertex[i+lFirstFrame*lNumVertices].z*MD3_XYZ_SCALE; fNextX=m_md3File.md3Mesh[lMesh-1].md3Vertex[i+lNextFrame*lNumVertices].x*MD3_XYZ_SCALE; fNextY=m_md3File.md3Mesh[lMesh-1].md3Vertex[i+lNextFrame*lNumVertices].y*MD3_XYZ_SCALE; fNextZ=m_md3File.md3Mesh[lMesh-1].md3Vertex[i+lNextFrame*lNumVertices].z*MD3_XYZ_SCALE; //Interpolate the first and second frames. m_lpVertices[i].Postion.x=(fFirstX + fTime*(fNextX-fFirstX)); m_lpVertices[i].Postion.y=(fFirstY + fTime*(fNextY-fFirstY)); m_lpVertices[i].Postion.z=(fFirstZ + fTime*(fNextZ-fFirstZ)); //Interpolate Normal vector. fFirstX=m_lppNormals[lMesh-1][i+lFirstFrame*lNumVertices].x; fFirstY=m_lppNormals[lMesh-1][i+lFirstFrame*lNumVertices].y; fFirstZ=m_lppNormals[lMesh-1][i+lFirstFrame*lNumVertices].z; fNextX=m_lppNormals[lMesh-1][i+lNextFrame*lNumVertices].x; fNextY=m_lppNormals[lMesh-1][i+lNextFrame*lNumVertices].y; fNextZ=m_lppNormals[lMesh-1][i+lNextFrame*lNumVertices].z; m_lpVertices[i].Normal.x=(fFirstX + fTime*(fNextX-fFirstX)); m_lpVertices[i].Normal.y=(fFirstY + fTime*(fNextY-fFirstY)); m_lpVertices[i].Normal.z=(fFirstZ + fTime*(fNextZ-fFirstZ)); //Get the texture coordinates. m_lpVertices[i].tu=m_md3File.md3Mesh[lMesh-1].md3TexCoords[i].tu; m_lpVertices[i].tv=m_md3File.md3Mesh[lMesh-1].md3TexCoords[i].tv; } IDirect3DVertexBuffer9_Lock(m_lppVB[lMesh-1], 0, 0, &lpBuffer, 0); memcpy(lpBuffer, m_lpVertices, sizeof(D3DMD3VERTEX)*lNumVertices); IDirect3DVertexBuffer9_Unlock(m_lppVB[lMesh-1]); IDirect3DDevice9_SetStreamSource(m_lpDevice, 0, m_lppVB[lMesh-1], 0, sizeof(D3DMD3VERTEX)); IDirect3DDevice9_SetIndices(m_lpDevice, m_lppIB[lMesh-1]); m_lpDevice->SetTexture(0, lpTexture); IDirect3DDevice9_SetFVF(m_lpDevice, D3DMD3VERTEX_TYPE); IDirect3DDevice9_DrawIndexedPrimitive( m_lpDevice, D3DPT_TRIANGLELIST, 0, 0, m_md3File.md3Mesh[lMesh-1].md3MeshHeader.lNumVertices, 0, m_md3File.md3Mesh[lMesh-1].md3MeshHeader.lNumTriangles); //#define DRAW_NORMAL_MESH #ifdef DRAW_NORMAL_MESH FLOAT Line[6]; m_lpDevice->SetTexture(0, NULL); for(int k=0; k<m_md3File.md3Mesh[lMesh-1].md3MeshHeader.lNumVertices; k++) { Line[0]=m_lpVertices[k].Postion.x; Line[1]=m_lpVertices[k].Postion.y; Line[2]=m_lpVertices[k].Postion.z; Line[3]=m_lpVertices[k].Normal.x; Line[4]=m_lpVertices[k].Normal.y; Line[5]=m_lpVertices[k].Normal.z; m_lpDevice->SetFVF(D3DFVF_XYZ); m_lpDevice->DrawPrimitiveUP( D3DPT_LINELIST, 1, &Line, sizeof(FLOAT)*3); m_lpDevice->SetFVF(D3DMD3VERTEX_TYPE); } #endif //DRAW_NORMAL_MESH //Restore saved D3D data. m_lpDevice->SetRenderState(D3DRS_CULLMODE, dwPrevCullMode); m_lpDevice->SetTexture(0, lpPrevTexture); SAFE_RELEASE(lpPrevTexture); return S_OK; } HRESULT CMD3Mesh::Render( CMD3SkinFile * lpSkin, FLOAT fTime, LONG lFirstFrame, LONG lNextFrame, DWORD dwFlags) { LONG i=0, j=0; LONG lVertexOffset=0; LONG lNumVertices=0; FLOAT fFirstX=0.0f; FLOAT fFirstY=0.0f; FLOAT fFirstZ=0.0f; FLOAT fNextX=0.0f; FLOAT fNextY=0.0f; FLOAT fNextZ=0.0f; LPVOID lpBuffer=NULL; LPDIRECT3DTEXTURE9 lpTexture=NULL; //Bail if MD3 is not loaded is is currently not valid. if(!m_bMD3Loaded) return S_FALSE; if(!m_bValid) return S_FALSE; //Make sure the frames are within the appropriate range. if((lFirstFrame < 0) || (lFirstFrame>=m_md3File.md3Header.lNumFrames)) return S_FALSE; if((lNextFrame < 0) || (lNextFrame>=m_md3File.md3Header.lNumFrames)) return S_FALSE; //Insure that fTime is between 0.0f and 1.0f. if(fTime>1.0f){ fTime-=(LONG)fTime; } //Loop for each mesh, interpolate the frames, and render the mesh. for(i=0; i<m_md3File.md3Header.lNumMeshes; i++){ lpSkin->GetTexturePointer(i, &lpTexture); if(lpTexture) { RenderWithTexture( lpTexture, i+1, fTime, lFirstFrame, lNextFrame, dwFlags); lpTexture->Release(); } } //#define TESTBOX #ifdef TESTBOX float box[2][3]; box[0][0]=m_md3File.md3Frame[lFirstFrame].vMin.x; box[0][1]=m_md3File.md3Frame[lFirstFrame].vMin.y; box[0][2]=m_md3File.md3Frame[lFirstFrame].vMax.z; box[1][0]=m_md3File.md3Frame[lFirstFrame].vMax.x; box[1][1]=m_md3File.md3Frame[lFirstFrame].vMax.y; box[1][2]=m_md3File.md3Frame[lFirstFrame].vMax.z; m_lpDevice->SetFVF(D3DFVF_XYZ); m_lpDevice->DrawPrimitiveUP( D3DPT_LINELIST, 1, &box, sizeof(FLOAT)*3); m_lpDevice->SetFVF(D3DMD3VERTEX_TYPE); #endif TESTBOX return S_OK; } HRESULT CMD3Mesh::Invalidate() { HRESULT hr=S_OK; HRESULT hrReturn=S_OK; //If MD3 is loaded silently return. if(!m_bMD3Loaded) return S_FALSE; //If MD3 is currently not valid we return. if(!m_bValid) return S_FALSE; // Delete Index Buffer and Vertex Buffer. hr=DeleteIB(); if(FAILED(hr)){ //Should set more specifict error message. hrReturn=E_FAIL; } hr=DeleteVB(); if(FAILED(hr)){ // Should send more specific error message. hrReturn=E_FAIL; } m_bValid=FALSE; return hrReturn; } HRESULT CMD3Mesh::Validate() { HRESULT hr=0; //If already validated we silently return. if(m_bValid) return S_FALSE; // Create Vertex Buffer, and Index Buffer. hr=CreateVB(); if(FAILED(hr)) return E_FAIL; hr=CreateIB(); if(FAILED(hr)){ DeleteVB(); return E_FAIL; } m_bValid=TRUE; return S_OK; } HRESULT CMD3Mesh::GetNumMeshes( LONG * lpNumMeshes) { if(!m_bMD3Loaded) return E_FAIL; if(!lpNumMeshes) return E_FAIL; *lpNumMeshes=m_md3File.md3Header.lNumMeshes; return S_OK; } HRESULT CMD3Mesh::GetShader( LONG lMesh, LONG lShader, char szShaderName[MAX_QPATH], LONG * lpShaderNum) { if(!m_bMD3Loaded) return E_FAIL; if( (lMesh < 1) || (lMesh > m_md3File.md3Header.lNumMeshes) ) return E_FAIL; if( (lShader <1) || (lShader > m_md3File.md3Mesh[lMesh-1].md3MeshHeader.lNumShaders) ) return E_FAIL; if(lpShaderNum) *lpShaderNum=m_md3File.md3Mesh[lMesh-1].md3Shader[lShader-1].lShaderNum; strcpy(szShaderName, m_md3File.md3Mesh[lMesh-1].md3Shader[lShader-1].szShaderName); return S_OK; } HRESULT CMD3Mesh::DumpDebug() { FILE * fout=fopen("md3dump.txt", "w"); DumpMD3DebugData(fout, &m_md3File, MD3DUMP_ALL); fclose(fout); return S_OK; } HRESULT CMD3Mesh::SetSkinRefs( CMD3SkinFile * lpSkin) { LONG i=0; if(!m_bMD3Loaded) return E_FAIL; for(i=0; i<m_md3File.md3Header.lNumMeshes; i++){ lpSkin->SetSkinRef(m_md3File.md3Mesh[i].md3MeshHeader.szMeshName, i); } return S_OK; } //////////////////////////////// /// Private Member Methods /// //////////////////////////////// HRESULT CMD3Mesh::CreateVB() { LONG i=0, j=0; DWORD dwVerticeSize=0; //Set each vertex buffer to NULL. for(i=0; i<m_md3File.md3Header.lNumMeshes; i++){ m_lppVB[i]=NULL; } //Create a vertex buffer for each mesh. for(i=0; i<m_md3File.md3Header.lNumMeshes; i++){ dwVerticeSize=m_md3File.md3Mesh[i].md3MeshHeader.lNumVertices * sizeof(D3DMD3VERTEX); //Create the vertex buffer. We don't fill it with data because //we will be interpolating at render time. if(FAILED(IDirect3DDevice9_CreateVertexBuffer( m_lpDevice, dwVerticeSize, D3DUSAGE_WRITEONLY, D3DMD3VERTEX_TYPE, m_Pool, &(m_lppVB[i]), NULL))) { for(j=0; j<i; j++){ SAFE_RELEASE(m_lppVB[j]); } return E_FAIL; } } return S_OK; } HRESULT CMD3Mesh::DeleteVB() { LONG i=0; for(i=0; i<m_md3File.md3Header.lNumMeshes; i++){ SAFE_RELEASE((m_lppVB[i])); } return S_OK; } HRESULT CMD3Mesh::CreateIB() { //This function should check to make sure everything worked properly //not just assume it did. LONG i=0, j=0, k=0; SHORT * pIndices=NULL; LPVOID pBuffer=NULL; DWORD dwIndexSize=0; for(i=0; i<m_md3File.md3Header.lNumMeshes; i++){ m_lppIB[i]=NULL; } //Load data from MD3 file into the index buffer. for(i=0; i<m_md3File.md3Header.lNumMeshes; i++){ //Create each mesh's index buffer in turn. // Allocate memory for temp buffer. dwIndexSize=m_md3File.md3Mesh[i].md3MeshHeader.lNumTriangles * 3 * sizeof(SHORT); pIndices=(SHORT*)malloc( dwIndexSize ); if(pIndices==NULL){ for(j=0; j<i; j++){ SAFE_RELEASE(m_lppIB[j]); } return E_FAIL; } //Put each index in temp buffer. for(j=0, k=0; j<m_md3File.md3Mesh[i].md3MeshHeader.lNumTriangles; j++, k+=3){ pIndices[k]=(SHORT)m_md3File.md3Mesh[i].md3Triangle[j].nIndexes[0]; pIndices[k+1]=(SHORT)m_md3File.md3Mesh[i].md3Triangle[j].nIndexes[1]; pIndices[k+2]=(SHORT)m_md3File.md3Mesh[i].md3Triangle[j].nIndexes[2]; } //Create the index buffer. if(FAILED(IDirect3DDevice9_CreateIndexBuffer( m_lpDevice, dwIndexSize, D3DUSAGE_WRITEONLY, D3DFMT_INDEX16, m_Pool, &(m_lppIB[i]), NULL))) { for(j=0; j<i; j++){ SAFE_RELEASE(m_lppIB[j]); SAFE_FREE(pIndices); } return E_FAIL; } //Load each index into index buffer. IDirect3DIndexBuffer9_Lock(m_lppIB[i], 0, 0, &pBuffer, 0); memcpy(pBuffer, pIndices, dwIndexSize); IDirect3DIndexBuffer9_Unlock(m_lppIB[i]); //Clear the temp index buffer. SAFE_FREE(pIndices); } return S_OK; } HRESULT CMD3Mesh::DeleteIB() { LONG i=0; for(i=0; i<m_md3File.md3Header.lNumMeshes; i++){ SAFE_RELEASE((m_lppIB[i])); } return S_OK; } HRESULT CMD3Mesh::CreateNormals() { LONG i=0, j=0; //Get the normals. m_lppNormals=(MD3VECTOR**)malloc(sizeof(MD3VECTOR*) * m_md3File.md3Header.lNumMeshes); if(m_lppNormals==NULL) return E_FAIL; for(i=0; i<m_md3File.md3Header.lNumMeshes; i++) { m_lppNormals[i]=(MD3VECTOR*)malloc(sizeof(MD3VECTOR) * m_md3File.md3Mesh[i].md3MeshHeader.lNumVertices * m_md3File.md3Mesh[i].md3MeshHeader.lNumFrames); if(m_lppNormals[i]==NULL) { for(j=0; j<i; j++) { SAFE_FREE(m_lppNormals[j]); } SAFE_FREE(m_lppNormals); return E_FAIL; } for(j=0; j<(m_md3File.md3Mesh[i].md3MeshHeader.lNumVertices*m_md3File.md3Mesh[i].md3MeshHeader.lNumFrames); j++) { DecodeNormalVector(&m_lppNormals[i][j], &m_md3File.md3Mesh[i].md3Vertex[j]); } } return S_OK; } HRESULT CMD3Mesh::CreateModel() { LONG i=0, j=0; DWORD dwSizeVB=0; // Allocate memory for the Direct3D objects m_lppVB=(LPDIRECT3DVERTEXBUFFER9*)malloc( sizeof(LPDIRECT3DVERTEXBUFFER9) * (m_md3File.md3Header.lNumMeshes) ); if(m_lppVB == NULL){ return E_FAIL; } m_lppIB=(LPDIRECT3DINDEXBUFFER9*)malloc( sizeof(LPDIRECT3DINDEXBUFFER9) * (m_md3File.md3Header.lNumMeshes) ); if(m_lppIB == NULL){ SAFE_FREE(m_lppVB); return E_FAIL; } //I should probably only create on3 interpolated vertex buffer //the size of the larges vertex buffer. for(i=0; i<m_md3File.md3Header.lNumMeshes; i++){ dwSizeVB = (m_md3File.md3Mesh[i].md3MeshHeader.lNumVertices > (LONG)dwSizeVB) ? m_md3File.md3Mesh[i].md3MeshHeader.lNumVertices : dwSizeVB; } //We also create the interpolated vertex buffer. It //should be the size of the largest meshes vertex buffer. m_lpVertices=(D3DMD3VERTEX*)malloc(sizeof(D3DMD3VERTEX) * dwSizeVB); if(m_lpVertices==NULL){ SAFE_FREE(m_lppVB); SAFE_FREE(m_lppIB); return E_FAIL; } if(FAILED(CreateNormals())) { SAFE_FREE(m_lppVB); SAFE_FREE(m_lppIB); SAFE_FREE(m_lpVertices); return E_FAIL; } // i will load the index buffers and vertex buffers. if(FAILED(Validate())){ SAFE_FREE(m_lppIB); SAFE_FREE(m_lppVB); for(i=0; i<m_md3File.md3Header.lNumMeshes; i++) { SAFE_FREE(m_lppNormals[i]); } SAFE_FREE(m_lppNormals); return E_FAIL; } return S_OK; } HRESULT CMD3Mesh::DeleteModel() { HRESULT hr=S_OK; LONG i=0; /// Invalidate objects. hr=Invalidate(); //Delete the interpolated vertex buffer. SAFE_FREE( (m_lpVertices) ); // Free space allocated for D3D Pool Objects. SAFE_FREE(m_lppIB); SAFE_FREE(m_lppVB); //Free space allocated to normals. for(i=0; i<m_md3File.md3Header.lNumMeshes; i++) { SAFE_FREE(m_lppNormals[i]); } SAFE_FREE(m_lppNormals); return hr; }<file_sep>/games/Legacy-Engine/Source/game/lw_ai_test.h #pragma once #include "lw_ai_sdk.h" class CLWAIJack: public CLWAIBase { struct AIJACK_DATA{ lg_dword nMode; }; public: void Init(LEntitySrv* pEnt); void PrePhys(LEntitySrv* pEnt); void PostPhys(LEntitySrv* pEnt); lg_dword PhysFlags(); }; class CLWAIBlaine: public CLWAIBase { struct AIBLAINE_DATA{ lg_float fElapsedTime; lg_bool bForward; lg_float fCurThrust; lg_float fRotSpeed; lg_dword nTicks; }; public: void Init(LEntitySrv* pEnt); void PrePhys(LEntitySrv* pEnt); void PostPhys(LEntitySrv* pEnt); lg_dword PhysFlags(); };<file_sep>/tools/fs_sys2/fs_bdio.c /* fs_bdio.c - Basic Disk Input Output. These functions should be used internally only, and not by outside systems. Copyright (C) 2007 <NAME> */ #if defined( __WIN32__ ) || defined( __WIN64__ ) #include "fs_bdio.win32.h" #else #error Platform not set. #endif<file_sep>/tools/MConvert/Source/Conversions.cpp #include "MConvert.h" #include <stdio.h> #include <math.h> #include <string.h> #include <windows.h> #include <tchar.h> int ExData::GetConversionInfo() /* I can't beleive I got this to work! */ { #define MAX_LINELEN 100 FILE *fin; char filename[] = "rates.inf"; char line[MAX_LINELEN]; int i=0; int offset; char tempConvRate[10]; numentries=0; if(( fin=fopen(filename, "r") )==NULL) return 110; fgets(line, MAX_LINELEN, fin); int timesaround=(int)_ttoi(line); //while(!feof(fin)){ for(int j=0;j<timesaround;j++){ fgets(line, MAX_LINELEN, fin); i=0; while(line[i]!=','){ countryName[numentries][i]=line[i]; i++; } i++; offset=i; i=0; while(line[i+offset]!=','){ countryCode[numentries][i]=line[i+offset]; i++; } i++; offset=offset+i; i=0; while(line[i+offset]!='\n'){ tempConvRate[i]=line[i+offset]; i++; } exchangeRate[numentries]=atof(tempConvRate); //char buf[100]; //sprintf(buf, "Conversion rate is %f", exchangeRate[numentries]); //MessageBox(NULL, buf, "NOTE", MB_OK); numentries++; } fclose(fin); return 0; }<file_sep>/games/Legacy-Engine/Scrapped/old/lp_physx.h #ifndef __LP_PHYSX_H__ #define __LP_PHYSX_H__ #include <NxPhysics.h> #include <NxCharacter.h> #include <NxBoxController.h> #include <NxUserOutputStream.h> #include <NxCooking.h> #include <NxStream.h> #include "lg_types.h" #include "lw_map.h" #include "lf_sys2.h" class CLPhysXOutputStream: public NxUserOutputStream { virtual void reportError(NxErrorCode code, const char* message, const char* file, int line); virtual NxAssertResponse reportAssertViolation(const char* message, const char* file, int line); virtual void print(const char* message); }; class CElementPhysX { private: static NxActor* s_pWorldActor; public: static NxPhysicsSDK* s_pNxPhysics; static NxScene* s_pNxScene; static CLPhysXOutputStream s_Output; static void Initialize(); static void Shutdown(); static void SetupWorld(CLWorldMap* pMap); static void Simulate(lg_float fSeconds); }; class CLNxStream: public NxStream { public: CLNxStream(const lg_char filename[], lg_bool bLoad): m_File(LG_NULL) { Open(filename, bLoad); } virtual ~CLNxStream() { Close(); } virtual NxU8 readByte()const { NxU8 b; LF_Read(m_File, &b, 1); return b; } virtual NxU16 readWord()const { NxU16 b; LF_Read(m_File, &b, 2); return b; } virtual NxU32 readDword()const { NxU32 b; LF_Read(m_File, &b, 4); return b; } virtual NxReal readFloat()const { NxReal b; LF_Read(m_File, &b, 4); return b; } virtual NxF64 readDouble()const { NxF64 b; LF_Read(m_File, &b, 8); return b; } virtual void readBuffer(void* buffer, NxU32 size)const { LF_Read(m_File, buffer, size); } virtual NxStream& storeByte(NxU8 n) { LF_Write(m_File, &n, 1); return *this; } virtual NxStream& storeWord(NxU16 w) { LF_Write(m_File, &w, 2); return *this; } virtual NxStream& storeDword(NxU32 d) { LF_Write(m_File, &d, 4); return *this; } virtual NxStream& storeFloat(NxReal f) { LF_Write(m_File, &f, 4); return *this; } virtual NxStream& storeDouble(NxF64 f) { LF_Write(m_File, &f, 8); return *this; } virtual NxStream& storeBuffer(const void* buffer, NxU32 size) { LF_Write(m_File, (lf_void*)buffer, size); return *this; } void Open(const lg_char filename[], lg_bool bLoad) { Close(); m_File=LF_Open(filename, LF_ACCESS_READ|LF_ACCESS_WRITE, bLoad?LF_OPEN_EXISTING:LF_CREATE_ALWAYS); } void Close() { if(m_File) { LF_Close(m_File); m_File=LG_NULL; } } LF_FILE3 m_File; }; #endif __LP_PHYSX_H__<file_sep>/tools/QInstall/Source/directoryex.h /* Directory.h - Header for directory functions Copyright (c) 2003, <NAME> */ #ifndef __DIRECTORY_H__ #define __DIRECTORY_H__ #include <windows.h> #ifdef __cplusplus extern "C"{ #endif //__cplusplus HRESULT CopyDirectory(LPCTSTR szSource, LPCTSTR szDest, DWORD dwFileAttributes); #ifdef __cplusplus } #endif //__cplusplus #endif //__DIRECTORY_H__<file_sep>/games/Legacy-Engine/Source/ws_sys/ws_file.h #ifndef __WS_FILE_H__ #define __WS_FILE_H__ #include "common.h" #include "ML_lib.h" #include <memory.h> class CWSMemFile { private: lg_byte* m_pData; lg_dword m_nSize; lg_dword m_nPosition; public: CWSMemFile():m_pData(LG_NULL),m_nSize(0),m_nPosition(0){} ~CWSMemFile(){} void Open(lg_byte* pData, lg_dword nSize) { m_pData=pData; m_nSize=nSize; m_nPosition=0; } void Seek(lg_dword nMode, lg_long nOffset) { if(nMode==MEM_SEEK_SET) { m_nPosition=nOffset; } else if(nMode==MEM_SEEK_CUR) { m_nPosition+=nOffset; } else if(nMode==MEM_SEEK_END) { m_nPosition=m_nSize+nOffset; } if(m_nPosition>m_nSize) m_nPosition=nOffset>=0?m_nSize:0; } lg_dword Tell() { return m_nPosition; } lg_dword Read(lg_void* pOut, lg_dword nSize) { if((m_nPosition+nSize)>m_nSize) { nSize=m_nSize-m_nPosition; } memcpy(pOut, &m_pData[m_nPosition], nSize); m_nPosition+=nSize; return nSize; } lg_byte* GetPointer(lg_dword nOffset) { if(nOffset>=m_nSize) return LG_NULL; return &m_pData[nOffset]; } lg_dword GetSize(){return m_nSize;} static const lg_dword MEM_SEEK_SET=0; static const lg_dword MEM_SEEK_CUR=1; static const lg_dword MEM_SEEK_END=2; }; #define WS_MAX_NAME 32 #define WS_MAX_PATH 256 typedef lg_char WS_PATH[WS_MAX_PATH]; typedef lg_char WS_NAME[WS_MAX_NAME]; typedef struct _WS_VERTEX{ ML_VEC3 v3Pos; ML_VEC2 v2Tex; ML_VEC2 v2LM; }WS_VERTEX; typedef struct _WS_MATERIAL{ WS_PATH szMaterial; lg_dword nRef; }WS_MATERIAL; typedef struct _WS_LIGHTMAP{ lg_byte* pLM; lg_dword nSize; lg_dword nRef; }WS_LIGHTMAP; typedef struct _WS_VISGROUP{ WS_NAME szName; lg_dword nRef; lg_dword nFirstFace; lg_dword nFaceCount; lg_dword nVisibleFaceCount; lg_dword nFirstVertex; lg_dword nVertexCount; lg_dword nFirstGeoBlock; lg_dword nGeoBlockCount; lg_dword nFirstLight; lg_dword nLightCount; ML_AABB aabbVisBounds; }WS_VISGROUP; typedef struct _WS_RASTER_FACE{ lg_bool bVisible; lg_dword nFirst; lg_dword nNumTriangles; lg_dword nMatRef; lg_dword nLMRef; lg_dword nVisGrp; }WS_RASTER_FACE; typedef struct _WS_GEO_BLOCK{ lg_dword nFirstVertex; lg_dword nVertexCount; lg_dword nFirstTri; lg_dword nNumTris; lg_dword nFirstGeoFace; lg_dword nGeoFaceCount; ML_AABB aabbBlock; lg_dword nVisGrp; }WS_GEO_BLOCK; typedef struct _WS_GEO_FACE{ ML_PLANE plnEq; }WS_GEO_FACE; typedef struct _WS_COLOR{ lg_byte r, g, b; }WS_COLOR; typedef struct _WS_LIGHT{ ML_VEC3 v3Pos; WS_COLOR Color; lg_float fIntensity; lg_dword nVisGrp; //lg_long nRange; //lg_bool linearfalloff... }WS_LIGHT; typedef struct _WS_GEO_VERT{ ML_VEC3 v3Pos; }WS_GEO_VERT; typedef struct _WS_GEO_TRIANGLE{ ML_VEC3 v3Vert[3]; }WS_GEO_TRI; class CWSFile { private: //Map Header. lg_word m_nVersion; lg_byte m_nFileFlags; lg_long m_nNameCount; lg_long m_nNameOffset; lg_long m_nObjectCount; lg_long m_nObjectOffset; lg_dword m_nMatCount; lg_dword m_nLMCount; lg_dword m_nLMMaxSize; lg_dword m_nBrushCount; lg_dword m_nFaceCount; lg_dword m_nVisibleFaceCount; lg_dword m_nVertexCount; lg_dword m_nVisGroupCount; lg_dword m_nLightCount; lg_dword m_nGeoVertCount; lg_dword m_nGeoTriCount; CWSMemFile m_File; ML_AABB m_aabbWorld; lg_char** m_szNames; WS_VERTEX* m_pVertexes; WS_MATERIAL* m_pMaterials; WS_LIGHTMAP* m_pLMs; WS_VISGROUP* m_pVisGrps; WS_RASTER_FACE* m_pRasterFaces; WS_GEO_FACE* m_pGeoFaces; WS_GEO_BLOCK* m_pGeoBlocks; WS_LIGHT* m_pLights; WS_GEO_VERT* m_pGeoVerts; WS_GEO_TRI* m_pGeoTris; void GetNames(); void GetCounts(); void GetObjects(); void ModifyRefsAndVertexOrder(); void SortAndCompactRasterObjects(); void SortAndCompactEntitys(); void SortAndCompactGeoObjects(); void AllocateMemory(); void DeallocateMemory(); lg_bool GetLight(WS_LIGHT* lt); WS_COLOR StringToColor(lg_str szColor); public: CWSFile(); ~CWSFile(); lg_bool Load(lg_byte* pData, lg_dword nSize); lg_bool SaveAsLW(lg_char* szFilename); void ScaleMap(lg_float fScale); }; #endif __WS_FILE_H__<file_sep>/Misc/README.md Beem-Misc ========= Various code written by Beem Software, some of these examles may be useful, but the code iteself doesn't compile.<file_sep>/games/Legacy-Engine/Source/3rdParty/ML_lib/ML_mat.h #ifndef __ml_mat_H__ #define __ml_mat_H__ #include "ML_lib.h" #ifdef __cplusplus extern "C"{ #endif __cplusplus //We don't declar ML_MatIdentity here because there is only one implimentation. ml_mat* ML_FUNC ML_MatMultiply_F(ml_mat* pOut, const ml_mat* pM1, const ml_mat* pM2); ml_mat* ML_FUNC ML_MatMultiply_SSE(ml_mat* pOut, const ml_mat* pM1, const ml_mat* pM2); ml_mat* ML_FUNC ML_MatMultiply_3DNOW(ml_mat* pOut, const ml_mat* pM1, const ml_mat* pM2); ml_mat* ML_FUNC ML_MatInverse_F(ml_mat* pOut, float* pDet, const ml_mat* pM); //ml_mat* ML_FUNC ML_MatInverse_SSE(ml_mat* pOut, float* pDet, ml_mat* pM); #ifdef __cplusplus } #endif __cplusplus #endif __ml_mat_H__<file_sep>/games/Legacy-Engine/Source/lm_sys/lm_xexp.h #ifndef __LM_XEXP_H__ #define __LM_XEXP_H__ #include "lm_sys.h" #include <pshpack1.h> typedef struct _XMESH_INDEX { lg_dword nNumVert; lg_dword v[3]; }XMESH_INDEX; #include <poppack.h> class CLMeshXExp: public CLMesh { public: lg_bool SaveAsX(char* szFilename); private: lg_bool AddMesh(void *pFileSaveRoot); }; #endif __LM_XEXP_H__<file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/ls_ogg.h /* ls_ogg.h - Header for ogg file support Copyright (c) 2006, <NAME>. */ #ifndef __LS_OGG_H__ #define __LS_OGG_H__ #include <windows.h> #include <vorbis\codec.h> #include <vorbis\vorbisfile.h> #include <lf_sys.h> #include "common.h" #ifdef __cplusplus extern "C"{ #endif /*__cplusplus*/ typedef struct _OGGFILE{ WAVEFORMATEX m_Format; L_bool m_bOpen; OggVorbis_File m_VorbisFile; vorbis_info* m_pVorbisInfo; void* m_pBufferPtr; void* m_pBuffer; L_dword m_nBufferSize; L_dword m_nNumSamples; L_bool m_bEOF; }OGGFILE, *POGGFILE; OGGFILE* Ogg_CreateFromDisk(char* szFilename); /*OGGFILE* Ogg_CreateFromData(void* lpData, L_dword dwDataSize);*/ L_bool Ogg_Delete(OGGFILE* lpWave); L_dword Ogg_Read(OGGFILE* lpWave, void* lpDest, L_dword dwSizeToRead); L_bool Ogg_Reset(OGGFILE* lpWave); WAVEFORMATEX* Ogg_GetFormat(OGGFILE* lpWave, WAVEFORMATEX* lpFormat); L_dword Ogg_GetSize(OGGFILE* lpWave); L_bool Ogg_IsEOF(OGGFILE* lpWave); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /*__LS_OGG_H__*/ <file_sep>/tools/fs_sys2/fs_sys2.h /****************************************************************************** File: fs_sys2.h Purpose: The Legacy File System. A file system for use in video games. This is the second version of this system. While the underlying code is in C++ the API is compatible with C and C++. (c) 2008 <NAME>. ******************************************************************************/ #ifndef __FS_SYS2_H__ #define __FS_SYS2_H__ /******************************** Disable some of VCs warnings *********************************/ #pragma warning(disable: 4267) #pragma warning(disable: 4996) #if defined(FS_DLL) #ifdef FS_SYS2_EXPORTS #undef FS_SYS2_EXPORTS #define FS_SYS2_EXPORTS __declspec(dllexport) #else #define FS_SYS2_EXPORTS __declspec(dllimport) #endif #else #ifdef FS_SYS2_EXPORTS #undef FS_SYS2_EXPORTS #endif #define FS_SYS2_EXPORTS #endif #ifdef __cplusplus extern "C"{ #endif __cplusplus /* File System Types */ typedef unsigned int fs_uint; typedef unsigned char fs_byte; typedef unsigned long fs_dword, fs_ulong; typedef signed long fs_long; typedef float fs_float; #if defined( __WIN32__ ) typedef __int32 fs_intptr_t; typedef unsigned __int32 fs_size_t; #elif defined( __WIN64__ ) typedef __int64 fs_intptr_t; typedef unsigned __int64 fs_size_t; #else #error Platform not set. #endif typedef char fs_char8; typedef fs_char8 *fs_str8; typedef const char *fs_cstr8; #ifdef __cplusplus typedef wchar_t fs_char16; #else !__cplusplus typedef unsigned short fs_char16; #endif __cplusplus typedef fs_char16 *fs_str16; typedef const fs_char16 *fs_cstr16; typedef struct _fs_large_integer { fs_dword dwLowPart; fs_long dwHighPart; }fs_large_integer, *fs_plarge_integer, *fs_lplarge_integer; typedef int fs_bool; #define FS_TRUE (1) #define FS_FALSE (0) #ifdef __cplusplus #define FS_NULL (0) #else __cplusplus #define FS_NULL ((void*)0) #endif __cplusplus #define FS_MAX_PATH 255 typedef fs_char8 fs_pathA[FS_MAX_PATH+1]; typedef fs_char16 fs_pathW[FS_MAX_PATH+1]; /******************************** Mouting options. ********************************/ static const fs_dword MOUNT_MOUNT_SUBDIRS = (1 << 1); static const fs_dword MOUNT_FILE_OVERWRITE = (1 << 2); static const fs_dword MOUNT_FILE_OVERWRITELPKONLY = (1 << 3); /********************************* Definitions for file access. *********************************/ typedef enum _LF_SEEK_TYPE { LF_SEEK_BEGIN =0, LF_SEEK_CURRENT=1, LF_SEEK_END =2, }LF_SEEK_TYPE; typedef enum _LF_CREATE_MODE { LF_CREATE_ALWAYS=1, LF_CREATE_NEW =2, LF_OPEN_ALWAYS =3, LF_OPEN_EXISTING=4, }LF_CREATE_MODE; /* File acces modes, more than one can be specified. */ /* Read privelages. */ static const fs_dword LF_ACCESS_READ = (1 << 2); /* Readable */ static const fs_dword LF_ACCESS_WRITE = (1 << 3); /* Writeable */ static const fs_dword LF_ACCESS_MEMORY = (1 << 4); /* Memory access (cannot use with LF_ACCESS_WRITE) */ /* Memory Functions */ typedef enum _LF_ALLOC_REASON { LF_ALLOC_REASON_SYSTEM, LF_ALLOC_REASON_FILE, LF_ALLOC_REASON_SCRATCH, } LF_ALLOC_REASON; typedef void* ( * FS_ALLOC_FUNC)(fs_size_t size, LF_ALLOC_REASON Reason, const fs_char8*const type, const fs_char8*const file, const fs_uint line); typedef void ( * FS_FREE_FUNC)(void* p, LF_ALLOC_REASON Reason); void FS_SYS2_EXPORTS FS_SetMemFuncs(FS_ALLOC_FUNC pAlloc, FS_FREE_FUNC pFree); typedef void ( * FS_ENUMERATE_FUNCA )( fs_cstr8 Filename , void* Data ); typedef void ( * FS_ENUMERATE_FUNCW )( fs_cstr16 Filename , void* Data ); void FS_SYS2_EXPORTS FS_EnumerateFilesOfTypeA( fs_cstr8 Ext , FS_ENUMERATE_FUNCA EnumerateFunc , void* Data ); void FS_SYS2_EXPORTS FS_EnumerateFilesOfTypeW( fs_cstr16 Ext , FS_ENUMERATE_FUNCW EnumerateFunc , void* Data ); /************************* Error Handling Stuff *************************/ typedef enum _FS_ERR_LEVEL { ERR_LEVEL_UNKNOWN=0, /* Messages are always printed. */ ERR_LEVEL_SUPERDETAIL=1, ERR_LEVEL_DETAIL, ERR_LEVEL_NOTICE, ERR_LEVEL_WARNING, ERR_LEVEL_ERROR, ERR_LEVEL_ALWAYS /* Message is always printed. */ }FS_ERR_LEVEL; void FS_SYS2_EXPORTS FS_SetErrLevel(FS_ERR_LEVEL nLevel); void FS_SYS2_EXPORTS FS_SetErrPrintFn(void (__cdecl*pfn)(fs_cstr16 szFormat)); typedef void (__cdecl * FS_ERR_CALLBACK)(fs_cstr16); /* File System Functions Mounting, etc. */ fs_bool FS_SYS2_EXPORTS FS_Initialize(FS_ALLOC_FUNC pAlloc, FS_FREE_FUNC pFree); fs_dword FS_SYS2_EXPORTS FS_MountBaseA(fs_cstr8 szOSPath); fs_dword FS_SYS2_EXPORTS FS_MountBaseW(fs_cstr16 szOSPath); fs_dword FS_SYS2_EXPORTS FS_MountA(fs_cstr8 szOSPath, fs_cstr8 szMountPath, fs_dword Flags); fs_dword FS_SYS2_EXPORTS FS_MountW(fs_cstr16 szOSPath, fs_cstr16 szMountPath, fs_dword Flags); fs_bool FS_SYS2_EXPORTS FS_ExistsA(fs_cstr8 szFilename); fs_bool FS_SYS2_EXPORTS FS_ExistsW(fs_cstr16 szFilename); fs_dword FS_SYS2_EXPORTS FS_MountLPKA(fs_cstr8 szMountedFile, fs_dword Flags); fs_dword FS_SYS2_EXPORTS FS_MountLPKW(fs_cstr16 szMountedFile, fs_dword Flags); fs_bool FS_SYS2_EXPORTS FS_UnMountAll(); fs_bool FS_SYS2_EXPORTS FS_Shutdown(); typedef enum _FS_PRINT_MOUNT_INFO_TYPE { PRINT_MOUNT_INFO_FULL, PRINT_MOUNT_INFO_FILENAME, } FS_PRINT_MOUNT_INFO_TYPE; void FS_SYS2_EXPORTS FS_PrintMountInfo(FS_PRINT_MOUNT_INFO_TYPE Type); /* File Access Functions Opening, Closing, Reading, Writing, etc. */ typedef void* LF_FILE3; LF_FILE3 FS_SYS2_EXPORTS LF_OpenA(fs_cstr8 szFilename, fs_dword Access, fs_dword CreateMode); LF_FILE3 FS_SYS2_EXPORTS LF_OpenW(fs_cstr16 szFilename, fs_dword Access, fs_dword CreateMode); fs_bool FS_SYS2_EXPORTS LF_Close(LF_FILE3 File); fs_dword FS_SYS2_EXPORTS LF_Read(LF_FILE3 File, void* pOutBuffer, fs_dword nSize); fs_dword FS_SYS2_EXPORTS LF_Write(LF_FILE3 File, const void* pInBuffer, fs_dword nSize); fs_dword FS_SYS2_EXPORTS LF_Tell(LF_FILE3 File); fs_dword FS_SYS2_EXPORTS LF_Seek(LF_FILE3 File, LF_SEEK_TYPE nMode, fs_long nOffset); fs_dword FS_SYS2_EXPORTS LF_GetSize(LF_FILE3 File); const void* FS_SYS2_EXPORTS LF_GetMemPointer(LF_FILE3 File); fs_bool FS_SYS2_EXPORTS LF_IsEOF(LF_FILE3 File); //Helper functions: fs_str8 FS_SYS2_EXPORTS FS_GetFileNameFromPathA(fs_str8 szFileName, fs_cstr8 szFullPath); fs_str16 FS_SYS2_EXPORTS FS_GetFileNameFromPathW(fs_str16 szFileName, fs_cstr16 szFullPath); #ifdef __cplusplus } /* extern "C" */ #endif __cplusplus #endif __FS_SYS2_H__ <file_sep>/games/Legacy-Engine/Scrapped/old/le_3dbase.h #ifndef __LE_3DBASE_H__ #define __LE_3DBASE_H__ #include "le_sys.h" #include "lm_d3d.h" //#include "li_sys.h" //#include "lt_sys.h" #include "lg_meshmgr.h" #include "lw_map.h" #define LOADMESH_BB90 0x00000001 #define LOADMESH_BB45 0x00000002 //#define PHYSICS_ENGINE CLPhysXEntity //#define PHYSICS_ENGINE CLNewtonEntity #define PHYSICS_ENGINE CLEntity class CLBase3DEntity: public PHYSICS_ENGINE { friend class CLBase3DEntity; protected: CLSkel* m_pSkel; CLMeshNode* m_pMeshNodes; lg_dword m_nMeshCount; lg_float m_fScale; public: CLBase3DEntity(); ~CLBase3DEntity(); virtual void Initialize(ML_VEC3* v3Pos); virtual void Render(); protected: void LoadMesh(lf_path szXMLScriptFile, lg_float fScale, lg_dword Flags); }; #endif __LE_3DBASE_H__<file_sep>/games/Legacy-Engine/Scrapped/old/le_sys.cpp //le_sys.cpp - The Legacy Entity class //Copyright (c) 2007 <NAME> #include "le_sys.h" #include "lg_err.h" #include "lw_sys.h" //Reusable var temp vars. ML_VEC3 CLEntity::s_v3Temp; ML_MAT CLEntity::s_matTemp; ML_MAT CLEntity::s_matTemp2; //The static pointers can be used by all //entities and need to be established before //any entities are created. CLWorldMap* CLEntity::s_pWorldMap=LG_NULL; lg_float CLEntity::s_fGrav=-20.0f; CLEntity::CLEntity(): m_fYaw(0.0f), m_fPitch(0.0f), m_fRoll(0.0f), m_fMass(1.0f), m_nFlags(0), m_fVelFwd(0.0f), m_fVelStrafe(0.0f), m_nMovementType(MOVEMENT_UNKNOWN), m_nNumRegions(0), m_bIntelligent(LG_FALSE) { m_v3Pos.x=m_v3Pos.y=m_v3Pos.z=0.0f; m_v3PhysVel.x=m_v3PhysVel.y=m_v3PhysVel.z=0.0f; m_v3PhysRot.x=m_v3PhysRot.y=m_v3PhysRot.z=0.0f; } CLEntity::~CLEntity() { } void CLEntity::InitPhys(lg_bool bIntelligent) { m_pPhysBody=CLWorld::s_LegacyPhysics.AddBody(&m_v3Pos, &m_aabbBase, m_fMass); } void CLEntity::ShutdownPhys() { } void CLEntity::ProcessFrame() { #if 1 m_pPhysBody->GetVelocity(&m_v3PhysVel); ProcessAI(); m_v3PhysVel.y+=s_fGrav*s_Timer.GetFElapsed(); //Process friction. lg_float fFriction=9.8f*m_fMass*0.02f*s_Timer.GetFElapsed(); m_v3PhysVel.x-=m_v3PhysVel.x*fFriction; m_v3PhysVel.z-=m_v3PhysVel.z*fFriction; m_pPhysBody->SetVelocity(&m_v3PhysVel); m_pPhysBody->GetPosition(&m_v3Pos); m_pPhysBody->GetAABB(&m_aabbCurrent); s_pWorldMap->CheckRegions(&m_aabbCurrent, m_nRegions, LW_MAX_O_REGIONS); m_fYaw+=m_v3PhysRot.y/50.0f; ML_MatRotationYawPitchRoll( &m_matOrient, m_fYaw, L_CHECK_FLAG(LENTITY_TRANSYAWONLY, m_nFlags)?0.0f:m_fPitch, L_CHECK_FLAG(LENTITY_TRANSYAWONLY, m_nFlags)?0.0f:m_fRoll); m_matOrient._41=m_v3Pos.x; m_matOrient._42=m_v3Pos.y; m_matOrient._43=m_v3Pos.z; m_nNumRegions=s_pWorldMap->CheckRegions(&m_aabbCurrent, m_nRegions, LW_MAX_O_REGIONS); #endif } void CLEntity::CalculateVelXZ() { //In a FPS based game movement will only be in two dimensions, except //for jumping and falling, but those velocities will be managed //by gravity and not by the object's movement. //The general calculation for velocity is x=vel*sin(yaw)+strafevel*sin(yaw+90deg (pi/2)) // z=vel*cos(yaw)+strafevel*cos(yaw+90deg (pi/2)) m_v3PhysVel.x=m_fVelFwd*ML_sinf(m_fYaw)+m_fVelStrafe*ML_sinf(m_fYaw+ML_PI*0.5f); m_v3PhysVel.z=m_fVelFwd*ML_cosf(m_fYaw)+m_fVelStrafe*ML_cosf(m_fYaw+ML_PI*0.5f); } void CLEntity::ProcessAI() { m_v3PhysVel.x=m_v3PhysVel.y=m_v3PhysVel.z=0.0f; } class CLEntity* CLEntity::GetNext() { return m_pNext; } class CLEntity* CLEntity::GetPrev() { return m_pPrev; } void CLEntity::SetNext(class CLEntity* pEnt) { m_pNext=pEnt; } void CLEntity::SetPrev(class CLEntity* pEnt) { m_pPrev=pEnt; } void CLEntity::Update() { //Update should only be called after all collisions with //the world and other entities have been adjusted for. //Add the velocity onto the current posisiton. //ML_Vec3Add(&m_v3Pos, &m_v3Pos, &m_v3Vel); //Update the current AABB (really this is only for rendering) //purposes //CalculateAABBs(CALC_AABB_CURRENTONLY); //Setup the transformation matrix with the objects rotation. ML_MatRotationYawPitchRoll( &m_matOrient, L_CHECK_FLAG(LENTITY_RENDER180, m_nFlags)?m_fYaw+ML_PI:m_fYaw, L_CHECK_FLAG(LENTITY_TRANSYAWONLY, m_nFlags)?0.0f:m_fPitch, L_CHECK_FLAG(LENTITY_TRANSYAWONLY, m_nFlags)?0.0f:m_fRoll); //Put the entities position in the transformation matrix. m_matOrient._41=m_v3Pos.x; m_matOrient._42=m_v3Pos.y; m_matOrient._43=m_v3Pos.z; } void CLEntity::Render() { } /*************************** PhysX entity controller ***************************/ CLPhysXEntity::CLPhysXEntity(): CLEntity(), m_pNxActor(LG_NULL) { } void CLPhysXEntity::InitPhys(lg_bool bIntelligent) { m_bIntelligent=bIntelligent; m_v3PhysVel.x=m_v3PhysVel.y=m_v3PhysVel.z=0.0f; m_v3PhysRot.x=m_v3PhysRot.y=m_v3PhysRot.z=0.0f; //Create the PhysX body. // Add a single-shape actor to the scene NxActorDesc actorDesc; NxBodyDesc bodyDesc; NxBoxShapeDesc boxDesc; boxDesc.dimensions.set( (m_aabbBase.v3Max.x-m_aabbBase.v3Min.x)/2.0f, (m_aabbBase.v3Max.y-m_aabbBase.v3Min.y)/2.0f, (m_aabbBase.v3Max.z-m_aabbBase.v3Min.z)/2.0f); ML_MAT matPos; ML_MatIdentity(&matPos); //ML_MatRotationZ(&matPos, 0.5f*ML_PI); matPos._41=(m_aabbBase.v3Max.x+m_aabbBase.v3Min.x)/2.0f; matPos._42=(m_aabbBase.v3Max.y+m_aabbBase.v3Min.y)/2.0f; matPos._43=0.0f;//(m_aabbBase.v3Max.z+m_aabbBase.v3Min.z)/2.0f; boxDesc.localPose.setColumnMajor44((NxF32*)&matPos); actorDesc.shapes.pushBack(&boxDesc); bodyDesc.setToDefault(); actorDesc.body = &bodyDesc; actorDesc.density = m_fMass; actorDesc.globalPose.t = NxVec3(m_v3Pos.x, m_v3Pos.y, m_v3Pos.z); m_pNxActor=s_pNxScene->createActor(actorDesc); m_v3PhysVel.x=m_v3PhysVel.y=m_v3PhysVel.z=0.0f; m_v3PhysRot.x=m_v3PhysRot.y=m_v3PhysRot.z=0.0f; } void CLPhysXEntity::ShutdownPhys() { } void CLPhysXEntity::ProcessFrame() { if(m_bIntelligent) { NxVec3 v3Vel=m_pNxActor->getLinearVelocity(); m_v3PhysVel.x=v3Vel.x; m_v3PhysVel.y=v3Vel.y; m_v3PhysVel.z=v3Vel.z; v3Vel=m_pNxActor->getAngularVelocity(); m_v3PhysRot.x=v3Vel.x; m_v3PhysRot.y=v3Vel.y; m_v3PhysRot.z=v3Vel.z; ProcessAI(); } m_pNxActor->getGlobalPose().getColumnMajor44((NxF32*)&m_matOrient); m_v3Pos.x=m_matOrient._41; m_v3Pos.y=m_matOrient._42; m_v3Pos.z=m_matOrient._43; NxVec3 force(m_v3PhysVel.x, m_v3PhysVel.y, m_v3PhysVel.z); m_pNxActor->setLinearVelocity((NxVec3)force); force.set(m_v3PhysRot.x, m_v3PhysRot.y, m_v3PhysRot.z); m_pNxActor->setAngularVelocity(force); ML_VEC3 v3={0.0f, 0.0f, 1.0f}; ML_Vec3TransformNormal(&v3, &v3, &m_matOrient); m_fYaw=v3.z>0.0f?ML_asinf(v3.x):ML_asinf(-v3.x)+ML_PI; m_pNxActor->getShapes()[0]->getWorldBounds((NxBounds3&)m_aabbCurrent); m_nNumRegions=s_pWorldMap->CheckRegions(&m_aabbCurrent, m_nRegions, LW_MAX_O_REGIONS); } /*************************** Newton Game Dynamics entity controller ***************************/ CLNewtonEntity::CLNewtonEntity(): CLEntity(), m_pNewtonBody(LG_NULL) { } void CLNewtonEntity::InitPhys(lg_bool bIntelligent) { m_bIntelligent=bIntelligent; //Create the newton body... ML_MAT matPos; ML_MatIdentity(&matPos); ML_MatRotationZ(&matPos, 0.5f*ML_PI); matPos._41=(m_aabbBase.v3Max.x+m_aabbBase.v3Min.x)/2.0f; matPos._42=(m_aabbBase.v3Max.y+m_aabbBase.v3Min.y)/2.0f; matPos._43=0.0f;//(m_aabbBase.v3Max.z+m_aabbBase.v3Min.z)/2.0f; NewtonCollision* pCollision=NewtonCreateCylinder( s_pNewtonWorld, (m_aabbBase.v3Max.x-m_aabbBase.v3Min.x)*0.5f, (m_aabbBase.v3Max.y-m_aabbBase.v3Min.y), (dFloat*)&matPos); /* NewtonCollision* pCollision=NewtonCreateBox( s_pNewtonWorld, m_aabbBase.v3Max.x-m_aabbBase.v3Min.x, m_aabbBase.v3Max.y-m_aabbBase.v3Min.y, m_aabbBase.v3Max.z-m_aabbBase.v3Min.z, (dFloat*)&matPos); */ m_pNewtonBody=NewtonCreateBody(s_pNewtonWorld, pCollision); NewtonReleaseCollision(s_pNewtonWorld, pCollision); ML_MatIdentity(&matPos); matPos._41=m_v3Pos.x; matPos._42=m_v3Pos.y; matPos._43=m_v3Pos.z; NewtonBodySetMatrix(m_pNewtonBody, (dFloat*)&matPos); ML_VEC3 v3={ m_aabbBase.v3Min.x+(m_aabbBase.v3Max.x-m_aabbBase.v3Min.x)/2.0f, m_aabbBase.v3Min.y+(m_aabbBase.v3Max.y-m_aabbBase.v3Min.y)/2.0f, m_aabbBase.v3Min.z+(m_aabbBase.v3Max.z-m_aabbBase.v3Min.z)/2.0f}; NewtonBodySetCentreOfMass(m_pNewtonBody, (dFloat*)&v3); m_v3PhysVel.x=m_v3PhysVel.y=m_v3PhysVel.z=0.0f; m_v3PhysRot.x=m_v3PhysRot.y=m_v3PhysRot.z=0.0f; NewtonBodySetMassMatrix(m_pNewtonBody, m_fMass, m_fMass, m_fMass, m_fMass); if(m_bIntelligent) { NewtonBodySetMaterialGroupID(m_pNewtonBody, MTR_CHARACTER); //NewtonBodySetMassMatrix(m_pNewtonBody, m_fMass, 1e30f, 1e30f, 1e30f); NewtonBodySetAutoFreeze(m_pNewtonBody, 0); NewtonWorldUnfreezeBody(s_pNewtonWorld, m_pNewtonBody); // add and up vector constraint to help in keeping the body upright ML_VEC3 upDirection ={0.0f, 1.0f, 0.0f}; m_pUpVec = NewtonConstraintCreateUpVector (s_pNewtonWorld, (dFloat*)&upDirection, m_pNewtonBody); } else { //NewtonBodySetMassMatrix(m_pNewtonBody, m_fMass, m_fMass, m_fMass, m_fMass); NewtonBodySetAutoFreeze(m_pNewtonBody, LG_TRUE); NewtonWorldFreezeBody(s_pNewtonWorld, m_pNewtonBody); NewtonBodySetMaterialGroupID(m_pNewtonBody, MTR_OBJECT); m_pUpVec=LG_NULL; } } void CLNewtonEntity::ShutdownPhys() { if(m_pUpVec) NewtonDestroyJoint(s_pNewtonWorld, m_pUpVec); if(m_pNewtonBody) NewtonDestroyBody(s_pNewtonWorld, m_pNewtonBody); } void CLNewtonEntity::ProcessFrame() { NewtonBodyGetVelocity(m_pNewtonBody, (dFloat*)&m_v3PhysVel); NewtonBodyGetOmega(m_pNewtonBody, (dFloat*)&m_v3PhysRot); ProcessAI(); //Apply gravity, this really only needs to be applied if //the object is a falling object (which most are), but flying //objects should not have gravity applied. if(NewtonBodyGetSleepingState(m_pNewtonBody)) m_v3PhysVel.y+=s_fGrav*s_Timer.GetFElapsed(); //NewtonWorldUnfreezeBody(s_pNewtonWorld, m_pNewtonBody); NewtonBodySetVelocity(m_pNewtonBody, (dFloat*)&m_v3PhysVel); NewtonBodySetOmega(m_pNewtonBody, (dFloat*)&m_v3PhysRot); NewtonBodyGetMatrix(m_pNewtonBody, (dFloat*)&m_matOrient); m_v3Pos.x=m_matOrient._41; m_v3Pos.y=m_matOrient._42; m_v3Pos.z=m_matOrient._43; NewtonBodyGetAABB(m_pNewtonBody, (dFloat*)&m_aabbCurrent.v3Min, (dFloat*)&m_aabbCurrent.v3Max); ML_VEC3 v3={0.0f, 0.0f, 1.0f}; ML_Vec3TransformNormal(&v3, &v3, &m_matOrient); m_fYaw=v3.z>0.0f?ML_asinf(v3.x):ML_asinf(-v3.x)+ML_PI; m_nNumRegions=s_pWorldMap->CheckRegions(&m_aabbCurrent, m_nRegions, LW_MAX_O_REGIONS); } <file_sep>/tools/PodSyncPrep/src/podsyncp/WaitWindow.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * WaitWindow.java * * Created on May 18, 2010, 1:48:56 PM */ package podsyncp; public class WaitWindow extends javax.swing.JDialog implements IProgressObject { private final SyncManager m_mgr; /** Creates new form WaitWindow */ public WaitWindow(java.awt.Frame parent, SyncManager mgr) { super(parent, true); m_mgr = mgr; initComponents(); setLocationRelativeTo(parent); ProcessFilesThread thread = new ProcessFilesThread(mgr, this); thread.start(); setVisible(true); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); m_progress = new javax.swing.JProgressBar(); setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); setModal(true); setName("Form"); // NOI18N setResizable(false); org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(podsyncp.PodSyncPApp.class).getContext().getResourceMap(WaitWindow.class); jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N jLabel1.setName("jLabel1"); // NOI18N m_progress.setName("m_progress"); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(m_progress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(m_progress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JProgressBar m_progress; // End of variables declaration//GEN-END:variables public void setProgress(int n) { if (m_progress != null) { m_progress.setValue(n); } } public void startProgress() { m_progress.setMinimum(0); m_progress.setMaximum(100); m_progress.setValue(0); } public void endProgress() { this.dispose(); } } <file_sep>/games/Explor2002/Source/ExplorED/Readme.txt WExplorED Copyright (C) 2002, <NAME> WExplorED is a win32 based application for developing maps for the Explor Engine. Notice: There are also many obsolete tools in the obsolete directory. None of which have any importance. I will not document the use of this application, because I may never work on explor again. The only way I will work on explor is if I learn Direct3D well enough to utilize it in the application, but I won't document this application anyway. This application was never really completed, it is impossible to change a property value, not that it matters because the game doesn't use property values. On an interesting note, there is not way to start a new map with this application. In fact the only way to create your own map is to either edit a file manually (impossible if you don't know the map format) or to load an existing map and modify it. The only exciting thing about this application is going through the screenshots because it shows how the application has evolved, from DOS to Windows.<file_sep>/games/Legacy-Engine/Scrapped/plugins/msLMEXP/ExportDialog.cpp // ExportDialog.cpp : implementation file // #include "stdafx.h" #include "msLMEXP.h" #include "ExportDialog.h" // CExportDialog dialog IMPLEMENT_DYNAMIC(CExportDialog, CDialog) CExportDialog::CExportDialog(CWnd* pParent /*=NULL*/) : CDialog(CExportDialog::IDD, pParent) , m_szMeshPath(_T("")) , m_szSkelPath(_T("")) , m_szMeshName(_T("")) , m_szSkelName(_T("")) , m_bMeshExport(TRUE) , m_bSkelExport(TRUE) { } CExportDialog::~CExportDialog() { } void CExportDialog::DoDataExchange(CDataExchange* pDX) { DDX_Text(pDX, IDC_MESHPATH, m_szMeshPath); DDX_Text(pDX, IDC_SKELPATH, m_szSkelPath); DDX_Text(pDX, IDC_MESHNAME, m_szMeshName); DDX_Text(pDX, IDC_SKELNAME, m_szSkelName); DDX_Check(pDX, IDC_MESHEXPORT, m_bMeshExport); DDX_Check(pDX, IDC_SKELEXPORT, m_bSkelExport); CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CExportDialog, CDialog) ON_BN_CLICKED(IDC_MESHBROWSE, &CExportDialog::OnBnClickedMeshbrowse) ON_BN_CLICKED(IDC_SKELBROWSE, &CExportDialog::OnBnClickedSkelbrowse) ON_BN_CLICKED(IDC_MESHEXPORT, &CExportDialog::OnBnClickedMeshexport) ON_BN_CLICKED(IDC_SKELEXPORT, &CExportDialog::OnBnClickedSkelexport) END_MESSAGE_MAP() // CExportDialog message handlers void CExportDialog::OnBnClickedMeshbrowse() { AFX_MANAGE_STATE(AfxGetStaticModuleState()); CFileDialog dlgFile( FALSE, _T(".lmsh"), NULL, OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT, _T("Legacy Mesh (*.lmsh)|*.lmsh|All Files (*.*)|*.*||")); if(dlgFile.DoModal()!=IDOK) return; SetDlgItemText(IDC_MESHPATH, dlgFile.GetPathName()); CLMBase::LMName szShortName; LG_GetShortNameFromPathA(szShortName, dlgFile.GetPathName()); SetDlgItemText(IDC_MESHNAME, szShortName); } void CExportDialog::OnBnClickedSkelbrowse() { AFX_MANAGE_STATE(AfxGetStaticModuleState()); CFileDialog dlgFile( FALSE, _T(".lskl"), NULL, OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT, _T("Legacy Skeleton (*.lskl)|*.lskl|All Files (*.*)|*.*||")); if(dlgFile.DoModal()!=IDOK) return; SetDlgItemText(IDC_SKELPATH, dlgFile.GetPathName()); CLMBase::LMName szShortName; LG_GetShortNameFromPathA(szShortName, dlgFile.GetPathName()); SetDlgItemText(IDC_SKELNAME, szShortName); } BOOL CExportDialog::OnInitDialog() { CDialog::OnInitDialog(); GetDlgItem(IDC_MESHEXPORT)->EnableWindow(m_bMeshExport); GetDlgItem(IDC_SKELEXPORT)->EnableWindow(m_bSkelExport); GetDlgItem(IDOK)->EnableWindow(m_bMeshExport||m_bSkelExport); GetDlgItem(IDC_VERSION)->SetWindowText(_T("version x.xx ("__DATE__" "__TIME__")")); UpdateActiveObjects(); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CExportDialog::OnBnClickedMeshexport() { UpdateActiveObjects(); } void CExportDialog::OnBnClickedSkelexport() { UpdateActiveObjects(); } void CExportDialog::UpdateActiveObjects(void) { //Update mesh export objects if(((CButton*)GetDlgItem(IDC_MESHEXPORT))->GetCheck()) { GetDlgItem(IDC_MESHNAME)->EnableWindow(TRUE); GetDlgItem(IDC_MESHBROWSE)->EnableWindow(TRUE); } else { GetDlgItem(IDC_MESHNAME)->EnableWindow(FALSE); GetDlgItem(IDC_MESHBROWSE)->EnableWindow(FALSE); } //Update skeleton export objects if(((CButton*)GetDlgItem(IDC_SKELEXPORT))->GetCheck()) { GetDlgItem(IDC_SKELNAME)->EnableWindow(TRUE); GetDlgItem(IDC_SKELBROWSE)->EnableWindow(TRUE); } else { GetDlgItem(IDC_SKELNAME)->EnableWindow(FALSE); GetDlgItem(IDC_SKELBROWSE)->EnableWindow(FALSE); } } <file_sep>/games/Legacy-Engine/Source/engine/wnd_sys/wnd_window.cpp #include "wnd_window.h" #include "lg_func.h" namespace wnd_sys{ CWindow::CWindow() : m_nFlags(0) { } CWindow::~CWindow() { } void CWindow::Create(lg_long nX, lg_long nY, lg_long nWidth, lg_long nHeight) { m_nX=nX; m_nY=nY; m_nWidth=nWidth; m_nHeight=nHeight; //m_Img.CreateFromColor(s_pDevice, m_nWidth, m_nHeight, D3DCOLOR_XRGB(LG_RandomLong(0, 100), 0, 0)); m_Img.CreateFromFile(s_pDevice, "/dbase/textures/WindowBG01.tga", NULL, m_nWidth, m_nHeight, 0); m_nFlags=WND_CREATED; } void CWindow::Destroy() { m_Img.Delete(); } void CWindow::Render() { CLImg2D::StartStopDrawing(s_pDevice, 400, 400, LG_TRUE); m_Img.Render(m_nX, m_nY); CLImg2D::StartStopDrawing(s_pDevice, 0, 0, LG_FALSE); } }//namespace wnd_sys<file_sep>/games/Legacy-Engine/Scrapped/old/lp_sys.cpp #include "lp_sys.h" CLPhysics::CLPhysics(): m_pFirstBody(LG_NULL), m_pMap(LG_NULL) { } CLPhysics::~CLPhysics() { RemoveAllBodies(); m_pMap=LG_NULL; } CLPhysBody* CLPhysics::AddBody(ML_VEC3* v3Pos, ML_AABB* aabb, lg_float fMass) { CLPhysBody* pNewBody=new CLPhysBody; if(!pNewBody) return LG_NULL; pNewBody->m_v3Pos=*v3Pos; pNewBody->m_fMass=fMass; memset(&pNewBody->m_v3PhysVel, 0, sizeof(ML_VEC3)); pNewBody->m_aabbBase=*aabb; pNewBody->CalculateAABBs(); pNewBody->m_pNext=m_pFirstBody; m_pFirstBody=pNewBody; return m_pFirstBody; } void CLPhysics::SetWorld(CLWorldMap* pMap) { m_pMap=pMap; } void CLPhysics::RemoveAllBodies() { CLPhysBody* pTemp=m_pFirstBody; while(pTemp) { CLPhysBody* pNext=pTemp->m_pNext; delete pTemp; pTemp=pNext; } m_pFirstBody=LG_NULL; } void CLPhysics::RemoveBody(CLPhysBody* pBody) { CLPhysBody* pTemp; if(m_pFirstBody==pBody) { pTemp=m_pFirstBody->m_pNext; delete m_pFirstBody; m_pFirstBody=pTemp; return; } pTemp=m_pFirstBody; while(pTemp) { if(pTemp==pBody) { pTemp=pTemp->m_pNext; delete pBody; return; } pTemp=pTemp->m_pNext; } return; } void CLPhysics::Processes(lg_dword nTimeStep) { lg_float fTime=nTimeStep/1000.0f; for(CLPhysBody* pBody=m_pFirstBody; pBody; pBody=pBody->m_pNext) { pBody->Process(fTime, m_pMap); } for(CLPhysBody* pEnt=m_pFirstBody; pEnt; pEnt=pEnt->m_pNext) { for(CLPhysBody* pEnt2=pEnt->m_pNext; pEnt2; pEnt2=pEnt2->m_pNext) { //Err_Printf("Detecting 0x%08X against 0x%08X", pEnt, pEnt2); pEnt->Collision(pEnt2, fTime); } } for(CLPhysBody* pBody=m_pFirstBody; pBody; pBody=pBody->m_pNext) { pBody->Update(); } } //////////// //Body Code //////////// ML_VEC3 CLPhysBody::s_v3WishVel; lg_dword CLPhysBody::s_nCollisionCount; lg_bool CLPhysBody::s_bWasInBlock; void CLPhysBody::Collision(CLPhysBody* pEnt, float fTime) { if(this==pEnt) return; //if(L_CHECK_FLAG(m_nFlags, LENTITY_NOENTITYCOLLIDE) || L_CHECK_FLAG(pEnt->m_nFlags, LENTITY_NOENTITYCOLLIDE)) // return; if(!ML_AABBIntersect(&m_aabbCat, &pEnt->m_aabbCat, LG_NULL)) return; //m_v3ScaleVel.x=m_v3ScaleVel.y=m_v3ScaleVel.z=0.0f; //pEnt->m_v3ScaleVel.x=pEnt->m_v3ScaleVel.y=pEnt->m_v3ScaleVel.z=0.0f; //return; ML_VEC3 v3Vel; ML_Vec3Subtract(&v3Vel, &m_v3ScaleVel, &pEnt->m_v3ScaleVel); lg_float fColTime=ML_AABBIntersectMoving( &m_aabbCurrent, &pEnt->m_aabbCurrent, &v3Vel); if(fColTime>=1e30f) return; //There was a collision, calulate the new velocities. //ML_VEC3 v3Temp; //AddExtForce(&pEnt->m_v3PhysVel);//ML_Vec3Scale(&v3Temp, &pEnt->m_v3Vel, 1.0f));//0.5f)); //pEnt->AddExtForce(&m_v3PhysVel);//ML_Vec3Scale(&v3Temp, &m_v3Vel, 1.0f));//0.5f)); #if 0 #elif 1 { ML_VEC3 v3Ref; ML_Vec3Subtract(&v3Ref, &m_v3PhysVel, &pEnt->m_v3PhysVel); lg_float fM1=(this->m_fMass-pEnt->m_fMass)/(m_fMass+pEnt->m_fMass); lg_float fM2=(this->m_fMass*2)/(this->m_fMass+pEnt->m_fMass); m_v3PhysVel.x=fM1*v3Ref.x; m_v3PhysVel.y=fM1*v3Ref.y; m_v3PhysVel.z=fM1*v3Ref.z; ML_VEC3 v3Temp; v3Temp.x=fM2*v3Ref.x; v3Temp.y=fM2*v3Ref.y; v3Temp.z=fM2*v3Ref.z; ML_Vec3Add(&m_v3PhysVel, &pEnt->m_v3PhysVel, &m_v3PhysVel); ML_Vec3Add(&pEnt->m_v3PhysVel, &pEnt->m_v3PhysVel, &v3Temp); m_v3ScaleVel.x=m_v3ScaleVel.y=m_v3ScaleVel.z=0.0f; pEnt->m_v3ScaleVel.x=pEnt->m_v3ScaleVel.y=pEnt->m_v3ScaleVel.z=0.0f; } #elif 0 if(0)//fColTime>0.2f) { ML_Vec3Scale(&m_v3Vel, &m_v3Vel, 0.8f*fColTime); ML_Vec3Scale(&pEnt->m_v3Vel, &pEnt->m_v3Vel, 0.8f*fColTime); } else { m_v3Vel.x=m_v3Vel.y=m_v3Vel.z=0.0f; pEnt->m_v3Vel.x=pEnt->m_v3Vel.y=pEnt->m_v3Vel.z=0.0f; } #elif 0 m_v3ScaleVel.x=m_v3ScaleVel.y=m_v3ScaleVel.z=0.0f; pEnt->m_v3ScaleVel.x=pEnt->m_v3ScaleVel.y=pEnt->m_v3ScaleVel.z=0.0f; #endif return; } void CLPhysBody::Update() { ML_Vec3Add(&m_v3Pos, &m_v3Pos, &m_v3ScaleVel); //Update the current AABB (really this is only for rendering) //purposes CalculateAABBs(); } void CLPhysBody::GetPosition(ML_VEC3* v3Pos) { *v3Pos=m_v3Pos; } void CLPhysBody::SetVelocity(ML_VEC3* v3Vel) { m_v3PhysVel=*v3Vel; } void CLPhysBody::GetVelocity(ML_VEC3* v3Vel) { *v3Vel=m_v3PhysVel; } void CLPhysBody::GetAABB(ML_AABB* aabb) { *aabb=m_aabbCurrent; } void CLPhysBody::Process(lg_float fTime, CLWorldMap* pMap) { ML_Vec3Scale(&m_v3ScaleVel, &m_v3PhysVel, fTime); CalculateAABBs(); if(!pMap) return; m_nNumRegions=pMap->CheckRegions(&m_aabbCat, m_nRegions, 8); WorldClip(pMap, LG_TRUE); ML_Vec3Scale(&m_v3PhysVel, &m_v3ScaleVel, 1.0f/fTime); } void CLPhysBody::WorldClip(CLWorldMap* pMap, lg_bool bSlide) { //For now this is just a test collision system. if(!pMap->m_bLoaded) return; //Start out with the proposed velocity as //the velocity determined by the AI. s_v3WishVel=m_v3ScaleVel; s_nCollisionCount=0; s_bWasInBlock=LG_FALSE; //Should really only check the regions that the entities //catenated aabb are within, this will be done in the future for(lg_dword i=0; i<m_nNumRegions; i++) { RegionClip(&pMap->m_pRegions[m_nRegions[i]], bSlide); } //If there was 1 or less collisions and //we were never in a block, then chances are //the clip worked fine. if(s_nCollisionCount<1 && !s_bWasInBlock) { m_v3ScaleVel=s_v3WishVel; return; } //If more than one collision occured we'll recheck //for any collisions... This time we won't slide //we'll just stop the movement. s_nCollisionCount=0; s_bWasInBlock=LG_FALSE; for(lg_dword i=0; i<m_nNumRegions; i++) { RegionClip(&pMap->m_pRegions[m_nRegions[i]], LG_FALSE); } //if(s_nCollisionCount) //{ // s_v3WishVel.x=s_v3WishVel.y=s_v3WishVel.z=0.0f; //} m_v3ScaleVel=s_v3WishVel; return; } void CLPhysBody::RegionClip(LW_REGION_EX* pRegion, lg_bool bSlide) { lg_dword nRes; for(lg_dword i=0; i<pRegion->nGeoBlockCount; i++) { if(!ML_AABBIntersect(&m_aabbCat, &pRegion->pGeoBlocks[i].aabbBlock, LG_NULL)) continue; nRes=BlockClip(&pRegion->pGeoBlocks[i], bSlide); if(nRes>0) { //If a collision occured we need to //recalculate the AABB for the entity... ML_Vec3Add(&m_aabbNext.v3Min, &m_aabbCurrent.v3Min, &s_v3WishVel); ML_Vec3Add(&m_aabbNext.v3Max, &m_aabbCurrent.v3Max, &s_v3WishVel); //and calculate the catenated AABB.... ML_AABBCatenate(&m_aabbCat, &m_aabbCurrent, &m_aabbNext); } } } lg_dword CLPhysBody::BlockClip(LW_GEO_BLOCK_EX* pBlock, lg_bool bSlide) { lg_bool bClipped=LG_FALSE; lg_float fTime; ML_PLANE plnIntr; lg_dword nRes=BlockCollision(pBlock, &s_v3WishVel, &fTime, &plnIntr); if(nRes==1) { if(bSlide) { #define MOVE_SCALE 0.9f ML_VEC3 v3Temp; ML_Vec3Scale(&v3Temp, &s_v3WishVel, fTime*MOVE_SCALE); ML_Vec3Subtract(&s_v3WishVel, &s_v3WishVel, &v3Temp); ClipVel(&s_v3WishVel, &s_v3WishVel, &plnIntr, 1.0001f); ML_Vec3Add(&s_v3WishVel, &s_v3WishVel, &v3Temp); } else { s_v3WishVel.x=s_v3WishVel.y=s_v3WishVel.z=0.0f; //ML_Vec3Scale(&s_v3WishVel, &s_v3WishVel, fTime*MOVE_SCALE); } s_nCollisionCount++; } else if(nRes==2) { s_nCollisionCount++; s_bWasInBlock=LG_TRUE; } return nRes; } lg_dword CLPhysBody::BlockCollision( LW_GEO_BLOCK_EX* pBlock, const ML_VEC3* pVel, lg_float* pColTime, ML_PLANE* pHitPlane, lg_bool bAABBCheck) { lg_float fColTime=1e30f; lg_dword nIntrPlane=0xFFFFFFFF; LW_GEO_BLOCK_EX* pChkBlock=pBlock; LW_GEO_BLOCK_EX blkAABB; LW_GEO_FACE plns[6]; if(bAABBCheck) { blkAABB.pFaces=plns; ML_AABBToPlanes((ML_PLANE*)blkAABB.pFaces, &pBlock->aabbBlock); blkAABB.nFaceCount=6; pChkBlock=&blkAABB; } for(lg_dword i=0; i<pChkBlock->nFaceCount; i++) { lg_float fTime; lg_dword nType; nType=ML_AABBIntersectPlaneVelType( &m_aabbCurrent, &pChkBlock->pFaces[i], pVel, &fTime); switch(nType) { case ML_INTERSECT_ONPOS: //If we made it here we weren't actually colliding. return 0; default: continue; case ML_INTERSECT_HITPOS: if(fColTime>fTime) { fColTime=fTime; nIntrPlane=i; } } } if(nIntrPlane<pChkBlock->nFaceCount) { if(pColTime) *pColTime=fColTime; if(pHitPlane) *pHitPlane=pChkBlock->pFaces[nIntrPlane]; return 1; } //If we made it here we need to check against the planes, //because we probably hit a corner. if(!bAABBCheck) return BlockCollision( pBlock, pVel, pColTime, pHitPlane, LG_TRUE); //If we made it here we we're probably already inside the block. return 2; } void CLPhysBody::ClipVel(ML_VEC3* pOut, ML_VEC3* pIn, ML_PLANE* pPlane, lg_float overbounce) { float backoff=ML_Vec3Dot(&m_v3ScaleVel, (ML_VEC3*)pPlane); #if 1 if(backoff<0.0f) { backoff*=overbounce; } else { backoff/=overbounce; } #endif float change=pPlane->a*backoff; pOut->x=pIn->x-change; change=pPlane->b*backoff; pOut->y=pIn->y-change; change=pPlane->c*backoff; pOut->z=pIn->z-change; } #if 0 OVERBOUCE 1.001f void PM_ClipVelocity( vec3_t in, vec3_t normal, vec3_t out, float overbounce ) { float backoff; float change; int i; backoff = DotProduct (in, normal); if ( backoff < 0 ) { backoff *= overbounce; } else { backoff /= overbounce; } for ( i=0 ; i<3 ; i++ ) { change = normal[i]*backoff; out[i] = in[i] - change; } } #endif void CLPhysBody::CalculateAABBs() { //Calculate the current AABB (add the position to the base AABB). ML_Vec3Add(&m_aabbCurrent.v3Min, &m_aabbBase.v3Min, &m_v3Pos); ML_Vec3Add(&m_aabbCurrent.v3Max, &m_aabbBase.v3Max, &m_v3Pos); //Calculate the potential AABB (add the velocity to the current AABB). ML_Vec3Add(&m_aabbNext.v3Min, &m_aabbCurrent.v3Min, &m_v3ScaleVel); ML_Vec3Add(&m_aabbNext.v3Max, &m_aabbCurrent.v3Max, &m_v3ScaleVel); //Calculate the concatenated AABB. ML_AABBCatenate(&m_aabbCat, &m_aabbCurrent, &m_aabbNext); } #if 0 TRACE_RESULT CLPhysBody::GroundTrace(LW_REGION_EX* pRegion, ML_PLANE* pGround) { lg_float fTrace=(m_v3PhysVel.y+s_fGrav*s_Timer.GetFElapsed())*s_Timer.GetFElapsed(); //if(fTrace>0.0f) // return LG_FALSE; ML_VEC3 v3={0.0f, fTrace, 0.0f}; ML_AABB aabb=m_aabbCurrent; if(fTrace>0.0f) aabb.v3Max.y+=fTrace; else aabb.v3Min.y+=fTrace; lg_float fTime=1e30f; ML_PLANE plnOut; lg_bool bHit=LG_FALSE; //Should only check against regions that the object is actually //in (region check is not implemented yet). for(lg_dword i=0; i<pRegion->nGeoBlockCount; i++) { if(!ML_AABBIntersect(&aabb, &pRegion->pGeoBlocks[i].aabbBlock, LG_NULL)) continue; ML_PLANE plnHit; lg_float fColTime; lg_dword nRes=BlockCollision( &pRegion->pGeoBlocks[i], &v3, &fColTime, &plnHit); if(nRes==1) { if(!bHit) { bHit=LG_TRUE; fTime=fColTime; plnOut=plnHit; } else if(fColTime<fTime) { fTime=fColTime; plnOut=plnHit; } } } if(!bHit) return TRACE_INAIR; if(pGround) *pGround=plnOut; if(fTrace>0.0f) return TRACE_HITCEILING; return TRACE_ONGROUND; } #endif <file_sep>/games/Explor2002/Source/ExplorED/Mapboard.cpp #include <stdlib.h> #include <windows.h> #include "mapboard.h" #include <stdio.h> //About ADJUSTMENT. It was necessary to add this as when compling //under microsoft the program was reading 2 bytes more for the file //header than it should have. ExplorMap::ExplorMap() { tiles=new USHORT[1]; prop=new USHORT[1]; } ExplorMap::~ExplorMap() { //MessageBox(NULL, "Destructor Called", "message", MB_OK); if(tiles){ delete []tiles; tiles=NULL; } if(prop){ delete []prop; prop=NULL; } } unsigned short ExplorMap::getNumProperty(void)const { return fileHeader.mapNumProperty; } unsigned short ExplorMap::getMapWidth(void)const { return fileHeader.mapWidth; } unsigned short ExplorMap::getMapHeight(void)const { return fileHeader.mapHeight; } unsigned short ExplorMap::tbase(int tx, int ty)const { return tx + fileHeader.mapWidth*(ty-1)-1; } USHORT ExplorMap::getTileStat(int x, int y, int propnum)const { if(x<1||x>fileHeader.mapWidth)return 0; if(y<1||y>fileHeader.mapHeight)return 0; if(propnum<1||propnum>fileHeader.mapNumProperty)return 0; return prop[fileHeader.mapWidth*fileHeader.mapHeight*(propnum-1)+tbase(x, y)]; } USHORT ExplorMap::getTileStat(int x, int y)const { if(x<1||x>fileHeader.mapWidth)return 0; if(y<1||y>fileHeader.mapHeight)return 0; return tiles[tbase(x, y)]; } int ExplorMap::boardEdit(int x, int y, unsigned int propnum, unsigned int newvalue) { if(propnum>fileHeader.mapNumProperty) return 210; prop[fileHeader.mapWidth*fileHeader.mapHeight*(propnum-1)+tbase(x, y)]=newvalue; if((prop[fileHeader.mapWidth*fileHeader.mapHeight*(propnum-1)+tbase(x, y)]<0)) prop[fileHeader.mapWidth*fileHeader.mapHeight*(propnum-1)+tbase(x, y)]=0; //reset if value is less than zero return 0; } int ExplorMap::boardEdit(int x, int y) { if(x<1||x>fileHeader.mapWidth)return 0; if(y<1||y>fileHeader.mapHeight)return 0; switch (tiles[tbase(x, y)]){ case 0: tiles[tbase(x, y)] = 10; return 10; case 10: tiles[tbase(x, y)] = 20; return 20; case 20: tiles[tbase(x, y)] = 0; return 0; default: tiles[tbase(x, y)] = 0; return 201; } } int ExplorMap::resetBoard(void) { //int i; //int j; ZeroMemory(tiles, fileHeader.mapTileDataSize); ZeroMemory(prop, fileHeader.mapTileDataSize*fileHeader.mapNumProperty); //for(i=0; i<NUMTILES; i++){ // tiles[i]=0; // for(j=0;j<fileHeader.mapNumProperty; j++) // prop[j][i]=0; //} return 0; } int ExplorMap::openMap(char openmap[_MAX_PATH]) { //Use createfile to open the map data from file HANDLE openfile; DWORD bytesread; if((openfile=CreateFile(openmap, GENERIC_READ, FILE_SHARE_READ, (LPSECURITY_ATTRIBUTES)NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, (HANDLE)NULL))==INVALID_HANDLE_VALUE)return 101; ReadFile(openfile, &fileHeader, sizeof(fileHeader), &bytesread, NULL); //Check Map statistics to make sure it is valid // if not return error code. if(!strcmp("EM", fileHeader.mapType)){ CloseHandle(openfile); return 110; } if(fileHeader.mapVersion != 3){ CloseHandle(openfile); return 115; } { if(tiles){ delete [] tiles; tiles=NULL; } tiles = new USHORT[fileHeader.mapHeight*fileHeader.mapWidth]; } ReadFile(openfile, tiles, fileHeader.mapTileDataSize, &bytesread, NULL); { if(prop){ delete [] prop; prop=NULL; } prop = new USHORT[fileHeader.mapHeight*fileHeader.mapWidth*fileHeader.mapNumProperty]; } ReadFile(openfile, prop, fileHeader.mapPropertyDataSize, &bytesread, NULL); CloseHandle(openfile); return 0; } int ExplorMap::saveMap(char openmap[_MAX_PATH]) { //Use createfile to save the tile data HANDLE savefile; DWORD byteswritten; if((savefile=CreateFile(openmap, GENERIC_WRITE, FILE_SHARE_WRITE, (LPSECURITY_ATTRIBUTES)NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, (HANDLE)NULL))==INVALID_HANDLE_VALUE)return 101; strcpy(fileHeader.mapType, "EM"); fileHeader.mapVersion=3; fileHeader.mapTileDataSize=fileHeader.mapWidth*fileHeader.mapHeight*sizeof(USHORT); fileHeader.mapPropertyDataSize=fileHeader.mapTileDataSize*fileHeader.mapNumProperty; fileHeader.mapDataSize=fileHeader.mapTileDataSize+ fileHeader.mapPropertyDataSize; fileHeader.mapFileSize=fileHeader.mapDataSize+sizeof(fileHeader); WriteFile(savefile, &fileHeader, sizeof(fileHeader), &byteswritten, NULL); WriteFile(savefile, tiles, fileHeader.mapTileDataSize, &byteswritten, NULL); WriteFile(savefile, prop, fileHeader.mapPropertyDataSize, &byteswritten, NULL); CloseHandle(savefile); return 0; }<file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/lm_sys.cpp #include <memory.h> #include <stdio.h> #include "lm_sys.h" #include "lg_err.h" extern "C" L_int Err_Printf(const char* format, ...); D3DXMATRIX* LM_EulerToMatrix(D3DXMATRIX* pOut, float* pEuler) { D3DXMATRIX MX, MY, MZ; D3DXMatrixRotationX(&MX, -pEuler[0]); D3DXMatrixRotationY(&MY, -pEuler[1]); D3DXMatrixRotationZ(&MZ, -pEuler[2]); *pOut=MX*MY*MZ; return pOut; } ////////////////////////////// /// The Legacy Mesh Class /// ////////////////////////////// CLegacyMesh::CLegacyMesh() { m_ID=0; m_nVersion=0; m_nNumVertices=0; m_nNumMeshes=0; m_nNumMaterials=0; m_pVertices=L_null; m_pVertexBoneList=L_null; m_pMeshes=L_null; m_pMaterials=L_null; m_bLoaded=L_false; } CLegacyMesh::~CLegacyMesh() { this->Unload(); } L_dword CLegacyMesh::GetNumFrames() { return m_cSkel.GetNumFrames(); } L_bool CLegacyMesh::Load(void* file, LMESH_CALLBACKS *pcb, char* szModelPath) { L_dword i=0, j=0; LMESH_CALLBACKS cb; cb.close=(int (__cdecl*)(void*))fclose; cb.read=(unsigned int (__cdecl *)(void *,unsigned int,unsigned int,void *))fread; cb.seek=(int (__cdecl *)(void *,long,int))fseek; cb.tell=(int (__cdecl *)(void *))ftell; if(!pcb) { pcb=&cb; } Unload(); //Read the header. pcb->read(&m_ID, 4, 1, file); pcb->read(&m_nVersion, 4, 1, file); pcb->read(&m_nNumVertices, 4, 1, file); pcb->read(&m_nNumMeshes, 4, 1, file); pcb->read(&m_nNumMaterials, 4, 1, file); if(m_ID!=LMESH_ID || m_nVersion!=LMESH_VERSION) { pcb->close(file); return L_false; } m_pVertices=new LMESH_VERTEX[m_nNumVertices]; m_pMeshes=new LMESH_SET[m_nNumMeshes]; m_pMaterials=new LMESH_MATERIAL[m_nNumMaterials]; m_pVertexBoneList=new L_dword[m_nNumVertices]; if(!m_pVertices || !m_pMeshes || !m_pMaterials || !m_pVertexBoneList) { L_safe_delete_array(m_pVertexBoneList); L_safe_delete_array(m_pVertices); L_safe_delete_array(m_pMeshes); L_safe_delete_array(m_pMaterials); pcb->close(file); return L_false; } //Read the vertexes. for(i=0; i<m_nNumVertices; i++) { pcb->read(&m_pVertices[i], sizeof(LMESH_VERTEX), 1, file); } //The bone list needs to be done a little differently, //the bone list needs to point to some names of joints. //So that the vertex knows whre the bone is based off of //its name, that way it can be compatible with different skeletal //animations. pcb->read(m_pVertexBoneList, sizeof(L_dword), m_nNumVertices, file); //Read the mesh information. for(i=0; i<m_nNumMeshes; i++) { pcb->read(&m_pMeshes[i], sizeof(LMESH_SET), 1, file); } //Read the material information. for(i=0; i<m_nNumMaterials; i++) { pcb->read(&m_pMaterials[i], 1, sizeof(LMESH_MATERIAL), file); //We wamt to convert the texture name to something that //the legacy engine can actuall find. Right now what we do //is get the text path, and if it is ".\" then we know that //the texture is in the same directory as the model. So we //add the model's path onto that to get what we want. char szTemp[LMESH_MAX_PATH]; L_getfilepath(szTemp, m_pMaterials[i].szTexture); if(L_strnicmp(szTemp, ".\\", 2) || L_strnicmp(szTemp, "./", 2)) { L_strncpy(szTemp, szModelPath, LMESH_MAX_PATH); L_strncat(szTemp, &m_pMaterials[i].szTexture[2], LMESH_MAX_PATH); L_strncpy(m_pMaterials[i].szTexture, szTemp, LMESH_MAX_PATH); } } //CLegacySkeleton::Load will call pcb->close(); m_cSkel.Load(file, pcb); //pcb->close(file); m_bLoaded=L_true; return L_true; } L_bool CLegacyMesh::Unload() { L_dword i=0; if(!m_bLoaded) return L_true; //Deallocate model's memory. L_safe_delete_array(this->m_pVertexBoneList); L_safe_delete_array(this->m_pMaterials); L_safe_delete_array(this->m_pMeshes); L_safe_delete_array(this->m_pVertices); //Unload the skeleton. m_cSkel.Unload(); m_ID=0; m_nVersion=0; m_nNumVertices=0; m_nNumMeshes=0; m_nNumMaterials=0; m_pVertices=L_null; m_pVertexBoneList=L_null; m_pMeshes=L_null; m_pMaterials=L_null; m_bLoaded=L_false; return L_true; } L_bool CLegacyMesh::Save(char* szFilename) { FILE* fout=L_null; fout=fopen(szFilename, "wb"); if(!fout) return L_false; //Write the file header. fwrite(&m_ID, 4, 1, fout); fwrite(&m_nVersion, 4, 1, fout); fwrite(&m_nNumVertices, 4, 1, fout); fwrite(&m_nNumMeshes, 4, 1, fout); fwrite(&m_nNumMaterials, 4, 1, fout); //Write the vertexes. L_dword i=0; for(i=0; i<m_nNumVertices; i++) { fwrite(&this->m_pVertices[i], sizeof(LMESH_VERTEX), 1, fout); } //Write the bone indexes. fwrite(this->m_pVertexBoneList, sizeof(L_dword), m_nNumVertices, fout); //Write the meses. for(i=0; i<m_nNumMeshes; i++) { fwrite(&this->m_pMeshes[i], sizeof(LMESH_SET), 1, fout); } //Write the materials. for(i=0; i<m_nNumMaterials; i++) { fwrite(&this->m_pMaterials[i], sizeof(LMESH_MATERIAL), 1, fout); } //Write the base skeleton. //Actually need to save a base skeleton with //the append option. fclose(fout); return L_true; }<file_sep>/games/Legacy-Engine/Source/engine/ld_sys.h #pragma once #include <d3d9.h> #include "ML_lib.h" void LD_DrawAABB(IDirect3DDevice9* pDevice, ML_AABB* pBox, D3DCOLOR Color); void LD_DrawVec(IDirect3DDevice9* pDevice, ML_VEC3* pOrigin, ML_VEC3* pVec); void LD_DrawTris(IDirect3DDevice9* pDevice, ml_vec3* pPoints, lg_dword nTriCount);<file_sep>/samples/D3DDemo/code/MD3Base/defines.h /* Defines.h - Definitions used for MD3 file support. */ #ifndef __DEFINES_H__ #define __DEFINES_H__ #define SAFE_FREE(p) { if(p) { free(p); (p)=NULL; } } #ifdef __cplusplus #define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } } #define SAFE_DELETE_ARRAY(p) { if(p) { delete [] (p); (p)=NULL; } } #endif /* __cplusplus */ #ifdef __cplusplus #define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } } #else /* __cplusplus */ #define SAFE_RELEASE(p) { if(p) { (p)->lpVtbl->Release((p)); (p)=NULL; } } #endif /* __cplusplus */ #endif /* __DEFINES_H__ */<file_sep>/samples/D3DDemo/code/MD3Base/MD3File.h #ifndef __MD3FILE_H__ #define __MD3FILE_H__ #include <windows.h> #ifdef __cplusplus extern "C"{ #endif /* __cplusplus */ #if (defined(WIN32) || defined(WIN64)) /* MD3 and Q3 Definitions */ #define MD3_VERSION 15 #define MD3_ID (*(DWORD*)"IDP3") #define MAX_QPATH 64 #define MD3_MAX_FRAMES 1024 #define MD3_MAX_SHADERS 256 #define MD3_MAX_SURFACES 32 #define MD3_MAX_TAGS 16 #define MD3_MAX_TRIANGLES 8192 #define MD3_MAX_VERTS 4096 #define MD3_XYZ_SCALE (1.0f/64.0f) /* MD3 File Header */ typedef struct tagMD3HEADER{ DWORD dwID; /* *(DWORD*)"IDP3" */ LONG lVersion; /* MD3_VERSION */ char szFileName[MAX_QPATH]; /* Filename for PK3 usage */ LONG lFlags; /* Unused, ??? */ LONG lNumFrames; /* Number of frame objects */ LONG lNumTags; /* Number of tag objects */ LONG lNumMeshes; /* Number of meshes, not greater than MD3_MAX_SURFACES */ LONG lNumSkins; /* Number of skin objects, unused?*/ LONG lFrameOffset; /* File position where frame objects begin */ LONG lTagOffset; /* File position where tag objects start */ LONG lMeshOffset; /* File position where mesh objects start */ LONG lFileSize; /* File position where relative data ends */ }MD3HEADER, *LPMD3HEADER; /* MD3 Vector */ typedef struct tagMD3VECTOR{ FLOAT x; FLOAT y; FLOAT z; }MD3VECTOR, *LPMD3VECTOR; /* MD3 Frame */ typedef struct tagMD3FRAME{ MD3VECTOR vMin; /* First corner of bounding box */ MD3VECTOR vMax; /* Second corner of bounding box */ MD3VECTOR vOrigin; /* local origin, usually (0, 0, 0) */ FLOAT fRadius; /* Radius of bounding sphere */ char szName[16]; /* Name of frame ASCII character sting NULL-terminated */ }MD3FRAME, *LPMD3FRAME; /* MD3 Tag */ typedef struct tagMD3TAG{ char szName[MAX_QPATH]; /* Name of tag object stirng, NULL-TERMINATED */ MD3VECTOR vPosition; /* Coordinates of tag objects relative to frame origin. */ MD3VECTOR vAxis[3]; /* Orientation of tag object. */ }MD3TAG, *LPMD3TAG; /* MD3 Mesh Header */ typedef struct tagMD3MESHHEADER{ DWORD dwID; /* *(WORD*)"IDP3" */ char szMeshName[MAX_QPATH]; /* Name of mesh object. */ LONG lFlags; /* Flags, unused? */ LONG lNumFrames; /* Number of animation frames should match with MD3HEADER */ LONG lNumShaders; /* Number of shader objects, Textures. */ LONG lNumVertices; /* Number of vertices in object */ LONG lNumTriangles; /* Number of traingles defined in this mesh */ LONG lTriangleOffset; /* Relative offset from mesh start where triangle list begins */ LONG lShaderOffset; /* Offset from start of mesh where shader data begins */ LONG lTexCoordOffset; /* offset from begining of mesh where texture coordinates begin */ LONG lVertexOffset; /* offset form begining of mesh wehre vertext objecs starts */ LONG lMeshDataSize; /* offet from begining of mesh where mesh ends */ }MD3MESHHEADER, *LPMD3MESHHEADER; /* MD3 Shader */ typedef struct tagMD3SHADER{ char szShaderName[MAX_QPATH]; /* Name of shader NULL-terminated */ LONG lShaderNum; /* Shade index number */ }MD3SHADER, *LPMD3SHADER; /* MD3 Triangle */ typedef struct tagMD3TRIANGLE{ LONG nIndexes[3]; /* References to vertex objects used to described a triangle in mesh */ }MD3TRIANGLE, *LPMD3TRIANGLE; /* MD3 Texture Coordinates */ typedef struct tagMD3TEXCOORDS{ FLOAT tu; FLOAT tv; }MD3TEXCOORDS, *LPMD3TEXCOORDS; /* MD3 Vertex */ typedef struct tagMD3VERTEX{ SHORT x; /* x-coordinate */ SHORT y; /* y-coordinate */ SHORT z; /* z-coordinate */ SHORT nNormal; /* Encoded normal vector */ }MD3VERTEX, *LPMD3VERTEX; /* MD3 Mesh (dynamic size) */ typedef struct tagMD3MESH{ MD3MESHHEADER md3MeshHeader; /* The Mesh Header */ MD3SHADER * md3Shader; /* Shader list */ MD3TRIANGLE * md3Triangle; /* Triangle list */ MD3TEXCOORDS * md3TexCoords; /* Texture coordinate list */ MD3VERTEX * md3Vertex; /* Vertex list */ }MD3MESH, *LPMD3MESH; /* MD3MESH2 is fixed in size. */ typedef struct tagMD3MESH2{ MD3MESHHEADER md3MeshHeader; MD3SHADER md3Shader[MD3_MAX_SHADERS]; MD3TRIANGLE md3Triangle[MD3_MAX_TRIANGLES]; MD3TEXCOORDS md3TexCoords[MD3_MAX_VERTS]; MD3VERTEX md3Vertex[MD3_MAX_VERTS]; }MD3MESH2, *LPMD3MESH2; /* MD3 File (dynamic size) */ typedef struct tagMD3FILE{ MD3HEADER md3Header; /* File Header */ MD3FRAME * md3Frame; /* List of md3 frames */ MD3TAG * md3Tag; /* List of md3 tag data */ MD3MESH * md3Mesh; /* List of md3 meshes */ }MD3FILE, *LPMD3FILE; /* MD3FILE2 is a fixed size structure for md3's. */ typedef struct tagMD3FILE2{ MD3HEADER md3Header; MD3FRAME md3Frame[MD3_MAX_FRAMES]; MD3TAG md3Tag[MD3_MAX_TAGS]; MD3MESH md3Mesh[MD3_MAX_SURFACES]; }MD3FILE2, *LPMD3FILE2; /* MD3 File reader functions for Windows */ /* ReadMD3File and ReadMD3Mesh are more advanced than simple file reading. DeleteMD3File and DeleteMD3Mesh must be used if ReadMD3File or ReadMD3Mesh successfuly return. All other functions are used to correctly read the described data. */ /* Read and Create an MD3 File in the MD3FILE structure. */ BOOL ReadMD3File( HANDLE hFile, LPVOID lpBuffer, LPDWORD lpNumBytesRead, LPOVERLAPPED lpOverlapped); /* Delete an MD3FILE that has been created. */ BOOL DeleteMD3File( LPVOID lpFile); /* Read and Create an MD3 Mesh (AKA MD3 Surface) in the MD3MESH structure. */ BOOL ReadMD3Mesh( HANDLE hFile, LPVOID lpBuffer, LPDWORD lpNumBytesRead, LPOVERLAPPED lpOverlapped); /* Delete an MD3MESH that has been created. */ BOOL DeleteMD3Mesh( LPVOID lpMesh); /* Finds the offset in the file in which the MD3 file begins. */ LONG FindMD3Header( HANDLE hFile, LPOVERLAPPED lpOverlapped); /* Read data from a file into MD3FRAME structure. */ BOOL ReadMD3Frame( HANDLE hFile, LPVOID lpBuffer, LPDWORD lpNumBytesRead, LPOVERLAPPED lpOverlapped); /* Read data from a file into MD3HEADER structure. */ BOOL ReadMD3Header( HANDLE hFile, LPVOID lpBuffer, LPDWORD lpNumBytesRead, LPOVERLAPPED lpOverlapped); /* Read data from a file into MD3MESHHEADER structure. */ BOOL ReadMD3MeshHeader( HANDLE hFile, LPVOID lpBuffer, LPDWORD lpNumBytesRead, LPOVERLAPPED lpOverlapped); /* Read data from a file into MD3SHADER structure. */ BOOL ReadMD3Shader( HANDLE hFile, LPVOID lpBuffer, LPDWORD lpNumBytesRead, LPOVERLAPPED lpOverlapped); /* Read data from a file into MD3TAG structure. */ BOOL ReadMD3Tag( HANDLE hFile, LPVOID lpBuffer, LPDWORD lpNumBytesRead, LPOVERLAPPED lpOverlapped); /* Read data from a file into MD3TEXCOORD structure. */ BOOL ReadMD3TexCoords( HANDLE hFile, LPVOID lpBuffer, LPDWORD lpNumBytesRead, LPOVERLAPPED lpOverlapped); /* Read data from a file into MD3TRIANGLE structure. */ BOOL ReadMD3Triangle( HANDLE hFile, LPVOID lpBuffer, LPDWORD lpNumBytesRead, LPOVERLAPPED lpOverlapped); /* Read data from a file into MD3VECTOR structure. */ BOOL ReadMD3Vector( HANDLE hFile, LPVOID lpBuffer, LPDWORD lpNumBytesRead, LPOVERLAPPED lpOverlapped); /* Read data from a file into MD3VERTEX structure. */ BOOL ReadMD3Vertex( HANDLE hFile, LPVOID lpBuffer, LPDWORD lpNumBytesRead, LPOVERLAPPED lpOverlapped); #endif /* (defined(WIN32) || defined(WIN64)) */ /* Generic MD3 Functions. */ /* Dumps copy of MD3 data to a file. */ #define MD3DUMP_BONEFRAME 0x00000001l #define MD3DUMP_TAG 0x00000002l #define MD3DUMP_MESH 0x00000004l #define MD3DUMP_MESHSHADER 0x00000008l #define MD3DUMP_MESHTRI 0x00000010l #define MD3DUMP_MESHTEXCOORD 0x00000020l #define MD3DUMP_MESHVERTEX 0x00000040l #define MD3DUMP_ALL 0xFFFFFFFFl BOOL DumpMD3DebugData(LPVOID fout, LPMD3FILE lpFile, DWORD dwDumpFlags); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __MD3FILE_H__ */<file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/console/lconsole/lc_defs.c /* ldefs.c - code for definitions for the console. */ #include <stdio.h> #include <malloc.h> #include <common.h> #include "lc_private.h" unsigned long g_nDefRefs=0; HLDEFS Defs_CreateDefs() { LDefs* newdef=NULL; newdef=malloc(sizeof(LDefs)); if(newdef==NULL) return NULL; newdef->list=NULL; return newdef; } int Defs_DeleteDefs(HLDEFS hDefs) { LDefs* lpDefs=(LDefs*)hDefs; LDef* def=NULL; LDef* nextdef=NULL; if(!lpDefs) return 0; def=lpDefs->list; while(def) { nextdef=def->next; L_safe_free(def->name); L_safe_free(def); g_nDefRefs--; def=nextdef; } Debug_printf("Number of definitions left: %i\n", g_nDefRefs); L_safe_free(lpDefs); hDefs=NULL; return 1; } int Defs_Add(HLDEFS* hDefs, char* szDef, float fValue) { LDefs* lpDefs=(LDefs*)hDefs; LDef* newdef=NULL; int bCheck=0; if(lpDefs==NULL) return 0; /* First check to see if the definition already exists. If it does the function fails.*/ Defs_Get(hDefs, szDef, &bCheck); if(bCheck) { //return Defs_ReDef(hDefs, szDef, fValue); return 0; } /* Now we need to check if the name is valid. We don't want the first letter to be a number, and we don't want selected characters in our def.*/ if(!L_CheckValueName(szDef, NULL, NULL)) return 0; /* Allocate memory for the new def. */ newdef=malloc(sizeof(LDef)); if(!newdef) return 0; newdef->name=malloc(L_strlen(szDef)+1); if(!newdef->name) { free(newdef); return 0; } L_strncpy(newdef->name, szDef, L_strlen(szDef)+1); newdef->value=fValue; newdef->next=lpDefs->list; lpDefs->list=newdef; g_nDefRefs++; return 1; } int Defs_ReDef(HLDEFS hDef, char* szName, float fNewValue) { LDefs* lpDefs=(LDefs*)hDef; LDef* def=NULL; if(!lpDefs) return 0; for(def=lpDefs->list; def; def=def->next) { if(L_strnicmp(szName, def->name, L_strlen(szName))) { def->value=fNewValue; return 1; } } return 0; } float Defs_Get(HLDEFS hDef, char* szName, int* bGotDef) { LDefs* lpDefs=(LDefs*)hDef; LDef* def=NULL; unsigned long nLen=0, nLen2=0;; if(bGotDef) *bGotDef=0; if(!lpDefs) return 0.0f; nLen=L_strlen(szName); for(def=lpDefs->list; def; def=def->next) { if(L_strnicmp(szName, def->name, 0)) { if(bGotDef) *bGotDef=1; return def->value; } } return 0.0f; } /* LDef* Defs_GetFirst(HLDEFS hDef) { LDefs *lpDefs=(LDefs*)hDef; if(!lpDefs) return L_null; else return lpDefs->list; } */ <file_sep>/games/Legacy-Engine/Source/engine/lw_skybox.h #ifndef __LV_SKYBOX_H__ #define __LV_SKYBOX_H__ #include "lm_mesh_lg.h" #include "lf_sys2.h" #include "lm_skin.h" //The skybox is simply a Legacy Mesh that gets rendered as if it //were over the head of the camera. Note that the CLCamera::RenderForSkybox() //method should be called before rendering the skybox. The static method //of SetSkyboxRenderMode should also be called before rendering. class CLSkybox3 { private: CLMeshLG* m_pSkyMesh; CLSkin m_Skin; public: CLSkybox3(); ~CLSkybox3(); void Load(lg_path szMeshFile, lg_path szSkinFile); void Unload(); void Render(); }; #endif __LV_SKYBOX_H__<file_sep>/games/Legacy-Engine/Scrapped/plugins/msLMEXP/ExportDialog.h #pragma once // CExportDialog dialog class CExportDialog : public CDialog { DECLARE_DYNAMIC(CExportDialog) public: CExportDialog(CWnd* pParent = NULL); // standard constructor virtual ~CExportDialog(); // Dialog Data enum { IDD = IDD_SAVEASDLG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support DECLARE_MESSAGE_MAP() public: afx_msg void OnBnClickedMeshbrowse(); public: afx_msg void OnBnClickedSkelbrowse(); public: CString m_szMeshPath; public: CString m_szSkelPath; public: CString m_szMeshName; public: CString m_szSkelName; public: virtual BOOL OnInitDialog(); public: BOOL m_bMeshExport; public: BOOL m_bSkelExport; public: afx_msg void OnBnClickedMeshexport(); public: afx_msg void OnBnClickedSkelexport(); void UpdateActiveObjects(void); }; <file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/lg_err.h #ifndef __L_ERROR_H__ #define __L_ERROR_H__ #include "lc_sys.h" #include "common.h" #ifdef __cplusplus extern "C"{ #endif __cplusplus #define MAX_ERR_MSG_LEN (1024) void Err_InitReporting(HLCONSOLE hConsole); L_int Err_Printf(const char* format, ...); L_int Err_PrintDX(const char* function, L_result result); void Err_ErrBox(const char* format, ...); void Err_PrintMatrix(void* pM); L_int Err_PrintVersion(); #ifdef __cplusplus } #endif __cplusplus #endif /*__L_ERROR_H__*/<file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/ls_wav.h /* ls_wav.h - Header for WAVE file reading. Copyright (c) 2006, <NAME> */ #ifndef __LS_WAV_H__ #define __LS_WAV_H__ #include <windows.h> #include "common.h" #ifdef __cplusplus extern "C"{ #endif /*__cplusplus*/ typedef struct _WAVEFILE{ WAVEFORMATEX m_Format; HMMIO m_hmmio; MMCKINFO m_ck; MMCKINFO m_ckRiff; L_dword m_dwSize; L_dword m_ReadPos; L_bool m_bEOF; L_bool m_bLoaded; }WAVEFILE, *PWAVEFILE; WAVEFILE* Wav_CreateFromDisk(char* szFilename); /*WAVEFILE* Wav_CreateFromData(void* lpData, L_dword dwDataSize);*/ L_bool Wav_Delete(WAVEFILE* lpWave); L_dword Wav_Read(WAVEFILE* lpWave, void* lpDest, L_dword dwSizeToRead); L_bool Wav_Reset(WAVEFILE* lpWave); WAVEFORMATEX* Wav_GetFormat(WAVEFILE* lpWave, WAVEFORMATEX* lpFormat); L_dword Wav_GetSize(WAVEFILE* lpWave); L_bool Wav_IsEOF(WAVEFILE* lpWave); LRESULT CALLBACK LS_MMIOProc( LPSTR lpmmioinfo, UINT uMsg, LPARAM lParam1, LPARAM lParam2); #ifdef __cplusplus } #endif /*__cplusplus*/ #endif /* __LS_WAV_H__ */<file_sep>/Misc/Music/Readme.txt Music converted to Qbasic by B.M. Software This folder includes: Canon.bas - The source code for canon Canon.exe - The executable for Canon Raiders.bas - The source code for raiders Raiders.exe - The executeable for raiders Readme.txt - This file Note: It's just two music files: Canon in D Major - <NAME> Indianna Jones Theme - <NAME> Canon sounds really bad. The Indianna Jones Theme sounds pretty good.<file_sep>/tools/ListingGen/GameLister/GameLister.h #ifndef __GAMELISTER_H__ #define __GAMELISTER_H__ #include "Lister.h" class CGameLister; CLister * ObtainLister(); class CGameLister: public CLister { private: char * m_szItemName; char * m_szItemType; char * m_szItemDesc1; char * m_szItemDesc2; char * m_szItemCondition; char * m_szOS; char * m_szCPU; char * m_szRAM; char * m_szCD; char * m_szHDD; char * m_szVideo; char * m_szSound; char * m_szInput; char * m_szOther; char * m_szRecommended; char * m_szShippingCost; char * m_szShippingInfo; char * m_szPaymentOptions; char * m_szShippingTerms; char * m_szFeedbackTerms; char * m_szWarrantyTerms; public: CGameLister() { m_szItemName=NULL; m_szItemType=NULL; m_szItemDesc1=NULL; m_szItemDesc2=NULL; m_szItemCondition=NULL; m_szOS=NULL; m_szCPU=NULL; m_szRAM=NULL; m_szCD=NULL; m_szHDD=NULL; m_szVideo=NULL; m_szSound=NULL; m_szInput=NULL; m_szOther=NULL; m_szRecommended=NULL; m_szShippingCost=NULL; m_szShippingInfo=NULL; m_szPaymentOptions=NULL; m_szShippingTerms=NULL; m_szFeedbackTerms=NULL; m_szWarrantyTerms=NULL; } virtual ~CGameLister() { SAFE_DELETE_ARRAY(m_szItemName); SAFE_DELETE_ARRAY(m_szItemType); SAFE_DELETE_ARRAY(m_szItemDesc1); SAFE_DELETE_ARRAY(m_szItemDesc2); SAFE_DELETE_ARRAY(m_szItemCondition); SAFE_DELETE_ARRAY(m_szOS); SAFE_DELETE_ARRAY(m_szCPU); SAFE_DELETE_ARRAY(m_szRAM); SAFE_DELETE_ARRAY(m_szCD); SAFE_DELETE_ARRAY(m_szHDD); SAFE_DELETE_ARRAY(m_szVideo); SAFE_DELETE_ARRAY(m_szSound); SAFE_DELETE_ARRAY(m_szInput); SAFE_DELETE_ARRAY(m_szOther); SAFE_DELETE_ARRAY(m_szRecommended); SAFE_DELETE_ARRAY(m_szShippingCost); SAFE_DELETE_ARRAY(m_szShippingInfo); SAFE_DELETE_ARRAY(m_szPaymentOptions); SAFE_DELETE_ARRAY(m_szShippingTerms); SAFE_DELETE_ARRAY(m_szFeedbackTerms); SAFE_DELETE_ARRAY(m_szWarrantyTerms); } virtual BOOL CreateListing(char szFilename[MAX_PATH]); virtual BOOL RunDialog(HWND hwndParent); virtual BOOL SaveListing(char szFilename[MAX_PATH]); virtual BOOL LoadListing(char szFilename[MAX_PATH]); BOOL SetItemName(LPSTR szItemName, LPSTR szItemType); BOOL SetItemDesc(LPSTR szItemDesc1, LPSTR szItemDesc2); BOOL SetItemCondition(LPSTR szItemCondition); BOOL SetSystemRequirements( LPSTR szOS, LPSTR szCPU, LPSTR szRAM, LPSTR szCD, LPSTR szHDD, LPSTR szVideo, LPSTR szSound, LPSTR szInput, LPSTR szOther, LPSTR szRecommended); BOOL SetShippingInfo(LPSTR szShippingCost, LPSTR szShippingInfo); BOOL SetPaymentOptions(LPSTR szPaymentOptions); BOOL SetShippingTerms(LPSTR szShippingTerms); BOOL SetFeedbackTerms(LPSTR szFeedbackTerms); BOOL SetWarrantyTerms(LPSTR szWarrantyTerms); //Friend Functions. friend BOOL CALLBACK TitleDesc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); friend BOOL CALLBACK SysRequire(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); friend BOOL CALLBACK ShipPay(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); friend BOOL CALLBACK Terms(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); }; #endif //__GAMELISTER_H__<file_sep>/games/Legacy-Engine/Source/engine/ls_sndfile.cpp #include "ls_sndfile.h" #include "ls_ogg.h" #include "ls_wav.h" #include "lg_err.h" CLSndFile::CLSndFile(): //m_CB(LG_NULL), m_pSnd(LG_NULL), m_nChannels(0), m_nBitsPerSample(0), m_nSamplesPerSecond(0), m_nDataSize(0), m_bOpen(LG_FALSE) { } CLSndFile::~CLSndFile() { Close(); } lg_bool CLSndFile::Open(lg_str szFilename) { Close(); SetupCallbacks(szFilename); m_pSnd=m_CB.Snd_CreateFromDisk(szFilename); if(!m_pSnd) { Err_Printf("Sound File Open ERROR: Could not load not create \"%s\"", szFilename); return LG_FALSE; } WAVEFORMATEX* pFormat=m_CB.Snd_GetFormat(m_pSnd, LG_NULL); m_nChannels=pFormat->nChannels; m_nBitsPerSample=pFormat->wBitsPerSample; m_nSamplesPerSecond=pFormat->nSamplesPerSec; m_nDataSize=m_CB.Snd_GetSize(m_pSnd); m_bOpen=LG_TRUE; return LG_TRUE; } void CLSndFile::Close() { if(!m_bOpen) return; m_CB.Snd_Delete(m_pSnd); m_pSnd=LG_NULL; m_nChannels=0; m_nBitsPerSample=0; m_nSamplesPerSecond=0; m_nDataSize=0; m_bOpen=LG_FALSE; return; } lg_dword CLSndFile::Read(lg_void* pBuffer, lg_dword nSize) { if(!m_bOpen) return 0; return m_CB.Snd_Read(m_pSnd, pBuffer, nSize); } lg_dword CLSndFile::GetNumChannels() { return m_nChannels; } lg_dword CLSndFile::GetDataSize() { return m_nDataSize; } lg_dword CLSndFile::GetBitsPerSample() { return m_nBitsPerSample; } lg_dword CLSndFile::GetSamplesPerSecond() { return m_nSamplesPerSecond; } lg_bool CLSndFile::IsEOF() { if(!m_bOpen) return LG_TRUE; return m_CB.Snd_IsEOF(m_pSnd); } lg_bool CLSndFile::Reset() { if(!m_bOpen) return LG_FALSE; return m_CB.Snd_Reset(m_pSnd); } void CLSndFile::SetupCallbacks(lg_str szFilename) { lg_str szExt=szFilename; for(lg_dword i=strlen(szFilename); i>0; i--) { if(szFilename[i]=='.') { szExt=&szFilename[i+1]; break; } } if(stricmp(szExt, "ogg")==0) { m_CB.Snd_CreateFromDisk=Ogg_CreateFromDisk; m_CB.Snd_Delete=Ogg_Delete; m_CB.Snd_GetFormat=Ogg_GetFormat; m_CB.Snd_GetSize=Ogg_GetSize; m_CB.Snd_IsEOF=Ogg_IsEOF; m_CB.Snd_Read=Ogg_Read; m_CB.Snd_Reset=Ogg_Reset; } else { m_CB.Snd_CreateFromDisk=Wav_CreateFromDisk; m_CB.Snd_Delete=Wav_Delete; m_CB.Snd_GetFormat=Wav_GetFormat; m_CB.Snd_GetSize=Wav_GetSize; m_CB.Snd_IsEOF=Wav_IsEOF; m_CB.Snd_Read=Wav_Read; m_CB.Snd_Reset=Wav_Reset; } } <file_sep>/games/Legacy-Engine/Scrapped/plugins/msLMEXP/resource.h //{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by msLMEXP.rc // #define IDD_SAVEASDLG 1000 #define IDC_MESHPATH 1000 #define IDC_SKELPATH 1001 #define IDC_MESHBROWSE 1002 #define IDC_SKELBROWSE 1003 #define IDC_MESHNAME 1004 #define IDC_SKELNAME 1005 #define IDC_MESHEXPORT 1006 #define IDC_CHECK2 1007 #define IDC_SKELEXPORT 1007 #define IDC_VERSION 1008 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 1001 #define _APS_NEXT_COMMAND_VALUE 32771 #define _APS_NEXT_CONTROL_VALUE 1009 #define _APS_NEXT_SYMED_VALUE 1000 #endif #endif <file_sep>/tools/ListingGen/README.md ListingGen ========== Software written to create some nice HTML for ebay listings. No longer useful except for an example of how to use DLLs for plugins in a Windows applicaiton.<file_sep>/games/Sometimes-Y/SometimesY/WndGameView.h #pragma once // CWndGameView class CWndGameView : public CWnd { DECLARE_DYNAMIC(CWndGameView) public: CWndGameView(CSYGame* pGame); virtual ~CWndGameView(); protected: DECLARE_MESSAGE_MAP() public: afx_msg void OnPaint(); private: CFont m_Font; CSYGame* m_pGame; CMenu m_mnuInsert; CPoint m_pntLastBlock; public: afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnRButtonDown(UINT nFlags, CPoint point); protected: virtual BOOL OnCommand(WPARAM wParam, LPARAM lParam); }; <file_sep>/tools/img_lib/README.md img_lib ======= Texture Viewer 3 with img_lib, this was originally on Sourceforge, but Github seems to be the place to be now. Previous versions including the COM version are still on Sourceforge. ================================================================================ TexView3 with img_lib (C) 2007-2012 <NAME> Open Source ================================================================================ Building -------- Because the TexView3 executable uses MFC you will need a Professional version of Visual Studio (MFC is not included with Visual Studio Express Editions). Also, the game uses the environment variable BEEMOUT to determine where the build output is set, so this should be set (go to advanced system settings ->environment variables). Something to the effect of set BEEMOUT=D:\TexView3Out The Release build will copy the executable back to the dist directory. Notes ----- img_lib is almost ANSI C, except I know I'm explicitely declaring functions as __cdecl which may be MS specific. TexView3 is MFC and will required a pro edition of Visual Studio to build (not the express version).<file_sep>/games/Legacy-Engine/Source/lf_sys2/lf_fs2.h #ifndef __LF_FS2_H__ #define __LF_FS2_H__ #include "lf_sys2.h" #include "lf_file.h" #include "lf_list_stack.h" class LF_SYS2_EXPORTS CLFileSystem { private: //Data containing information about a mounted file: struct MOUNT_FILE{ lf_pathW szMountFileW; lf_pathW szOSFileW; lf_dword Flags; lf_dword nSize; lf_dword nCmpSize; lf_dword nOffset; static const lf_dword MOUNT_FILE_ARCHIVED=0x00000001; //This file is archived. static const lf_dword MOUNT_FILE_READONLY=0x00000002; //The file is read only. static const lf_dword MOUNT_FILE_ZLIBCMP=0x00000004; //The file is compressed with zlib compression. static const lf_dword MOUNT_FILE_DIRECTORY=0x00000008; //The mount file is a directory. static const lf_dword MOUNT_FILE_EMPTY=0x00000010; //This partition table entry is empty and can be mounted over. }; //The partition table is used to store all the mounted file information. //It stores an array of MOUNT_FILEs in a hash table and uses hash values //to lookup information. class LF_SYS2_EXPORTS CPartitionTable { private: struct MOUNT_FILE_EX: public MOUNT_FILE, CLfListStack::LSItem{ lf_dword nHashValue; MOUNT_FILE_EX* pNext; }; MOUNT_FILE_EX** m_pHashList; const lf_dword m_nMaxFiles; MOUNT_FILE_EX* m_pMasterList; CLfListStack m_UnusedFiles; public: CPartitionTable(lf_dword nMaxFiles); ~CPartitionTable(); void Clear(); //The MountFile function mounts the specified MOUNT_FILE data. //The only flag that is meaningful here is MOUNT_FILE_OVERWRITE //and MOUNT_FILE_OVERWRITELPKONLY. //which, when specified, will cause a duplicate mount file to //overwrite a previous mount file. If not specifed the duplicate //will not be overwritten. The LPK only will only overwrite a file //if the previous file is archived. If the file is a disk file it //will not be overwritten. This is useful so that new lpk files //will take priority over old ones, but disk files still have //the highest priority. lf_bool MountFile(MOUNT_FILE* pFile, lf_dword Flags); const CLFileSystem::MOUNT_FILE* FindFile(lf_cwstr szFile); void PrintMountInfo(); static void PrintFileInfo(MOUNT_FILE_EX* pFile); private: static lf_dword GetHashValue1024(lf_cwstr szString); static lf_dword GetHashValue1024_Short(lf_cwstr szString); }; private: const lf_dword m_nMaxFiles; CPartitionTable m_PrtTable; lf_bool m_bBaseMounted; lf_pathW m_szBasePath; lf_dword MountDirW(lf_cwstr szOSPath, lf_cwstr szMountPath, lf_dword Flags); lf_dword MountDirA(lf_cstr szOSPath, lf_cstr szMountPath, lf_dword Flags); lf_bool MountFile(MOUNT_FILE* pFile, lf_dword Flags); const MOUNT_FILE* GetFileInfoW(lf_cwstr szMountPath); const MOUNT_FILE* GetFileInfoA(lf_cstr szMountPath); CLFile* OpenExistingFile(const MOUNT_FILE* pMountInfo, BDIO_FILE File, lf_dword Access, lf_bool bNew); public: CLFileSystem(lf_dword nMaxFiles); ~CLFileSystem(); lf_dword MountBaseA(lf_cstr szOSPath); lf_dword MountBaseW(lf_cwstr szOSPath); lf_dword MountA(lf_cstr szOSPath, lf_cstr szMountPath, lf_dword Flags); lf_dword MountW(lf_cwstr szOSPath, lf_cwstr szMountPath, lf_dword Flags); lf_dword MountLPKA(lf_cstr szMountedFile, lf_dword Flags); lf_dword MountLPKW(lf_cwstr szMountedFile, lf_dword Flags); lf_bool UnMountAll(); CLFile* OpenFileA(lf_cstr szFilename, lf_dword Access, lf_dword CreateMode); CLFile* OpenFileW(lf_cwstr szFilename, lf_dword Access, lf_dword CreateMode); lf_bool CloseFile(CLFile* pFile); #ifdef UNICODE #define MountBase MountBaseW #define Mount MountW #define MountLPK MountLPKW #define OpenFile OpenFileW #else !UNICODE #define MountBase MountBaseA #define Mount MountA #define MountLPK MountLPKA #define OpenFile OpenFileA #endif UNICODE void PrintMountInfo(); }; #endif __LF_FS2_H__<file_sep>/games/Explor2002/Source_Old/ExplorED DOS/borland/Mapboard.h #define NUMTILES 225 #define MAXPROPNUM 10 #define FNAMELEN 256 #define TBASE tbase(x, y) typedef unsigned short BIT; typedef struct eMapHeader { char mapType[2]; unsigned short mapVersion; unsigned long mapFileSize; unsigned short mapReserved1; unsigned short mapReserved2; unsigned short mapWidth; unsigned short mapHeight; unsigned long mapDataSize; unsigned long mapTileDataSize; unsigned long mapPropertyDataSize; unsigned short mapNumProperty; } MAPHEADER; typedef class ExplorMap { private: BIT tiles[NUMTILES]; BIT prop[MAXPROPNUM][NUMTILES]; MAPHEADER fileHeader; unsigned short tbase(int tx, int ty)const; public: int saveMap(char openmap[FNAMELEN]); int resetBoard(void); int openMap(char openmap[FNAMELEN]); int boardEdit(int x, int y, unsigned int propedit, unsigned int newvalue); int boardEdit(int x, int y); char boardname[FNAMELEN]; int getTileStat(int x, int y, int propnum)const; int getTileStat(int x, int y)const; unsigned short getMapWidth(void)const; unsigned short getMapHeight(void)const; } EXPLORMAP; <file_sep>/Misc/DBXExporter/DBXExporter/oedbx/library/dbxFileHeader.cpp //*************************************************************************************** #define AS_OE_IMPLEMENTATION #include <oedbx/dbxFileHeader.h> //*************************************************************************************** DbxFileHeader::DbxFileHeader(InStream ins) { readFileHeader(ins); } //*************************************************************************************** void DbxFileHeader::readFileHeader(InStream ins) { ins.seekg(0); ins.read((char *)Buffer, FileHeaderSize); if(!ins) throw DbxException("Error reading object from input stream !"); } //*************************************************************************************** struct Entry { int4 index; char * text; }; const int1 HeaderValues = 31; const Entry entries[HeaderValues] = { { fhFileInfoLength, "file info length" }, { 0x09, "pointer to the last variable segment" }, { 0x0a, "length of a variable segment" }, { 0x0b, "used space of the last variable segment" }, { 0x0c, "pointer to the last tree segment" }, { 0x0d, "length of a tree segment" }, { 0x0e, "used space of the last tree segment" }, { 0x0f, "pointer to the last message segment" }, { 0x10, "length of a message segment" }, { 0x11, "used space of the last message segment" }, { 0x12, "root pointer to the deleted message list" }, { 0x13, "root pointer to the deleted tree list" }, { 0x15, "used space in the middle sector of the file" }, { 0x16, "reusable space in the middle sector of the file" }, { 0x17, "index of the last entry in the tree" }, { fhFirstFolderListNode, "pointer to the first folder list node" }, { fhLastFolderListNode, "pointer to the last folder list node" }, { 0x1f, "used space of the file" }, { fhMessageConditionsPtr, "pointer to the message conditions object" }, { fhFolderConditionsPtr, "pointer to the folder conditions object" }, { fhEntries, "entries in the tree" }, { fhEntries+1, "entries in the 2.nd tree" }, { fhEntries+2, "entries in the 3.rd tree" }, { fhTreeRootNodePtr, "pointer to the root node of the tree" }, { fhTreeRootNodePtr+1, "pointer to the root node of the 2.nd tree" }, { fhTreeRootNodePtr+2, "pointer to the root node of the 3.rd tree" }, { 0x9f, "used space for indexed info objects" }, { 0xa0, "used space for conditions objects" }, { 0xa2, "used space for folder list objects" }, { 0xa3, "used space for tree objects" }, { 0xa4, "used space for message objects" } }; void DbxFileHeader::ShowResults(OutStream outs) const { int4 temp[FileHeaderEntries], i, *ptr; for(i=0; i<FileHeaderEntries; ++i) temp[i] = Buffer[i]; outs << std::endl << "file header : " << std::endl; for(i=0; i<HeaderValues; ++i) { ptr = temp + entries[i].index; if(*ptr) { outs << std::left << std::setw(50) << (entries[i].text) << " : 0x" << std::hex << (*ptr) << std::endl; *ptr = 0; } } outs << std::endl << "Show the rest ..." << std::endl; rows2File(outs,0,(int1 *)temp,FileHeaderSize); } <file_sep>/games/Explor2002/Source/Game/ddsetup.h #ifndef __DDSETUP_H__ #define __DDSETUP_H__ #include <ddraw.h> extern long CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); DWORD color(COLORREF rgb, LPDIRECTDRAWSURFACE surface); BOOL InitSurfaces(HWND hWnd); HWND CreateDefaultWindow(char *name, HINSTANCE hInstance); BOOL InitDirectDraw(HWND hWnd); #endif<file_sep>/games/Legacy-Engine/Source/lm_sys/lm_mesh_edit.h #ifndef __LM_EDIT_H__ #define __LM_EDIT_H__ #include "lm_base.h" #include "lm_mesh_anim.h" #include <d3d9.h> //CLMeshEditD3D the editable and renderable //version of CLMesh... class CLMeshEdit: public CLMeshAnim { friend class CLSkelEdit; private: IDirect3DTexture9** m_ppTex; MeshVertex* m_pTransfVB; static const lg_dword LM_FLAG_RENDER_TEX=0x00020000; public: virtual lg_bool Load(LMPath szFile); virtual lg_bool Save(LMPath szFile); virtual lg_void Unload(); protected: virtual MeshVertex* LockTransfVB(); virtual lg_void UnlockTransfVB(); static lg_str GetDirFromPath(lg_str szDir, lg_cstr szFullPath); public: CLMeshEdit(): CLMeshAnim(), m_ppTex(LG_NULL), m_pTransfVB(LG_NULL){}; lg_void Render(); lg_void SetRenderTexture(lg_bool bRenderTexture); const ml_aabb* GetBoundingBox(); static IDirect3DDevice9* s_pDevice; private: //The read function: static lg_uint __cdecl ReadFn(lg_void* file, lg_void* buffer, lg_uint size); static lg_uint __cdecl WriteFn(lg_void* file, lg_void* buffer, lg_uint size); }; #endif __LM_EDIT_H__<file_sep>/games/Legacy-Engine/Scrapped/libs/ML_lib2008April/ML_aabb.c #include "ML_lib.h" __inline void ML_AABBMinMax(ml_float* fMin, ml_float* fMax, const ML_AABB*pAABB, const ML_PLANE* pPlane) { // Inspect the normal and compute the minimum and maximum // D values. fMin is the D value of the "frontmost" corner point if(pPlane->a > 0.0f) { *fMin=pPlane->a*pAABB->v3Min.x; *fMax=pPlane->a*pAABB->v3Max.x; } else { *fMin=pPlane->a*pAABB->v3Max.x; *fMax=pPlane->a*pAABB->v3Min.x; } if(pPlane->b > 0.0f) { *fMin+=pPlane->b*pAABB->v3Min.y; *fMax+=pPlane->b*pAABB->v3Max.y; } else { *fMin+=pPlane->b*pAABB->v3Max.y; *fMax+=pPlane->b*pAABB->v3Min.y; } if(pPlane->c > 0.0f) { *fMin+=pPlane->c*pAABB->v3Min.z; *fMax+=pPlane->c*pAABB->v3Max.z; } else { *fMin+=pPlane->c*pAABB->v3Max.z; *fMax+=pPlane->c*pAABB->v3Min.z; } } ml_bool ML_FUNC ML_AABBIntersectBlock(ML_AABB* pAABB, ML_PLANE* pPlanes, ml_dword nPlaneCount) { //This function is only for testing because it isn't very fast, and it isn't //acurate for blocks smaller than the aabb. ml_dword i; ml_bool bIntersect; for(i=0, bIntersect=ML_TRUE; i<nPlaneCount; i++) { bIntersect=bIntersect&&ML_AABBIntersectPlane(pAABB, &pPlanes[i]); } return bIntersect; } ml_dword ML_FUNC ML_AABBIntersectPlane(const ML_AABB* pAABB, const ML_PLANE* pPlane) { ml_float fMin, fMax; ml_bool bPosFound, bNegFound; ml_dword i; ML_AABBMinMax(&fMin, &fMax, pAABB, pPlane); fMin-=pPlane->d; fMax-=pPlane->d; if(fMax<=0.0f) { return 0x00000001; } //We have to do the full check... bPosFound=ML_FALSE; bNegFound=ML_FALSE; for(i=0; i<8; i++) { ML_VEC3 vT; if(ML_PlaneDotCoord(pPlane, ML_AABBCorner(&vT, pAABB, i))>0.0f) bPosFound=ML_TRUE; else bNegFound=ML_TRUE; if(bPosFound && bNegFound) { //An actuall intersection occured return 0x00000002; } } //The aabb was on the negative side of the plane if(bNegFound && !bPosFound) return 0x00000001; //The aabb was on the positive side of the plane return 0x00000000; } ml_float ML_FUNC ML_AABBIntersectPlaneVel(const ML_AABB* pAABB, const ML_PLANE* pPlane, const ML_VEC3* pVel) { const float kNoIntersection=1e30f; ml_float fTime; ml_float fMin, fMax; ml_float fDot=ML_Vec3Dot(pVel, (ML_VEC3*)pPlane); //We're moving away from the plane, so there is no intersection. if(fDot>=0.0f) { return 0.0f;//kNoIntersection; } ML_AABBMinMax(&fMin, &fMax, pAABB, pPlane); //We're already on the negative side of the plane if(fMax<=pPlane->d) return 0.0f;//kNoIntersection; fTime=(pPlane->d-fMin)/fDot; if(fTime<=0.0f) { //We were already penetrating return 0.0f; } //If fTime is > 1 then the plane was never hit. return fTime; } ML_PLANE* ML_FUNC ML_AABBToPlanes(ML_PLANE* pOut, ML_AABB* pAABB) { pOut[0].a=0.0f; pOut[0].b=0.0f; pOut[0].c=-1.0f; pOut[0].d=ML_Vec3Dot(&pAABB->v3Min, (ML_VEC3*)&pOut[0]); pOut[1].a=1.0f; pOut[1].b=0.0f; pOut[1].c=0.0f; pOut[1].d=ML_Vec3Dot(&pAABB->v3Max, (ML_VEC3*)&pOut[1]); pOut[2].a=0.0f; pOut[2].b=0.0f; pOut[2].c=1.0f; pOut[2].d=ML_Vec3Dot(&pAABB->v3Max, (ML_VEC3*)&pOut[2]); pOut[3].a=-1.0f; pOut[3].b=0.0f; pOut[3].c=0.0f; pOut[3].d=ML_Vec3Dot(&pAABB->v3Min, (ML_VEC3*)&pOut[3]); pOut[4].a=0.0f; pOut[4].b=1.0f; pOut[4].c=0.0f; pOut[4].d=ML_Vec3Dot(&pAABB->v3Max, (ML_VEC3*)&pOut[4]); pOut[5].a=0.0f; pOut[5].b=-1.0f; pOut[5].c=0.0f; pOut[5].d=ML_Vec3Dot(&pAABB->v3Min, (ML_VEC3*)&pOut[5]); return pOut; } ml_dword ML_FUNC ML_AABBIntersectPlaneVelType( const ML_AABB* pAABB, const ML_PLANE* pPlane, const ML_VEC3* pVel, ml_float* pTime) { ml_float fMin, fMax; ml_float fTime; ml_float fDot=ML_Vec3Dot(pVel, (ML_VEC3*)pPlane); ml_dword nStartPos; ml_bool bToward; ML_AABBMinMax(&fMin, &fMax, pAABB, pPlane); //Find out where the box started at... if(fMax<=pPlane->d) nStartPos=ML_INTERSECT_ONNEG; else if(fMin>=pPlane->d) nStartPos=ML_INTERSECT_ONPOS; else nStartPos=ML_INTERSECT_CUR; //If we we're already intersecting we won't //worry about complex calculations... if(nStartPos==ML_INTERSECT_CUR) return nStartPos; //If we weren't moving at all (relative to the planes axis), //the start position is the final position. if(fDot==0.0f) return nStartPos; //Determine if we are moving toward the positive or negative side of //the plane bToward=fDot>0.0f?ML_FALSE:ML_TRUE; if(nStartPos==ML_INTERSECT_ONPOS) { //If moving away from the plane and started on //the positive side, then we are still on the positive side. if(!bToward) return nStartPos; //If we are moving towrd and started on the positive side //then we will hit the plane at some point with the min //vertex. fTime=(pPlane->d-fMin)/fDot; if(fTime>1.0f) return nStartPos; if(pTime)*pTime=fTime; return ML_INTERSECT_HITPOS; } if(nStartPos==ML_INTERSECT_ONNEG) { //If moving toward the plane and started on the negative side, //then we are still on the negative side if(bToward) return nStartPos; //If we are moving away from the plane and we started //on the negative side then we will hit the plane //at some point with the max vertex. fTime=(pPlane->d-fMax)/fDot; if(fTime>1.0f) return nStartPos; if(pTime)*pTime=fTime; return ML_INTERSECT_HITNEG; } //Otherwise we were already inside the plane //and therefore we either stayed inside, left out //the pos side, or left out the neg side. //This should have been caught above, but just //in case we somehow got here... return ML_INTERSECT_CUR; } /* ML_AABB* ML_AABBTransform(ML_AABB* pOut, ML_AABB* pAABB, ML_MAT* pM) { *pOut=*pAABB; if(pM->_11>0.0f) { pOut->v3Min.x+=pM->_11*pOut->v3Min.x; pOut->v3Max.x+=pM->_11*pOut->v3Max.x; } return pOut; } */ ML_AABB* ML_FUNC ML_AABBAddPoint(ML_AABB* pOut, const ML_AABB* pBox, const ML_VEC3* pVec) { ML_VEC3 v3[3]; v3[0]=pBox->v3Min; v3[1]=pBox->v3Max; v3[2]=*pVec; return ML_AABBFromVec3s(pOut, v3, 3); } ML_AABB* ML_FUNC ML_AABBCatenate(ML_AABB* pOut, const ML_AABB* pBox1, const ML_AABB* pBox2) { ML_VEC3 v3[4]; v3[0]=pBox1->v3Min; v3[1]=pBox1->v3Max; v3[2]=pBox2->v3Min; v3[3]=pBox2->v3Max; return ML_AABBFromVec3s(pOut, v3, 4); } ml_bool ML_FUNC ML_AABBIntersect(const ML_AABB* pBox1, const ML_AABB* pBox2, ML_AABB* pIntersect) { if(pBox1->v3Min.x > pBox2->v3Max.x)return ML_FALSE; if(pBox1->v3Max.x < pBox2->v3Min.x)return ML_FALSE; if(pBox1->v3Min.y > pBox2->v3Max.y)return ML_FALSE; if(pBox1->v3Max.y < pBox2->v3Min.y)return ML_FALSE; if(pBox1->v3Min.z > pBox2->v3Max.z)return ML_FALSE; if(pBox1->v3Max.z < pBox2->v3Min.z)return ML_FALSE; if(pIntersect) { pIntersect->v3Min.x=MLG_Max(pBox1->v3Min.x, pBox2->v3Min.x); pIntersect->v3Max.x=MLG_Min(pBox1->v3Max.x, pBox2->v3Max.x); pIntersect->v3Min.y=MLG_Max(pBox1->v3Min.y, pBox2->v3Min.y); pIntersect->v3Max.y=MLG_Min(pBox1->v3Max.y, pBox2->v3Max.y); pIntersect->v3Min.z=MLG_Max(pBox1->v3Min.z, pBox2->v3Min.z); pIntersect->v3Max.z=MLG_Min(pBox1->v3Max.z, pBox2->v3Max.z); } return ML_TRUE; } ml_bool ML_FUNC ML_AABBIntersectVel(ML_VEC3* pOut, const ML_AABB* pBox1Start, const ML_AABB* pBox1End, const ML_AABB* pBox2Static) { return ML_FALSE; /* ML_AABB aabbI1, aabbI2; ml_bool bResult=ML_AABBIntersect(pBox1Start, pBox2Static, &aabbI1); bResult==bResult || ML_AABBIntersect(pBox1End, pBox2Static, &aabbI2); if(!bResult) return ML_FALSE; ML_VEC3 v3Max, v3Min, v3Temp; ML_Vec3Subtract(&v3Max, &pBox1End->v3Max, &pBox1Start->v3Max); ML_Vec3Subtract(&v3Min, &pBox1End->v3Min, &pBox1Start->v3Min); */ } float ML_FUNC ML_AABBIntersectMoving(const ML_AABB* pBoxMove, const ML_AABB* pBoxStat, const ML_VEC3* pVel) { // We'll return this huge number if no intersection #define swap(a, b) {float f=b; b=a; a=f;} const float kNoIntersection = 1e30f; // Initialize interval to contain all the time under consideration float tEnter = 0.0f; float tLeave = 1.0f; // // Compute interval of overlap on each dimension, and intersect // this interval with the interval accumulated so far. As soon as // an empty interval is detected, return a negative result // (no intersection.) In each case, we have to be careful for // an infinite of empty interval on each dimension // // Check x-axis if (pVel->x == 0.0f) { // Empty or infinite inverval on x if ( (pBoxStat->v3Min.x >= pBoxMove->v3Max.x) || (pBoxStat->v3Max.x <= pBoxMove->v3Min.x) ) { // Empty time interval, so no intersection return kNoIntersection; } // Inifinite time interval - no update necessary } else { // Divide once float oneOverD = 1.0f / pVel->x; // Compute time value when they begin and end overlapping float xEnter = (pBoxStat->v3Min.x - pBoxMove->v3Max.x) * oneOverD; float xLeave = (pBoxStat->v3Max.x - pBoxMove->v3Min.x) * oneOverD; // Check for interval out of order if (xEnter > xLeave) { swap(xEnter, xLeave); } // Update interval if (xEnter > tEnter) tEnter = xEnter; if (xLeave < tLeave) tLeave = xLeave; // Check if this resulted in empty interval if (tEnter > tLeave) { return kNoIntersection; } } // Check y-axis if (pVel->y == 0.0f) { // Empty or infinite inverval on y if ( (pBoxStat->v3Min.y >= pBoxMove->v3Max.y) || (pBoxStat->v3Max.y <= pBoxMove->v3Min.y) ) { // Empty time interval, so no intersection return kNoIntersection; } // Inifinite time interval - no update necessary } else { // Divide once float oneOverD = 1.0f / pVel->y; // Compute time value when they begin and end overlapping float yEnter = (pBoxStat->v3Min.y - pBoxMove->v3Max.y) * oneOverD; float yLeave = (pBoxStat->v3Max.y - pBoxMove->v3Min.y) * oneOverD; // Check for interval out of order if (yEnter > yLeave) { swap(yEnter, yLeave); } // Update interval if (yEnter > tEnter) tEnter = yEnter; if (yLeave < tLeave) tLeave = yLeave; // Check if this resulted in empty interval if (tEnter > tLeave) { return kNoIntersection; } } // Check z-axis if (pVel->z == 0.0f) { // Empty or infinite inverval on z if ( (pBoxStat->v3Min.z >= pBoxMove->v3Max.z) || (pBoxStat->v3Max.z <= pBoxMove->v3Min.z) ) { // Empty time interval, so no intersection return kNoIntersection; } // Inifinite time interval - no update necessary } else { // Divide once float oneOverD = 1.0f / pVel->z; // Compute time value when they begin and end overlapping float zEnter = (pBoxStat->v3Min.z - pBoxMove->v3Max.z) * oneOverD; float zLeave = (pBoxStat->v3Max.z - pBoxMove->v3Min.z) * oneOverD; // Check for interval out of order if (zEnter > zLeave) { swap(zEnter, zLeave); } // Update interval if (zEnter > tEnter) tEnter = zEnter; if (zLeave < tLeave) tLeave = zLeave; // Check if this resulted in empty interval if (tEnter > tLeave) { return kNoIntersection; } } // OK, we have an intersection. Return the parametric point in time // where the intersection occurs return tEnter; } /* float intersectMovingAABB( const AABB3 &stationaryBox, const AABB3 &movingBox, const Vector3 &d ) { // We'll return this huge number if no intersection const float kNoIntersection = 1e30f; // Initialize interval to contain all the time under consideration float tEnter = 0.0f; float tLeave = 1.0f; // // Compute interval of overlap on each dimension, and intersect // this interval with the interval accumulated so far. As soon as // an empty interval is detected, return a negative result // (no intersection.) In each case, we have to be careful for // an infinite of empty interval on each dimension // // Check x-axis if (d.x == 0.0f) { // Empty or infinite inverval on x if ( (stationaryBox.min.x >= movingBox.max.x) || (stationaryBox.max.x <= movingBox.min.x) ) { // Empty time interval, so no intersection return kNoIntersection; } // Inifinite time interval - no update necessary } else { // Divide once float oneOverD = 1.0f / d.x; // Compute time value when they begin and end overlapping float xEnter = (stationaryBox.min.x - movingBox.max.x) * oneOverD; float xLeave = (stationaryBox.max.x - movingBox.min.x) * oneOverD; // Check for interval out of order if (xEnter > xLeave) { swap(xEnter, xLeave); } // Update interval if (xEnter > tEnter) tEnter = xEnter; if (xLeave < tLeave) tLeave = xLeave; // Check if this resulted in empty interval if (tEnter > tLeave) { return kNoIntersection; } } // Check y-axis if (d.y == 0.0f) { // Empty or infinite inverval on y if ( (stationaryBox.min.y >= movingBox.max.y) || (stationaryBox.max.y <= movingBox.min.y) ) { // Empty time interval, so no intersection return kNoIntersection; } // Inifinite time interval - no update necessary } else { // Divide once float oneOverD = 1.0f / d.y; // Compute time value when they begin and end overlapping float yEnter = (stationaryBox.min.y - movingBox.max.y) * oneOverD; float yLeave = (stationaryBox.max.y - movingBox.min.y) * oneOverD; // Check for interval out of order if (yEnter > yLeave) { swap(yEnter, yLeave); } // Update interval if (yEnter > tEnter) tEnter = yEnter; if (yLeave < tLeave) tLeave = yLeave; // Check if this resulted in empty interval if (tEnter > tLeave) { return kNoIntersection; } } // Check z-axis if (d.z == 0.0f) { // Empty or infinite inverval on z if ( (stationaryBox.min.z >= movingBox.max.z) || (stationaryBox.max.z <= movingBox.min.z) ) { // Empty time interval, so no intersection return kNoIntersection; } // Inifinite time interval - no update necessary } else { // Divide once float oneOverD = 1.0f / d.z; // Compute time value when they begin and end overlapping float zEnter = (stationaryBox.min.z - movingBox.max.z) * oneOverD; float zLeave = (stationaryBox.max.z - movingBox.min.z) * oneOverD; // Check for interval out of order if (zEnter > zLeave) { swap(zEnter, zLeave); } // Update interval if (zEnter > tEnter) tEnter = zEnter; if (zLeave < tLeave) tLeave = zLeave; // Check if this resulted in empty interval if (tEnter > tLeave) { return kNoIntersection; } } // OK, we have an intersection. Return the parametric point in time // where the intersection occurs return tEnter; } */ ML_AABB* ML_AABBFromVec3s(ML_AABB* pOut, const ML_VEC3* pVList, const ml_dword nNumVecs) { ml_dword i; if(!nNumVecs) return pOut; /* Set the AABB equal to the first vector. */ pOut->v3Max.x=pVList[0].x; pOut->v3Max.y=pVList[0].y; pOut->v3Max.z=pVList[0].z; pOut->v3Min.x=pVList[0].x; pOut->v3Min.y=pVList[0].y; pOut->v3Min.z=pVList[0].z; for(i=1; i<nNumVecs; i++) { pOut->v3Min.x=MLG_Min(pVList[i].x, pOut->v3Min.x); pOut->v3Min.y=MLG_Min(pVList[i].y, pOut->v3Min.y); pOut->v3Min.z=MLG_Min(pVList[i].z, pOut->v3Min.z); pOut->v3Max.x=MLG_Max(pVList[i].x, pOut->v3Max.x); pOut->v3Max.y=MLG_Max(pVList[i].y, pOut->v3Max.y); pOut->v3Max.z=MLG_Max(pVList[i].z, pOut->v3Max.z); } return pOut; } ML_VEC3* ML_AABBCorner(ML_VEC3* pV, const ML_AABB* pAABB, const ML_AABB_CORNER ref) { pV->x=(ref&0x01)?pAABB->v3Max.x:pAABB->v3Min.x; pV->y=(ref&0x02)?pAABB->v3Max.y:pAABB->v3Min.y; pV->z=(ref&0x04)?pAABB->v3Max.z:pAABB->v3Min.z; return pV; } ML_AABB* ML_AABBTransform(ML_AABB* pOut, const ML_AABB* pAABB, const ML_MAT* pM) { ML_AABB aabbTmp; // Start with the translation portion aabbTmp.v3Min.x=pM->_41; aabbTmp.v3Min.y=pM->_42; aabbTmp.v3Min.z=pM->_43; aabbTmp.v3Max=aabbTmp.v3Min; // Examine each of the 9 matrix elements // and compute the new AABB if (pM->_11 > 0.0f) { aabbTmp.v3Min.x += pM->_11 * pAABB->v3Min.x; aabbTmp.v3Max.x += pM->_11 * pAABB->v3Max.x; } else { aabbTmp.v3Min.x += pM->_11 * pAABB->v3Max.x; aabbTmp.v3Max.x += pM->_11 * pAABB->v3Min.x; } if (pM->_12 > 0.0f) { aabbTmp.v3Min.y += pM->_12 * pAABB->v3Min.x; aabbTmp.v3Max.y += pM->_12 * pAABB->v3Max.x; } else { aabbTmp.v3Min.y += pM->_12 * pAABB->v3Max.x; aabbTmp.v3Max.y += pM->_12 * pAABB->v3Min.x; } if (pM->_13 > 0.0f) { aabbTmp.v3Min.z += pM->_13 * pAABB->v3Min.x; aabbTmp.v3Max.z += pM->_13 * pAABB->v3Max.x; } else { aabbTmp.v3Min.z += pM->_13 * pAABB->v3Max.x; aabbTmp.v3Max.z += pM->_13 * pAABB->v3Min.x; } if (pM->_21 > 0.0f) { aabbTmp.v3Min.x += pM->_21 * pAABB->v3Min.y; aabbTmp.v3Max.x += pM->_21 * pAABB->v3Max.y; } else { aabbTmp.v3Min.x += pM->_21 * pAABB->v3Max.y; aabbTmp.v3Max.x += pM->_21 * pAABB->v3Min.y; } if (pM->_22 > 0.0f) { aabbTmp.v3Min.y += pM->_22 * pAABB->v3Min.y; aabbTmp.v3Max.y += pM->_22 * pAABB->v3Max.y; } else { aabbTmp.v3Min.y += pM->_22 * pAABB->v3Max.y; aabbTmp.v3Max.y += pM->_22 * pAABB->v3Min.y; } if (pM->_23 > 0.0f) { aabbTmp.v3Min.z += pM->_23 * pAABB->v3Min.y; aabbTmp.v3Max.z += pM->_23 * pAABB->v3Max.y; } else { aabbTmp.v3Min.z += pM->_23 * pAABB->v3Max.y; aabbTmp.v3Max.z += pM->_23 * pAABB->v3Min.y; } if (pM->_31 > 0.0f) { aabbTmp.v3Min.x += pM->_31 * pAABB->v3Min.z; aabbTmp.v3Max.x += pM->_31 * pAABB->v3Max.z; } else { aabbTmp.v3Min.x += pM->_31 * pAABB->v3Max.z; aabbTmp.v3Max.x += pM->_31 * pAABB->v3Min.z; } if (pM->_32 > 0.0f) { aabbTmp.v3Min.y += pM->_32 * pAABB->v3Min.z; aabbTmp.v3Max.y += pM->_32 * pAABB->v3Max.z; } else { aabbTmp.v3Min.y += pM->_32 * pAABB->v3Max.z; aabbTmp.v3Max.y += pM->_32 * pAABB->v3Min.z; } if (pM->_33 > 0.0f) { aabbTmp.v3Min.z += pM->_33 * pAABB->v3Min.z; aabbTmp.v3Max.z += pM->_33 * pAABB->v3Max.z; } else { aabbTmp.v3Min.z += pM->_33 * pAABB->v3Max.z; aabbTmp.v3Max.z += pM->_33 * pAABB->v3Min.z; } *pOut=aabbTmp; return pOut; } ML_AABB* ML_AABBTransformAlt(ML_AABB* pOut, const ML_AABB* pAABB, const ML_MAT* pM) { ml_dword i; ML_VEC3 v3Corners[8]; //The idea behind this is to get all the corners, transform the corners and then //make a new AABB based on the transformed corners. More math is required for //this. for(i=0; i<8; i++) { ML_AABBCorner(&v3Corners[i], pAABB, (ML_AABB_CORNER)i); ML_Vec3TransformCoord(&v3Corners[i], &v3Corners[i], pM); } return ML_AABBFromVec3s(pOut, v3Corners, 8); } <file_sep>/games/Legacy-Engine/Source/engine/lp_newton2.cpp #include "lp_newton2.h" #include "lg_err_ex.h" #include "lg_err.h" #include "lg_func.h" #include "lw_entity.h" #include "lw_map.h" CLPhysNewton* CLPhysNewton::s_pPhys=LG_NULL; void CLPhysNewton::Init(lg_dword nMaxBodies) { s_pPhys=this; m_fTimeStep=0.0f; Err_Printf("Initializing Newton Game Dynamics physics engine..."); m_pNewtonWorld=NewtonCreate(0, 0);//(NewtonAllocMemory)LG_Malloc, (NewtonFreeMemory)LG_Free); if(!m_pNewtonWorld) throw CLError(LG_ERR_DEFAULT, __FILE__, __LINE__, "Newton Initialization: Could not create physics model."); Err_Printf("Newton World version %i.", NewtonWorldGetVersion(m_pNewtonWorld)); Err_Printf("Setting up basic materials."); MTR_DEFAULT=0; MTR_DEFAULT=NewtonMaterialGetDefaultGroupID(m_pNewtonWorld); NewtonMaterialSetDefaultSoftness(m_pNewtonWorld, MTR_DEFAULT, MTR_DEFAULT, 1.0f); NewtonMaterialSetDefaultElasticity(m_pNewtonWorld, MTR_DEFAULT, MTR_DEFAULT, 0.0f); NewtonMaterialSetDefaultCollidable(m_pNewtonWorld, MTR_DEFAULT, MTR_DEFAULT, 1); NewtonMaterialSetDefaultFriction(m_pNewtonWorld, MTR_DEFAULT, MTR_DEFAULT, 0.0f, 0.0f); //NewtonMaterialSetCollisionCallback (m_pNewtonWorld, MTR_DEFAULT, MTR_DEFAULT, &wood_wood, GenericContactBegin, GenericContactProcess, GenericContactEnd); MTR_LEVEL=NewtonMaterialCreateGroupID(m_pNewtonWorld); MTR_CHARACTER=NewtonMaterialCreateGroupID(m_pNewtonWorld); MTR_OBJECT=NewtonMaterialCreateGroupID(m_pNewtonWorld); NewtonMaterialSetDefaultSoftness(m_pNewtonWorld, MTR_CHARACTER, MTR_LEVEL, 1.0f); NewtonMaterialSetDefaultElasticity(m_pNewtonWorld, MTR_CHARACTER, MTR_LEVEL, 0.0f); NewtonMaterialSetDefaultCollidable(m_pNewtonWorld, MTR_CHARACTER, MTR_LEVEL, 1); NewtonMaterialSetDefaultFriction(m_pNewtonWorld, MTR_CHARACTER, MTR_LEVEL, 0.0f, 0.0f); NewtonMaterialSetDefaultSoftness(m_pNewtonWorld, MTR_OBJECT, MTR_LEVEL, 1.0f); NewtonMaterialSetDefaultElasticity(m_pNewtonWorld, MTR_OBJECT, MTR_LEVEL, 0.0f); NewtonMaterialSetDefaultCollidable(m_pNewtonWorld, MTR_OBJECT, MTR_LEVEL, 1); NewtonMaterialSetDefaultFriction(m_pNewtonWorld, MTR_OBJECT, MTR_LEVEL, 0.0f, 0.0f); NewtonMaterialSetDefaultSoftness(m_pNewtonWorld, MTR_OBJECT, MTR_CHARACTER, 0.5f); NewtonMaterialSetDefaultElasticity(m_pNewtonWorld, MTR_OBJECT, MTR_CHARACTER, 0.0f); NewtonMaterialSetDefaultCollidable(m_pNewtonWorld, MTR_OBJECT, MTR_CHARACTER, 1); NewtonMaterialSetDefaultFriction(m_pNewtonWorld, MTR_OBJECT, MTR_CHARACTER, 1.0f, 0.5f); NewtonMaterialSetDefaultSoftness(m_pNewtonWorld, MTR_CHARACTER, MTR_CHARACTER, 0.5f); NewtonMaterialSetDefaultElasticity(m_pNewtonWorld, MTR_CHARACTER, MTR_CHARACTER, 0.0f); NewtonMaterialSetDefaultCollidable(m_pNewtonWorld, MTR_CHARACTER, MTR_CHARACTER, 1); NewtonMaterialSetDefaultFriction(m_pNewtonWorld, MTR_CHARACTER, MTR_CHARACTER, 1.0f, 0.5f); NewtonMaterialSetDefaultSoftness(m_pNewtonWorld, MTR_OBJECT, MTR_OBJECT, 0.5f); NewtonMaterialSetDefaultElasticity(m_pNewtonWorld, MTR_OBJECT, MTR_OBJECT, 0.0f); NewtonMaterialSetDefaultCollidable(m_pNewtonWorld, MTR_OBJECT, MTR_OBJECT, 1); NewtonMaterialSetDefaultFriction(m_pNewtonWorld, MTR_OBJECT, MTR_OBJECT, 1.0f, 0.5f); //Setup some base values m_v3Grav=s_v3Zero; m_pWorldBody=LG_NULL; } /* Shutdown PRE: Init should have been called. POST: Memory allocated to the physics engine is released, after this method is called any created bodies that might still ahve references on the server should not be used. */ void CLPhysNewton::Shutdown() { NewtonDestroyAllBodies(m_pNewtonWorld); NewtonMaterialDestroyAllGroupID(m_pNewtonWorld); NewtonDestroy(m_pNewtonWorld); } /* AddBody PRE: pEnt should be an entity in the server world, pInfo should be set with all information about the body to be created. POST: A new body is added to the world (or if a new body could not be added, null is returned. Note that the return value is a pointer that should be used whenever updates by the server need to be applied to the physics engine. */ lg_void* CLPhysNewton::AddBody(lg_void* pEnt, lp_body_info* pInfo) { ML_MAT matPos; ML_MatIdentity(&matPos); matPos._41=(pInfo->m_aabbBody.v3Max.x+pInfo->m_aabbBody.v3Min.x)*0.5f; matPos._42=(pInfo->m_aabbBody.v3Max.y+pInfo->m_aabbBody.v3Min.y)*0.5f; matPos._43=(pInfo->m_aabbBody.v3Max.z+pInfo->m_aabbBody.v3Min.z)*0.5f; NewtonCollision* pClsn=NewtonCreateBox( m_pNewtonWorld, pInfo->m_aabbBody.v3Max.x-pInfo->m_aabbBody.v3Min.x, pInfo->m_aabbBody.v3Max.y-pInfo->m_aabbBody.v3Min.y, pInfo->m_aabbBody.v3Max.z-pInfo->m_aabbBody.v3Min.z, (dFloat*)&matPos); NewtonBody* pBdy=NewtonCreateBody( m_pNewtonWorld, pClsn); NewtonReleaseCollision(m_pNewtonWorld, pClsn); NewtonBodySetMatrix(pBdy, (dFloat*)&pInfo->m_matPos); #if 0 ML_VEC3 v3={ pInfo->m_aabbBody.v3Min.x+(pInfo->m_aabbBody.v3Max.x-pInfo->m_aabbBody.v3Min.x)*0.5f, pInfo->m_aabbBody.v3Min.y+(pInfo->m_aabbBody.v3Max.y-pInfo->m_aabbBody.v3Min.y)*0.5f, pInfo->m_aabbBody.v3Min.z+(pInfo->m_aabbBody.v3Max.z-pInfo->m_aabbBody.v3Min.z)*0.5f}; NewtonBodySetCentreOfMass(pBdy, (dFloat*)&v3); #else NewtonBodySetCentreOfMass(pBdy, (dFloat*)pInfo->m_fMassCenter); #endif NewtonBodySetMassMatrix(pBdy, pInfo->m_fMass, pInfo->m_fMass, pInfo->m_fMass, pInfo->m_fMass); NewtonBodySetMaterialGroupID(pBdy, MTR_OBJECT); NewtonBodySetAutoFreeze(pBdy, 0); NewtonBodySetUserData(pBdy, pEnt); //Set the force and torque callback to the update from srv. NewtonBodySetForceAndTorqueCallback(pBdy, UpdateFromSrv); //Set the transform callback, wich sends data back to the srv. NewtonBodySetTransformCallback(pBdy, UpdateToSrv); if(LG_CheckFlag(pInfo->m_nAIPhysFlags, AI_PHYS_INT)) { //Err_Printf("Created UPRIGHT object!"); // add and up vector constraint to help in keeping the body upright ML_VEC3 upDirection ={0.0f, 1.0f, 0.0f}; NewtonJoint* pUpVec = NewtonConstraintCreateUpVector(m_pNewtonWorld, (dFloat*)&upDirection, pBdy); } UpdateToSrv(pBdy, (dFloat*)&pInfo->m_matPos); return pBdy; #if 0 if(m_bIntelligent) { NewtonBodySetMaterialGroupID(m_pNewtonBody, MTR_CHARACTER); //NewtonBodySetMassMatrix(m_pNewtonBody, m_fMass, 1e30f, 1e30f, 1e30f); NewtonBodySetAutoFreeze(m_pNewtonBody, 0); NewtonWorldUnfreezeBody(s_pNewtonWorld, m_pNewtonBody); // add and up vector constraint to help in keeping the body upright ML_VEC3 upDirection ={0.0f, 1.0f, 0.0f}; m_pUpVec = NewtonConstraintCreateUpVector (s_pNewtonWorld, (dFloat*)&upDirection, m_pNewtonBody); } else { //NewtonBodySetMassMatrix(m_pNewtonBody, m_fMass, m_fMass, m_fMass, m_fMass); NewtonBodySetAutoFreeze(m_pNewtonBody, LG_TRUE); NewtonWorldFreezeBody(s_pNewtonWorld, m_pNewtonBody); NewtonBodySetMaterialGroupID(m_pNewtonBody, MTR_OBJECT); m_pUpVec=LG_NULL; } #endif } void CLPhysNewton::RemoveBody(lg_void* pBody) { NewtonBody* pPhysBody=(NewtonBody*)pBody; NewtonDestroyBody(m_pNewtonWorld, pPhysBody); } void CLPhysNewton::SetupWorld(lg_void* pWorldMap) { if(m_pWorldBody) { NewtonDestroyBody(m_pNewtonWorld, m_pWorldBody); m_pWorldBody=LG_NULL; } if(!pWorldMap) return; CLMap* pMap=(CLMap*)pWorldMap; NewtonCollision* pCol=NewtonCreateTreeCollision(m_pNewtonWorld, LG_NULL); if(!pCol) { Err_Printf("NEWTON GAME: SetupWorld: Could not create Newton collision."); return; } NewtonTreeCollisionBeginBuild(pCol); for(lg_dword i=0; i<pMap->m_nVertexCount/3; i++) { NewtonTreeCollisionAddFace( pCol, 3, (dFloat*)&pMap->m_pVertexes[i*3], sizeof(LW_VERTEX), MTR_LEVEL); } NewtonTreeCollisionEndBuild(pCol, LG_TRUE); m_pWorldBody=NewtonCreateBody(m_pNewtonWorld, pCol); NewtonReleaseCollision(m_pNewtonWorld, pCol); NewtonBodySetMaterialGroupID(m_pWorldBody, MTR_LEVEL); NewtonSetWorldSize( m_pNewtonWorld, (dFloat*)&pMap->m_aabbMapBounds.v3Min, (dFloat*)&pMap->m_aabbMapBounds.v3Max); } void CLPhysNewton::SetGravity(ML_VEC3* pGrav) { m_v3Grav=*pGrav; } /* Simulate PRE: Everything needs to be initialized, fTimeStepSec >= 0.0f and represents how many seconds have elapsed since the last update (usually a small number such as 1/30 seconds (at 30 fps) etc.). POST: The physics engine simulates all physical interactions. This method updates the entities on the server. After it finishes any changes in a body's velocity, torque, position, etc. will already be updated on the server, so there is no need to loop through all the ents on the server and update their physical information. Note that the server's entity's thrust and torque are set to zero, this is because if an entity wants to continue accelerating it needs to keep setting the forces (that is in order to speed up forces need to be applied over time, remember that forces imply acceleration, but if the object only accelerates a little then it will not have a big velocity, and if there is a significant amount of friction, then the veloctiy will be reduced to zero very quickly). Future Notes: Additionally if a body's veloctiy becomes extremely low, that body will be put to sleep and will not be effected by calls to UpdateBody. If another bodies collides with a sleeping body it will then become awake. Note that AI controlled bodies should be set to never fall asleep, only dumb objects. */ void CLPhysNewton::Simulate(lg_float fTimeStepSec) { //::NewtonBodySetAp(m_pNewtonWorld, UpdateFromSrv); static lg_float fCumuSecs=0.0f; fCumuSecs+=fTimeStepSec; if(fCumuSecs<=0.003f) return; m_fTimeStep=fCumuSecs; NewtonUpdate(m_pNewtonWorld, fCumuSecs); fCumuSecs=0; } void CLPhysNewton::SetBodyFlag(lg_void* pBody, lg_dword nFlagID, lg_dword nValue) { } void CLPhysNewton::SetBodyVector(lg_void* pBody, lg_dword nVecID, ML_VEC3* pVec) { } void CLPhysNewton::SetBodyFloat(lg_void* pBody, lg_dword nFloatID, lg_float fValue) { } /* SetBodyPosition PRE: pBody must point to a body created by the phys engine. POST: The new position is set, and the server's entity's m_v3Face and m_v3Pos is updated as well (so it does not need to be updated on the server side). NOTES: This should rarely be called, it may need to be called in the case of teleports of some kind, or in the case that precise rotation needs to be specifed (as in the case of a first person shooter, if we just had the mouse do a certain amount of torque rotation might not be as smooth as directly updating the rotation, but in that case the translation part of the matrix should not be changed, only the rotation part). */ void CLPhysNewton::SetBodyPosition(lg_void* pBody, ML_MAT* pMat) { NewtonBody* pPhysBody=(NewtonBody*)pBody; LEntitySrv* pEntSrv=(LEntitySrv*)::NewtonBodyGetUserData(pPhysBody); NewtonBodySetMatrix(pPhysBody, (dFloat*)pMat); pEntSrv->m_matPos=*pMat; //Calculate the face vectors. ML_Vec3TransformNormalArray( pEntSrv->m_v3Face, sizeof(ML_VEC3), s_v3StdFace, sizeof(ML_VEC3), pMat, 3); } lg_void* CLPhysNewton::GetBodySaveInfo(lg_void* pBody, lg_dword* pSize) { return LG_NULL; } lg_void* CLPhysNewton::LoadBodySaveInfo(lg_void* pData, lg_dword nSize) { return LG_NULL; } void CLPhysNewton::UpdateFromSrv(const NewtonBody* body) { static lg_dword nPhysFlags; LEntitySrv* pEnt=(LEntitySrv*)NewtonBodyGetUserData(body); nPhysFlags=pEnt->m_pAI->PhysFlags(); if(LG_CheckFlag(nPhysFlags, AI_PHYS_DIRECT_LINEAR)) { } else { //ML_Vec3Scale(&pEnt->m_v3Thrust, &pEnt->m_v3Thrust, 1.0f/s_pPhys->m_fTimeStep); NewtonBodyAddForce(body, (dFloat*)&pEnt->m_v3Thrust); ML_Vec3Scale(&pEnt->m_v3Impulse, &pEnt->m_v3Impulse, 1.0f/s_pPhys->m_fTimeStep); NewtonBodyAddForce(body, (dFloat*)&pEnt->m_v3Impulse); } if(LG_CheckFlag(nPhysFlags, AI_PHYS_DIRECT_ANGULAR)) { /* NewtonBodySetOmega(body, (dFloat*)&s_v3Zero); ML_Vec3Scale(&pEnt->m_v3Torque, &pEnt->m_v3Torque, 60); NewtonBodyAddTorque(body, (dFloat*)&pEnt->m_v3Torque); ML_MAT matTemp, matTemp2; NewtonBodyGetMatrix(body, (dFloat*)&matTemp); ML_MatRotationAxis(&matTemp2, &pEnt->m_v3Torque, ML_Vec3Length(&pEnt->m_v3Torque)); ML_MatMultiply(&matTemp, &matTemp, &matTemp2); NewtonBodySetMatrix(body, (dFloat*)&matTemp); */ #if 0 static dFloat mass[4]; //static dFloat omega[3]; //NewtonBodyGetOmega(body, omega); NewtonBodyGetMassMatrix(body, &mass[0], &mass[1], &mass[2], &mass[3]); ML_Vec3Scale(&pEnt->m_v3Torque, &pEnt->m_v3Torque, mass[0]); //ML_Vec3Add(&pEnt->m_v3Torque, (ML_VEC3*)omega, &pEnt->m_v3Torque); NewtonBodySetOmega(body, (dFloat*)&pEnt->m_v3Torque); #elif 0 ML_VEC3 v3Temp; NewtonBodyGetTorque(body, (dFloat*)&v3Temp); ML_Vec3Scale(&v3Temp, &v3Temp, -2.0f); NewtonBodyAddTorque(body, (dFloat*)&v3Temp); NewtonBodyAddTorque(body, (dFloat*)&pEnt->m_v3Torque); #elif 1 ML_Vec3Scale(&pEnt->m_v3Torque, &pEnt->m_v3Torque, 1000.0f); NewtonBodyAddTorque(body, (dFloat*)&pEnt->m_v3Torque); #else #endif } else { NewtonBodyAddTorque(body, (dFloat*)&pEnt->m_v3Torque); } //Apply grav //ML_VEC3 v3Grav={0.0f, -9.8f*pEnt->m_fMass, 0.0f}; //NewtonBodyAddForce(body, (dFloat*)&v3Grav); /* ML_VEC3 v3Grav; ML_Vec3Scale(&v3Grav, &s_pPhys->m_v3Grav, pEnt->m_fMass); NewtonBodyAddForce(body, (dFloat*)&v3Grav); */ pEnt->m_v3Torque=s_v3Zero; pEnt->m_v3Thrust=s_v3Zero; pEnt->m_v3Impulse=s_v3Zero; #if 0 if(LG_CheckFlag(pEnt->m_nFlags1, LEntitySrv::ENT_INT)) { NewtonBodySetTorque(body, (dFloat*)&s_v3Zero.x); } #endif } void CLPhysNewton::UpdateToSrv(const NewtonBody* body, const dFloat* matrix) { LEntitySrv* pEnt=(LEntitySrv*)NewtonBodyGetUserData(body); pEnt->m_matPos=(ML_MAT)*(ML_MAT*)matrix; NewtonBodyGetVelocity(body, (dFloat*)&pEnt->m_v3Vel); NewtonBodyGetTorque(body, (dFloat*)&pEnt->m_v3Torque); ML_Vec3TransformNormalArray( pEnt->m_v3Face, sizeof(ML_VEC3), s_v3StdFace, sizeof(ML_VEC3), &pEnt->m_matPos, 3); NewtonBodyGetAABB(body, (dFloat*)&pEnt->m_aabbBody.v3Min, (dFloat*)&pEnt->m_aabbBody.v3Max); //Call the post physics AI routine. pEnt->m_pAI->PostPhys(pEnt); } <file_sep>/samples/D3DDemo/code/GFX3D9/GFX3D9.h /* GFX3D9.h - Header for 3D graphics library Copyright (c) 2003, <NAME> */ #ifndef __GFX3D9_H__ #define __GFX3D9_H__ #include <d3d9.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #define GFX3D9_EXPORTS /* Macros for quicker functionality. */ #ifndef SAFE_DELETE #define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } } #endif /* SAFE_DELETE */ #ifndef SAFE_DELETE_ARRAY #define SAFE_DELETE_ARRAY(p) { if(p) { delete [] (p); (p)=NULL; } } #endif /* SAFE_DELETE_ARRAY */ #ifndef SAFE_FREE #define SAFE_FREE(p) { if(p) { free(p); (p)=NULL; } } #endif /* SAFE_FREE */ #ifndef SAFE_RELEASE #ifdef __cplusplus #define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } } #else /* __cplusplus */ #define SAFE_RELEASE(p) { if(p) { (p)->lpVtbl->Release((p)); (p)=NULL; } } #endif /* __cplusplus */ #endif /* SAFE_RELEASE */ /* The custom vertex type */ #define CUSTOMVERTEX_TYPE \ ( \ D3DFVF_XYZ| \ D3DFVF_NORMAL| \ D3DFVF_DIFFUSE| \ D3DFVF_SPECULAR| \ D3DFVF_TEX1 \ ) /* The custom vertex structure */ #ifdef __cplusplus typedef struct GFX3D9_EXPORTS tagCUSTOMVERTEX #else /* __cplusplus */ typedef struct tagCUSTOMVERTEX #endif /* __cplusplus */ { D3DVECTOR Position; /* Vertex Position */ D3DVECTOR Normal; /* Vertex Normal */ D3DCOLOR DiffuseColor; /* Vertex Diffuse Color */ D3DCOLOR SpecularColor; /* Vertex Specular color */ float tu, tv; /* Vertex Texture Coordinates */ /* C++ adds additional functionality */ #ifdef __cplusplus tagCUSTOMVERTEX(); tagCUSTOMVERTEX( float px, float py, float pz, float nx, float ny, float nz, D3DCOLOR dwDiffuse, D3DCOLOR dwSpecular, float txu, float txv); tagCUSTOMVERTEX operator = (const tagCUSTOMVERTEX & ); /* Assignment operator overload */ int operator == (const tagCUSTOMVERTEX & ); /* Equality operator overload */ int operator != (const tagCUSTOMVERTEX & ); /* Inequality operator overload */ #endif /* __cplusplus */ }CUSTOMVERTEX, *LPCUSTOMVERTEX; /* 2D Image Functionality. */ typedef HANDLE HD3DIMAGE; #ifdef UNICODE #define CreateD3DImageFromFile CreateD3DImageFromFileW #else /* UNICODE */ #define CreateD3DImageFromFile CreateD3DImageFromFileA #endif /* UNICODE */ GFX3D9_EXPORTS HD3DIMAGE CreateD3DImageFromFileA( LPDIRECT3DDEVICE9 lpDevice, char szFilename[MAX_PATH], DWORD dwWidth, DWORD dwHeight, D3DCOLOR dwTransparent); GFX3D9_EXPORTS HD3DIMAGE CreateD3DImageFromFileW( LPDIRECT3DDEVICE9 lpDevice, WCHAR szFilename[MAX_PATH], DWORD dwWidth, DWORD dwHeight, D3DCOLOR dwTransparent); GFX3D9_EXPORTS HD3DIMAGE CreateD3DImageFromTexture( LPDIRECT3DDEVICE9 lpDevice, DWORD dwWidth, DWORD dwHeight, LPDIRECT3DTEXTURE9 lpTexture); GFX3D9_EXPORTS HD3DIMAGE CreateD3DImageFromColor( LPDIRECT3DDEVICE9 lpDevice, DWORD dwWidth, DWORD dwHeight, D3DCOLOR dwColor); GFX3D9_EXPORTS BOOL InvalidateD3DImage( HD3DIMAGE hImage); GFX3D9_EXPORTS BOOL ValidateD3DImage( HD3DIMAGE hImage); GFX3D9_EXPORTS BOOL DeleteD3DImage( HD3DIMAGE hImage); GFX3D9_EXPORTS BOOL RenderD3DImage( HD3DIMAGE hImage, LONG x, LONG y); GFX3D9_EXPORTS BOOL RenderD3DImageEx( HD3DIMAGE hImage, LONG nXDest, LONG nYDest, LONG nWidthDest, LONG nHeightDest, LONG nXSrc, LONG nYSrc, LONG nWidthSrc, LONG nHeightSrc); GFX3D9_EXPORTS BOOL RenderD3DImageRelativeEx( HD3DIMAGE hImage, float fXDest, float fYDest, float fWidthDest, float fHeightDest, LONG nXSrc, LONG nYSrc, LONG nWidthSrc, LONG nHeightSrc); GFX3D9_EXPORTS HD3DIMAGE CopyD3DImage( HD3DIMAGE hImageSrc); GFX3D9_EXPORTS LONG GetD3DImageWidth( HD3DIMAGE hImage); GFX3D9_EXPORTS LONG GetD3DImageHeight( HD3DIMAGE hImage); /* The font functionality. */ typedef HANDLE HD3DFONT; #ifdef UNICODE #define CreateD3DFontFromImage CreateD3DFontFromImageW #else /* UNICODE */ #define CreateD3DFontFromImage CreateD3DFontFromImageA #endif /* UNICODE */ GFX3D9_EXPORTS HD3DFONT GetD3DFontDefault( LPDIRECT3DDEVICE9 lpDevice); GFX3D9_EXPORTS BOOL SetD3DFontSize( HD3DFONT hFont, WORD wWidth, WORD wHeight); GFX3D9_EXPORTS BOOL GetD3DFontDims( HD3DFONT hFont, WORD * lpWidth, WORD * lpHeight); GFX3D9_EXPORTS HD3DFONT CreateD3DFontFromFont( LPDIRECT3DDEVICE9 lpDevice, HFONT hFont, DWORD dwColor); GFX3D9_EXPORTS HD3DFONT CreateD3DFontFromD3DImage( LPDIRECT3DDEVICE9 lpDevice, HD3DIMAGE hImage, WORD wCharsPerLine, WORD wNumLines); GFX3D9_EXPORTS HD3DFONT CreateD3DFontFromImageA( LPDIRECT3DDEVICE9 lpDevice, char szFilename[MAX_PATH], WORD wCharsPerLine, WORD wNumLines); GFX3D9_EXPORTS HD3DFONT CreateD3DFontFromImageW( LPDIRECT3DDEVICE9 lpDevice, WCHAR szFilename[MAX_PATH], WORD wCharsPerLine, WORD wNumLines); GFX3D9_EXPORTS HD3DFONT CreateD3DFontFromTexture( LPDIRECT3DDEVICE9 lpDevice, LPDIRECT3DTEXTURE9 lpTexture, WORD wCharsPerLine, WORD wNumLines); GFX3D9_EXPORTS BOOL InvalidateD3DFont( HD3DFONT hFont); GFX3D9_EXPORTS BOOL ValidateD3DFont( HD3DFONT hFont); GFX3D9_EXPORTS BOOL DeleteD3DFont( HD3DFONT hFont); GFX3D9_EXPORTS BOOL RenderD3DFontChar( HD3DFONT hFont, LONG nXDest, LONG nYDest, char cChar); GFX3D9_EXPORTS BOOL RenderD3DFontString( HD3DFONT hFont, LONG nXDest, LONG nYDest, char szString[]); GFX3D9_EXPORTS HD3DFONT CopyD3DFont( LPDIRECT3DDEVICE9 lpDevice, HD3DFONT hFontSrc); /* Console functionality. */ typedef HANDLE HBEEMCONSOLE; typedef BOOL ( * LPCOMMAND)(LPSTR szCommand, LPSTR szParams, HBEEMCONSOLE hConsole); GFX3D9_EXPORTS BOOL ScrollBeemConsole( HBEEMCONSOLE hConsole, LONG lScrollDist); GFX3D9_EXPORTS BOOL ToggleActivateBeemConsole( HBEEMCONSOLE hConsole); GFX3D9_EXPORTS HBEEMCONSOLE CreateBeemConsole( LPDIRECT3DDEVICE9 lpDevice, HD3DFONT hFont, HD3DIMAGE hConsoleBG, LPCOMMAND CommandFunction); GFX3D9_EXPORTS BOOL DeleteBeemConsole( HBEEMCONSOLE hConsole); GFX3D9_EXPORTS BOOL InvalidateBeemConsole( HBEEMCONSOLE hConsole); GFX3D9_EXPORTS BOOL ValidateBeemConsole( HBEEMCONSOLE hConsole); GFX3D9_EXPORTS BOOL BeemConsoleClearEntries( HBEEMCONSOLE hConsole); GFX3D9_EXPORTS BOOL AddBeemConsoleEntry( HBEEMCONSOLE hConsole, LPSTR szEntry); GFX3D9_EXPORTS BOOL SendBeemConsoleCommand( HBEEMCONSOLE hConsole, LPSTR szCommandLine); GFX3D9_EXPORTS BOOL SendBeemConsoleMessage( HBEEMCONSOLE hConsole, LPSTR szMessage); GFX3D9_EXPORTS BOOL BeemConsoleOnChar( HBEEMCONSOLE hConsole, char cChar); GFX3D9_EXPORTS BOOL RenderBeemConsole( HBEEMCONSOLE hConsole); GFX3D9_EXPORTS BOOL BeemParseGetParam( LPSTR szParamOut, LPSTR szParams, WORD wParam); GFX3D9_EXPORTS BOOL BeemParseGetString( LPSTR szStringOut, LPSTR szString); GFX3D9_EXPORTS BOOL BeemParseGetFloat( FLOAT * lpValue, LPSTR szParams, WORD wParam); GFX3D9_EXPORTS BOOL BeemParseGetInt( LONG * lpValue, LPSTR szParams, WORD wParam); #define BEGINCHOICE if(0){ #define CHOICE(s) }else if( _stricmp(#s, szCommand)==0){ #define INVALIDCHOICE }else{ #define ENDCHOICE } /* InitD3D Initializes the device and backbuffer. */ GFX3D9_EXPORTS BOOL InitD3D( HWND hWndTarget, DWORD dwWidth, DWORD dwHeight, BOOL bWindowed, BOOL bVsync, D3DFORMAT d3dfFullScreenFormat, LPDIRECT3D9 lppD3D, LPDIRECT3DDEVICE9 * lppDevice, LPDIRECT3DSURFACE9 * lppBackSurface, D3DPRESENT_PARAMETERS * d3dSavedParams); /* CorrectWindowSize adjusts the client area of a window to specified size. */ GFX3D9_EXPORTS BOOL CorrectWindowSize( HWND hWnd, DWORD nWidth, DWORD nHeight, BOOL bWindowed, HMENU hMenu); GFX3D9_EXPORTS BOOL SetProjectionMatrix( LPDIRECT3DDEVICE9 lpDevice, DWORD dwWidth, DWORD dwHeight, FLOAT zn, FLOAT zf); GFX3D9_EXPORTS BOOL SetViewPort( LPDIRECT3DDEVICE9 lpDevice, DWORD dwWidth, DWORD dwHeight); typedef enum tagD3DFILTER{ D3DFILTER_POINT=0x00000000l, D3DFILTER_BILINEAR, D3DFILTER_TRILINEAR, D3DFILTER_ANISOTROPIC }D3DFILTER; GFX3D9_EXPORTS BOOL SetTextureFilter( LPDIRECT3DDEVICE9 lpDevice, DWORD Stage, D3DFILTER FilterMode); /* ValidateDevice validates the device and restores backbuffer. It also calls a RestoreGraphics function if one is specified. */ typedef BOOL ( * POOLFN)(); GFX3D9_EXPORTS BOOL ValidateDevice( LPDIRECT3DDEVICE9 * lppDevice, LPDIRECT3DSURFACE9 * lppBackSurface, D3DPRESENT_PARAMETERS d3dpp, POOLFN fpReleasePool, POOLFN fpRestorePool); GFX3D9_EXPORTS BOOL ScreenSwitch( DWORD dwWidth, DWORD dwHeight, BOOL bWindowed, D3DFORMAT FullScreenFormat, BOOL bVsync, LPDIRECT3DDEVICE9 lpDevice, LPDIRECT3DSURFACE9 * lppBackSurface, D3DPRESENT_PARAMETERS * lpSavedParams, POOLFN fpReleasePool, POOLFN fpRestorePool); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __GFX3D9_H__ */<file_sep>/games/Explor2002/Source/ExplorED/Mapboard.h #ifndef __MAPBOARD_H__ #define __MAPBOARD_H__ //We need to pack the stucts to 1 so they read/write correctly. #pragma pack(1) typedef unsigned short USHORT; typedef struct eMapHeader { char mapType[2]; unsigned short mapVersion; unsigned long mapFileSize; unsigned short mapReserved1; unsigned short mapReserved2; unsigned short mapWidth; unsigned short mapHeight; unsigned long mapDataSize; unsigned long mapTileDataSize; unsigned long mapPropertyDataSize; unsigned short mapNumProperty; } MAPHEADER; typedef class ExplorMap { public: ExplorMap(); ~ExplorMap(); private: USHORT * tiles; USHORT * prop; MAPHEADER fileHeader; unsigned short tbase(int tx, int ty)const; public: int saveMap(char openmap[_MAX_PATH]); int resetBoard(void); int openMap(char openmap[_MAX_PATH]); int boardEdit(int x, int y, unsigned int propnum, unsigned int newvalue); int boardEdit(int x, int y); char boardname[_MAX_PATH]; USHORT getTileStat(int x, int y, int propnum)const; USHORT getTileStat(int x, int y)const; unsigned short getMapWidth(void)const; unsigned short getMapHeight(void)const; unsigned short getNumProperty(void)const; } EXPLORMAP; #endif <file_sep>/games/Legacy-Engine/Source/engine/lg_stack.h #ifndef __LG_STACK_H__ #define __LG_STACK_H__ #include "lg_types.h" #include "memory.h" template <class T> class CLStack{ private: lg_dword m_nSize; lg_dword m_nPointer; T* m_pStack; T m_objDummy; public: CLStack():m_nSize(10), m_nPointer(0) { m_pStack = new T[m_nSize]; memset(&m_objDummy, 0, sizeof(T)); } CLStack(lg_dword nSize):m_nSize(nSize), m_nPointer(0) { m_pStack = new T[m_nSize]; memset(&m_objDummy, 0, sizeof(T)); } ~CLStack() { if(m_pStack) delete[]m_pStack; } void Push(T obj) { if(m_nPointer<m_nSize) m_pStack[m_nPointer++]=obj; } T Peek() { if(m_nPointer>0) return m_pStack[m_nPointer-1]; else return m_objDummy; } T Pop() { if(m_nPointer>0) return m_pStack[--m_nPointer]; else return m_objDummy; } lg_bool IsEmpty() { return m_nPointer>0?LG_FALSE:LG_TRUE; } }; #endif //__LG_STACK__<file_sep>/games/Legacy-Engine/Source/engine/lg_list_stack.cpp //See header file for instructions. #include "lg_list_stack.h" //We keep track of a ID identifier which //is assigned to each list, that way we can //distinguish lists, so that we can identify //to what list a node belongs. lg_dword CLListStack::s_nNextID=811983; CLListStack::CLListStack(): m_nID(s_nNextID++), m_pFirst(LG_NULL), m_pLast(LG_NULL), m_nCount(0) {} CLListStack::~CLListStack() {} CLListStack::LSItem* CLListStack::Pop() { if(!m_pFirst) return LG_NULL; CLListStack::LSItem* pRes=m_pFirst; //Removing the first node is a special case. m_pFirst=m_pFirst->m_pNext; //If the first node was also the last node then we also //need to set the last node to null. if(m_pFirst==LG_NULL) { m_pLast=LG_NULL; } else { //The first node's previous must be set to null. m_pFirst->m_pPrev=LG_NULL; } m_nCount--; pRes->m_nListStackID=0; return pRes; } CLListStack::LSItem* CLListStack::Peek() { return m_pFirst; } void CLListStack::Push(CLListStack::LSItem* pNode) { #if 0 if(pNode->m_nListStackID!=0) { //Warning the node was still in a list. } #endif pNode->m_pPrev=LG_NULL; pNode->m_pNext=m_pFirst; pNode->m_nListStackID=m_nID; if(m_pFirst) { m_pFirst->m_pPrev=pNode; } else { m_pLast=pNode; } m_pFirst=pNode; m_nCount++; } lg_bool CLListStack::IsEmpty() { return m_pFirst?LG_FALSE:LG_TRUE; } void CLListStack::Clear() { for(LSItem* pNode=m_pFirst; pNode; pNode=pNode->m_pNext) { pNode->m_nListStackID=0; } m_pFirst=LG_NULL; m_pLast=LG_NULL; m_nCount=0; } void CLListStack::Remove(CLListStack::LSItem* pNode) { //If this node wasn't even in this list, we just //return. if(pNode->m_nListStackID!=m_nID) { return; } if(pNode==m_pFirst) { //Removing the first node is a special case. m_pFirst=m_pFirst->m_pNext; //If the first node was also the last node then we also //need to set the last node to null. if(m_pFirst==LG_NULL) { m_pLast=LG_NULL; } else { //The first node's previous must be set to null. m_pFirst->m_pPrev=LG_NULL; } } else if(pNode==m_pLast) { //The last node is also a special case, but we know it isn't the only //node in the list because that would have been checked above. m_pLast=m_pLast->m_pPrev; m_pLast->m_pNext=LG_NULL; } else { //One problem here is that it isn't gauranteed that pNode //was actually in pList, but it is a quick way to remove //a node, the id check above should prevent weird removals. if(pNode->m_pPrev && pNode->m_pNext) { pNode->m_pPrev->m_pNext=pNode->m_pNext; pNode->m_pNext->m_pPrev=pNode->m_pPrev; } } m_nCount--; } void CLListStack::Init(CLListStack::LSItem* pList, lg_dword nCount, lg_dword nItemSize) { this->Clear(); for(lg_dword i=0; i<nCount; i++) { LSItem* pCurItem=(LSItem*)((lg_byte*)pList+i*nItemSize); pCurItem->m_nListStackID=0; pCurItem->m_nItemID=i; Push(pCurItem); /* pList[i].m_nListStackID=0; Push(&pList[i]); */ } }<file_sep>/games/Legacy-Engine/Source/engine/lv_sys.cpp //lv_sys.cpp Copyright (c) 2007 <NAME> //This is the legacy video system, the methods here //are used to initialize CElementD3D elements for use //throughout the game. #include "lv_sys.h" #include "lg_err.h" #include "lg_cvars.h" #include "lg_func.h" #include "../lc_sys2/lc_sys2.h" CLVideo::CLVideo()//: //s_cvars(LG_NULL) { } CLVideo::~CLVideo() { } lg_bool CLVideo::SetStates() { /* If there is no device, there is no point in setting any sampler states. */ if(!s_pDevice) return LG_FALSE; /*********************** Set the filter mode. ************************/ SetFilterMode((lg_int)CV_Get(CVAR_v_TextureFilter)->nValue, 0); if(CV_Get(CVAR_v_DebugWireframe)->nValue) { IDirect3DDevice9_SetRenderState(s_pDevice, D3DRS_FILLMODE, D3DFILL_WIREFRAME); } else { IDirect3DDevice9_SetRenderState(s_pDevice, D3DRS_FILLMODE, D3DFILL_SOLID); } return LG_TRUE; } lg_bool CLVideo::SetFilterMode(lg_int nFilterMode, lg_dword dwStage) { switch(nFilterMode) { default: case FILTER_UNKNOWN: CV_Set(CV_Get(CVAR_v_TextureFilter), DEF_POINT); /* Fall through and set filter mode to point. */ case FILTER_POINT: /* 1 is point filtering, see LG_RegisterCVars(). */ IDirect3DDevice9_SetSamplerState(s_pDevice, dwStage, D3DSAMP_MAGFILTER, D3DTEXF_POINT); IDirect3DDevice9_SetSamplerState(s_pDevice, dwStage, D3DSAMP_MINFILTER, D3DTEXF_POINT); IDirect3DDevice9_SetSamplerState(s_pDevice, dwStage, D3DSAMP_MIPFILTER, D3DTEXF_POINT); break; case FILTER_BILINEAR: /* 2 is bilinear filtering. */ IDirect3DDevice9_SetSamplerState(s_pDevice, dwStage, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); IDirect3DDevice9_SetSamplerState(s_pDevice, dwStage, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); IDirect3DDevice9_SetSamplerState(s_pDevice, dwStage, D3DSAMP_MIPFILTER, D3DTEXF_POINT); break; case FILTER_TRILINEAR: /* 3 is trilinear filtering. */ IDirect3DDevice9_SetSamplerState(s_pDevice, dwStage, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); IDirect3DDevice9_SetSamplerState(s_pDevice, dwStage, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); IDirect3DDevice9_SetSamplerState(s_pDevice, dwStage, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR); break; case FILTER_ANISOTROPIC: /* 4 is anisotropic filtering. */ { lg_dword nMaxAnisotropy=0; D3DCAPS9 d3dcaps; memset(&d3dcaps, 0, sizeof(D3DCAPS9)); IDirect3DDevice9_GetDeviceCaps(s_pDevice, &d3dcaps); IDirect3DDevice9_SetSamplerState(s_pDevice, dwStage, D3DSAMP_MAGFILTER, D3DTEXF_ANISOTROPIC); IDirect3DDevice9_SetSamplerState(s_pDevice, dwStage, D3DSAMP_MINFILTER, D3DTEXF_ANISOTROPIC); IDirect3DDevice9_SetSamplerState(s_pDevice, dwStage, D3DSAMP_MIPFILTER, D3DTEXF_ANISOTROPIC); nMaxAnisotropy=(lg_dword)CV_Get(CVAR_v_MaxAnisotropy)->nValue; if((nMaxAnisotropy<1) || (nMaxAnisotropy>d3dcaps.MaxAnisotropy)) { nMaxAnisotropy=d3dcaps.MaxAnisotropy; CV_Set_l(CV_Get(CVAR_v_MaxAnisotropy), nMaxAnisotropy); } break; } } Err_Printf("Texture filter mode: %s", CV_Get(CVAR_v_TextureFilter)->szValue); return LG_TRUE; } /******************************************************************* LV_Restart() Resets the video with the present parameters located in the cvar list. This is called from LV_ValidateDevice() when the device gets reset, or when the user sends the VRESTART command to the console. ********************************************************************/ lg_bool CLVideo::Restart() { //All POOL_DEFAULT Direct3D items should be released //before calling Restart... D3DPRESENT_PARAMETERS pp; lg_bool bBackSurface=LG_FALSE; lg_result nResult=0; /* Reset the device. */ /* If there was a back surface invalidate it. */ if(s_pBackSurface) { s_pBackSurface->Release(); s_pBackSurface=LG_NULL; bBackSurface=LG_TRUE; } /* Reset the device. */ memset(&pp, 0, sizeof(pp)); SetPPFromCVars(&pp); /* Call reset. */ nResult=s_pDevice->Reset(&pp); Err_PrintDX("IDirect3DDevice9::Reset", nResult); if(LG_FAILED(nResult)) { return LG_FALSE; } else { Err_Printf("Reset Device With the following Present Parameters:"); PrintPP(&pp); if(bBackSurface) { nResult=s_pDevice->GetBackBuffer( 0, 0, D3DBACKBUFFER_TYPE_MONO, &(s_pBackSurface)); Err_PrintDX("IDirect3DDevice9::GetBackBuffer", nResult); } } s_nDisplayWidth=pp.BackBufferWidth; s_nDisplayHeight=pp.BackBufferHeight; return LG_TRUE; } //Direct3D Display Initialization: lg_bool CLVideo::Init(HWND hwnd) { m_hwnd=hwnd; if(s_pD3D) { Err_Printf("Video Init WARNING: IDirect3D interface exists at 0x%08X.", s_pD3D); Err_Printf(" Direct3D may have already been initialized, exiting LV_Init()..."); return LG_FALSE; } D3DPRESENT_PARAMETERS pp; lg_dword dwBehaviorFlags=0; lg_dword dwVertexProcFlag=0; lg_result nResult=0x00000000l; /* To initialize the video we need to create an IDirect3D interface, set the present parameters, then create the device. */ /* First create the IDirect3D interface. */ Err_Printf("Creating IDirect3D9 interface..."); s_pD3D=Direct3DCreate9(D3D_SDK_VERSION); if(s_pD3D) { Err_Printf("IDirect3D9 interface created at 0x%08X.", s_pD3D); } else { Err_Printf("Failed to create IDirect3D9 interface."); MessageBox( m_hwnd, "This application requires ""DirectX 9.0c", "Legacy", MB_OK|MB_ICONINFORMATION); return LG_FALSE; } /* Get the Direct3D setup parameters from the cvarlist. */ s_nAdapterID=(UINT)CV_Get(CVAR_v_AdapterID)->nValue; s_nDeviceType=(D3DDEVTYPE)(lg_int)CV_Get(CVAR_v_DeviceType)->nValue; dwVertexProcFlag=(lg_dword)CV_Get(CVAR_v_VertexProc)->nValue; dwBehaviorFlags=0; if(CV_Get(CVAR_v_FPU_Preserve)->nValue) dwBehaviorFlags|=D3DCREATE_FPU_PRESERVE; if(CV_Get(CVAR_v_MultiThread)->nValue) dwBehaviorFlags|=D3DCREATE_MULTITHREADED; if(CV_Get(CVAR_v_PureDevice)->nValue) dwBehaviorFlags|=D3DCREATE_PUREDEVICE; if(CV_Get(CVAR_v_DisableDriverManagement)->nValue) dwBehaviorFlags|=D3DCREATE_DISABLE_DRIVER_MANAGEMENT; if(CV_Get(CVAR_v_AdapterGroupDevice)->nValue) dwBehaviorFlags|=D3DCREATE_ADAPTERGROUP_DEVICE; //dwBehaviorFlags=0; Err_Printf("Flags 0x%08X", dwBehaviorFlags); /* Make sure the adapter is valid. */ if(s_nAdapterID >= s_pD3D->GetAdapterCount()) { Err_Printf( "Adapter %i not available, using default adapter.", s_nAdapterID); CV_Set(CV_Get(CVAR_v_AdapterID), DEF_ADAPTER_DEFAULT); s_nAdapterID=0; } /* Show the adapter identifier information. */ D3DADAPTER_IDENTIFIER9 adi; memset(&adi, 0, sizeof(adi)); s_pD3D->GetAdapterIdentifier(s_nAdapterID,0,&adi); Err_Printf("Using \"%s\".", adi.Description); /* We set the present parameters using the cvars. */ memset(&pp, 0, sizeof(pp)); Err_Printf("Initialzing present parameters from cvarlist..."); if(!SetPPFromCVars(&pp)) { Err_Printf("Could not initialize present parameters."); LG_SafeRelease(s_pD3D); return LG_FALSE; } Err_Printf("Present parameters initialization complete."); /* Check to see that the adapter type is available. */ nResult=s_pD3D->CheckDeviceType( s_nAdapterID, s_nDeviceType, pp.BackBufferFormat, pp.BackBufferFormat, pp.Windowed); if(LG_FAILED(nResult)) { Err_PrintDX("CheckDeviceType", nResult); Err_Printf("Cannot use selected device type, defaulting."); /* If the HAL device can't be used then CreateDevice will fail. */ s_nDeviceType=D3DDEVTYPE_HAL; } Err_Printf("Creating IDirect3DDevice9 interface..."); nResult=s_pD3D->CreateDevice( s_nAdapterID, s_nDeviceType, m_hwnd, dwBehaviorFlags|dwVertexProcFlag, &pp, &s_pDevice); Err_PrintDX("IDirect3D9::CreateDevice", nResult); /* If we failed to create the device, we can try a some different vertex processing modes, if it still fails we exit. */ while(LG_FAILED(nResult)) { if(dwVertexProcFlag==D3DCREATE_SOFTWARE_VERTEXPROCESSING) break; else if(dwVertexProcFlag==D3DCREATE_HARDWARE_VERTEXPROCESSING) { dwVertexProcFlag=D3DCREATE_MIXED_VERTEXPROCESSING; CV_Set(CV_Get(CVAR_v_VertexProc), DEF_MIXEDVP); } else { dwVertexProcFlag=D3DCREATE_SOFTWARE_VERTEXPROCESSING; CV_Set(CV_Get(CVAR_v_VertexProc), DEF_SWVP); } nResult=s_pD3D->CreateDevice( s_nAdapterID, s_nDeviceType, m_hwnd, dwBehaviorFlags|dwVertexProcFlag, &pp, &s_pDevice); Err_PrintDX("IDirect3D9::CreateDevice", nResult); } if(LG_SUCCEEDED(nResult)) { Err_Printf("IDirect3DDevice9 interface created at 0x%08X", s_pDevice); Err_Printf("Using the following Present Parameters:"); PrintPP(&pp); } else { Err_Printf("Failed to create IDirect3DDevice9 interface.", nResult); Err_Printf("Try software vertex processing."); LG_SafeRelease(s_pD3D);; return LG_FALSE; } s_nDisplayWidth=pp.BackBufferWidth; s_nDisplayHeight=pp.BackBufferHeight; Err_Printf("Calling SetStates..."); if(!SetStates()) Err_Printf("An error occured while setting the sampler and render states."); /* Call present to change the resolution.*/ /* Could load up a loading screen here!.*/ IDirect3DDevice9_Clear(s_pDevice, 0,0,D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER,0xFF5050FF,1.0f,0); IDirect3DDevice9_Present(s_pDevice, NULL, NULL, NULL, NULL); /* Display allowed formats, and also set a few cvars that control them. The allowed formats function only deals with the basic formats, not any advanced or compressed texture formats.*/ //SupportedTexFormats(); #if 0 LV_InitTexLoad(); #endif return LG_TRUE; } /********************************************************* LV_Shutdown() This uninitialized everything that was initialized in LV_Init(), it doesn't necessarly shut down other items that were initialized by Direct3D such as textures and vertex buffers used by in the game. This function should only be called after all Direct3D pool objects have been released. ***********************************************************/ void CLVideo::Shutdown() { lg_ulong nNumLeft=0; Err_Printf("Releasing IDirect3DDevice9 interface..."); if(s_pDevice) { nNumLeft=s_pDevice->Release(); Err_Printf( "Released IDirect3DDevice9 interface at 0x%08X with %i references left.", s_pDevice, nNumLeft); s_pDevice=LG_NULL; } Err_Printf("Releasing IDirect3D9 interface..."); if(s_pD3D) { nNumLeft=s_pD3D->Release(); Err_Printf( "Released IDirect3D9 interface at 0x%08X with %i references left.", s_pD3D, nNumLeft); s_pD3D=LG_NULL; } } #if 0 lg_bool CLVideo::SupportedTexFormats() { lg_result nResult=0; Err_Printf("Supported Texture Formats:"); /* We check to see which texture formats are supported, we are only checking the ones that we plan on using in this application. We set appropriate cvars for the texture formats, so that when we call the texture loading funcitons, they can check the cvars to determine what format to generate the textrues. This code is not bug proof as it doesn't set an cvars that note that D3DFMT_R5G6B5 textures are supported, it just assumes they are supported (pretty much all video cards I've encountered support this format that is why I assume it will work.*/ #define TEX_CHECK(fmt) IDirect3D9_CheckDeviceFormat(s_pD3D,s_nAdapterID,s_nDeviceType,s_nBackBufferFormat,0,D3DRTYPE_TEXTURE, fmt); nResult=TEX_CHECK(D3DFMT_A8R8G8B8); if(LG_FAILED(nResult))CV_Set(CV_Get(CVAR_tm_32BitTextureAlpha), DEF_FALSE); else Err_Printf(" %s", CLVideo::D3DFMTToString(D3DFMT_A8R8G8B8)); nResult=TEX_CHECK(D3DFMT_X8R8G8B8) if(LG_FAILED(nResult))CV_Set(CV_Get(CVAR_tm_Force16BitTextures), DEF_TRUE); else Err_Printf(" %s", CLVideo::D3DFMTToString(D3DFMT_X8R8G8B8)); nResult=TEX_CHECK(D3DFMT_A1R5G5B5) if(LG_FAILED(nResult))CV_Set(CV_Get(CVAR_tm_16BitTextureAlpha), DEF_FALSE); else Err_Printf(" %s", CLVideo::D3DFMTToString(D3DFMT_A1R5G5B5)); nResult=TEX_CHECK(D3DFMT_X1R5G5B5) if(LG_SUCCEEDED(nResult))Err_Printf(" %s", CLVideo::D3DFMTToString(D3DFMT_X1R5G5B5)); nResult=TEX_CHECK(D3DFMT_R5G6B5) if(LG_SUCCEEDED(nResult))Err_Printf(" %s", CLVideo::D3DFMTToString(D3DFMT_R5G6B5)); return LG_TRUE; } #endif lg_bool CLVideo::SetPPFromCVars(D3DPRESENT_PARAMETERS* pp) { //CVar* cvar=NULL; DWORD dwFlags=0; lg_long nBackBufferFmt=0; lg_dword nBitDepth=0; lg_result nResult=0; lg_dword nQualityLevels=0; if(!pp) return LG_FALSE; /* This function will attemp to get the appropriate values for the present parameters from the cvars, if it can't get the cvar it will SET_PP_FROM_CVAR an appropriate default value, that should work on most systems. */ #define SET_PP_FROM_CVAR(prpr, cvarname, defvalue, type) {cvar=CV_Get(cvarname);\ pp->prpr=cvar?(type)cvar->nValue:defvalue;} lg_cvar* cvar; SET_PP_FROM_CVAR(BackBufferWidth, CVAR_v_Width, 640, UINT); SET_PP_FROM_CVAR(BackBufferHeight, CVAR_v_Height, 480, UINT); /* Create the back buffer format. */ cvar=CV_Get(CVAR_v_BitDepth); if(cvar)nBitDepth=(int)cvar->nValue; /* Transform the bit depth to a D3DFORMAT, not if the bit depth is not valid, we just go for D3DFMT_R5G6B5.*/ if(nBitDepth==32) pp->BackBufferFormat=D3DFMT_X8R8G8B8; else if(nBitDepth==16) pp->BackBufferFormat=D3DFMT_R5G6B5; else if(nBitDepth==15) pp->BackBufferFormat=D3DFMT_X1R5G5B5; else { nBitDepth=16; pp->BackBufferFormat=D3DFMT_R5G6B5; CV_Set_l(CV_Get(CVAR_v_BitDepth), 16); } SET_PP_FROM_CVAR(BackBufferCount, CVAR_v_ScreenBuffers, 1, UINT); SET_PP_FROM_CVAR(SwapEffect, CVAR_v_SwapEffect, D3DSWAPEFFECT_DISCARD, D3DSWAPEFFECT); pp->hDeviceWindow=m_hwnd; nQualityLevels=(int)CV_Get(CVAR_v_FSAAQuality)->nValue; SET_PP_FROM_CVAR(Windowed, CVAR_v_Windowed, LG_FALSE, BOOL); SET_PP_FROM_CVAR(EnableAutoDepthStencil, CVAR_v_EnableAutoDepthStencil, TRUE, BOOL); SET_PP_FROM_CVAR(AutoDepthStencilFormat, CVAR_v_AutoDepthStencilFormat, D3DFMT_D16, D3DFORMAT); /* Set the flags. */ cvar=CV_Get(CVAR_v_LockableBackBuffer); if(cvar) if(cvar->nValue) dwFlags|=D3DPRESENTFLAG_LOCKABLE_BACKBUFFER; cvar=CV_Get(CVAR_v_DiscardDepthStencil); if(cvar) if(cvar->nValue) dwFlags|=D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL; cvar=CV_Get(CVAR_v_DeviceClip); if(cvar) if(cvar->nValue) dwFlags|=D3DPRESENTFLAG_DEVICECLIP; cvar=CV_Get(CVAR_v_VideoHint); if(cvar) if(cvar->nValue) dwFlags|=D3DPRESENTFLAG_VIDEO; pp->Flags=dwFlags; SET_PP_FROM_CVAR(FullScreen_RefreshRateInHz, CVAR_v_RefreshRate, D3DPRESENT_RATE_DEFAULT, UINT); pp->PresentationInterval = CV_Get(CVAR_v_EnableVSync)->nValue? D3DPRESENT_INTERVAL_ONE: D3DPRESENT_INTERVAL_IMMEDIATE; /* Now we do need to make some adjustment depending on some of the cvars. */ /* If we are windowed we need to set certain presentation parameters. */ if(pp->Windowed) { D3DDISPLAYMODE dmode; memset(&dmode, 0, sizeof(dmode)); //pp->PresentationInterval=0; CorrectWindowSize( m_hwnd, pp->BackBufferWidth, pp->BackBufferHeight); s_pD3D->GetAdapterDisplayMode( s_nAdapterID, &dmode); pp->BackBufferFormat=dmode.Format; } if(!nQualityLevels) { pp->MultiSampleType=D3DMULTISAMPLE_NONE; pp->MultiSampleQuality=0; } else { pp->MultiSampleType=D3DMULTISAMPLE_NONMASKABLE; pp->MultiSampleQuality=nQualityLevels-1; nQualityLevels=0; /* Check if multisample type is available. */ s_pD3D->CheckDeviceMultiSampleType( s_nAdapterID, s_nDeviceType, pp->BackBufferFormat, pp->Windowed, pp->MultiSampleType, &nQualityLevels); if(LG_FAILED(nResult)) { Err_Printf("FSAA mode not allowed, using default."); pp->MultiSampleType=D3DMULTISAMPLE_NONE; pp->MultiSampleQuality=0; CV_Set_l(CV_Get(CVAR_v_FSAAQuality), 0); } else { if(pp->MultiSampleQuality>=nQualityLevels) { pp->MultiSampleQuality=nQualityLevels-1; } //Err_Printf("FSAA Sample Quality set to: %i", pp->MultiSampleQuality+1); } if((pp->MultiSampleType>0) && (pp->SwapEffect!=D3DSWAPEFFECT_DISCARD)) { Err_Printf("FSAA not allowed unless swap effect is DISCARD."); pp->MultiSampleType=D3DMULTISAMPLE_NONE; pp->MultiSampleQuality=0; } if((pp->MultiSampleType>0) && (LG_CheckFlag(dwFlags, D3DPRESENTFLAG_LOCKABLE_BACKBUFFER))) { Err_Printf("FSAA not allowed with Lockable Back Buffer."); pp->MultiSampleType=D3DMULTISAMPLE_NONE; pp->MultiSampleQuality=0; } } /* Check to see if the display format is supported. */ /* Make sure the display mode is valid. */ /* If we are windowed we need to set certain values. */ if(pp->Windowed) { pp->FullScreen_RefreshRateInHz=0; s_nBackBufferFormat=pp->BackBufferFormat; } /* Make sure the format is valid. */ if(!pp->Windowed) { lg_uint nCount=0; lg_uint i=0; lg_bool bDisplayAllowed=LG_FALSE; D3DDISPLAYMODE dmode; memset(&dmode, 0, sizeof(dmode)); if(s_pD3D->GetAdapterModeCount( s_nAdapterID, pp->BackBufferFormat)<1) { /* We are assuming that the device supports the R5G6B5 format, if not then IDirect3D::CreateDevice will fail and we can't do anything. */ pp->BackBufferFormat=D3DFMT_R5G6B5; CV_Set_l(CV_Get(CVAR_v_BitDepth), 16); Err_Printf("Could not use selected bit depth, defaulting."); } nCount=s_pD3D->GetAdapterModeCount( s_nAdapterID, pp->BackBufferFormat); if(nCount<1) { Err_Printf("Cannot find a suitable display mode."); return 0; } for(i=0, bDisplayAllowed=LG_FALSE; i<nCount; i++) { s_pD3D->EnumAdapterModes( s_nAdapterID, pp->BackBufferFormat, i, &dmode); if((dmode.Width==pp->BackBufferWidth) && (dmode.Height==pp->BackBufferHeight)) { /* The display mode is acceptable. */ bDisplayAllowed=LG_TRUE; break; } } if(!bDisplayAllowed) { Err_Printf( "The display mode of %ix%i is not allowed, defaulting.", pp->BackBufferWidth, pp->BackBufferHeight); /* We are assuming 640x480 will work, if not, then IDirect3D9::CreateDevice will fail anyway. */ pp->BackBufferWidth=640; pp->BackBufferHeight=480; CV_Set_l(CV_Get(CVAR_v_Width), 640); CV_Set_l(CV_Get(CVAR_v_Height), 480); } s_nBackBufferFormat=pp->BackBufferFormat; } return LG_TRUE; } void CLVideo::PrintPP(D3DPRESENT_PARAMETERS* pp) { Err_Printf(" Resolution: %iX%iX%i(%s) at %iHz, %s", pp->BackBufferWidth, pp->BackBufferHeight, D3DFMTToBitDepth(pp->BackBufferFormat), D3DFMTToString(pp->BackBufferFormat), pp->FullScreen_RefreshRateInHz, pp->Windowed?"WINDOWED":"FULL SCREEN"); Err_Printf(" FSAA %s (%i)", pp->MultiSampleType==D3DMULTISAMPLE_NONE?"Disabled":"Enabled", pp->MultiSampleQuality); Err_Printf(" Back Buffers: %i, Swap Effect: %s", pp->BackBufferCount, pp->SwapEffect==D3DSWAPEFFECT_DISCARD?"DISCARD":pp->SwapEffect==D3DSWAPEFFECT_FLIP?"FLIP":"COPY"); Err_Printf(" Flags: %s%s%s%s", LG_CheckFlag(pp->Flags, D3DPRESENTFLAG_DEVICECLIP)?"DEVICECLIP ":"", LG_CheckFlag(pp->Flags, D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL)?"DISCARD_DEPTHSTRENCIL ":"", LG_CheckFlag(pp->Flags, D3DPRESENTFLAG_LOCKABLE_BACKBUFFER)?"LOCKABLE_BACKBUFFER ":"", LG_CheckFlag(pp->Flags, D3DPRESENTFLAG_VIDEO)?"VIDEO ":""); Err_Printf(" Device Window At 0x%08X", pp->hDeviceWindow); Err_Printf(" Auto Depth Stencil %s (%s)", pp->EnableAutoDepthStencil?"Enabled":"Disabled", D3DFMTToString(pp->AutoDepthStencilFormat)); if(pp->PresentationInterval==0x80000000) Err_Printf(" Presentation Interval: IMMEDIATE"); else Err_Printf(" Presentation Interval: %d", pp->PresentationInterval); } lg_dword CLVideo::D3DFMTToBitDepth(D3DFORMAT fmt) { #define FMT_TO_BITDEPTH(f, b) if(fmt==f)return b; FMT_TO_BITDEPTH(D3DFMT_UNKNOWN, 0) FMT_TO_BITDEPTH(D3DFMT_R8G8B8, 24) FMT_TO_BITDEPTH(D3DFMT_A8R8G8B8, 32) FMT_TO_BITDEPTH(D3DFMT_X8R8G8B8, 32) FMT_TO_BITDEPTH(D3DFMT_R5G6B5, 16) FMT_TO_BITDEPTH(D3DFMT_X1R5G5B5, 16) FMT_TO_BITDEPTH(D3DFMT_A1R5G5B5, 16) FMT_TO_BITDEPTH(D3DFMT_A4R4G4B4, 16) FMT_TO_BITDEPTH(D3DFMT_R3G3B2, 8) FMT_TO_BITDEPTH(D3DFMT_A8, 8) FMT_TO_BITDEPTH(D3DFMT_A8R3G3B2, 16) FMT_TO_BITDEPTH(D3DFMT_X4R4G4B4, 16) FMT_TO_BITDEPTH(D3DFMT_A2B10G10R10, 32) FMT_TO_BITDEPTH(D3DFMT_A8B8G8R8, 32) FMT_TO_BITDEPTH(D3DFMT_X8B8G8R8, 32) FMT_TO_BITDEPTH(D3DFMT_G16R16, 32) FMT_TO_BITDEPTH(D3DFMT_A2R10G10B10, 32) FMT_TO_BITDEPTH(D3DFMT_A16B16G16R16, 64) FMT_TO_BITDEPTH(D3DFMT_A8P8, 16) FMT_TO_BITDEPTH(D3DFMT_P8, 8) FMT_TO_BITDEPTH(D3DFMT_L8, 8) FMT_TO_BITDEPTH(D3DFMT_A8L8, 16) FMT_TO_BITDEPTH(D3DFMT_A4L4, 8) FMT_TO_BITDEPTH(D3DFMT_V8U8, 16) FMT_TO_BITDEPTH(D3DFMT_L6V5U5, 16) FMT_TO_BITDEPTH(D3DFMT_X8L8V8U8, 32) FMT_TO_BITDEPTH(D3DFMT_Q8W8V8U8, 32) FMT_TO_BITDEPTH(D3DFMT_V16U16, 32) FMT_TO_BITDEPTH(D3DFMT_A2W10V10U10, 32) FMT_TO_BITDEPTH(D3DFMT_UYVY, 0) FMT_TO_BITDEPTH(D3DFMT_R8G8_B8G8, 16) FMT_TO_BITDEPTH(D3DFMT_YUY2, 0) FMT_TO_BITDEPTH(D3DFMT_G8R8_G8B8, 16) FMT_TO_BITDEPTH(D3DFMT_DXT1, 32) FMT_TO_BITDEPTH(D3DFMT_DXT2, 32) FMT_TO_BITDEPTH(D3DFMT_DXT3, 32) FMT_TO_BITDEPTH(D3DFMT_DXT4, 32) FMT_TO_BITDEPTH(D3DFMT_DXT5, 32) FMT_TO_BITDEPTH(D3DFMT_D16_LOCKABLE, 16) FMT_TO_BITDEPTH(D3DFMT_D32, 32) FMT_TO_BITDEPTH(D3DFMT_D15S1, 16) FMT_TO_BITDEPTH(D3DFMT_D24S8, 32) FMT_TO_BITDEPTH(D3DFMT_D24X8, 32) FMT_TO_BITDEPTH(D3DFMT_D24X4S4, 32) FMT_TO_BITDEPTH(D3DFMT_D16, 16) FMT_TO_BITDEPTH(D3DFMT_D32F_LOCKABLE, 32) FMT_TO_BITDEPTH(D3DFMT_D24FS8, 32) FMT_TO_BITDEPTH(D3DFMT_L16, 16) FMT_TO_BITDEPTH(D3DFMT_VERTEXDATA, 0) FMT_TO_BITDEPTH(D3DFMT_INDEX16, 16) FMT_TO_BITDEPTH(D3DFMT_INDEX32, 32) FMT_TO_BITDEPTH(D3DFMT_Q16W16V16U16, 64) FMT_TO_BITDEPTH(D3DFMT_MULTI2_ARGB8, 32) FMT_TO_BITDEPTH(D3DFMT_R16F, 16) FMT_TO_BITDEPTH(D3DFMT_G16R16F, 32) FMT_TO_BITDEPTH(D3DFMT_A16B16G16R16F, 64) FMT_TO_BITDEPTH(D3DFMT_R32F, 32) FMT_TO_BITDEPTH(D3DFMT_G32R32F, 64) FMT_TO_BITDEPTH(D3DFMT_A32B32G32R32F, 128) FMT_TO_BITDEPTH(D3DFMT_CxV8U8, 16) return 0; } lg_dword CLVideo::StringToD3DFMT(lg_cstr szfmt) { #define STRING_TO_FMT(fmt) if(strnicmp((char*)szfmt, #fmt, 0)==0)return fmt; STRING_TO_FMT(D3DFMT_UNKNOWN) STRING_TO_FMT(D3DFMT_R8G8B8) STRING_TO_FMT(D3DFMT_A8R8G8B8) STRING_TO_FMT(D3DFMT_X8R8G8B8) STRING_TO_FMT(D3DFMT_R5G6B5) STRING_TO_FMT(D3DFMT_X1R5G5B5) STRING_TO_FMT(D3DFMT_A1R5G5B5) STRING_TO_FMT(D3DFMT_A4R4G4B4) STRING_TO_FMT(D3DFMT_R3G3B2) STRING_TO_FMT(D3DFMT_A8) STRING_TO_FMT(D3DFMT_A8R3G3B2) STRING_TO_FMT(D3DFMT_X4R4G4B4) STRING_TO_FMT(D3DFMT_A2B10G10R10) STRING_TO_FMT(D3DFMT_A8B8G8R8) STRING_TO_FMT(D3DFMT_X8B8G8R8) STRING_TO_FMT(D3DFMT_G16R16) STRING_TO_FMT(D3DFMT_A2R10G10B10) STRING_TO_FMT(D3DFMT_A16B16G16R16) STRING_TO_FMT(D3DFMT_A8P8) STRING_TO_FMT(D3DFMT_P8) STRING_TO_FMT(D3DFMT_L8) STRING_TO_FMT(D3DFMT_A8L8) STRING_TO_FMT(D3DFMT_A4L4) STRING_TO_FMT(D3DFMT_V8U8) STRING_TO_FMT(D3DFMT_L6V5U5) STRING_TO_FMT(D3DFMT_X8L8V8U8) STRING_TO_FMT(D3DFMT_Q8W8V8U8) STRING_TO_FMT(D3DFMT_V16U16) STRING_TO_FMT(D3DFMT_A2W10V10U10) STRING_TO_FMT(D3DFMT_UYVY) STRING_TO_FMT(D3DFMT_R8G8_B8G8) STRING_TO_FMT(D3DFMT_YUY2) STRING_TO_FMT(D3DFMT_G8R8_G8B8) STRING_TO_FMT(D3DFMT_DXT1) STRING_TO_FMT(D3DFMT_DXT2) STRING_TO_FMT(D3DFMT_DXT3) STRING_TO_FMT(D3DFMT_DXT4) STRING_TO_FMT(D3DFMT_DXT5) STRING_TO_FMT(D3DFMT_D16_LOCKABLE) STRING_TO_FMT(D3DFMT_D32) STRING_TO_FMT(D3DFMT_D15S1) STRING_TO_FMT(D3DFMT_D24S8) STRING_TO_FMT(D3DFMT_D24X8) STRING_TO_FMT(D3DFMT_D24X4S4) STRING_TO_FMT(D3DFMT_D16) STRING_TO_FMT(D3DFMT_D32F_LOCKABLE) STRING_TO_FMT(D3DFMT_D24FS8) STRING_TO_FMT(D3DFMT_L16) STRING_TO_FMT(D3DFMT_VERTEXDATA) STRING_TO_FMT(D3DFMT_INDEX16) STRING_TO_FMT(D3DFMT_INDEX32) STRING_TO_FMT(D3DFMT_Q16W16V16U16) STRING_TO_FMT(D3DFMT_MULTI2_ARGB8) STRING_TO_FMT(D3DFMT_R16F) STRING_TO_FMT(D3DFMT_G16R16F) STRING_TO_FMT(D3DFMT_A16B16G16R16F) STRING_TO_FMT(D3DFMT_R32F) STRING_TO_FMT(D3DFMT_G32R32F) STRING_TO_FMT(D3DFMT_A32B32G32R32F) STRING_TO_FMT(D3DFMT_CxV8U8) STRING_TO_FMT(D3DFMT_FORCE_DWORD) return D3DFMT_UNKNOWN; } lg_cstr CLVideo::D3DFMTToString(D3DFORMAT fmt) { #define FMT_TO_STRING(f) if(f==fmt)return #f; FMT_TO_STRING(D3DFMT_UNKNOWN) FMT_TO_STRING(D3DFMT_R8G8B8) FMT_TO_STRING(D3DFMT_A8R8G8B8) FMT_TO_STRING(D3DFMT_X8R8G8B8) FMT_TO_STRING(D3DFMT_R5G6B5) FMT_TO_STRING(D3DFMT_X1R5G5B5) FMT_TO_STRING(D3DFMT_A1R5G5B5) FMT_TO_STRING(D3DFMT_A4R4G4B4) FMT_TO_STRING(D3DFMT_R3G3B2) FMT_TO_STRING(D3DFMT_A8) FMT_TO_STRING(D3DFMT_A8R3G3B2) FMT_TO_STRING(D3DFMT_X4R4G4B4) FMT_TO_STRING(D3DFMT_A2B10G10R10) FMT_TO_STRING(D3DFMT_A8B8G8R8) FMT_TO_STRING(D3DFMT_X8B8G8R8) FMT_TO_STRING(D3DFMT_G16R16) FMT_TO_STRING(D3DFMT_A2R10G10B10) FMT_TO_STRING(D3DFMT_A16B16G16R16) FMT_TO_STRING(D3DFMT_A8P8) FMT_TO_STRING(D3DFMT_P8) FMT_TO_STRING(D3DFMT_L8) FMT_TO_STRING(D3DFMT_A8L8) FMT_TO_STRING(D3DFMT_A4L4) FMT_TO_STRING(D3DFMT_V8U8) FMT_TO_STRING(D3DFMT_L6V5U5) FMT_TO_STRING(D3DFMT_X8L8V8U8) FMT_TO_STRING(D3DFMT_Q8W8V8U8) FMT_TO_STRING(D3DFMT_V16U16) FMT_TO_STRING(D3DFMT_A2W10V10U10) FMT_TO_STRING(D3DFMT_UYVY) FMT_TO_STRING(D3DFMT_R8G8_B8G8) FMT_TO_STRING(D3DFMT_YUY2) FMT_TO_STRING(D3DFMT_G8R8_G8B8) FMT_TO_STRING(D3DFMT_DXT1) FMT_TO_STRING(D3DFMT_DXT2) FMT_TO_STRING(D3DFMT_DXT3) FMT_TO_STRING(D3DFMT_DXT4) FMT_TO_STRING(D3DFMT_DXT5) FMT_TO_STRING(D3DFMT_D16_LOCKABLE) FMT_TO_STRING(D3DFMT_D32) FMT_TO_STRING(D3DFMT_D15S1) FMT_TO_STRING(D3DFMT_D24S8) FMT_TO_STRING(D3DFMT_D24X8) FMT_TO_STRING(D3DFMT_D24X4S4) FMT_TO_STRING(D3DFMT_D16) FMT_TO_STRING(D3DFMT_D32F_LOCKABLE) FMT_TO_STRING(D3DFMT_D24FS8) FMT_TO_STRING(D3DFMT_L16) FMT_TO_STRING(D3DFMT_VERTEXDATA) FMT_TO_STRING(D3DFMT_INDEX16) FMT_TO_STRING(D3DFMT_INDEX32) FMT_TO_STRING(D3DFMT_Q16W16V16U16) FMT_TO_STRING(D3DFMT_MULTI2_ARGB8) FMT_TO_STRING(D3DFMT_R16F) FMT_TO_STRING(D3DFMT_G16R16F) FMT_TO_STRING(D3DFMT_A16B16G16R16F) FMT_TO_STRING(D3DFMT_R32F) FMT_TO_STRING(D3DFMT_G32R32F) FMT_TO_STRING(D3DFMT_A32B32G32R32F) FMT_TO_STRING(D3DFMT_CxV8U8) FMT_TO_STRING(D3DFMT_FORCE_DWORD) return "D3DFMT_UNKNOWN"; } #include <windowsx.h> lg_bool CLVideo::CorrectWindowSize( HWND hWnd, DWORD nWidth, DWORD nHeight) { RECT rc; SetRect(&rc, 0, 0, nWidth, nHeight); AdjustWindowRectEx( &rc, GetWindowStyle(hWnd), GetMenu(hWnd)!=NULL, GetWindowExStyle(hWnd)); SetWindowPos( hWnd, NULL, 0, 0, rc.right-rc.left, rc.bottom-rc.top, SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE); return LG_TRUE; } <file_sep>/readme.txt Beem Media Archive Depot ======================== This depot contains an archive of the software developed by Beem Media that are no longer in active development. Most of the code was engineered by Blaine Myers. Open source active projects are in other repositories, and closed source projects are on private servers. Most of this software is not particular useful (or even good) at this point and is obsolete or is superceded by active projects. The most interesting parts, in my opinion, are the QBasic games in the games directory. All content (c) 1997-2015 Beem Media unless otherwise noted. <file_sep>/games/Legacy-Engine/Source/lm_sys/lm_mesh_anim.cpp #include <string.h> #include "lm_mesh_anim.h" #include "lg_func.h" CLMeshAnim::CLMeshAnim() : CLMesh2() , m_pAnimMats(LG_NULL) , m_pAttachMats(LG_NULL) , m_pBoneRef(LG_NULL) { } CLMeshAnim::~CLMeshAnim() { DeleteAnimData(); } lg_bool CLMeshAnim::InitAnimData() { //Make sure the data is deleted... DeleteAnimData(); //Prepare the joints for rendering. m_pAnimMats=new ML_MAT[m_nNumBones*2]; memset( m_pAnimMats , 0 , sizeof(*m_pAnimMats)*m_nNumBones*2 ); m_pAttachMats=&m_pAnimMats[m_nNumBones]; //Set up the bone references m_pBoneRef=new lg_dword[m_nNumBones]; memset( m_pBoneRef , 0 , sizeof(*m_pBoneRef)*m_nNumBones ); //We we couldn't allocate memory //the make sure no memory is allocated an return. if(!m_pAnimMats || !m_pBoneRef) { DeleteAnimData(); return LG_FALSE; } for(lg_dword i=0; i<m_nNumBones; i++) m_pBoneRef[i]=i; return LG_TRUE; } lg_void CLMeshAnim::DeleteAnimData() { if(m_pAnimMats){delete[]m_pAnimMats;} if(m_pBoneRef){delete[]m_pBoneRef;} m_pAnimMats=LG_NULL; m_pAttachMats=LG_NULL; m_pBoneRef=LG_NULL; } lg_void CLMeshAnim::SetupDefFrame() { for(lg_dword i=0; i<m_nNumBones*2; i++) ML_MatIdentity(&m_pAnimMats[i]); } /********************************************************************** *** Technically the prepare frame functions should *** get a compatible skeleton, not all skeleton's are compatible *** with every model so in the future there will be a method to *** check compatibility, but this should not be called every frame *** as it would only use unecessary processor power, instead *** it is up to the the programmer to make sure a skeleton is *** compatible before using it for rendering, as the function stands *** right now the PrepareFrame functions simply try to prepare a *** frame based off joint references ***********************************************************************/ lg_void CLMeshAnim::SetupFrame(lg_dword dwFrame1, lg_dword dwFrame2, lg_float t, CLSkel2* pSkel) { if(!pSkel || !pSkel->IsLoaded()) { SetupDefFrame(); return; } ML_MAT* pJointTrans=(ML_MAT*)m_pAnimMats; //Prepare each joints final transformation matrix. for(lg_dword i=0; i<m_nNumBones; i++) { //To calculate the interpolated transform matrix //we need only call MCSkel's GenerateJointTransform method. pSkel->GenerateJointTransform(&pJointTrans[i], m_pBoneRef[i], dwFrame1, dwFrame2, t); //We don't necessarily need to setup attachment matrices for every bone (only for the //ones that actually get objects attached to them), but for now we set them up for //all bone anyway. ML_MatMultiply(&m_pAttachMats[i], pSkel->GetBaseTransform(m_pBoneRef[i]), &pJointTrans[i]); } return; } //TransformVerts is called to actually transform //all the vertices in the mesh based upon the joint transforms. lg_void CLMeshAnim::DoTransform() { //Don't need to do the transform if the mesh isn't loaded. if(!LG_CheckFlag(m_nFlags, LM_FLAG_LOADED)) return; //Lock the vertex buffer to prepare to write the data. MeshVertex* pVerts=LockTransfVB(); //If we couldn't lock the buffer, there is nothing we can do. if(!pVerts) return; //Now that the transformations are all set up, //all we have to do is multiply each vertex by the //transformation matrix for it's joint. Note that //the texture coordinates have already been established //so they are not recopyed here. for(lg_dword i=0; i<m_nNumVerts; i++) { //Copy the vertex we want. //memcpy(&pVerts[i], &m_pVertices[i], sizeof(LMESH_VERTEX)); //If the vertex's bone is -1 it means that it is //not attached to a joint so we don't need to transform it. if(m_pVertBoneList[i]!=-1) { //Multiply each vertex by it's joints transform. ML_Vec3TransformCoord((ML_VEC3*)&pVerts[i].x, (ML_VEC3*)&m_pVerts[i].x, &m_pAnimMats[m_pVertBoneList[i]]); //Do the same for each vertex's normal, but we don't transorm by the //x,y,z.. so we call Vec3TransformNormal instead of Coord. ML_Vec3TransformNormal((ML_VEC3*)&pVerts[i].nx, (ML_VEC3*)&m_pVerts[i].nx, &m_pAnimMats[m_pVertBoneList[i]]); } } //We've written all the vertices so lets unlock the VB. UnlockTransfVB(); return; } //TransitionTo should be called after a Setup* call, //it will generate transforms to transform the current frame to the new animation. //DoTransform must be called again afterwards. lg_void CLMeshAnim::TransitionTo(lg_dword nAnim, lg_float fTime, CLSkel2* pSkel) { const CLSkel2::SkelAnim* pAnim=pSkel->GetAnim(nAnim); for(lg_dword i=0; i<m_nNumBones; i++) { ML_MAT matTemp; ML_MAT matTemp2; pSkel->GenerateJointTransform(&matTemp, m_pBoneRef[i], pAnim->nFirstFrame, pAnim->nFirstFrame, 0.0f); ML_MatMultiply(&matTemp2, pSkel->GetBaseTransform(m_pBoneRef[i]), &matTemp); ML_MatSlerp(&m_pAnimMats[i], &m_pAnimMats[i], &matTemp, fTime); ML_MatSlerp(&m_pAttachMats[i], &m_pAttachMats[i], &matTemp2, fTime); } } lg_dword CLMeshAnim::GetJointRef(lg_cstr szJoint) { for(lg_dword i=0; i<m_nNumBones; i++) { if(_stricmp(m_pBoneNameList[i], szJoint)==0) return i; } return 0xFFFFFFFF; } const ML_MAT* CLMeshAnim::GetJointTransform(lg_dword nRef) { if(nRef<m_nNumBones) return &m_pAnimMats[nRef]; else return &ML_matIdentity; } const ML_MAT* CLMeshAnim::GetJointAttachTransform(lg_dword nRef) { if(nRef<m_nNumBones) return &m_pAttachMats[nRef];//&m_pAnimMats[nRef+m_nNumBones]; else return LG_NULL; } //This verison of prepare frames takes an animation and //it wants a value from 0.0f to 100.0f. 0.0f would be //the first frame of the animation, and 100.0f would also //be the first frame of the animation. lg_void CLMeshAnim::SetupFrame(lg_dword nAnim, lg_float fTime, CLSkel2* pSkel) { lg_dword nFrame1, nFrame2; nFrame1=pSkel->GetFrameFromTime(nAnim, fTime, &fTime, &nFrame2); SetupFrame(nFrame1, nFrame2, fTime, pSkel); } lg_void CLMeshAnim::SetCompatibleWith(CLSkel2* pSkel) { if(!pSkel || !pSkel->IsLoaded()) return; for(lg_dword i=0; i<m_nNumBones; i++) { for(lg_dword j=0; j<pSkel->m_nNumJoints; j++) { if(_stricmp(m_pBoneNameList[i], pSkel->m_pBaseSkeleton[j].szName)==0) { m_pBoneRef[i]=j; j=pSkel->m_nNumJoints+1; } } } } <file_sep>/tools/fs_sys2/fs_c_interface.cpp //fs_c_interface.cpp - Code for the C interface for the file system. #include "fs_fs2.h" CLFileSystem* g_pFS=FS_NULL; //A testing function, this will not be the final directory listing function extern "C" void FS_PrintMountInfo(FS_PRINT_MOUNT_INFO_TYPE Type) { g_pFS->PrintMountInfo(Type); } //File system function (c-interface). extern "C" fs_bool FS_Initialize(FS_ALLOC_FUNC pAlloc, FS_FREE_FUNC pFree) { if(!pAlloc || !pFree) __debugbreak(); if(pAlloc && pFree) FS_SetMemFuncs(pAlloc, pFree); g_pFS=new CLFileSystem; if(!g_pFS) { FS_ErrPrintW(L"FS_Initalize Error: Not enough memory.", ERR_LEVEL_ERROR); return FS_FALSE; } return FS_TRUE; } extern "C" fs_bool FS_Shutdown() { if(!g_pFS) return FS_FALSE; fs_bool bResult=g_pFS->UnMountAll(); delete g_pFS; g_pFS=FS_NULL; return bResult; } extern "C" fs_dword FS_MountBaseA(fs_cstr8 szOSPath) { return g_pFS->MountBaseA(szOSPath); } extern "C" fs_dword FS_MountBaseW(fs_cstr16 szOSPath) { return g_pFS->MountBaseW(szOSPath); } extern "C" fs_dword FS_MountA(fs_cstr8 szOSPath, fs_cstr8 szMountPath, fs_dword Flags) { return g_pFS->MountA(szOSPath, szMountPath, Flags); } extern "C" fs_dword FS_MountW(fs_cstr16 szOSPath, fs_cstr16 szMountPath, fs_dword Flags) { return g_pFS->MountW(szOSPath, szMountPath, Flags); } extern "C" fs_bool FS_ExistsA(fs_cstr8 szFilename) { return g_pFS->ExistsA(szFilename); } extern "C" fs_bool FS_ExistsW(fs_cstr16 szFilename) { return g_pFS->ExistsW(szFilename); } extern "C" fs_dword FS_MountLPKA(fs_cstr8 szMountedFile, fs_dword Flags) { return g_pFS->MountLPKA(szMountedFile, Flags); } extern "C" fs_dword FS_MountLPKW(fs_cstr16 szMountedFile, fs_dword Flags) { return g_pFS->MountLPKW(szMountedFile, Flags); } extern "C" fs_bool FS_UnMountAll() { return g_pFS->UnMountAll(); } //File access functions c-interface. extern "C" LF_FILE3 LF_OpenA(fs_cstr8 szFilename, fs_dword Access, fs_dword CreateMode) { return g_pFS->OpenFileA(szFilename, Access, CreateMode); } extern "C" LF_FILE3 LF_OpenW(fs_cstr16 szFilename, fs_dword Access, fs_dword CreateMode) { return g_pFS->OpenFileW(szFilename, Access, CreateMode); } extern "C" fs_bool LF_Close(LF_FILE3 File) { return g_pFS->CloseFile((CLFile*)File); } extern "C" fs_dword LF_Read(LF_FILE3 File, void* pOutBuffer, fs_dword nSize) { CLFile* pFile=(CLFile*)File; return pFile->Read(pOutBuffer, nSize); } extern "C" fs_dword LF_Write(LF_FILE3 File, const void* pInBuffer, fs_dword nSize) { CLFile* pFile=(CLFile*)File; return pFile->Write(pInBuffer, nSize); } extern "C" fs_dword LF_Tell(LF_FILE3 File) { CLFile* pFile=(CLFile*)File; return pFile->Tell(); } extern "C" fs_dword LF_Seek(LF_FILE3 File, LF_SEEK_TYPE nMode, fs_long nOffset) { CLFile* pFile=(CLFile*)File; return pFile->Seek(nMode, nOffset); } extern "C" fs_dword LF_GetSize(LF_FILE3 File) { CLFile* pFile=(CLFile*)File; return pFile->GetSize(); } extern "C" const void* LF_GetMemPointer(LF_FILE3 File) { CLFile* pFile=(CLFile*)File; return pFile->GetMemPointer(); } extern "C" fs_bool LF_IsEOF(LF_FILE3 File) { CLFile* pFile=(CLFile*)File; return pFile->IsEOF(); } extern "C" void FS_EnumerateFilesOfTypeA( fs_cstr8 Ext , FS_ENUMERATE_FUNCA EnumerateFunc , void* Data ) { return g_pFS->EnumerateFilesOfTypeA( Ext , EnumerateFunc, Data ); } extern "C" void FS_EnumerateFilesOfTypeW( fs_cstr16 Ext , FS_ENUMERATE_FUNCW EnumerateFunc , void* Data ) { return g_pFS->EnumerateFilesOfTypeW( Ext , EnumerateFunc, Data ); }<file_sep>/games/Legacy-Engine/Source/LMEdit/LMEditDoc.cpp // LMEditDoc.cpp : implementation of the CLMEditDoc class // #include "stdafx.h" #include "LMEdit.h" #include "LMEditDoc.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CLMEditDoc IMPLEMENT_DYNCREATE(CLMEditDoc, CDocument) BEGIN_MESSAGE_MAP(CLMEditDoc, CDocument) ON_COMMAND(ID_ANIMATION_EDITANIMATIONS, &CLMEditDoc::OnAnimationEditanimations) ON_COMMAND(ID_ANIMATION_IMPORTFRAMES, &CLMEditDoc::OnAnimationImportframes) ON_COMMAND(ID_ANIMATION_CALCULATEAABB, &CLMEditDoc::OnAnimationCalculateaabb) END_MESSAGE_MAP() // CLMEditDoc construction/destruction CLMEditDoc::CLMEditDoc() : m_pDevice(NULL) { // TODO: add one-time construction code here OutputDebugString("Document class is being created!\n"); } CLMEditDoc::~CLMEditDoc() { OutputDebugString("Document class is being destroyed!\n"); } BOOL CLMEditDoc::OnNewDocument() { if (!CDocument::OnNewDocument()) return FALSE; m_cMesh.Unload(); m_cSkel.Unload(); return TRUE; } lg_uint CLMEditDoc::Doc_Read(void* buffer, lg_uint size, lg_uint count, void* stream) { CFile* par=(CFile*)stream; return par->Read(buffer, size*count); } lg_uint CLMEditDoc::Doc_Write(void* buffer, lg_uint size, lg_uint count, void* stream) { CFile* par=(CFile*)stream; par->Write(buffer, size*count); return count; } void CLMEditDoc::Serialize(CArchive& ar) { OutputDebugString("Serialize Being Called.\n"); if (ar.IsStoring()) { } else { } } // CLMEditDoc diagnostics #ifdef _DEBUG void CLMEditDoc::AssertValid() const { CDocument::AssertValid(); } void CLMEditDoc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG // CLMEditDoc commands void CLMEditDoc::OnCloseDocument() { // TODO: Add your specialized code here and/or call the base class Err_Printf("Closing %s.\n", this->GetPathName()); m_cMesh.Unload(); m_cSkel.Unload(); CDocument::OnCloseDocument(); } BOOL CLMEditDoc::SetDevice(IDirect3DDevice9* lpDevice) { //Make sure the current device gets //released if it exists. LG_SafeRelease(m_pDevice); //Set the new device. (Really this function is only called initially //when the device is created, then again when the window is destroyed. if(lpDevice) { m_pDevice=lpDevice; m_pDevice->AddRef(); return TRUE; } return FALSE; } void CLMEditDoc::OnAnimationEditanimations() { CAnimDialog dlgAnim; dlgAnim.SetSkel(&m_cSkel); if(dlgAnim.DoModal()==IDOK) { UpdateAllViews(NULL); SetModifiedFlag(TRUE); } } void CLMEditDoc::OnAnimationImportframes() { //CLSkelEdit* pSkel=(CLSkelEdit*)m_cMesh.GetSkel(); if(!m_cSkel.IsLoaded())//pSkel || !pSkel->IsLoaded()) { AfxMessageBox("A skeleton must be loaded to import frames!", MB_ICONINFORMATION); return; } CFileDialog dlgOpen( TRUE, _T("lskl"), 0, 0, _T("Skeleton Files (*.lskl;*.lmsh)|*.lskl;*.lmsh|All Files (*.*)|*.*|"), AfxGetMainWnd()); if(dlgOpen.DoModal()!=IDOK) return; CFile cFile(dlgOpen.GetPathName(), CFile::modeRead); if(cFile.m_hFile==CFile::hFileNull) { AfxMessageBox(CString("An error occured while attempting to open ") + dlgOpen.GetFileName()); return; } DWORD nHeader=0; cFile.Read(&nHeader, 4); //We now search for the LSKEL_ID, since it isn't gauranteed //to be at the beginning of the file we just search the whole thing. ULONGLONG nLength=0, nPosition=0; nLength=cFile.GetLength(); for(nPosition=0; nPosition<nLength; nPosition++) { cFile.Seek(nPosition, CFile::begin); cFile.Read(&nHeader, 4); if(nHeader==CLSkel2::LM_SKEL_ID) break; } if(nPosition==nLength) { AfxMessageBox(CString(cFile.GetFileName()) + " does not contain a skeleton!", MB_ICONINFORMATION); return; } cFile.Seek(-4, CFile::current); cFile.Close(); //We are now at the beginning of the skeleton. CLSkelEdit cTempSkel; BOOL bResult=cTempSkel.Load(dlgOpen.GetPathName().GetBuffer()); if(bResult) { bResult=m_cSkel.ImportFrames(&cTempSkel);//((CLSkelEdit*)&m_cSkel)->ImportFrames((CLSkelEditD3D*)&cTempSkel); } cTempSkel.Unload(); if(bResult) { UpdateAllViews(NULL); SetModifiedFlag(); AfxMessageBox("Successfully imported frames!", MB_ICONINFORMATION); } else AfxMessageBox("Could not import frames!", MB_ICONERROR); } BOOL CLMEditDoc::OnSaveDocument(LPCTSTR lpszPathName) { // TODO: Add your specialized code here and/or call the base class //AfxMessageBox(CString(lpszPathName) + "\n" + m_szSkelFilename + "\n" + m_szMeshFilename); OnSaveMesh(m_szMeshFilename); OnSaveSkel(m_szSkelFilename); SetModifiedFlag(FALSE); return TRUE; } BOOL CLMEditDoc::OnOpenDocument(LPCTSTR lpszPathName) { /* if (!CDocument::OnOpenDocument(lpszPathName)) return FALSE; */ CFile File(lpszPathName, CFile::modeRead|CFile::shareDenyWrite); //The first thing we need to do is find out if we are loading //a skeleton or a mesh. DWORD dwType; File.Read(&dwType, 4); File.SeekToBegin(); CString szFilename=File.GetFilePath(); if(dwType==CLMesh2::LM_MESH_ID) { File.Close(); m_szMeshFilename=szFilename; m_cMesh.Load((lg_char*)m_szMeshFilename.GetBuffer()); } else if(dwType==CLSkel2::LM_SKEL_ID) { File.Close(); //Load the skeleton (in the future the files may not be attached at all) m_szSkelFilename=szFilename; m_cSkel.Load((lg_char*)m_szSkelFilename.GetBuffer()); } else { return FALSE;//Not a valid file. } m_cMesh.SetCompatibleWith(&m_cSkel); UpdateAllViews(NULL, 0x00000011); return TRUE; } BOOL CLMEditDoc::DoSave(LPCTSTR lpszPathName, BOOL bReplace) { CString szNewName=lpszPathName; if(szNewName.IsEmpty()) { //If the filename was empty it means that save as //was called. CDlgSaveAs dlgSaveAs(m_szMeshFilename, m_szSkelFilename); if(dlgSaveAs.DoModal()==IDCANCEL) return FALSE; if(!dlgSaveAs.m_szSkelFile.IsEmpty()) m_szSkelFilename=dlgSaveAs.m_szSkelFile; if(!dlgSaveAs.m_szMeshFile.IsEmpty()) m_szMeshFilename=dlgSaveAs.m_szMeshFile; lpszPathName=m_szMeshFilename; } return CDocument::DoSave(lpszPathName, bReplace); } BOOL CLMEditDoc::OnSaveSkel(LPCTSTR lpszPathName) { /* CFile File; if(!File.Open(lpszPathName, CFile::modeCreate|CFile::modeWrite|CFile::shareDenyWrite)) { OutputDebugString(CString("Could not open file ") + lpszPathName + " to save skel.\n"); return FALSE; } */ return m_cSkel.Save((lg_char*)lpszPathName); } BOOL CLMEditDoc::OnSaveMesh(LPCTSTR lpszPathName) { return m_cMesh.Save((lg_char*)lpszPathName);//, Doc_Write); } void CLMEditDoc::SetTitle(LPCTSTR /*lpszTitle*/) { // TODO: Add your specialized code here and/or call the base class TCHAR *szMesh, *szSkel; //L_GetNameFromPath(szMesh, m_szMeshFilename); //L_GetNameFromPath(szSkel, m_szSkelFilename); szMesh=m_szMeshFilename.GetBuffer(); szSkel=m_szSkelFilename.GetBuffer(); CString szTitle=CString("Mesh: ")+ szMesh + " Skeleton: " + szSkel; CDocument::SetTitle(szTitle); //CDocument::SetTitle(lpszTitle); } void CLMEditDoc::OnAnimationCalculateaabb() { if(m_cSkel.IsLoaded()) { m_cSkel.CalculateAABBs(0.0f); SetModifiedFlag(); } else { AfxMessageBox(_T("A skeleton must be loaded to calculate AABBs!"), MB_ICONINFORMATION); } } <file_sep>/games/Legacy-Engine/Scrapped/UnitTests/FS_Test/FS_Test.cpp #include <lf_sys.h> #include <stdio.h> #include <string.h> #include <process.h> int main(int argc, char* argv[]) { char szCommand[MAX_F_PATH]; char* szFunc=L_null; system("cls"); printf("Beem Software Command Line Explorer [version 1.00]\n(C) Copyright 2006 <NAME>.\n\n"); LF_Init("C:\\", 0); do { printf("%s>", LF_GetDir(L_null, MAX_F_PATH)); gets(szCommand); szFunc=L_strtok(szCommand, " \"", '"'); if(L_strnicmp(szFunc, "CD", 0)) { LF_ChangeDir(L_strtok(L_null, L_null, 0)); } }while (!L_strnicmp(szCommand, "QUIT", 0) && !L_strnicmp(szCommand, "EXIT", 0)); return 0; } <file_sep>/tools/MConvert/Dist/Readme.txt Money Conversion Coyright 2001, <NAME> for Beem Software. This tool converts values one kind of currency to another. Conversion rates are stored in rates.ini. This file must be updated with appropriate rates. The first line must contain the number of entries.<file_sep>/games/Legacy-Engine/Source/engine/lw_client.h #ifndef __LW_CLIENT_H__ #define __LW_CLIENT_H__ #include "li_sys.h" #include "lw_server.h" #include "lw_map.h" #include "lv_sys.h" #include "lw_skybox.h" #include "lg_fxmgr.h" #include <d3dx9.h> //For a test: #include "lm_mesh_lg.h" #include "lm_mesh_tree.h" typedef struct _LEntRasterInfo{ //lg_dword m_nMeshCount; //lg_dword m_nSkelCount; CLMeshTree m_MeshTree; //CLSkelLG** m_pSkels; //lg_float m_fScale; }LEntRasterInfo; class CLWorldClnt: public CElementD3D, public CElementInput{ private: CLNT_CONNECT_TYPE m_nConnectType; CLMapD3D m_Map; CLSkybox3 m_Skybox; CLWorldSrv* m_pSrvLocal; //The entities. lg_dword m_nMaxEnts; //Maximum number of ents availabe (gotten from server). LEntityClnt* m_pEntList; //Master list of entities. LEntList m_EntsAll; //List of any entities that are used. lg_dword m_nPCEnt; //Ent controlled by the player. lg_dword m_nIDOnSrv; //ID of this client, as stored on the server. CLInput* m_pInput; lg_bool m_bRunning; public: CLWorldClnt(); ~CLWorldClnt(); void Init(CLInput* pInput); void Shutdown(); lg_void ConnectLocal(CLWorldSrv* pSrv); lg_void ConnectTCP(); lg_void Disconnect(); lg_void Update(); lg_void SetCamera(ML_MAT* pMat); lg_void Render(); lg_void Validate(); lg_void Invalidate(); private: lg_void ClearEntities(); lg_void AddEnt(const lg_dword nUEID, const LEntityClnt* pEnt, const lg_path szObjScipt); __inline lg_void RemoveEnt(const lg_dword nUEID); //Networking: private: lg_void Broadcast(); lg_void Receive(); lg_void ProcessSrvCmd(const CLWCmdItem* pCmd); private: __inline static lg_void UpdateEntSrvToCli(LEntityClnt* pDest, const LEntitySrv* pSrc); __inline static lg_void* CreateRasterInfo(const lg_path szObjScript); __inline static lg_void DeleteRasterInfo(lg_void* pRasterInfo); }; #endif __LW_CLIENT_H__<file_sep>/games/Legacy-Engine/Scrapped/UnitTests/VarTest/var_var.cpp #include "var_var.h" #include "var_mgr.h" namespace var_sys { void CVar::CopyString(var_char* out, const var_char* in) { _tcsncpy_s(out, VAR_STR_LEN, in, VAR_STR_LEN); out[VAR_STR_LEN]=0; } var_word CVar::HexToDword(const var_char* in) { var_char c=0; var_word nHexValue=0; /* The idea behind this is keep adding to value, until we reach an invalid character, or the end of the string. */ for(var_word i=2; in[i]!=0; i++) { c=in[i]; if(c>='0' && c<='9') nHexValue=(nHexValue<<4)|(c-'0'); else if(c>='a' && c<='f') nHexValue=(nHexValue<<4)|(c-'a'+10); else if(c>='A' && c<='F') nHexValue=(nHexValue<<4)|(c-'A'+10); else break; } return nHexValue; } void CVar::StringToNumber(const var_char* in, var_float * fValue, var_long * nValue) { if(in[0]=='0' && (in[1]=='x' || in[1]=='X')) { *nValue = HexToDword(in); *fValue = (var_float)*nValue; } else { //Get definiton. if(!CVarMgr::DefToValues(in, fValue, nValue)) { //If no definition. *nValue = _ttol(in); *fValue = (var_float)_tstof(in); } } } void CVar::Init(const var_char* name) { m_nFlags=0; CopyString(m_strName, name); Set(_T("")); } CVar::CVar(void) : m_nFlags(0) { //_tprintf(_T("No arg constructor\n")); CopyString(m_strName, _T("(Not Initialized)")); Set(_T("")); } CVar::~CVar(void) { } void CVar::SetFlags(var_word flags) { m_nFlags=flags; } var_float CVar::Float()const { return m_fValue; } var_word CVar::Word()const { return (var_word)m_nValue; } var_long CVar::Long()const { return (var_long)m_nValue; } const var_char* CVar::String()const { return &m_strValue[0]; } const var_char* CVar::Name()const { return &m_strName[0]; } void CVar::Set(var_float value) { if(m_nFlags&F_ROM) return; m_fValue=value; m_nValue=(var_word)(var_long)value; _sntprintf_s(m_strValue, VAR_STR_LEN, VAR_STR_LEN, _T("%f"), value); } void CVar::Set(var_word value) { if(m_nFlags&F_ROM) return; m_fValue=(var_float)value; m_nValue=value; _sntprintf_s(m_strValue, VAR_STR_LEN, VAR_STR_LEN, _T("%u"), value); } void CVar::Set(var_long value) { if(m_nFlags&F_ROM) return; m_fValue=(var_float)value; m_nValue=value; _sntprintf_s(m_strValue, VAR_STR_LEN, VAR_STR_LEN, _T("%i"), value); } void CVar::Set(const var_char* value) { if(m_nFlags&F_ROM) return; CopyString(m_strValue, value); StringToNumber(value, &m_fValue, (var_long*)&m_nValue); } void CVar::Set(const CVar& rhs) { if(m_nFlags&F_ROM) return; CopyString(this->m_strValue, rhs.m_strValue); this->m_nValue=rhs.m_nValue; this->m_fValue=rhs.m_fValue; } void CVar::operator= (var_float value) { Set(value); } void CVar::operator= (var_word value) { Set(value); } void CVar::operator= (var_long value) { Set(value); } void CVar::operator= (const var_char* value) { Set(value); } void CVar::operator= (CVar & rhs) { //_tprintf(_T("= operator\n")); Set(rhs); } } //namespace var_sys <file_sep>/samples/D3DDemo/code/GFX3D9/Vertex.cpp /* Vertext.cpp - The Custom Vertext Format Copyright (c) 2003, <NAME> */ #include "GFX3D9.h" tagCUSTOMVERTEX::tagCUSTOMVERTEX() { Position.x=0; Position.y=0; Position.z=0; Normal.x=0; Normal.y=0; Normal.z=0; DiffuseColor=0; SpecularColor=0; tu=0; tv=0; } tagCUSTOMVERTEX::tagCUSTOMVERTEX( float px, float py, float pz, float nx, float ny, float nz, D3DCOLOR dwDiffuse, D3DCOLOR dwSpecular, float txu, float txv) { Position.x=px; Position.y=py; Position.z=pz; Normal.x=nx; Normal.y=ny; Normal.z=nz; DiffuseColor=dwDiffuse; SpecularColor=dwSpecular; tu=txu; tv=txv; } tagCUSTOMVERTEX tagCUSTOMVERTEX::operator = (const tagCUSTOMVERTEX & rhs) { if(this == &rhs) return *this; Position.x=rhs.Position.x; Position.y=rhs.Position.y; Position.z=rhs.Position.z; Normal.x=rhs.Normal.x; Normal.y=rhs.Normal.y; Normal.z=rhs.Normal.z; DiffuseColor=rhs.DiffuseColor; SpecularColor=rhs.SpecularColor; tu=rhs.tu; tv=rhs.tv; return *this; } int tagCUSTOMVERTEX::operator == (const tagCUSTOMVERTEX & rhs) { if(this == &rhs) return 1; if ( (Position.x==rhs.Position.x) && (Position.y==rhs.Position.y) && (Position.z==rhs.Position.z) && (Normal.x==rhs.Normal.x) && (Normal.y==rhs.Normal.y) && (Normal.z==rhs.Normal.z) && (DiffuseColor==rhs.DiffuseColor) && (SpecularColor==rhs.SpecularColor) && (tu==rhs.tu) && (tv==rhs.tv) )return 1; else return 0; } int tagCUSTOMVERTEX::operator != (const tagCUSTOMVERTEX & rhs) { if(*this == rhs)return 0; else return 1; }<file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/lg_math/lg_math_test.c #include <stdio.h> #include <conio.h> #include <d3d9.h> #include <d3dx9.h> #include "lg_math.h" #pragma comment(lib, "d3dx9.lib") #pragma comment(lib, "winmm.lib") void printmatrix(L_matrix* pM1) { printf("%f\t%f\t%f\t%f\n", pM1->_11, pM1->_12, pM1->_13, pM1->_14); printf("%f\t%f\t%f\t%f\n", pM1->_21, pM1->_22, pM1->_23, pM1->_24); printf("%f\t%f\t%f\t%f\n", pM1->_31, pM1->_32, pM1->_33, pM1->_34); printf("%f\t%f\t%f\t%f", pM1->_41, pM1->_42, pM1->_43, pM1->_44); printf("\n\n"); } void printvec3(L_vector3* pV1) { printf("%f\t%f\t%f\t", pV1->x, pV1->y, pV1->z); printf("\n"); } void testvec3(int test) { L_vector3 V1={11.3f, 438.71f, 2.345f}; L_vector3 V2={325.34f, 26.4f, 64.87f}; //printf("%f\n", L_vec3normalize(&V1, &V1)); //printf("%f\n", sqrt(V1.x*V1.x+V1.y*V1.y+V1.z*V1.z)); if(test==1) { printf("D3DX:\n"); printf("Length: %f\n", D3DXVec3Length((void*)&V1)); printf("Normal: "); printvec3((void*)D3DXVec3Normalize((void*)&V1, (void*)&V1)); printf("Scale: "); printvec3((void*)D3DXVec3Scale((void*)&V1, (void*)&V1, 89.25f)); printf("Scale again: "); printvec3((void*)D3DXVec3Scale((void*)&V1, (void*)&V1, 2.0f)); } else if(test==2) { printf("L_math:\n"); printf("Length: %f\n", L_vec3length(&V1)); printf("Normal: "); printvec3(L_vec3normalize(&V1, &V1)); printf("Scale: "); printvec3((void*)L_vec3scale((void*)&V1, (void*)&V1, 89.25f)); printf("Scale again: "); printvec3((void*)L_vec3scale((void*)&V1, (void*)&V1, 2.0f)); } } void test(int d3d) { L_matrix Mat1={1.2f, 56.7f, 2.0f, 3.5f, 5.6f, 7.0f, 8.0f, 90.0f, 10.0f, 5.0f, 4.3f, 2.1f, 3.0f, 4.0f, 5.0f, 7.0f}; L_matrix Mat2={5.0f, 6.0f, 7.0f, 20.2f, 13.0f, 12.56f, 7.5f, 2.1f, 5.6f, 7.0f, 3.0f, 2.0f, 7.0f, 5.6f, 7.0f, 2.4f}; if(d3d==1) { printf("D3DX\n"); printmatrix((void*)D3DXMatrixMultiply((void*)&Mat1, (void*)&Mat1, (void*)&Mat2)); } else if(d3d==2) { printf("L_math\n"); printmatrix(L_matmultiply(&Mat1, &Mat1, &Mat2)); } else if(d3d==3) { printf("L_mathC\n"); printmatrix(L_matmultiply_C(&Mat1, &Mat1, &Mat2)); } else return; } #define TEST_FUNC(label, func){dwTime=timeGetTime();for(i=0; i<dwNumTimes; i++)func;dwTime=timeGetTime()-dwTime;printf("%s: Performed %i in %i milliseconds\n", label, dwNumTimes, dwTime);} int main(void) { L_matrix Mat1={1.2f, 56.7f, 2.0f, 3.5f, 5.6f, 7.0f, 8.0f, 90.0f, 10.0f, 5.0f, 4.3f, 2.1f, 3.0f, 4.0f, 5.0f, 7.0f}; L_matrix Mat2={5.0f, 6.0f, 7.0f, 20.2f, 13.0f, 12.56f, 7.5f, 2.1f, 5.6f, 7.0f, 3.0f, 2.0f, 7.0f, 5.6f, 7.0f, 2.4f}; L_vector3 V1={1.3f, 56.7f, 28.345f}; L_vector3 V2={345.34f, 2.4f, 67.87f}; unsigned long dwTime=0; unsigned long dwNumTimes=1000000; unsigned long i=0; /* testvec3(1); testvec3(2); getch(); return 0; */ //i=0xFFFFFFFF; //printf("The number is: %i (0x%08X)\n", L_nextpow2_ASM(i), L_nextpow2_ASM(i)); //return 0; /* TEST_FUNC("L_mathC", L_vec3distance_C(&V1, &V2)); TEST_FUNC("L_math", L_vec3distance(&V1, &V2)); */ /* test(1); test(2); test(3); */ TEST_FUNC("D3DX", D3DXMatrixMultiply((void*)&Mat1, (void*)&Mat1, (void*)&Mat2)); TEST_FUNC("L_math", L_matmultiply(&Mat1, &Mat1, &Mat2)); TEST_FUNC("L_mathC", L_matmultiply_C(&Mat1, &Mat1, &Mat2)); /* TEST_FUNC("L_mathC", L_nextpow2_C(5000)); TEST_FUNC("L_math", L_nextpow2(5000)); */ /* memcpy(&dwTime, &fTest, 4); printf("%f is 0x%8X\n", fTest, dwTime); */ getch(); return 0; } /* void testdump() { int row=0, column=0; FILE* fout=fopen("out.txt", "w"); for(row=0; row<4; row++) { for(column=0; column<4; column++) { fprintf(fout, ";_%i%i\n", row+1, column+1); fprintf(fout, "fld dword [ecx+%i]\n", 16*row+0); fprintf(fout, "fmul dword [edx+%i]\n", 4*column+0); fprintf(fout, "fld dword [ecx+%i]\n", 16*row+4); fprintf(fout, "fmul dword [edx+%i]\n", 4*column+16); fprintf(fout, "faddp st1\n"); fprintf(fout, "fld dword [ecx+%i]\n", 16*row+8); fprintf(fout, "fmul dword [edx+%i]\n", 4*column+32); fprintf(fout, "faddp st1\n"); fprintf(fout, "fld dword [ecx+%i]\n", 16*row+12); fprintf(fout, "fmul dword [edx+%i]\n", 4*column+48); fprintf(fout, "faddp st1\n"); fprintf(fout, "fstp dword [eax+%i]\n\n", 16*row+4*column); } } fclose(fout); } */<file_sep>/games/Legacy-Engine/Source/common/lg_func.c #include "lg_func.h" #include <string.h> #include <stdlib.h> lg_char* LG_GetShortNameFromPathA(lg_char* szName, const lg_char* szFilename) { lg_dword dwLen=strlen(szFilename); lg_dword i=0, j=0; for(i=dwLen; i>0; i--) { if(szFilename[i]=='\\' || szFilename[i]=='/') { i++; break; } } for(j=0 ;i<dwLen+1; i++, j++) { szName[j]=szFilename[i]; if(szName[j]=='.') { szName[j]=0; break; } } return szName; } /* LG_HashFilename: See remarks in lg_func.h*/ lg_dword LG_HashFilename(lg_char* szPath) { lg_dword nLen=strlen(szPath); //This is basically <NAME>' One-At-A-Time-Hash. //http://www.burtleburtle.net/bob/hash/doobs.html lg_dword nHash=0; lg_dword i=0; for(i=nLen; (i>=0) && (szPath[i]!='\\') && (szPath[i]!='/'); i--) { nHash+=szPath[i]; nHash+=(nHash<<10); nHash^=(nHash>>6); } nHash+=(nHash<<3); nHash^=(nHash>>11); nHash+=(nHash<<15); return nHash; } /*LG_RandomSeed: See remarks in lg_func.h*/ void LG_RandomSeed(lg_uint Seed) { srand(Seed); } /*LG_RandomFloat: See remarks in lg_func.h*/ lg_float LG_RandomFloat(lg_float fMin, lg_float fMax) { return (lg_float)rand() / (RAND_MAX + 1) * (fMax - fMin) + fMin; } /*LG_RandomLong: See remarks in lg_func.h*/ lg_long LG_RandomLong(lg_long nMin, lg_long nMax) { return rand()%(nMax-nMin+1) + nMin; } /* LG_strncpy: See remarks in lg_func.h */ lg_char* LG_strncpy(lg_char* strDest, const lg_char* strSrc, lg_size_t count) { #if 1 strncpy(strDest, strSrc, count); strDest[count]=0; return strDest; #else unsigned long i=0; if((strDest==LG_NULL) || (strSrc==LG_NULL)) return 0; for(i=0; strSrc[i]!=0, i<count; i++) { strDest[i]=strSrc[i]; } if(i<count) strDest[i]=0; else strDest[count-1]=0; return i; #endif } /* LG_wcsncpy: See remarks in lg_func.h */ lg_wchar_t* LG_wcsncpy(lg_wchar_t* strDest, const lg_wchar_t* strSrc, lg_size_t count) { wcsncpy(strDest, strSrc, count); strDest[count]=0; return strDest; }<file_sep>/games/Legacy-Engine/Source/lf_sys2/lf_file.h #include "lf_sys2.h" #include "lf_bdio.h" class LF_SYS2_EXPORTS CLFile { friend class CLFileSystem; //Private types, enums, and constants. private: //static const lf_dword LF_TYPE_FILE= 0x00000001; //static const lf_dword LF_TYPE_MEMORY= 0x00000002; //static const lf_dword LF_TYPE_ZLIB_CMP=0x00000004; //static const lf_dword LF_TYPE_ARCHIVED=0x00000008; //Private members. private: //lf_dword m_nTypeFlags; lf_dword m_nAccess; lf_dword m_nSize; //lf_dword m_nSizeCmp; lf_dword m_nFilePointer; //lf_pathA m_szPathA; lf_pathW m_szPathW; lf_pbyte m_pData; BDIO_FILE m_BaseFile; lf_dword m_nBaseFileBegin; //Where the CLFile starts in the base file (0 if the file is being accessed directly from the disk). //lf_bool m_bIsOpen; lf_bool m_bEOF; //Types, enums, and constants used with the CLFile class. public: //Public methods. public: CLFile(); ~CLFile(); /* lf_bool OpenA(lf_cstr szFilename, lf_dword nAccess=ACCESS_READ|ACCESS_WRITE, CREATE_MODE nMode=OPEN_EXISTING); lf_bool OpenW(lf_cwstr szFilename, lf_dword nAccess=ACCESS_READ|ACCESS_WRITE, CREATE_MODE nMode=OPEN_EXISTING); lf_bool Close(); */ lf_dword Read(lf_void* pOutBuffer, lf_dword nSize); lf_dword Write(lf_void* pInBuffer, lf_dword nSize); lf_dword Tell(); lf_dword Seek(LF_SEEK_TYPE nMode, lf_long nOffset); lf_dword GetSize(); const lf_pvoid GetMemPointer(); lf_bool IsEOF(); };<file_sep>/tools/CornerBin/CornerBin/CornerBin.cpp // CornerBin.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "afxwinappex.h" #include "afxdialogex.h" #include "CornerBin.h" #include "MainFrm.h" #include "DlgSettings.h" LPCTSTR g_strAPP_GUID = _T("{7368B213-598B-4240-8C94-65420F2F9B3D}"); #ifdef _DEBUG #define new DEBUG_NEW #endif // CCornerBinApp BEGIN_MESSAGE_MAP(CCornerBinApp, CWinApp) ON_COMMAND(ID_APP_ABOUT, &CCornerBinApp::OnAppAbout) ON_COMMAND(ID_OPEN_SETTINGS, &CCornerBinApp::OnOpenSettings) ON_COMMAND(ID_OPEN_R_B, &CCornerBinApp::OnOpenRB) ON_COMMAND(ID_EMPTY_R_B, &CCornerBinApp::OnEmptyRB) END_MESSAGE_MAP() // CCornerBinApp construction CCornerBinApp::CCornerBinApp() { // support Restart Manager m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_RESTART; #ifdef _MANAGED // If the application is built using Common Language Runtime support (/clr): // 1) This additional setting is needed for Restart Manager support to work properly. // 2) In your project, you must add a reference to System.Windows.Forms in order to build. System::Windows::Forms::Application::SetUnhandledExceptionMode(System::Windows::Forms::UnhandledExceptionMode::ThrowException); #endif SetAppID(_T("Beem Software.CornerBin.1.0.0")); } // The one and only CCornerBinApp object CCornerBinApp theApp; // CCornerBinApp initialization BOOL CCornerBinApp::InitInstance() { //Load up the settings file: m_Settings.LoadSettings(); CString strCmdLine(m_lpCmdLine); if(-1 != strCmdLine.Find(_T("-settings"))) { //See if an application is already running, if it //is, just have the currently running app open it's //settings dailaog box: HWND hwnd = ::FindWindow(g_strAPP_GUID, NULL); if(hwnd) { PostMessage(hwnd, WM_EXTSETTINGSUP, 0, 0); return FALSE; } else { CDlgSettings dlg(NULL, &m_Settings); dlg.DoModal(); } } //Single instance at a time code: { //We'll create a mutex to make sure only one copy of the app runs at a time. CString strMutexName(g_strAPP_GUID); //The mutex name will append the user name, that way the program can still //be run by more than one user simoltaneously. TCHAR strTemp[UNLEN + 1]; DWORD nLen = UNLEN; ::GetUserName(strTemp, &nLen); strMutexName.Append(strTemp); m_hMutex = ::CreateMutex(NULL, FALSE, strMutexName); if(ERROR_ALREADY_EXISTS == GetLastError()) { ::AfxMessageBox(_T("CornerBin is already running.")); return FALSE; } } // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinApp::InitInstance(); // Initialize OLE libraries if (!AfxOleInit()) { AfxMessageBox(IDP_OLE_INIT_FAILED); return FALSE; } AfxEnableControlContainer(); EnableTaskbarInteraction(FALSE); // AfxInitRichEdit2() is required to use RichEdit control // AfxInitRichEdit2(); // To create the main window, this code creates a new frame window // object and then sets it as the application's main window object CMainFrame* pFrame = new CMainFrame(&m_Settings); if (!pFrame) return FALSE; m_pMainWnd = pFrame; // create and load the frame with its resources pFrame->LoadFrame(IDR_MENU_CORNERBIN, WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, NULL, NULL); //Load up the tray icon: m_CBTrayIcon.Init(m_hInstance, m_pMainWnd->m_hWnd, &m_Settings); //With the settings loaded we can start the main window timer to query //the status of the recycle bin. pFrame->SetTimerUpdate(m_Settings.GetUpdateFreq()); //We insure that the main window is never visible. pFrame->ShowWindow(SW_HIDE); //pFrame->ShowWindow(SW_SHOW); //pFrame->UpdateWindow(); // call DragAcceptFiles only if there's a suffix // In an SDI app, this should occur after ProcessShellCommand return TRUE; } int CCornerBinApp::ExitInstance() { //TODO: handle additional resources you may have added //Go ahead and save the current settings, just in case they were never saved. m_Settings.SaveSettings(); //Destroy the icon as well... m_CBTrayIcon.UnInit(); AfxOleTerm(FALSE); //Destroy our mutex so the app may run again. CloseHandle(m_hMutex); return CWinApp::ExitInstance(); } // CCornerBinApp message handlers // CAboutDlg dialog used for App About class CAboutDlg : public CDialogEx { public: CAboutDlg(); // Dialog Data enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // App command to run the dialog void CCornerBinApp::OnAppAbout() { CAboutDlg aboutDlg; aboutDlg.DoModal(); } // CCornerBinApp message handlers void CCornerBinApp::OnOpenSettings() { OpenSettingsDlg(); } void CCornerBinApp::OnOpenRB() { /* LPITEMIDLIST pidRecycle; //SHGetSpecialFolderLocation(NULL, CSIDL_BITBUCKET, &pidRecycle) ; SHELLEXECUTEINFO EI; memset(&EI, 0, sizeof(EI)); EI.cbSize = sizeof(EI); EI.fMask = SEE_MASK_IDLIST; EI.nShow = SW_SHOWNORMAL; EI.lpIDList = &pidRecycle; ShellExecuteEx(&EI); */ //I don't necessarily like this code, because future versions of windows may not use the same identifier for the trash bin. ShellExecute(NULL, NULL, TEXT("::{645FF040-5081-101B-9F08-00AA002F954E}"), NULL, NULL, SW_SHOWNORMAL); } void CCornerBinApp::OnEmptyRB() { //Note the prompt is determined by the settings: if(this->m_CBTrayIcon.IsRBFull()) ::SHEmptyRecycleBin(NULL, NULL, (m_Settings.GetEmptyPrompt()?0:SHERB_NOCONFIRMATION)); //Also, we'll always update the icon to insure an immediate change. this->OnTimerUpdate(); } void CCornerBinApp::OnDblClkTrayIcon(void) { //Depending on the settings we decide what to do... if(m_Settings.GetOpenOnDblClk()) { //Open the recycle bin this->OnOpenRB(); } else { //Open the settings dialog OpenSettingsDlg(); } } void CCornerBinApp::OnTimerUpdate(void) { m_CBTrayIcon.Update(); } void CCornerBinApp::OpenSettingsDlg(void) { CDlgSettings dlgSettings(m_pMainWnd, &m_Settings); if(IDOK == dlgSettings.DoModal()) { //At this point we should update any changes that may have occured. //Might actually want to have a function that simple updates since this //current code makes the icon dissapear then reapear. m_CBTrayIcon.UnInit(); m_CBTrayIcon.Init(this->m_hInstance, this->m_pMainWnd->m_hWnd, &m_Settings); } } <file_sep>/games/Legacy-Engine/Source/engine/lx_sys.cpp #include "lg_xml.h" #include "lx_sys.h" lg_bool LX_Process(const lg_path szXMLFile, XML_StartElementHandler startH, XML_EndElementHandler endH, XML_CharacterDataHandler charDataH, lg_void* pData) { LF_FILE3 fin=LF_Open(szXMLFile, LF_ACCESS_READ|LF_ACCESS_MEMORY, LF_OPEN_EXISTING); if(!fin) return LG_FALSE; XML_Parser parser= XML_ParserCreate_LG(LG_NULL); if(!parser) { LF_Close(fin); return LG_FALSE; } XML_ParserReset(parser, LG_NULL); XML_SetUserData(parser, pData); XML_SetElementHandler(parser, startH, endH); XML_SetCharacterDataHandler(parser, charDataH); lg_bool bRes=XML_Parse(parser, (const char*)LF_GetMemPointer(fin), LF_GetSize(fin), LG_TRUE); if(!bRes) { Err_Printf("LX ERROR: Parse error at line %d: \"%s\"", XML_GetCurrentLineNumber(parser), XML_ErrorString(XML_GetErrorCode(parser))); } XML_ParserFree(parser); LF_Close(fin); return bRes; } <file_sep>/games/Legacy-Engine/Source/lm_sys/lm_base.h #ifndef __LM_BASE_H__ #define __LM_BASE_H__ #include "ML_lib.h" #include "lg_types.h" class CLMBase{ //Types and constants: public: static const lg_dword LM_MAX_NAME=31; typedef lg_char LMName[LM_MAX_NAME+1]; static const lg_dword LM_MAX_PATH=259; typedef lg_char LMPath[LM_MAX_PATH+1]; protected: enum RW_MODE{ RW_UNKNOWN=0, RW_READ, RW_WRITE }; typedef lg_uint (__cdecl * ReadWriteFn)(lg_void* file, lg_void* buffer, lg_uint size); static const lg_dword LM_FLAG_LOADED=0x00000001; //Private data: protected: lg_dword m_nFlags; //Private required methods: protected: CLMBase(): m_nFlags(0){} ~CLMBase(){} virtual lg_bool Serialize( lg_void* file, ReadWriteFn read_or_write, RW_MODE mode)=0; public: lg_bool IsLoaded(){return m_nFlags&LM_FLAG_LOADED;} }; #endif __LM_BASE_H__<file_sep>/games/Legacy-Engine/Scrapped/old/lv_font.h /* lv_font.h - Header for the legacy font functionality. */ #ifndef __LV_FONT_H__ #define __LV_FONT_H__ #include "lv_img2d.h" #ifdef __cplusplus extern "C"{ #endif /* __cplusplus */ typedef struct _LVFONT{ IDirect3DDevice9* lpDevice; IDirect3DTexture9* lpTexture; LV2DIMAGE* lpChars[96]; /* Our font supports 96 characters. */ float fCharWidth; float fCharHeight; }LVFONT, *LPLVFONT; LVFONT* Font_Create( IDirect3DDevice9* lpDevice, char* szFilename, float fCharWidth, float fCharHeight, L_dword dwFontWidth, L_dword dwFontHeight); L_bool Font_Delete(LVFONT* lpFont); L_bool Font_DrawChar(LVFONT* lpFont, IDirect3DDevice9* lpDevice, char c, float x, float y); L_bool Font_DrawString(LVFONT* lpFont, IDirect3DDevice9* lpDevice, char* szString, float x, float y); L_bool Font_Validate(LVFONT* lpFont, IDirect3DDevice9* lpDevice); L_bool Font_Invalidate(LVFONT* lpFont); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /*__LV_FONT_H__*/<file_sep>/games/Legacy-Engine/Source/lm_sys/lm_skin.cpp #include "lm_skin.h" #include "lx_sys.h" #include "lg_malloc.h" #include "lg_err.h" CLSkin::CLSkin() : CLMBase() , m_nMtrCount(0) , m_nGrpCount(0) , m_pMaterials(LG_NULL) , m_pGrps(LG_NULL) , m_pMem(LG_NULL) { } CLSkin::~CLSkin() { Unload(); } lg_bool CLSkin::Load(lg_path szFilename) { //Make sure the skin is loaded Unload(); lg_bool bLoaded=LX_LoadSkin(szFilename, this); m_nFlags=bLoaded?LM_FLAG_LOADED:0; #if 0 Err_Printf("SknMgr: Loaded \"%s\".", szFilename); Err_Printf(" Materials: %d", m_nMtrCount); for(lg_dword i=0; i<m_nMtrCount; i++) { Err_Printf(" Material[%d]: %d", i+1, m_pMaterials[i]); } Err_Printf(" Groups: %d", m_nGrpCount); for(lg_dword i=0; i<m_nGrpCount; i++) { Err_Printf(" Group[%d]: %s, %d", i, this->m_pGrps[i].szName, m_pGrps[i].nMtr); } #endif return bLoaded; } void CLSkin::Unload() { //We've got to zero out everything. m_nMtrCount=0; m_nGrpCount=0; m_nFlags=0; m_pMaterials=LG_NULL; m_pGrps=LG_NULL; //Memory was allocated using LG_Malloc not new. LG_SafeFree(m_pMem); } void CLSkin::MakeCompatibleWithMesh(CLMesh2* pMesh) { //If the files aren't loaded we can't do anything. if(!pMesh || !pMesh->IsLoaded() || !LG_CheckFlag(m_nFlags, LM_FLAG_LOADED)) return; lg_dword nLoopCount=LG_Min(m_nGrpCount, pMesh->m_nNumSubMesh); //Loop through each of the groups (meshes in the mesh file) //and set up the references. for(lg_dword i=0; i<nLoopCount; i++) { //We'll set it to 0 by default (we should probably set it to //something that represents null), that way if we don't //find anything, it will at least match something. //Loop through each of the meshes to find a matching one. for(lg_dword j=0; j<nLoopCount; j++) { //If we found a matching group we set the compatible array. if(stricmp(m_pGrps[i].szName, pMesh->m_pSubMesh[j].szName)==0) { m_pCmpRefs[j]=m_pMaterials[m_pGrps[i].nMtr-1]; //Err_Printf("%s is %d=%d", pMesh->m_pMeshes[j].szName, m_pCmpRefs[j], m_pGrps[i].nMtr-1); //Set j high to break out of the loop j=pMesh->m_nNumSubMesh+1; } } } #if 0 for(lg_dword i=0; i<pMesh->m_nNumMeshes; i++) { if(m_pCmpRefs[i]==0) Err_Printf("%s IS NOT COMPATIBLE.", pMesh->m_pMeshes[i].szName); } #endif } lg_bool CLSkin::Serialize(lg_void *file, ReadWriteFn read_or_write, RW_MODE mode) { return LG_FALSE; } <file_sep>/games/Legacy-Engine/Scrapped/old/lm_d3d.cpp #include "lm_d3d.h" #include "ML_lib.h" #include <stdio.h> #include "lg_func.h" /************************************************************** The Renderable Skeleton Code... (Really only used in LMEdit and not the Legacy Engine) **************************************************************/ CLSkelD3D::CLSkelD3D(): CLSkel(), m_pDevice(LG_NULL), m_bD3DValid(LG_FALSE), m_nColor(0xFFFF0000), m_pSkel(LG_NULL) { } CLSkelD3D::~CLSkelD3D() { Unload(); } lg_bool CLSkelD3D::CreateD3DComponents(IDirect3DDevice9* lpDevice) { if(!m_bLoaded || !lpDevice) return LG_FALSE; L_safe_release(m_pDevice); m_pDevice=lpDevice; m_pDevice->AddRef(); m_pSkel=new JOINTVERTEX[m_nNumJoints]; if(!m_pSkel) { m_pDevice->Release(); return LG_FALSE; } //We need the animation matrices to be the number //of joints*2 so we can store the matrices for //the first and second frame. if(!Validate()) { L_safe_delete_array(m_pSkel); L_safe_release(m_pDevice); return LG_FALSE; } PrepareFrame(0, 0, 0.0f); return LG_TRUE; } lg_bool CLSkelD3D::Validate() { m_bD3DValid=LG_TRUE; return m_bD3DValid; } lg_bool CLSkelD3D::Invalidate() { m_bD3DValid=LG_FALSE; return LG_TRUE; } lg_bool CLSkelD3D::Unload() { if(!m_bLoaded) return LG_TRUE; lg_dword i=0; Invalidate(); L_safe_delete_array(m_pSkel); L_safe_release(m_pDevice); this->CLSkel::Unload(); m_pDevice=LG_NULL; m_bD3DValid=LG_FALSE; m_pSkel=LG_NULL; return LG_TRUE; } lg_bool CLSkelD3D::PrepareFrame(lg_dword nAnim, float fTime) { // The range could easily be changed by modifying this //value, 100.0f seemed to be a good range to me. #define PREP_MAX_RANGE 100.0f if(m_nNumAnims<1) return LG_FALSE; nAnim=LG_Clamp(nAnim, 0, m_nNumAnims-1); fTime=LG_Clamp(fTime, 0.0f, PREP_MAX_RANGE); float fFrame; lg_dword nFrame1=0, nFrame2=0; //Get the animation we are dealing with. const LSKEL_ANIM* pAnim=GetAnim(nAnim); if(L_CHECK_FLAG(pAnim->m_nFlags, LSKEL_ANIM_LOOPBACK)) { if(fTime>=50.0f) fTime=100.0f-fTime; fFrame=pAnim->m_nFirstFrame+((float)pAnim->m_nNumFrames-1-0.000001f)*fTime/(PREP_MAX_RANGE*0.5f); } else { fFrame=pAnim->m_nFirstFrame+((float)pAnim->m_nNumFrames-0.000001f)*fTime/PREP_MAX_RANGE; } nFrame1=(lg_dword)fFrame; nFrame2=nFrame1>=(pAnim->m_nFirstFrame+pAnim->m_nNumFrames-1)?pAnim->m_nFirstFrame:nFrame1+1; //To get the interpolation value we need only find the fraction portion of fFrame fFrame-nFrame1. return PrepareFrame(nFrame1, nFrame2, fFrame-nFrame1); } lg_bool CLSkelD3D::PrepareFrame(lg_dword nFrame1, lg_dword nFrame2, float t) { lg_dword i=0; if(!m_bLoaded || !m_bD3DValid) return LG_FALSE; lg_dword nNumJoints=this->m_nNumJoints; for(i=0; i<nNumJoints; i++) { ML_MAT Trans; GenerateJointTransform(&Trans, i, nFrame1, nFrame2, t); ML_MatMultiply( &Trans, GetBaseTransform(i), &Trans); //To find the final location of a joint we need to (1) find the //relative location of the joint. (2) multiply that by all of //it parent/grandparent's/etc transformation matrices. //(1) m_pSkel[i].x=0.0f; m_pSkel[i].y=0.0f; m_pSkel[i].z=0.0f; m_pSkel[i].psize=4.0f; m_pSkel[i].color=m_nColor; //(2) ML_Vec3TransformCoord((ML_VEC3*)&m_pSkel[i].x, (ML_VEC3*)&m_pSkel[i].x, &Trans);//pJointTrans[i]); } //ML_AABB aabb; GenerateAABB(&m_aabb, nFrame1, nFrame2, t); return LG_TRUE; } lg_bool CLSkelD3D::Render() { //We now want to render the skelton for testing purposes. lg_dword i=0; //If there are no joints just return true cause there is nothing //to render. if(!m_nNumJoints) return LG_TRUE; BONEVERTEX Line[2]; //We want to render the bones first, this //is simply a line from the bone to it's parent. //If it has no parent nothing gets rendered. m_pDevice->SetRenderState(D3DRS_ZENABLE, FALSE); m_pDevice->SetTexture(0, LG_NULL); m_pDevice->SetFVF(BONEVERTEX_FVF); for(i=0; i<GetNumJoints(); i++) { memcpy(&Line[0].x, &m_pSkel[i].x, 12); Line[0].color=m_pSkel[i].color; lg_dword nBone=GetParentBoneRef(i); if(nBone) { memcpy(&Line[1].x, &m_pSkel[nBone-1].x, 12); Line[1].color=m_pSkel[nBone-1].color; m_pDevice->DrawPrimitiveUP(D3DPT_LINELIST, 1, &Line, sizeof(BONEVERTEX)); } } //We can render all the joints at once since they are just points. m_pDevice->SetFVF(JOINTVERTEX_FVF); m_pDevice->DrawPrimitiveUP(D3DPT_POINTLIST, GetNumJoints(), m_pSkel, sizeof(JOINTVERTEX)); //Render the AABB. m_pDevice->SetRenderState(D3DRS_ZENABLE, TRUE); RenderAABB(); return LG_TRUE; } lg_bool CLSkelD3D::RenderAABB() { //ML_AABB aabb; //GenerateAABB(&aabb, nFrame1, nFrame2, t); ML_MAT matTmp; m_pDevice->GetTransform(D3DTS_WORLD, (D3DMATRIX*)&matTmp); //ML_AABB aabb=m_aabb; ML_AABB aabbTrans; ML_AABBTransform(&aabbTrans, &m_aabb, &matTmp); ML_MAT matIdent; ML_MatIdentity(&matIdent); for(lg_dword i=0; i<16; i++) { m_vAABB[i].color=0xFFFFFF90; } ML_VEC3 vTmp; memcpy(&m_vAABB[0], ML_AABBCorner(&vTmp, &aabbTrans, ML_AABB_BLF), 12); memcpy(&m_vAABB[1], ML_AABBCorner(&vTmp, &aabbTrans, ML_AABB_TLF), 12); m_vAABB[2].x=aabbTrans.v3Min.x; m_vAABB[2].y=aabbTrans.v3Max.y; m_vAABB[2].z=aabbTrans.v3Max.z; m_vAABB[3].x=aabbTrans.v3Max.x; m_vAABB[3].y=aabbTrans.v3Max.y; m_vAABB[3].z=aabbTrans.v3Max.z; m_vAABB[4].x=aabbTrans.v3Max.x; m_vAABB[4].y=aabbTrans.v3Max.y; m_vAABB[4].z=aabbTrans.v3Min.z; m_vAABB[5].x=aabbTrans.v3Max.x; m_vAABB[5].y=aabbTrans.v3Min.y; m_vAABB[5].z=aabbTrans.v3Min.z; m_vAABB[6].x=aabbTrans.v3Max.x; m_vAABB[6].y=aabbTrans.v3Min.y; m_vAABB[6].z=aabbTrans.v3Max.z; m_vAABB[7].x=aabbTrans.v3Min.x; m_vAABB[7].y=aabbTrans.v3Min.y; m_vAABB[7].z=aabbTrans.v3Max.z; m_vAABB[8].x=aabbTrans.v3Min.x; m_vAABB[8].y=aabbTrans.v3Min.y; m_vAABB[8].z=aabbTrans.v3Min.z; m_vAABB[9].x=aabbTrans.v3Max.x; m_vAABB[9].y=aabbTrans.v3Min.y; m_vAABB[9].z=aabbTrans.v3Min.z; m_vAABB[10].x=aabbTrans.v3Max.x; m_vAABB[10].y=aabbTrans.v3Min.y; m_vAABB[10].z=aabbTrans.v3Max.z; m_vAABB[11].x=aabbTrans.v3Max.x; m_vAABB[11].y=aabbTrans.v3Max.y; m_vAABB[11].z=aabbTrans.v3Max.z; m_vAABB[12].x=aabbTrans.v3Max.x; m_vAABB[12].y=aabbTrans.v3Max.y; m_vAABB[12].z=aabbTrans.v3Min.z; m_vAABB[13].x=aabbTrans.v3Min.x; m_vAABB[13].y=aabbTrans.v3Max.y; m_vAABB[13].z=aabbTrans.v3Min.z; m_vAABB[14].x=aabbTrans.v3Min.x; m_vAABB[14].y=aabbTrans.v3Max.y; m_vAABB[14].z=aabbTrans.v3Max.z; m_vAABB[15].x=aabbTrans.v3Min.x; m_vAABB[15].y=aabbTrans.v3Min.y; m_vAABB[15].z=aabbTrans.v3Max.z; for(lg_dword i=0; i<16; i++) { if(m_vAABB[i].z==aabbTrans.v3Max.z) m_vAABB[i].color=0xFF870178; else m_vAABB[i].color=0xffff7df1; } //Render the AABB. m_pDevice->SetTransform(D3DTS_WORLD, (D3DMATRIX*)&matIdent); m_pDevice->SetFVF(BONEVERTEX_FVF); m_pDevice->DrawPrimitiveUP(D3DPT_LINESTRIP, 15, &m_vAABB, sizeof(BONEVERTEX)); m_pDevice->SetTransform(D3DTS_WORLD, (D3DMATRIX*)&matTmp); /* BONEVERTEX Test[16]; ML_VEC3 Corners[8]; ML_AABB aabbTemp; for(lg_dword i=0; i<8; i++) { ML_AABBCorner(&Corners[i], &m_aabb, (ML_AABB_CORNER)i); ML_Vec3TransformCoord(&Corners[i], &Corners[i], &matTmp); } ML_AABBFromVec3s(&aabbTemp, Corners, 8); for(lg_dword i=0; i<16; i++) { Test[i].color=0xFFFFFF00; } memcpy(&Test[0], ML_AABBCorner(&vTmp, &aabbTemp, ML_AABB_BLF), 12); memcpy(&Test[1], ML_AABBCorner(&vTmp, &aabbTemp, ML_AABB_TLF), 12); Test[2].x=aabbTemp.v3Min.x; Test[2].y=aabbTemp.v3Max.y; Test[2].z=aabbTemp.v3Max.z; Test[3].x=aabbTemp.v3Max.x; Test[3].y=aabbTemp.v3Max.y; Test[3].z=aabbTemp.v3Max.z; Test[4].x=aabbTemp.v3Max.x; Test[4].y=aabbTemp.v3Max.y; Test[4].z=aabbTemp.v3Min.z; Test[5].x=aabbTemp.v3Max.x; Test[5].y=aabbTemp.v3Min.y; Test[5].z=aabbTemp.v3Min.z; Test[6].x=aabbTemp.v3Max.x; Test[6].y=aabbTemp.v3Min.y; Test[6].z=aabbTemp.v3Max.z; Test[7].x=aabbTemp.v3Min.x; Test[7].y=aabbTemp.v3Min.y; Test[7].z=aabbTemp.v3Max.z; Test[8].x=aabbTemp.v3Min.x; Test[8].y=aabbTemp.v3Min.y; Test[8].z=aabbTemp.v3Min.z; Test[9].x=aabbTemp.v3Max.x; Test[9].y=aabbTemp.v3Min.y; Test[9].z=aabbTemp.v3Min.z; Test[10].x=aabbTemp.v3Max.x; Test[10].y=aabbTemp.v3Min.y; Test[10].z=aabbTemp.v3Max.z; Test[11].x=aabbTemp.v3Max.x; Test[11].y=aabbTemp.v3Max.y; Test[11].z=aabbTemp.v3Max.z; Test[12].x=aabbTemp.v3Max.x; Test[12].y=aabbTemp.v3Max.y; Test[12].z=aabbTemp.v3Min.z; Test[13].x=aabbTemp.v3Min.x; Test[13].y=aabbTemp.v3Max.y; Test[13].z=aabbTemp.v3Min.z; Test[14].x=aabbTemp.v3Min.x; Test[14].y=aabbTemp.v3Max.y; Test[14].z=aabbTemp.v3Max.z; Test[15].x=aabbTemp.v3Min.x; Test[15].y=aabbTemp.v3Min.y; Test[15].z=aabbTemp.v3Max.z; //Render the AABB. m_pDevice->SetTransform(D3DTS_WORLD, (D3DMATRIX*)&matIdent); m_pDevice->SetFVF(BONEVERTEX_FVF); m_pDevice->DrawPrimitiveUP(D3DPT_LINESTRIP, 15, &Test, sizeof(BONEVERTEX)); m_pDevice->SetTransform(D3DTS_WORLD, (D3DMATRIX*)&matTmp); */ return LG_TRUE; } <file_sep>/tools/QInstall/Demo/Data/Readme.txt This demo was designed to show how QInstall works.<file_sep>/games/Legacy-Engine/Scrapped/old/lm_mesh_d3d_basic.cpp #include <stdio.h> #include "lf_sys2.h" #include "lm_mesh_d3d_basic.h" IDirect3DDevice9* CLMeshD3DBasic::s_pDevice=LG_NULL; CLMesh2::MeshVertex* CLMeshD3DBasic::LockTransfVB() { return m_pTransfVB; } lg_void CLMeshD3DBasic::UnlockTransfVB() { } lg_bool CLMeshD3DBasic::Load(LMPath szFile) { Unload(); LF_FILE3 fin=LF_Open(szFile, LF_ACCESS_READ, LF_OPEN_EXISTING); if(!fin) return LG_FALSE; lg_bool bResult=Serialize(fin, ReadFn, RW_READ); LF_Close(fin); m_nFlags=bResult?LM_FLAG_LOADED:0; if(bResult) { lf_path szTexDir; lf_path szTexPath; LF_GetDirFromPath(szTexDir, szFile); m_pTex=new tm_tex[m_nNumMtrs]; for(lg_dword i=0; i<m_nNumMtrs; i++) { _snprintf(szTexPath, LF_MAX_PATH, "%s%s", szTexDir, m_pMtrs[i].szFile); szTexPath[LF_MAX_PATH]=0; m_pTex[i]=CLTMgr::TM_LoadTex(szTexPath, 0); } m_pTransfVB=new MeshVertex[m_nNumVerts]; for(lg_dword i=0; i<m_nNumVerts; i++) { m_pTransfVB[i]=m_pVerts[i]; } InitAnimData(); } return bResult; } lg_bool CLMeshD3DBasic::Save(LMPath szFile) { return LG_FALSE; } lg_void CLMeshD3DBasic::Unload() { CLMesh2::Unload(); if(m_pTex){delete [] m_pTex; m_pTex=LG_NULL;} if(m_pTransfVB){delete[]m_pTransfVB; m_pTransfVB=LG_NULL;} DeleteAnimData(); } lg_void CLMeshD3DBasic::Render() { if(!m_nFlags&LM_FLAG_LOADED) return; s_pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); s_pDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); s_pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); s_pDevice->SetRenderState(D3DRS_NORMALIZENORMALS, TRUE); s_pDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); s_pDevice->SetRenderState(D3DRS_ZENABLE, TRUE); s_pDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE); s_pDevice->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP); s_pDevice->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP); s_pDevice->SetFVF(D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX1); for(lg_dword i=0; i<m_nNumSubMesh; i++) { CLTMgr::TM_SetTexture(m_pTex[m_pSubMesh[i].nMtrIndex], 0); s_pDevice->DrawIndexedPrimitiveUP( D3DPT_TRIANGLELIST, 0, m_nNumVerts, m_pSubMesh[i].nNumTri, &m_pIndexes[m_pSubMesh[i].nFirstIndex], D3DFMT_INDEX16, m_pTransfVB, sizeof(MeshVertex)); } } lg_uint __cdecl CLMeshD3DBasic::ReadFn(lg_void* file, lg_void* buffer, lg_uint size) { return LF_Read(file, buffer, size); }<file_sep>/games/Legacy-Engine/Source/lf_sys2/lf_bdio.h #ifndef _LF_BDIO_H__ #define _LF_BDIO_H__ #include "lf_sys2.h" #ifdef __cplusplus extern "C"{ #endif __cplusplus /* Basic DIO stuff, should only be used internally only. */ typedef enum _BDIO_SEEK_MODE { BDIO_SEEK_BEGIN=LF_SEEK_BEGIN, BDIO_SEEK_CURRENT=LF_SEEK_CURRENT, BDIO_SEEK_END=LF_SEEK_END }BDIO_SEEK_MODE; #define BDIO_ACCESS_READ LF_ACCESS_READ #define BDIO_ACCESS_WRITE LF_ACCESS_WRITE #define BDIO_ACCESS_TEMP 0x00000080 typedef enum _BDIO_CREATE_MODE { BDIO_CREATE_ALWAYS=LF_CREATE_ALWAYS, //Create a new file, deleting the old file if the file exists. BDIO_CREATE_NEW=LF_CREATE_NEW, //Create a new file, failing if the file already exists. BDIO_OPEN_ALWAYS=LF_OPEN_ALWAYS, //Open a file, creating a new file if the file doesn't exist. BDIO_OPEN_EXISTING=LF_OPEN_EXISTING //OPen a file, failing if the file does not exist. }BDIO_CREATE_MODE; typedef void* BDIO_FILE; BDIO_FILE LF_SYS2_EXPORTS BDIO_OpenA(lf_cstr szFilename, BDIO_CREATE_MODE nMode, lf_dword nAccess); BDIO_FILE LF_SYS2_EXPORTS BDIO_OpenW(lf_cwstr szFilename, BDIO_CREATE_MODE nMode, lf_dword nAccess); #ifdef UNICODE #define BDIO_Open BDIO_OpenW #else UNICODE #define BDIO_Open BDIO_OpenA #endif UNICODE lf_bool LF_SYS2_EXPORTS BDIO_Close(BDIO_FILE File); lf_dword LF_SYS2_EXPORTS BDIO_Read(BDIO_FILE File, lf_dword nSize, void* pOutBuffer); lf_dword LF_SYS2_EXPORTS BDIO_Write(BDIO_FILE File, lf_dword nSize, void* pInBuffer); lf_dword LF_SYS2_EXPORTS BDIO_Tell(BDIO_FILE File); lf_dword LF_SYS2_EXPORTS BDIO_Seek(BDIO_FILE File, lf_long nOffset, BDIO_SEEK_MODE nOrigin); lf_dword LF_SYS2_EXPORTS BDIO_GetSize(BDIO_FILE File); lf_dword LF_SYS2_EXPORTS BDIO_WriteCompressed(BDIO_FILE File, lf_dword nSize, void* pInBuffer); lf_dword LF_SYS2_EXPORTS BDIO_ReadCompressed(BDIO_FILE File, lf_dword nSize, void* pOutBuffer); lf_bool LF_SYS2_EXPORTS BDIO_ChangeDirA(lf_cstr szDir); lf_bool LF_SYS2_EXPORTS BDIO_ChangeDirW(lf_cwstr szDir); lf_dword LF_SYS2_EXPORTS BDIO_GetCurrentDirA(lf_str szDir, lf_dword nSize); lf_dword LF_SYS2_EXPORTS BDIO_GetCurrentDirW(lf_wstr szDir, lf_dword nSize); BDIO_FILE LF_SYS2_EXPORTS BDIO_OpenTempFileA(BDIO_CREATE_MODE nMode, lf_dword nAccess); BDIO_FILE LF_SYS2_EXPORTS BDIO_OpenTempFileW(BDIO_CREATE_MODE nMode, lf_dword nAccess); lf_dword LF_SYS2_EXPORTS BDIO_CopyData(BDIO_FILE DestFile, BDIO_FILE SourceFile, lf_dword nSize); lf_dword LF_SYS2_EXPORTS BDIO_GetFullPathNameW(lf_pathW szPath, const lf_pathW szFilename); lf_dword LF_SYS2_EXPORTS BDIO_GetFullPathNameA(lf_pathA szPath, const lf_pathA szFilename); #ifdef UNICODE #define BDIO_ChangeDir BDIO_ChangeDirW #define BDIO_GetCurrentDir BDIO_GetCurrentDirW #define BDIO_OpenTempFile BDIO_OpenTempFileW #define BDIO_GetFullPathName BDIO_GetFullPathNameW #else UNICODE #define BDIO_ChangeDir BDIO_ChangeDirA #define BDIO_GetCurrentDir BDIO_GetCurrentDirA #define BDIO_OpenTempFile BDIO_OpenTempFileA #define BDIO_GetFullPathName BDIO_GetFullPathNameA #endif UNICODE typedef void* BDIO_FIND; typedef struct _BDIO_FIND_DATAW{ lf_bool bDirectory; lf_bool bReadOnly; lf_bool bHidden; lf_bool bNormal; lf_large_integer nFileSize; lf_pathW szFilename; }BDIO_FIND_DATAW; typedef struct _BDIO_FIND_DATAA{ lf_bool bDirectory; lf_bool bReadOnly; lf_bool bHidden; lf_bool bNormal; lf_large_integer nFileSize; lf_pathA szFilename; }BDIO_FIND_DATAA; BDIO_FIND LF_SYS2_EXPORTS BDIO_FindFirstFileW(lf_cwstr szFilename, BDIO_FIND_DATAW* pFindData); lf_bool LF_SYS2_EXPORTS BDIO_FindNextFileW(BDIO_FIND hFindFile, BDIO_FIND_DATAW* pFindData); BDIO_FIND LF_SYS2_EXPORTS BDIO_FindFirstFileA(lf_cstr szFilename, BDIO_FIND_DATAA* pFindData); lf_bool LF_SYS2_EXPORTS BDIO_FindNextFileA(BDIO_FIND hFindFile, BDIO_FIND_DATAA* pFindData); lf_bool LF_SYS2_EXPORTS BDIO_FindClose(BDIO_FIND hFindFile); #ifdef __cplusplus } #endif __cplusplus #endif _LF_BDIO_H__<file_sep>/games/Legacy-Engine/Scrapped/old/lv_reset.h #ifdef __LV_RESTORE_H__ #define __LV_RESTORE_H__ #include "common.h" #include "lg_sys.h" #ifdef __cplusplus extern "C"{ #endif /*__cplusplus*/ #define LVERR_NODEVICE 0x80000010l #define LVERR_DEVICELOST 0x80000000l #define LVERR_CANTRECOVER 0x80000001l #define LVERR_DEVICERESET 0x80000002l L_result LV_ValidateDevice(L3DGame* lpGame); L_result LV_ValidateGraphics(L3DGame* lpGame); L_result LV_InvalidateGraphics(L3DGame* lpGame); L_result LV_Restart(L3DGame* lpGame); #ifdef __cplusplus } #endif /*__cplusplus*/ #endif /* __LV_RESTORE_H__*/<file_sep>/games/Legacy-Engine/Source/engine/lx_sys.h /* lx_sys.h - XML Loading routines. Copyright (c) 2007 <NAME> Notes: The XML loading routines are used to load various .xml files and returns the information contained in those files in a more computer usable data structure. Each XML loader comes in two parts. LX_Load#TYPE# which loads the specified file and returns computer understandable information about the file. And LX_Destroy#TYPE# which frees any memory used in loading the file. XML Loading routines only convert the data in the files into usable information. They do not actually load the specified data into the game engine. */ #include "common.h" #include "lf_sys2.h" #include "lg_xml.h" #include "lg_err.h" #define LX_START_TAG {if(0){} #define LX_END_TAG else {Err_Printf("WARNING: %s is not recognized as a valid tag.", name);}} #define LX_TAG(tag_name) else if(stricmp(name, #tag_name)==0) //Helper macros #define LX_START_ATTR for(lg_dword i=0; atts[i]; i+=2){if(0){} #define LX_END_ATTR } #define LX_ATTR_DWORD(dest, name) else if(stricmp(atts[i], #name)==0){dest=atoi(atts[i+1]);} #define LX_ATTR_FLOAT(dest, name) else if(stricmp(atts[i], #name)==0){dest=(lg_float)atof(atts[i+1]);} #define LX_ATTR_STRING(dest, name, size) else if(stricmp(atts[i], #name)==0){LG_strncpy(dest, atts[i+1], size);} #define LX_ATTR_FLOAT3(dest, name) else if(stricmp(atts[i], #name)==0){ \ XML_Char* szTok=strtok((XML_Char*)atts[i+1], ", "); \ ((lg_float*)dest)[0]=szTok?(lg_float)atof(szTok):0.0f; \ szTok=strtok(LG_NULL, ", "); \ ((lg_float*)dest)[1]=szTok?(lg_float)atof(szTok):0.0f; \ szTok=strtok(LG_NULL, ", "); \ ((lg_float*)dest)[2]=szTok?(lg_float)atof(szTok):0.0f; \ } #define LX_MISC_ATTR(name) else if(stricmp(atts[i], #name)==0){ #define LX_END_MISC_ATTR } #define LX_MAX_NAME 255 typedef lg_char lx_name[LX_MAX_NAME+1]; typedef struct _lx_ent_template { lg_dword nID; lg_path szScript; }lx_ent_template; lx_ent_template* LX_LoadEntTemplate(const lg_path szFilename, lg_dword* pCount); lg_void LX_DestroyEntTemplate(lx_ent_template* pTemplate); typedef struct _lx_object_mode{ lx_name szName; }lx_object_mode; /* class CLXLoader { public: CLXLoader(); ~CLXLoader(); lg_void Load(lg_path szXMLFile); }; */ lg_bool LX_Process(const lg_path szXMLFile, XML_StartElementHandler startH, XML_EndElementHandler endH, XML_CharacterDataHandler charDataH, lg_void* pData); //LX_OBJECT: XML Loading for objects (aka entities). //The LX_OBJ_PHYS_ flags are set in lx_object::pPhysFlags //and tell information about how the object should be //created physics wise. #define LX_OBJ_PHYS_AUTO_CENTER 0x00000001 /* #define LX_OBJ_PHYS_SHAPE_CAPSULE 0x00000002 #define LX_OBJ_PHYS_SHAPE_BOX 0x00000004 #define LX_OBJ_PHYS_SHAPE_SPHERE 0x00000008 #define LX_OBJ_PHYS_SHAPE_CYLINDER 0x00000010 */ #define LX_OBJ_PHYS_BOUNDS_SKEL 0x00000020 #define LX_OBJ_PHYS_BOUNDS_MESH 0x00000040 typedef struct _lx_object{ lf_path szModelFile; lg_dword nNumSkels; lf_path* pSkelFiles; lx_name* pSkelMeshes; lx_name szAiFunction; //Physics stuff. lg_float fMass; //lg_float fXC, fYC, fZC; lg_float fMassCenter[3]; lg_dword nPhysFlags; lg_dword nShape; //lg_float fScale; lg_float fHeight; lg_float fRadius; lg_float fShapeOffset[3]; //Modes lg_dword nModeCount; lx_object_mode* pModes; }lx_object; /* LX_LoadObject PRE: File System Initialized. szXMLFile should point to a properly declared "object" xml file. POST: A new lx_object is created based on the specifications in the xml file. If null is returned it means there was some kind of error. Though if an actual object is returned it doesn't necessarily mean there was no error. Check the console to see if an error occured while loading. That said, just because there was no errors doesn't mean a valid object can get created off the information. It must contain valid files, mesh references and so forth. See the declaration of the lx_object structure for details on what is returned. */ lx_object* LX_LoadObject(const lf_path szXMLFile); /* LX_DestroyObject PRE: pObject != null and should have been created by LX_LoadObject. Any pointer returned by LX_LoadObject should be deleted using this method. POST: The memory associated with pObject is freed. pObject should no longer be used. */ lg_void LX_DestroyObject(lx_object* pObject); /* The level loading XML, gets all information to load a level. */ typedef struct _lx_level_object{ lg_path szObjFile; lg_float fPosition[3]; }lx_level_object; typedef struct _lx_level{ lg_path szMapFile; lg_path szSkyBoxFile; lg_path szSkyBoxSkin; lg_path szMusicFile; lg_dword nObjCount; lg_dword nActorCount; lx_level_object* pObjs; lx_level_object* pActors; }lx_level; /* PRE: See LoadObject for example. POST: See LoadObject for example. */ lx_level* LX_LoadLevel(const lg_path szXMLFile); /* PRE: See DestroyObject for example. POST: See DestroyObject for example. */ lg_void LX_DestroyLevel(lx_level* pLevel); /*********************** *** Material Loading *** ***********************/ typedef struct _lx_mtr{ lg_path szTexture; lg_path szFx; }lx_mtr; /* PRE: pMtr should be a MtrItem. POST: If LG_TRUE was returend then pMtr contains a valid material, if not then the material is invalid. */ lg_bool LX_LoadMtr(const lg_path szFilename, lx_mtr* pMtr); /* PRE: N/A POST: Loads teh skin, returns false if it can't. */ lg_bool LX_LoadSkin(const lg_path szFilename, void* pSkin); /************************ *** Mesh Tree loading *** ************************/ #include "lm_mesh_tree.h" typedef struct _lx_mesh_node{ lg_string szName; lg_path szMeshFile; lg_path szSkinFile; lg_path szDefSkelFile; lg_dword nParentNode; lg_string szParentJoint; }lx_mesh_node; typedef struct _lx_mesh_tree_data{ lg_string szName; lg_dword nNodeCount; lg_dword nSkelCount; lg_bool bYaw180; lg_float fScale; lx_mesh_node Nodes[CLMeshTree::MT_MAX_MESH_NODES]; lg_path szSkels[CLMeshTree::MT_MAX_SKELS]; }lx_mesh_tree_data; /* PRE: szFilename is the file to load. POST: If true is returned then pOut will be full of infor about the tree. If not the data is invalid. The data doesn't need to be deallocated. */ lg_bool LX_LoadMeshTree(const lg_path szFilename, lx_mesh_tree_data* pOut);<file_sep>/tools/GFX/GFXG7/DDFunc.c /* DDFunc.c - Functions for setting up and using DirectDraw. Copyright (c) 2003 <NAME> */ #include <windowsx.h> #include "GFXG7.h" HRESULT PageFlip( LPDIRECTDRAWSURFACE7 lpPrimary, LPDIRECTDRAWSURFACE7 lpBackBuffer, BOOL bWindowed, RECT * rcWindow, HRESULT ( * Restore)()) { HRESULT hr=0; RECT rcSource; DDSURFACEDESC2 desc; /* Bail if buffers do not exist as we cannot do anything. */ if(!lpPrimary || !lpBackBuffer) return E_POINTER; while(TRUE){ if(bWindowed){ desc.dwSize=sizeof(DDSURFACEDESC2); desc.dwFlags=DDSD_WIDTH|DDSD_HEIGHT; lpBackBuffer->lpVtbl->GetSurfaceDesc(lpBackBuffer, &desc); rcSource.top=rcSource.left=0; rcSource.bottom=desc.dwHeight; rcSource.right=desc.dwWidth; if(hr = lpPrimary->lpVtbl->Blt( lpPrimary, rcWindow, lpBackBuffer, &rcSource, DDBLT_WAIT, NULL )==DDERR_SURFACELOST) { return Restore(); } }else{ if(lpPrimary->lpVtbl->Flip(lpPrimary, NULL,DDFLIP_WAIT)==DDERR_SURFACELOST){ return Restore(); } } if(hr!=DDERR_WASSTILLDRAWING) return hr; } return S_OK; } void SetSavedParameters( SAVEDPARAMETERS * pSavedParams, DWORD dwWidth, DWORD dwHeight, DWORD dwColorDepth, DWORD dwTransparentColor, HWND hWnd, RECT * rcWindow, BOOL bWindowed) { pSavedParams->dwWidth=dwWidth; pSavedParams->dwHeight=dwHeight; pSavedParams->dwColorDepth=dwColorDepth; pSavedParams->dwTransparentColor=dwTransparentColor; pSavedParams->hWnd=hWnd; if(rcWindow!=NULL) memcpy(&(pSavedParams->rcWindow), rcWindow, sizeof(RECT)); else ZeroMemory(&(pSavedParams->rcWindow), sizeof(RECT)); pSavedParams->bWindowed=bWindowed; } HRESULT AdjustWindowSize( HWND hWnd, DWORD nWidth, DWORD nHeight, BOOL bWindowed, HMENU hMenu) { if(bWindowed){ /* Make sure window styles are correct. */ RECT rcWork; RECT rc; DWORD dwStyle; if(hMenu) SetMenu(hWnd, hMenu); dwStyle=GetWindowStyle(hWnd); dwStyle &= ~WS_POPUP; dwStyle |= WS_SYSMENU|WS_OVERLAPPED|WS_CAPTION | WS_DLGFRAME | WS_MINIMIZEBOX; SetWindowLong(hWnd, GWL_STYLE, dwStyle); SetRect(&rc, 0, 0, nWidth, nHeight); AdjustWindowRectEx(&rc, GetWindowStyle(hWnd), GetMenu(hWnd)!=NULL, GetWindowExStyle(hWnd)); SetWindowPos( hWnd, NULL, 0, 0, rc.right-rc.left, rc.bottom-rc.top, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE ); SetWindowPos( hWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE ); /* Make sure our window does not hang outside of the work area. */ SystemParametersInfo( SPI_GETWORKAREA, 0, &rcWork, 0 ); GetWindowRect( hWnd, &rc ); if( rc.left < rcWork.left ) rc.left = rcWork.left; if( rc.top < rcWork.top ) rc.top = rcWork.top; SetWindowPos( hWnd, NULL, rc.left, rc.top, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE ); return S_OK; }else return S_FALSE; } HRESULT UpdateBounds(BOOL bWindowed, HWND hWnd, RECT * rcWindow) { if( bWindowed ) { GetClientRect(hWnd, rcWindow ); ClientToScreen(hWnd, (POINT*)rcWindow ); ClientToScreen(hWnd, (POINT*)rcWindow+1 ); } else { SetRect(rcWindow, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN) ); } return S_OK; } HRESULT InitDirectDrawEx( LPDIRECTDRAW7 * lppDDraw, LPDIRECTDRAWSURFACE7 * lppPrimary, LPDIRECTDRAWSURFACE7 * lppBack, SAVEDPARAMETERS * pSavedParams) { return InitDirectDraw( lppDDraw, lppPrimary, lppBack, pSavedParams->hWnd, pSavedParams->bWindowed, pSavedParams->dwWidth, pSavedParams->dwHeight, pSavedParams->dwColorDepth, &(pSavedParams->rcWindow), &(pSavedParams->dwTransparentColor)); } HRESULT InitDirectDraw( LPDIRECTDRAW7 *lppDDraw, LPDIRECTDRAWSURFACE7 *lppPrimary, LPDIRECTDRAWSURFACE7 *lppBack, HWND hwnd, BOOL bWindowed, DWORD dwWidth, DWORD dwHeight, DWORD dwBitDepth, RECT *rcWindow, DWORD *dwTransparentColor) { HRESULT hr=0; if(bWindowed){ hr=InitWindowedDirectDraw( lppDDraw, lppBack, lppPrimary, hwnd, dwWidth, dwHeight, rcWindow, dwTransparentColor); }else{ hr=InitFullScreenDirectDraw( lppDDraw, lppBack, lppPrimary, hwnd, dwWidth, dwHeight, dwBitDepth, rcWindow, dwTransparentColor); } return hr; } HRESULT InitWindowedDirectDraw( LPDIRECTDRAW7 * lppDDraw, LPDIRECTDRAWSURFACE7 * lppBackBuffer, LPDIRECTDRAWSURFACE7 * lppPrimary, HWND hWnd, DWORD dwWidth, DWORD dwHeight, RECT * rcWindow, DWORD * lpTransparentColor) { HRESULT hr=0; DDSURFACEDESC2 ddsd; LPDIRECTDRAWCLIPPER pcClipper=NULL; ZeroMemory(&ddsd, sizeof(DDSURFACEDESC2)); /* Create Direcdraw and set cooperative level. */ if(FAILED(hr=DirectDrawCreateEx( NULL, (VOID**)&*lppDDraw, &IID_IDirectDraw7, NULL)))return E_FAIL; hr=(*lppDDraw)->lpVtbl->SetCooperativeLevel((*lppDDraw), hWnd, DDSCL_NORMAL); if(FAILED(hr))return E_FAIL; /* Create the primary surface. */ ZeroMemory( &ddsd, sizeof( ddsd ) ); ddsd.dwSize = sizeof( ddsd ); ddsd.dwFlags = DDSD_CAPS; ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE; if( FAILED( (*lppDDraw)->lpVtbl->CreateSurface((*lppDDraw), &ddsd, &*lppPrimary, NULL ))) return E_FAIL; if(FAILED((*lppDDraw)->lpVtbl->CreateClipper((*lppDDraw), 0, &pcClipper, NULL)))return E_FAIL; if( FAILED( hr = pcClipper->lpVtbl->SetHWnd(pcClipper, 0, hWnd))) { pcClipper->lpVtbl->Release(pcClipper); return E_FAIL; } if( FAILED( hr = (*lppPrimary)->lpVtbl->SetClipper((*lppPrimary), pcClipper))) { pcClipper->lpVtbl->Release(pcClipper); return E_FAIL; } /* Done with clipper. */ pcClipper->lpVtbl->Release(pcClipper); /* Create the backbuffer surface. */ ddsd.dwFlags = DDSD_CAPS|DDSD_WIDTH|DDSD_HEIGHT; ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN| DDSCAPS_3DDEVICE; ddsd.dwWidth = dwWidth; ddsd.dwHeight = dwHeight; if( FAILED( hr = (*lppDDraw)->lpVtbl->CreateSurface((*lppDDraw), &ddsd, &*lppBackBuffer, NULL))) return E_FAIL; *lpTransparentColor=WindowsColorToDirectDraw(*lpTransparentColor, *lppPrimary); UpdateBounds(TRUE, hWnd, rcWindow); return S_OK; } DWORD WindowsColorToDirectDraw(COLORREF rgb, LPDIRECTDRAWSURFACE7 surface){ DWORD dw=CLR_INVALID; COLORREF rgbT; HDC hDc; DDSURFACEDESC2 ddsd; HRESULT hres; if(rgb!=CLR_INVALID&&SUCCEEDED(surface->lpVtbl->GetDC(surface, &hDc))){ rgbT=GetPixel(hDc, 0, 0); SetPixel(hDc, 0, 0, rgb); surface->lpVtbl->ReleaseDC(surface, hDc); } ddsd.dwSize=sizeof(ddsd); while((hres=surface->lpVtbl->Lock(surface, NULL, &ddsd, 0, NULL))==DDERR_WASSTILLDRAWING); if(SUCCEEDED(hres)){ dw=*(DWORD*)ddsd.lpSurface; if(ddsd.ddpfPixelFormat.dwRGBBitCount!=32) dw&=(1<<ddsd.ddpfPixelFormat.dwRGBBitCount)-1; surface->lpVtbl->Unlock(surface, NULL); } if(rgb!=CLR_INVALID&&SUCCEEDED(surface->lpVtbl->GetDC(surface, &hDc))){ SetPixel(hDc, 0, 0, rgbT); surface->lpVtbl->ReleaseDC(surface, hDc); } return dw; } HRESULT InitFullScreenDirectDraw( LPDIRECTDRAW7 *lppDDraw, LPDIRECTDRAWSURFACE7 *lppBackBuffer, LPDIRECTDRAWSURFACE7 *lppPrimary, HWND hWnd, DWORD dwWidth, DWORD dwHeight, DWORD dwBitDepth, RECT *rcWindow, DWORD *nTransparentColor) { HRESULT hr=0; DDSURFACEDESC2 ddsd; DDSCAPS2 ddscaps; DWORD dwStyle=0; SetMenu(hWnd, NULL); if(FAILED(hr=DirectDrawCreateEx( NULL, (VOID**)&*lppDDraw, &IID_IDirectDraw7, NULL)))return E_FAIL; hr=(*lppDDraw)->lpVtbl->SetCooperativeLevel((*lppDDraw), hWnd, DDSCL_EXCLUSIVE|DDSCL_FULLSCREEN); if(FAILED(hr))return E_FAIL; if(FAILED((*lppDDraw)->lpVtbl->SetDisplayMode((*lppDDraw), dwWidth, dwHeight, dwBitDepth, 0, 0))) return E_FAIL; /* Create the primary surface. */ ZeroMemory(&ddsd,sizeof( ddsd ) ); ddsd.dwSize = sizeof( ddsd ); ddsd.dwFlags = DDSD_CAPS|DDSD_BACKBUFFERCOUNT; ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE|DDSCAPS_FLIP| DDSCAPS_COMPLEX|DDSCAPS_3DDEVICE; ddsd.dwBackBufferCount = 1; if(FAILED(hr=(*lppDDraw)->lpVtbl->CreateSurface((*lppDDraw), &ddsd, &*lppPrimary, NULL))) return E_FAIL; /* Get a pointer to the back buffer. */ ZeroMemory(&ddscaps, sizeof(ddscaps)); ddscaps.dwCaps=DDSCAPS_BACKBUFFER; if(FAILED(hr =(*lppPrimary)->lpVtbl->GetAttachedSurface((*lppPrimary), &ddscaps, &*lppBackBuffer))) return E_FAIL; dwStyle=WS_POPUP; SetWindowLong( hWnd, GWL_STYLE, dwStyle ); *nTransparentColor=WindowsColorToDirectDraw(*nTransparentColor, *lppPrimary); UpdateBounds(FALSE, hWnd, rcWindow); return hr; }<file_sep>/games/Legacy-Engine/Source/engine/lg_mtr_mgr.h #ifndef __LG_MTR_MGR_H__ #define __LG_MTR_MGR_H__ #include "lg_types.h" #include "lg_hash_mgr.h" #include "lg_tmgr.h" #include "lg_fxmgr.h" #include "lg_list_stack.h" typedef hm_item lg_material; struct MtrItem: public CLListStack::LSItem { public: tm_tex Texture; fxm_fx Effect; }; LG_CACHE_ALIGN class CLMtrMgr: public CLHashMgr<MtrItem> { private: //We are using a list stack to create and destroy //materials, in the manner as for the CLMeshMgr and CLSkelMgr. MtrItem* m_pMtrMem; CLListStack m_stkMtr; MtrItem m_DefMtr; public: /* PRE: Specify the maximum number of materials in nMaxMtr POST: Ready for use. */ CLMtrMgr(lg_dword nMaxMtr); /* PRE: N/A POST: Manager is destroyed. */ ~CLMtrMgr(); private: //Internally used methods. virtual MtrItem* DoLoad(lg_path szFilename, lg_dword nFlags); virtual void DoDestroy(MtrItem* pItem); public: /* PRE: mtr should be a material, and pVB a valid vertex buffer. Should be within the Device methdos of BeginScene and EndScene. POST: Currently just renders whatever is passed into the method. In the future it will probably stick the vertices into some kind of buffer. */ void RenderVB( lg_material mtr, IDirect3DDevice9* pDevice, IDirect3DVertexBuffer9* pVB); /* PRE: PRE: mtr should be loaded. POST: Obtains the interfaces as specified. */ void GetInterfaces(lg_material mtr, tm_tex* pTex, ID3DXEffect** pFX); //Static stuff: private: static CLMtrMgr* s_pMtrMgr; public: static lg_material MTR_Load(lg_path szFilename, lg_dword nFlags); static void MTR_RenderVB(lg_material mtr, IDirect3DDevice9* pDevice, IDirect3DVertexBuffer9* pVB); static void MTR_GetInterfaces(lg_material mtr, tm_tex* pTex, ID3DXEffect** pFX); }; #endif __LG_MTR_MGR_H__<file_sep>/games/Legacy-Engine/Scrapped/plugins/msLMEXP/LegacyExp.cpp //Milkshape Exporter for the Legacy Mesh and Skeleton Formats (lmsh, lskl). #include <windows.h> #include "stdafx.h" #include "ExportDialog.h" #pragma comment(lib, "msLib\\lib\\msModelLib.lib") #pragma comment(lib, "ML_lib.lib") // -------------------------------------------------------- class CLegacyExp:public cMsPlugIn { private: public: CLegacyExp(){} virtual ~CLegacyExp(){}; int GetType(){return cMsPlugIn::eTypeExport;} const char* GetTitle(){return "Legacy Engine Format...";} int Execute(msModel* pModel); }; int CLegacyExp::Execute(msModel* pModel) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); //Get a filename to export our data to. //Initialize the math library. ML_Init(ML_INSTR_F); CExportDialog dlgExport; if(msModel_GetMeshCount(pModel)<1) dlgExport.m_bMeshExport=FALSE; if(msModel_GetBoneCount(pModel)<1) dlgExport.m_bSkelExport=FALSE; do { if(dlgExport.DoModal()==IDCANCEL) { msModel_Destroy(pModel); return 0; } BOOL bError=FALSE; if(dlgExport.m_bMeshExport) { bError=bError||dlgExport.m_szMeshName.IsEmpty(); bError=bError||dlgExport.m_szMeshPath.IsEmpty(); } if(dlgExport.m_bSkelExport) { bError=bError||dlgExport.m_szSkelName.IsEmpty(); bError=bError||dlgExport.m_szSkelPath.IsEmpty(); } if(bError) { AfxMessageBox(_T("A required parameter was not specified!")); continue; } break; }while(TRUE); //All we need to to is load the mesh //from the milkshape model then call //the save function. if(dlgExport.m_bMeshExport) { CLMeshMS Mesh(pModel, dlgExport.m_szMeshName.GetBuffer()); if(Mesh.IsLoaded()) { Mesh.Save(dlgExport.m_szMeshPath.GetBuffer()); } Mesh.Unload(); } if(dlgExport.m_bSkelExport) { CLSkelMS Skel(pModel, dlgExport.m_szSkelName.GetBuffer()); if(Skel.IsLoaded()) { Skel.Save(dlgExport.m_szSkelPath.GetBuffer()); } Skel.Unload(); } MessageBox( NULL, _T("Legacy Object(s) Exported"), _T("Legacy Engine Exporter"), MB_OK|MB_ICONINFORMATION); msModel_Destroy(pModel); return 0; } //Our export function so milkshape can perform //the operations. cMsPlugIn *CreatePlugIn() { return new CLegacyExp; } <file_sep>/games/Legacy-Engine/Source/engine/lg_sys.cpp #include <d3dx9.h> #include <stdio.h> #include "lg_sys.h" #include "ML_lib.h" #include "lt_sys.h" CLGame::CLGame(): m_nGameState(LGSTATE_NOTSTARTED), m_nGameType(LGTYPE_SERVER_CLIENT), m_hwnd(LG_NULL), #ifdef OLD_WORLD m_pMeshMgr(LG_NULL), #endif OLD_WORLD #ifdef OLD_WORLD m_pWorld(LG_NULL), #endif m_WorldSrv(), m_WorldCln(), //m_pMMgr(LG_NULL) CLMgrs() { } CLGame::~CLGame() { } /* The game loop everything in the game controlled from here, or at least by one of the functions called from here. The parameter hwnd, is the handle of the games window, the nShutdownMsg is used to determine if windows is telling the game it should shutdown. GameLoop returns TRUE if the game is still running, if the game is not running it returns FALSE in which case the application should close itself.*/ lg_bool CLGame::LG_GameLoop() { if(m_nGameState!=LGSTATE_RUNNING) return LG_FALSE; LG_ProcessGame(); if(cv_l_ShouldQuit->nValue)//l_ShouldQuit->value) { LG_GameShutdown(); return LG_FALSE; } return LG_TRUE; } void CLGame::LG_ProcessGame() { //First thing we should do is update the timer //Note that the timer should only be updated here as //the whole frame should be processed as if it were the //same time, even though some time will pass durring //the processing. s_Timer.Update(); //Now update input (if the console is active //we'll let windows handle keyboard input to //the console (see win_sys.cpp). if(!m_VCon.IsActive()) { if(m_Input.LI_Update(LI_UPDATE_ALL)==LIS_CONSOLE) m_VCon.Toggle(); } else m_Input.LI_Update(LI_UPDATE_MOUSE|LI_UPDATE_GP); //Should process AI. #ifdef OLD_WORLD m_pWorld->ProcessEntities(); #endif m_WorldSrv.ProcessServer(); m_WorldCln.Update(); //The render everything... LG_RenderGraphics(); //Now update the sound engine... m_SndMgr.Update(); //Here is some week framerate code. static lg_dword dwLastTick=s_Timer.GetTime(); static lg_dword dwFrame=0; if((s_Timer.GetTime()-dwLastTick)>250) { CV_Set_l(cv_l_AverageFPS, dwFrame*4); dwFrame=0; dwLastTick=s_Timer.GetTime(); m_VCon.SetMessage(1, cv_l_AverageFPS->szValue); } dwFrame++; } //LG_OnChar is only for console input, //it is called from the windows messaging //system, all other keyboard input is //managed by the CLInput class. void CLGame::LG_OnChar(char c) { m_VCon.OnCharA(c); } void CLGame::LG_SendCommand(lg_cstr szCommand) { LC_SendCommand(szCommand); } lg_result CLGame::LG_RenderGraphics() { D3DXMATRIX matT; lg_result nResult=0; /* Make sure the device can still render. If not call LV_ValidateDevice() until the device can render again.*/ if(LG_FAILED(s_pDevice->TestCooperativeLevel())) return LV_ValidateDevice(); D3DVIEWPORT9 vp; s_pDevice->Clear(0,0,D3DCLEAR_ZBUFFER|D3DCLEAR_TARGET,0xFF5050FF,1.0f,0); s_pDevice->BeginScene(); #ifdef OLD_WORLD m_pWorld->Render(); #endif //Render the client. SetWorldRS(); m_WorldCln.Render(); SetWindowRS(); m_WndMgr.Render(); SetConsoleRS(); m_VCon.Render(); s_pDevice->EndScene(); s_pDevice->Present(NULL, NULL, NULL, NULL); return LG_OK; } void CLGame::SetWorldRS() { } void CLGame::SetWindowRS() { } void CLGame::SetConsoleRS() { } <file_sep>/games/Explor2002/Dist/Readme.txt Explore Copyright (c) 2002, <NAME> for Beem Software Version 3.xxB System Requirments: Windows ME/98/2000/XP (May work on NT and 95); DirectX 8.0 or higher; DirectX compatible sound card; DirectX compatible video card. I'm not sure about any other requirements, but here's a guess. 32 MB RAM; 200 MHz Intel or AMD processor (or compatible). To play run the EXE file. Use the arrow keys to move around. At this point in development there is nothing to do except move around, no monsters or anything. I doubt I'll ever finish this game. I wrote it more or less as practice. ScrollGIN technology will be a lot better anyhow. Copyright (c) 2002 <NAME>. Beem Software, Explor, ExplorED, ExplorSCRIPT, and their respective logos are trademarks and/or registered trademarks of Blaine Myers. All rights reserved. ======================================================== === Version History === === for Explor: A New World === ======================================================== v3.00B Now uses DirectX and Win32 technology. vX.XX Developing stages of Exlor Beta 2. v0.04b (August 6, 2000) Added automap. Made it so automap can be turned off if the value is false. v0.03b (August 6, 2000) Now there is only one load () function. Fixed a bug that appeared while facing north v0.02b The Beta release of this software title. v0.00c A 2D version of the game before it was rendered 3D.<file_sep>/games/Legacy-Engine/Source/lf_sys2/lf_lpk.h #ifndef __LF_ARC_H__ #define __LF_ARC_H__ #include "lf_sys2.h" #include "lf_bdio.h" #define LPK_VERSION 102 #define LPK_TYPE 0x314B504C //(*(lf_dword*)"LPK1") #define LPK_VERSIONTXT ("1.02") #define LPK_FILE_TYPE_NORMAL 0x00000001 #define LPK_FILE_TYPE_ZLIBCMP 0x00000002 #define LPK_OPEN_ENABLEWRITE 0x00000001 #define LPK_ADD_ZLIBCMP 0x00000002 typedef struct _LPK_FILE_INFO{ lf_pathW szFilename; lf_dword nType; lf_dword nOffset; lf_dword nSize; lf_dword nCmpSize; }LPK_FILE_INFO; #define LPK_FILE_POS_TEMP 0x00000020 #define LPK_FILE_POS_MAIN 0x00000030 typedef struct _LPK_FILE_INFO_EX: public LPK_FILE_INFO{ lf_dword nInternalPosition; }LPK_FILE_INFO_EX; class LF_SYS2_EXPORTS CLArchive { private: lf_dword m_nType; lf_dword m_nVersion; lf_dword m_nCount; lf_dword m_nInfoOffset; LPK_FILE_INFO_EX* m_pFileList; BDIO_FILE m_File; BDIO_FILE m_TempFile; lf_bool m_bOpen; lf_bool m_bWriteable; lf_dword m_nMainFileWritePos; lf_bool m_bHasChanged; lf_dword m_nCmpThreshold; lf_bool ReadArcInfo(); lf_dword DoAddFile(BDIO_FILE fin, lf_cwstr szNameInArc, lf_dword dwFlags); lf_bool OpenOld(); public: CLArchive(); ~CLArchive(); lf_bool CreateNewW(lf_cwstr szFilename); lf_bool CreateNewA(lf_cstr szFilename); lf_bool OpenW(lf_cwstr szFilename, lf_dword Flags=0); lf_bool OpenA(lf_cstr szFilename, lf_dword Flags=0); void Close(); lf_bool Save(); lf_dword AddFileW(lf_cwstr szFilename, lf_cwstr szNameInArc, lf_dword Flags); lf_dword AddFileA(lf_cstr szFilename, lf_cstr szNameInArc, lf_dword Flags); lf_dword GetNumFiles(); lf_bool GetFileInfo(lf_dword nRef, LPK_FILE_INFO* pInfo); const LPK_FILE_INFO* GetFileInfo(lf_dword nRef); lf_bool IsOpen(); lf_dword GetFileRef(const lf_pathW szName); lf_byte* ExtractFile(lf_byte* pOut, lf_dword nRef); #ifdef UNICODE #define CreateNew CreateNewW #define Open OpenW #define AddFile AddFileW #else !UNICODE #define CreateNew CreateNewA #define Open OpenA #define AddFile AddFileA #endif UNICODE }; #endif __LF_ARC_H__<file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/console/lconsole/lc_common.c #include "common.h" /* L_CheckValueName makes sure that the definition name is allowed. */ int L_CheckValueName(char* szDef, char* szNoFirstAllow, char* szNoAllow) { unsigned long len=L_strlen(szDef), lenallow=0; unsigned long i=0, j=0; /* The idea behind the default checks, is that the first number cannot be a number, and no special characters are allowed in the name, this is similar to what c language allows. */ char szDefNoFirstAllow[]="0987654321"; char szDefNoAllow[]="{}[]\'\";:.,<>?/\\`~=+)(*&$^%#@!~ "; if(szNoFirstAllow==L_null) szNoFirstAllow=szDefNoFirstAllow; if(szNoAllow==L_null) szNoAllow=szDefNoAllow; /* Check to see if the first character is a no allow. */ for(i=0, lenallow=L_strlen(szNoFirstAllow); i<lenallow; i++) { if(szDef[0]==szNoFirstAllow[i]) return 0; } /* Now make sure no invalid characters are in the string. */ for(i=0, lenallow=L_strlen(szNoAllow); i<lenallow; i++) { for(j=0; j<len; j++) { if(szDef[j]==szNoAllow[i]) return 0; } } return 1; }<file_sep>/games/Legacy-Engine/Source/engine/lw_net.h #ifndef __LW_NET_H__ #define __LW_NET_H__ #include "lg_list_stack.h" enum CLNT_CONNECT_TYPE{ CLNT_CONNECT_DISC=0, //Not connected. CLNT_CONNECT_TCP, //Connected using TCP. CLNT_CONNECT_UDP, CLNT_CONNECT_LOCAL,//Connected to local server. }; //Server to client commands: typedef enum _SRV_TO_CLNT_CMDS{ //Server shutdown: //Params: None. //Notes: This is broadcast to all clients //before the server shuts down. After this message //has been broadcast, the client should assume that //it should disconnect. STCC_SHUTDOWN=0, //Client Disconnect: //Params: None. //Notes: When a client is sent this message it should //assume that it will no longer receive updates from //the server, and as far as the server is concerned //the client is no longer connected. STCC_DISCONNECT, //Entity Move: //Params: Information about the entity. //Notes: This is broadcast to clients when something //about an entity changes. It will be followed by //additional information about what changed. Note, //that just because an entity changes, doesn't mean //that this message is sent to the client. The server //will usually only send relevant changes to a client //so if an object is too far away to matter, information //about it will not be sent. STCC_ENT_MOVE, //Entity create: //Params: ID of the entity that was created, and //information about the entity. //Notes: Indicates that an entity was created, all //clients need to receive this information, and need //to reply with confirmation that the entity was //created. STCC_ENT_CREATE, //Entity Destroy: //Params: ID of the entity to be destroyed. //Notes: Indicates that an entity was destroyed, and //therefore the client no longer needs to rasterize the entity. STCC_ENT_DESTROY, //Entity Info: //Params: Ent ID, information about ent. //Notes: Generally sent because the client asked for an //update on the information about an entity, similar information //is sent as compared to STCC_ENT_MOVE, but when this command //is specified, it is possible that the entity specified, //no longer exists, or is a different type of entity. STCC_ENT_INFO, //Map change: //Params: New map information. //Notes: Typically if the map changes, then all entities //will change as well. Either way, the client is going //to take time to load the new map, so there will be lag //no matter what, so typically if a map change is specified //then STCC_ENT creates and destroys will be called as //well. STCC_MAP_CHANGE, //Level chagne: //Params: N/A //Notes: Unlike map change, when the client receives this //command it knows that it should destroy all entities, and //expect to receive information about all entities within //the map. STCC_LEVEL_CHANGE }SRV_TO_CLNT_CMDS; //Client to server commands: typedef enum _CLNT_TO_SRV_CMDS{ //Disconnect: //Params: None. //Notes: Indicates that the client is disconnecting from //the server, and will no longer receive or send data. CTSC_DISCONNECT=0, //Input: //Params: ID of the entity to receive input, input data. //Notes: Indicates that the client wants the entity it //owns to process input. CTSC_INPUT, //Request Ent Info: //Params: ID of the ent, info is desired for. //Notes: Sends a request for the info about the ent, //a STCC_ENT_INFO is expected. CTSC_REQUEST_ENT_INFO }CLNT_TO_SRV_CMDS; //Command stack: struct CLWCmdItem: public CLListStack::LSItem { lg_byte Command; lg_word Size; //Parameter list size. lg_byte Padding[1]; lg_byte Params[128]; }; struct STCC_ENT_DESTROY_INFO{ lg_dword nEntID; }; struct STCC_ENT_MOVE_INFO{ lg_dword nEntID; ml_mat matPos; ml_aabb aabbBody; lg_dword nFlags[2]; lg_dword nAnimFlags[2]; ml_vec3 v3Vel; ml_vec3 v3Look[3]; }; struct CTSC_INPUT_INFO{ lg_dword nEntID; lg_dword nCmdsActive[1]; lg_dword nCmdsPressed[1]; lg_float fAxis[2]; }; #endif __LW_NET_H__<file_sep>/games/Dicexpo/Readme.txt Dicexpo v1.01a Copyright (C) 2000, <NAME> for Beem Software This folder includes: Dicexpo.bas - The Source code for Dicexpo Readme.txt - This File Instructions: Run the program, online instructions are available for each game. Note: This was not converted to an .exe because it's code was incapable of being converted. This game will never be completed because the authors beleive it sucks. ================================================= === Version History === === for Dicexpo === ================================================= v1.01a Second verion added the ability to press ESCAPE to exit. Still only one game. v1.00a First release only included one game really crappy engine.<file_sep>/games/Legacy-Engine/Scrapped/old/lm_math.c #include <d3dx9.h> #include "lm_math.h" L_dword __cdecl L_nextpow2_C(L_dword n) { L_byte i=0; while(!L_CHECK_FLAG(n-1, 0x80000000l>>i)) i++; return 1<<(0x80000000-i); } void* L_matslerp(void* pOut, void* pM1, void* pM2, float t) { D3DXMATRIX *pXOut=pOut, *pXM1=pM1, *pXM2=pM2; D3DXQUATERNION Q1, Q2; float x=pXM1->_41+t*(pXM2->_41-pXM1->_41); float y=pXM1->_42+t*(pXM2->_42-pXM1->_42); float z=pXM1->_43+t*(pXM2->_43-pXM1->_43); D3DXQuaternionRotationMatrix(&Q1, pM1); D3DXQuaternionRotationMatrix(&Q2, pM2); D3DXQuaternionSlerp(&Q1, &Q1, &Q2, t); D3DXMatrixRotationQuaternion(pXOut, &Q1); pXOut->_41=x; pXOut->_42=y; pXOut->_43=z; return pOut; }<file_sep>/tools/ListingGen/MovieLister/MovieLister.cpp #include <stdio.h> #include "MovieLister.h" #include "resource.h" #define COPYSTRINGEX(out, in) {if(out){delete[]out;out=NULL;}if(in){out=new char[strlen(in)+1];if(out)memcpy(out, in, strlen(in)+1);}} #define GETTEXTEX(out, ctlid){hwndTemp=GetDlgItem(hwnd, ctlid);dwLen=GetWindowTextLength(hwndTemp);if(dwLen<1){out=NULL;}else{out=new char[dwLen+1];GetWindowText(hwndTemp, out, dwLen+1);}} static const char szModule[]="MovieLister.dll"; static RECT g_rcWindow; typedef enum tagDLGSCREENS{ SCREEN_FINISHED=0, SCREEN_TITLEDESC, SCREEN_SHIPPING, SCREEN_TERMS }DLGSCREENS; typedef struct tagDGLRESULT { int nResult; RECT rcWindow; }DLGRESULT, *LPDLGRESULT; // The function that acquires the lister. // CLister * ObtainLister() { return new CGameLister; } /////////////////////////////////////// // The callbacks for the dialog box. // /////////////////////////////////////// // Callback for the terms. // BOOL CALLBACK Terms(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { static CGameLister * lpLister=NULL; char * szShippingTerms=NULL; char * szFeedbackTerms=NULL; char * szWarrantyTerms=NULL; switch(uMsg) { case WM_INITDIALOG: MoveWindow( hwnd, g_rcWindow.left, g_rcWindow.top, g_rcWindow.right-g_rcWindow.left, g_rcWindow.bottom-g_rcWindow.top, TRUE); if(lpLister==NULL) { lpLister=(CGameLister*)lParam; SetDlgItemText(hwnd, IDC_TERMSHIP, "Shipping costs are actual PLUS handling, packaging, and materials fee."); SetDlgItemText(hwnd, IDC_TERMFEEDBACK, "I leave feedback upon feedback, that way I know if everything has gone smoothly and has been completed successfully as planned. Please keep in mind, if you do not let me know what has gone wrong I will not know and assume all is well, if you let me know before leaving a negative or a neutral feedback I will try to fix any and all problems that have occurred."); SetDlgItemText(hwnd, IDC_TERMWARRANTY, "This item is guaranteed not to be Dead-On-Arriaval (DOA)."); } else { SetDlgItemText(hwnd, IDC_TERMSHIP, lpLister->m_szShippingTerms); SetDlgItemText(hwnd, IDC_TERMFEEDBACK, lpLister->m_szFeedbackTerms); SetDlgItemText(hwnd, IDC_TERMWARRANTY, lpLister->m_szWarrantyTerms); } break; case WM_COMMAND: { switch(LOWORD(wParam)) { case IDC_PREV: //fall through. case IDC_NEXT: { HWND hwndTemp=NULL; DWORD dwLen=0; GETTEXTEX(szShippingTerms, IDC_TERMSHIP); GETTEXTEX(szFeedbackTerms, IDC_TERMFEEDBACK); GETTEXTEX(szWarrantyTerms, IDC_TERMWARRANTY); lpLister->SetShippingTerms(szShippingTerms); lpLister->SetFeedbackTerms(szFeedbackTerms); lpLister->SetWarrantyTerms(szWarrantyTerms); SAFE_DELETE_ARRAY(szShippingTerms); SAFE_DELETE_ARRAY(szFeedbackTerms); SAFE_DELETE_ARRAY(szWarrantyTerms); GetWindowRect(hwnd, &g_rcWindow); EndDialog(hwnd, LOWORD(wParam)); break; } default: break; } break; } case WM_CLOSE: EndDialog(hwnd, 0); break; default: return FALSE; } return TRUE; } // Callback to acquire shipping and payment info. // BOOL CALLBACK ShipPay(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { static CGameLister * lpLister=NULL; char * szShippingCost=NULL; char * szShippingInfo=NULL; char * szPaymentOptions=NULL; switch(uMsg) { case WM_INITDIALOG: MoveWindow( hwnd, g_rcWindow.left, g_rcWindow.top, g_rcWindow.right-g_rcWindow.left, g_rcWindow.bottom-g_rcWindow.top, TRUE); if(lpLister==NULL) { lpLister=(CGameLister*)lParam; SetDlgItemText(hwnd, IDC_COST, "ACTUAL plus handling, packaging, and materials fee"); SetDlgItemText(hwnd, IDC_SHIPINFO, "E-Mail me or use ebay's calculator if a shipping cost estimate is desired. Any USPS shipping options may be added at the cost of the buyer. I ship worldwide. Item usually ships business day after payment is recieved."); SetDlgItemText(hwnd, IDC_PAYOPTION, "I accept Paypal and US Money Order/Cashiers Check only. Payment must be in United States Dollars (USD), and should be sent within 10 days of the auction end."); } else { SetDlgItemText(hwnd, IDC_COST, lpLister->m_szShippingCost); SetDlgItemText(hwnd, IDC_SHIPINFO, lpLister->m_szShippingInfo); SetDlgItemText(hwnd, IDC_PAYOPTION, lpLister->m_szPaymentOptions); } break; case WM_COMMAND: { switch(LOWORD(wParam)) { case IDC_PREV: //fall through. case IDC_NEXT: { HWND hwndTemp=NULL; DWORD dwLen=0; GETTEXTEX(szShippingCost, IDC_COST); GETTEXTEX(szShippingInfo, IDC_SHIPINFO); GETTEXTEX(szPaymentOptions, IDC_PAYOPTION); lpLister->SetShippingInfo(szShippingCost, szShippingInfo); lpLister->SetPaymentOptions(szPaymentOptions); SAFE_DELETE_ARRAY(szShippingCost); SAFE_DELETE_ARRAY(szShippingInfo); SAFE_DELETE_ARRAY(szPaymentOptions); GetWindowRect(hwnd, &g_rcWindow); EndDialog(hwnd, LOWORD(wParam)); break; } default: break; } break; } case WM_CLOSE: EndDialog(hwnd, 0); break; default: return FALSE; } return TRUE; } // Callback to acquire title, type, and descriptions. // BOOL CALLBACK TitleDesc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { static CGameLister * lpLister=NULL; char * szCondition=NULL; switch(uMsg) { case WM_INITDIALOG: { MoveWindow( hwnd, g_rcWindow.left, g_rcWindow.top, g_rcWindow.right-g_rcWindow.left, g_rcWindow.bottom-g_rcWindow.top, TRUE); if(lpLister==NULL) { lpLister=(CGameLister*)lParam; } else { //Attempt to restore previous text. SetDlgItemText(hwnd, IDC_ITEMNAME, lpLister->m_szItemName); SetDlgItemText(hwnd, IDC_ITEMTYPE, lpLister->m_szItemType); SetDlgItemText(hwnd, IDC_MOVIEDESC, lpLister->m_szItemDesc); SetDlgItemText(hwnd, IDC_CONDITION, lpLister->m_szItemCondition); } break; } case WM_COMMAND: { switch(LOWORD(wParam)) { case IDC_NEXT: { char * szTemp=NULL, * szTemp2=NULL; DWORD dwLen=0; HWND hwndTemp=NULL; //Get and set the item name and type. GETTEXTEX(szTemp, IDC_ITEMNAME); GETTEXTEX(szTemp2, IDC_ITEMTYPE); lpLister->SetItemName(szTemp, szTemp2); SAFE_DELETE_ARRAY(szTemp); SAFE_DELETE_ARRAY(szTemp2); //Get and set the item descriptions. GETTEXTEX(szTemp, IDC_MOVIEDESC); lpLister->SetItemDesc(szTemp); SAFE_DELETE_ARRAY(szTemp); GETTEXTEX(szCondition, IDC_CONDITION); lpLister->SetItemCondition(szCondition); SAFE_DELETE_ARRAY(szCondition); //Finish up the dialog and specify that next was set. GetWindowRect(hwnd, &g_rcWindow); EndDialog(hwnd, LOWORD(wParam)); break; } case IDC_PREV: EndDialog(hwnd, IDC_PREV); break; } return TRUE; } case WM_CLOSE: EndDialog(hwnd, 0); break; default: return FALSE; } return TRUE; } BOOL CGameLister::RunDialog(HWND hwndParent) { DLGSCREENS nScreen=SCREEN_TITLEDESC; int nResult=0; SetRect(&g_rcWindow, 0, 0, 609, 409); do { nResult=0; switch(nScreen) { case SCREEN_TITLEDESC: { nResult=DialogBoxParam( GetModuleHandle(szModule), MAKEINTRESOURCE(IDD_TITLEDESC), hwndParent, TitleDesc, (LPARAM)this); if(nResult==IDC_NEXT) { nScreen=SCREEN_SHIPPING; break; } else { nScreen=SCREEN_FINISHED; return FALSE; break; } break; } case SCREEN_SHIPPING: { nResult=DialogBoxParam( GetModuleHandle(szModule), MAKEINTRESOURCE(IDD_SHIPPAY), hwndParent, ShipPay, (LPARAM)this); switch(nResult) { case IDC_PREV: nScreen=SCREEN_TITLEDESC; break; case IDC_NEXT: nScreen=SCREEN_TERMS; break; default: nScreen=SCREEN_FINISHED; return FALSE; break; } break; } case SCREEN_TERMS: { nResult=DialogBoxParam( GetModuleHandle(szModule), MAKEINTRESOURCE(IDD_TERMS), hwndParent, Terms, (LPARAM)this); switch(nResult) { case IDC_PREV: nScreen=SCREEN_SHIPPING; break; case IDC_NEXT: nScreen=SCREEN_FINISHED; break; default: nScreen=SCREEN_FINISHED; return FALSE; break; } break; } default: nScreen=SCREEN_FINISHED; break; } }while(nScreen != SCREEN_FINISHED); return TRUE; } BOOL CGameLister::SaveListing(char szFilename[MAX_PATH]) { MessageBox(NULL, "This Template does not support the save feature!", "GameLister", MB_OK|MB_ICONERROR); return TRUE; } BOOL CGameLister::LoadListing(char szFilename[MAX_PATH]) { return FALSE; } BOOL CGameLister::CreateListing(char szFilename[MAX_PATH]) { FILE * fout=NULL; fout=fopen(szFilename, "w"); //Begin the table and print out the item name and type. fprintf(fout, "<table border=5 cellspacing=0>"); fprintf(fout, "<tr><th bgcolor=0xFFB0B0FF><font color=0x00000000>"); if(m_szItemName) fprintf(fout, "<h1>%s</h1>", m_szItemName); if(m_szItemType) fprintf(fout, "<h2>%s</h2>", m_szItemType); fprintf(fout, "</font></th></tr>"); //Print the item description. fprintf(fout, "<tr><td bgcolor=white>"); if(m_szItemDesc) fprintf(fout, "<font color=black>%s</font>", m_szItemDesc); fprintf(fout, "</td></tr>"); //Print the condition of the item. if(m_szItemCondition) { fprintf(fout, "<tr><th bgcolor=orange><font color=black><big>Item Condition</big></font></th></tr>"); fprintf(fout, "<tr><td>%s</td></tr>", m_szItemCondition); } //Close the table fprintf(fout, "</table><p>"); //Start the shipping and payment table. fprintf(fout, "<table border=5 cellspacing=0>"); //Start the shipping information. fprintf(fout, "<tr><th bgcolor=black><font color=white>Shipping Information</font></th></tr><tr><td>"); if(m_szShippingCost) fprintf(fout, "Shipping is<big><b>%s</b></big>.", m_szShippingCost); if(m_szShippingInfo) fprintf(fout, " %s", m_szShippingInfo); fprintf(fout, "</td></tr>"); //Start the payment information. if(m_szPaymentOptions) fprintf(fout, "<tr><th bgcolor=black><font color=white>Payment Options</th></tr><tr><td>%s</td></tr>", m_szPaymentOptions); //Close the table. fprintf(fout, "</table><p>"); //Print the last table terms and conditions. fprintf(fout, "<table border=5 cellspacing=0><tr><th bgcolor=darkblue><font color=white>Terms and Conditions</font></th></tr>"); fprintf(fout, "<tr><td>"); if(m_szShippingTerms) fprintf(fout, "<b>Shipping:</b> %s<p>", m_szShippingTerms); if(m_szFeedbackTerms) fprintf(fout, "<b>Feedback:</b> %s<p>", m_szFeedbackTerms); if(m_szWarrantyTerms) fprintf(fout, "<b>Warranty:</b> %s<p>", m_szWarrantyTerms); fprintf(fout, "</td></tr></table>"); //We're done. Close the file. fclose(fout); return TRUE; } BOOL CGameLister::SetItemName(LPSTR szItemName, LPSTR szItemType) { COPYSTRINGEX(m_szItemName, szItemName); COPYSTRINGEX(m_szItemType, szItemType); return TRUE; } BOOL CGameLister::SetItemDesc(LPSTR szItemDesc) { COPYSTRINGEX(m_szItemDesc, szItemDesc); return TRUE; } BOOL CGameLister::SetItemCondition(LPSTR szItemCondition) { COPYSTRINGEX(m_szItemCondition, szItemCondition); return TRUE; } BOOL CGameLister::SetShippingInfo(LPSTR szShippingCost, LPSTR szShippingInfo) { COPYSTRINGEX(m_szShippingCost, szShippingCost); COPYSTRINGEX(m_szShippingInfo, szShippingInfo); return TRUE; } BOOL CGameLister::SetPaymentOptions(LPSTR szPaymentOptions) { COPYSTRINGEX(m_szPaymentOptions, szPaymentOptions); return TRUE; } BOOL CGameLister::SetShippingTerms(LPSTR szShippingTerms) { COPYSTRINGEX(m_szShippingTerms, szShippingTerms); return TRUE; } BOOL CGameLister::SetFeedbackTerms(LPSTR szFeedbackTerms) { COPYSTRINGEX(m_szFeedbackTerms, szFeedbackTerms); return TRUE; } BOOL CGameLister::SetWarrantyTerms(LPSTR szWarrantyTerms) { COPYSTRINGEX(m_szWarrantyTerms, szWarrantyTerms); return TRUE; }<file_sep>/samples/D3DDemo/code/MD3Base/Functions.c #include <math.h> #include <stdio.h> #include "Functions.h" BOOL DecodeNormalVector(LPMD3VECTOR lpOut, const LPMD3VERTEX lpVertex) { FLOAT lat=0, lng=0; FLOAT x=0, y=0, z=0; /* Get the latitude and longitude. */ lat=(lpVertex->nNormal&0x00FF)*(2.0f*3.141592654f)/255.0f; lng=((lpVertex->nNormal&0xFF00)>>8)*(2.0f*3.141592654f)/255.0f; /* Get the x, y, z values. */ x=(FLOAT)(cos(lat)*sin(lng)); y=(FLOAT)(sin(lat)*sin(lng)); z=(FLOAT)(cos(lng)); /* Adjust the normal vector. */ /* lpOut->x=x+(lpVertex->x*MD3_XYZ_SCALE); lpOut->y=y+(lpVertex->y*MD3_XYZ_SCALE); lpOut->z=z+(lpVertex->z*MD3_XYZ_SCALE); */ return TRUE; } BOOL RemoveDirectoryFromStringA(char szLineOut[], const char szLineIn[]) { DWORD dwStrLen=0; DWORD i=0, j=0; char szFinal[MAX_PATH]; dwStrLen=strlen(szLineIn); for(i=dwStrLen; i>0; i--){ if((szLineIn[i]=='/') || (szLineIn[i]=='\\')){ i++; break; } } for(j=0; j<dwStrLen; j++, i++){ szFinal[j]=szLineIn[i]; } szFinal[j]=0; strcpy(szLineOut, szFinal); return TRUE; } BOOL RemoveDirectoryFromStringW(WCHAR szLineOut[], const WCHAR szLineIn[]) { DWORD dwStrLen=0; DWORD i=0, j=0; WCHAR szFinal[MAX_PATH]; dwStrLen=wcslen(szLineIn); for(i=dwStrLen; i>0; i--){ if((szLineIn[i]==L'/') || (szLineIn[i]==L'\\')){ i++; break; } } for(j=0; j<dwStrLen; j++, i++){ szFinal[j]=szLineIn[i]; } szFinal[j]=0; wcscpy(szLineOut, szFinal); return TRUE; } BOOL GetDirectoryFromStringA(char szLineOut[], const char szLineIn[]) { DWORD dwStrLen=0; DWORD i=0, j=0; char szFinal[MAX_PATH]; dwStrLen=strlen(szLineIn); for(i=dwStrLen; i>0; i--){ if((szLineIn[i]=='/') || (szLineIn[i]=='\\')){ break; } } for(j=0; j<=i; j++){ szFinal[j]=szLineIn[j]; } szFinal[j]=0; strcpy(szLineOut, szFinal); return TRUE; } BOOL GetDirectoryFromStringW(WCHAR szLineOut[], const WCHAR szLineIn[]) { DWORD dwStrLen=0; DWORD i=0, j=0; WCHAR szFinal[MAX_PATH]; dwStrLen=wcslen(szLineIn); for(i=dwStrLen; i>0; i--){ if((szLineIn[i]=='/') || (szLineIn[i]=='\\')){ break; } } for(j=0; j<=i; j++){ szFinal[j]=szLineIn[j]; } szFinal[j]=0; wcscpy(szLineOut, szFinal); return TRUE; } HRESULT ReadLine(HANDLE hFile, LPSTR szLine) { char cChar=0; DWORD dwBytesRead=0; DWORD i=0; DWORD dwFileSize=0; if(!hFile) return E_FAIL; dwFileSize=GetFileSize(hFile, NULL); do{ if( dwFileSize==SetFilePointer(hFile, 0, NULL, FILE_CURRENT) ){ szLine[i]=0; if(strlen(szLine) < 2) return RLSUC_FINISHED; else{ return RLSUC_EOF; } } if( !ReadFile(hFile, &cChar, sizeof(char), &dwBytesRead, NULL) ){ return RLERR_INVALIDFILE; } szLine[i]=cChar; i++; }while ((cChar != '\n') && (cChar != '\r')); szLine[i-1]=0; if(strlen(szLine) < 2)return ReadLine(hFile, szLine); return RLSUC_READSUCCESS; } DWORD GetNumLinesInFile(HANDLE hFile) { char szLine[MAX_PATH]; HRESULT hr=0; DWORD i=0; DWORD dwFilePointer=0; /* Get the file pointer then set it to the beginning of the file. */ dwFilePointer=SetFilePointer(hFile, 0, 0, FILE_CURRENT); SetFilePointer(hFile, 0, 0, FILE_BEGIN); while(SUCCEEDED(hr=ReadLine(hFile, szLine))) { i++; if(hr==RLSUC_EOF) break; if(hr==RLSUC_FINISHED){ i--; break; } } /* Restore the file pointer. */ SetFilePointer(hFile, dwFilePointer, 0, FILE_BEGIN); return i; } HRESULT ReadWordFromLine(LPSTR szLineOut, LPSTR szLine, DWORD dwStart, DWORD * dwEnd) { DWORD i=0, j=0; DWORD dwLen=0; BOOL bReadChar=FALSE; dwLen=strlen(szLine); for(i=dwStart,j=0; i<dwLen; i++,j++){ if(szLine[i]==' ' && bReadChar){ break; } szLineOut[j]=szLine[i]; if(szLine[i]==' ' || szLine[i]=='\t') j--; else bReadChar=TRUE; } szLineOut[j]=0; if(dwEnd) *dwEnd=dwStart+j+1; return S_OK; } <file_sep>/tools/PodSyncPrep/README.md Podcast-Sync-Prep ================= Software for preparing podcasts for syncing to an MP3 player. Basically I wrote this because I wanted to listen to podcasts at work and I wanted them to play in a specific order. This software allows the user to drag and drop MP3 files into any order, then it will rename the files and strip MP3 tags so that they are alphabetically in the order desired. Any MP3 device that plays songs in order will then be fine to play these. I no longer support this software since I have a desk job and can basically just pick whatever podcast I want to play and then just switch it up when I'm done. The software is written in Java and includes a NetBEANS project. <file_sep>/games/Legacy-Engine/Source/engine/lw_entity.h //le_base.h - base structure for entities. #ifndef __LW_ENTITY_H__ #define __LW_ENTITY_H__ #include "lw_ai.h" #include "lg_types.h" #include "ML_lib.h" #include "lg_list_stack.h" #include "lw_ent_sdk.h" struct LEntityClnt: public CLListStack::LSItem{ //Physical properties of the entity: (Position is gotten by server, AngVel and Thrust are sent to server) ML_MAT m_matPos; //Position of the entitiy. ML_VEC3 m_v3Vel; //Velcoity (m/s). ML_VEC3 m_v3AngVel; //Angular velocity (radians/sec). ML_VEC3 m_v3Thrust; //Thrust force of object (Newtons) (Self propelled movement). ML_AABB m_aabbBody; //Square space occupied (volume: meters^3). //Some additional information //The following vector arrays are for At, Up, and Right vectors (non translated). ML_VEC3 m_v3Look[3]; //3 vectors describing what the entity is looking at. //The look is described by yaw pitch and roll lg_float m_fLook[3]; //Animation information: lg_dword m_nAnimFlags1; lg_dword m_nAnimFlags2; //Additional information for the entity: (Updated by server, except m_nUIED which doesn't change). lg_dword m_nFlags1; //32 slots for misc flags. lg_dword m_nFlags2; //32 more slots for misc flags. lg_dword m_nMode1; //32 bits for information about the mode the entity is in. lg_dword m_nMode2; //32 more bits (a mode might be: walking, running, jumping, ducking, etc). lg_dword m_nUEID; //The unique ID (should match server, and all other clients). //Information about the entity relative to the world: (might be updated by client) lg_dword m_nNumRegions; //The number of regions the entity is occupying. lg_dword m_nRegions[MAX_O_REGIONS]; //References to the regions the entity is occupying. //Raster information (excluding position matrix, see above): (Strictly for client use). lg_void* m_pRasterInfo; //Information used to rasterize entity. }; typedef CLListStack LEntList; typedef LEntitySrv lg_srv_ent; typedef LEntityClnt lg_clnt_ent; #endif __LW_ENTITY_H__<file_sep>/tools/img_lib/TexView3/TexView3View.h // TexView3View.h : interface of the CTexView3View class // #pragma once #include "afxwin.h" class CTexView3View : public CScrollView { protected: // create from serialization only CTexView3View(); DECLARE_DYNCREATE(CTexView3View) // Attributes public: CTexView3Doc* GetDocument() const; // Operations public: // Overrides public: virtual void OnDraw(CDC* pDC); // overridden to draw this view virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual BOOL OnPreparePrinting(CPrintInfo* pInfo); virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo); // Implementation public: virtual ~CTexView3View(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // Generated message map functions protected: DECLARE_MESSAGE_MAP() virtual void OnUpdate(CView* /*pSender*/, LPARAM /*lHint*/, CObject* /*pHint*/); public: virtual void OnInitialUpdate(); public: afx_msg BOOL OnEraseBkgnd(CDC* pDC); public: afx_msg void OnTextureAlphaMode(UINT nID); //DWORD m_nAlphaMode; public: afx_msg void OnUpdateTextureImage(CCmdUI *pCmdUI); public: afx_msg void OnUpdateTextureImagewithalpha(CCmdUI *pCmdUI); public: afx_msg void OnUpdateTextureAlphaonly(CCmdUI *pCmdUI); private: BOOL m_bTextureRepeat; public: afx_msg void OnTextureRepeating(); public: afx_msg void OnUpdateTextureRepeating(CCmdUI *pCmdUI); private: DWORD m_nWidth; DWORD m_nHeight; CBitmap m_bmImg; DWORD m_nAlphaMode; BOOL DrawBitmap(int x, int y, CDC* pDC); IMGFILTER m_nFilter; public: afx_msg void OnUpdateTextureLinearfilter(CCmdUI *pCmdUI); afx_msg void OnUpdateTexturePointfilter(CCmdUI *pCmdUI); afx_msg void OnTextureFilter(UINT nID); void RebuildBitmap(void); }; #ifndef _DEBUG // debug version in TexView3View.cpp inline CTexView3Doc* CTexView3View::GetDocument() const { return reinterpret_cast<CTexView3Doc*>(m_pDocument); } #endif <file_sep>/games/Legacy-Engine/Source/lf_sys2/lf_list_stack.cpp //See header file for instructions. #include "lf_list_stack.h" //We keep track of a ID identifier which //is assigned to each list, that way we can //distinguish lists, so that we can identify //to what list a node belongs. lf_dword CLfListStack::s_nNextID=811983; CLfListStack::CLfListStack(): m_nID(s_nNextID++), m_pFirst(LF_NULL), m_pLast(LF_NULL), m_nCount(0) {} CLfListStack::~CLfListStack() {} CLfListStack::LSItem* CLfListStack::Pop() { if(!m_pFirst) return LF_NULL; CLfListStack::LSItem* pRes=m_pFirst; //Removing the first node is a special case. m_pFirst=m_pFirst->m_pNext; //If the first node was also the last node then we also //need to set the last node to null. if(m_pFirst==LF_NULL) { m_pLast=LF_NULL; } else { //The first node's previous must be set to null. m_pFirst->m_pPrev=LF_NULL; } m_nCount--; pRes->m_nListStackID=0; return pRes; } CLfListStack::LSItem* CLfListStack::Peek() { return m_pFirst; } void CLfListStack::Push(CLfListStack::LSItem* pNode) { #if 0 if(pNode->m_nListStackID!=0) { //Warning the node was still in a list. } #endif pNode->m_pPrev=LF_NULL; pNode->m_pNext=m_pFirst; pNode->m_nListStackID=m_nID; if(m_pFirst) { m_pFirst->m_pPrev=pNode; } else { m_pLast=pNode; } m_pFirst=pNode; m_nCount++; } lf_bool CLfListStack::IsEmpty() { return m_pFirst?LF_FALSE:LF_TRUE; } void CLfListStack::Clear() { for(LSItem* pNode=m_pFirst; pNode; pNode=pNode->m_pNext) { pNode->m_nListStackID=0; } m_pFirst=LF_NULL; m_pLast=LF_NULL; m_nCount=0; } void CLfListStack::Remove(CLfListStack::LSItem* pNode) { //If this node wasn't even in this list, we just //return. if(pNode->m_nListStackID!=m_nID) return; if(pNode==m_pFirst) { //Removing the first node is a special case. m_pFirst=m_pFirst->m_pNext; //If the first node was also the last node then we also //need to set the last node to null. if(m_pFirst==LF_NULL) { m_pLast=LF_NULL; } else { //The first node's previous must be set to null. m_pFirst->m_pPrev=LF_NULL; } } else if(pNode==m_pLast) { //The last node is also a special case, but we know it isn't the only //node in the list because that would have been checked above. m_pLast=m_pLast->m_pPrev; m_pLast->m_pNext=LF_NULL; } else { //One problem here is that it isn't gauranteed that pNode //was actually in pList, but it is a quick way to remove //a node, the id check above should prevent weird removals. if(pNode->m_pPrev && pNode->m_pNext) { pNode->m_pPrev->m_pNext=pNode->m_pNext; pNode->m_pNext->m_pPrev=pNode->m_pPrev; } } m_nCount--; } void CLfListStack::Init(CLfListStack::LSItem* pList, lf_dword nCount, lf_dword nItemSize) { for(lf_dword i=0; i<nCount; i++) { LSItem* pCurItem=(LSItem*)((lf_byte*)pList+i*nItemSize); pCurItem->m_nListStackID=0; pCurItem->m_nItemID=i; Push(pCurItem); /* pList[i].m_nListStackID=0; Push(&pList[i]); */ } }<file_sep>/games/Legacy-Engine/Scrapped/old/le_sys.h // le_sys.h - The Legacy Entity class //Copyright (c) 2007 <NAME> #ifndef __LE_SYS_H__ #define __LE_SYS_H__ #include "Newton/Newton.h" #include "ML_lib.h" #include "common.h" #include "lw_map.h" #include "lt_sys.h" #include "lp_sys.h" #include "li_sys.h" #include "lp_physx.h" #include "lp_newton.h" //This is the maximum number of rooms that an //entity can occupy at one time. #define LW_MAX_O_REGIONS 8 typedef enum _ENTITY_MOVEMENT{ MOVEMENT_WALKING=0, MOVEMENT_FALLING, MOVEMENT_FLYING, MOVEMENT_SWIMMING, MOVEMENT_UNKNOWN, }ENTITY_MOVEMENT; class CLEntity: public CElementInput, public CElementTimer { friend class CLCamera; friend class CLEntity; friend class CLWorld; protected: static lg_float s_fGrav; //Static reusabel and global variables: protected: //Temp reusable vars. static ML_VEC3 s_v3Temp; static ML_MAT s_matTemp; static ML_MAT s_matTemp2; protected: static CLWorldMap* s_pWorldMap; protected: class CLEntity* m_pPrev; class CLEntity* m_pNext; //The position of the entity. ML_VEC3 m_v3Pos; //The velocity of the entity. (m/s). ML_VEC3 m_v3PhysVel; //The rotation of the entity (rad/s). ML_VEC3 m_v3PhysRot; //The orientation of the entity. float m_fYaw, m_fPitch, m_fRoll; float m_fVelFwd; float m_fVelStrafe; ML_MAT m_matOrient; ML_AABB m_aabbBase; //Untransformed AABB ML_AABB m_aabbCurrent; //Transformed AABB //The legacy physics body (unused)... CLPhysBody* m_pPhysBody; lg_float m_fMass; lg_bool m_bIntelligent; lg_dword m_nNumRegions; //The number of rooms that the entity is in. lg_dword m_nRegions[LW_MAX_O_REGIONS]; //The rooms that the entity is in static const lg_dword LENTITY_RENDER180=0x00000001; static const lg_dword LENTITY_TRANSYAWONLY=0x00000002; static const lg_dword LENTITY_NOWORLDCLIP=0x00000004; static const lg_dword LENTITY_NOENTITYCOLLIDE=0x00000008; ENTITY_MOVEMENT m_nMovementType; lg_dword m_nFlags; public: CLEntity(); ~CLEntity(); void Update(); virtual void Render(); virtual void InitPhys(lg_bool bIntelligent); virtual void ShutdownPhys(); virtual void ProcessFrame(); virtual void ProcessAI(); void CalculateVelXZ(); class CLEntity* GetNext(); class CLEntity* GetPrev(); void SetNext(class CLEntity* pEnt); void SetPrev(class CLEntity* pEnt); }; class CLPhysXEntity: public CLEntity, public CElementPhysX { private: NxActor* m_pNxActor; public: CLPhysXEntity(); virtual void InitPhys(lg_bool bIntelligent); virtual void ShutdownPhys(); virtual void ProcessFrame(); }; class CLNewtonEntity: public CLEntity, public CElementNewton { private: //The newton body... NewtonBody* m_pNewtonBody; NewtonJoint* m_pUpVec; public: CLNewtonEntity(); virtual void InitPhys(lg_bool bIntelligent); virtual void ShutdownPhys(); virtual void ProcessFrame(); }; #endif __LE_SYS_H__<file_sep>/games/Legacy-Engine/Source/engine/lg_cvars.cpp /* lg_cvars.cpp has just one purpose, when it includes lg_cvars.h it actually declares and defines the cvars, in that way every file that uses the cvar list doesn't have to have memory allocated for the entire list. */ #define DECLARING_CVARS #include "lg_cvars.h" #include "lg_sys.h" #include "lp_sys2.h" #include "../lc_sys2/lc_sys2.h" /*************************************************************************************** LG_RegisterCVars() Register the cvars that the game will use, we set some default values for all of them. The cvarlist should report any errors in registering to the console, so we don't test it out ourselves. If we need to save a cvar we can. All cvars should be registered in this function. The user can register cvars on the fly using the regcvar console command, but this is discouraged. ***************************************************************************************/ void CLGame::LG_RegisterCVars() { /* We'll register the built in definitions. The user can define definitions on the fly with define, which is dangerous because the define function will redefine values. */ #define CVAR_DEF(a, b) CV_Define_f(DEF_##a, (float)b) //Definitions, users should not change these. CVAR_DEF(TRUE, 1); CVAR_DEF(FALSE, 0); CVAR_DEF(ADAPTER_DEFAULT, D3DADAPTER_DEFAULT); //typedef enum _D3DDEVTYPE CVAR_DEF(HAL, D3DDEVTYPE_HAL); CVAR_DEF(REF, D3DDEVTYPE_REF); CVAR_DEF(SW, D3DDEVTYPE_SW); //Vertex processing methods. CVAR_DEF(SWVP, D3DCREATE_SOFTWARE_VERTEXPROCESSING); CVAR_DEF(HWVP, D3DCREATE_HARDWARE_VERTEXPROCESSING); CVAR_DEF(MIXEDVP, D3DCREATE_MIXED_VERTEXPROCESSING); //typdef enum _D3DFORMAT //Back buffer formats. CVAR_DEF(FMT_UNKNOWN, D3DFMT_UNKNOWN); CVAR_DEF(FMT_A8R8G8B8, D3DFMT_A8R8G8B8); CVAR_DEF(FMT_X8R8G8B8, D3DFMT_X8R8G8B8); CVAR_DEF(FMT_R5G6B5, D3DFMT_R5G6B5); CVAR_DEF(FMT_X1R5G5B5, D3DFMT_X1R5G5B5); CVAR_DEF(FMT_A1R5G5B5, D3DFMT_A1R5G5B5); CVAR_DEF(FMT_A2R10G10B10, D3DFMT_A2R10G10B10); //Depth buffer formats. CVAR_DEF(FMT_D16_LOCKABLE, D3DFMT_D16_LOCKABLE); CVAR_DEF(FMT_D32, D3DFMT_D32); CVAR_DEF(FMT_D15S1, D3DFMT_D15S1); CVAR_DEF(FMT_D24S8, D3DFMT_D24S8); CVAR_DEF(FMT_D24X8, D3DFMT_D24X8); CVAR_DEF(FMT_D24X4S4, D3DFMT_D24X4S4); CVAR_DEF(FMT_D16, D3DFMT_D16); CVAR_DEF(FMT_D32F_LOCKABLE, D3DFMT_D32F_LOCKABLE); CVAR_DEF(FMT_D24FS8, D3DFMT_D24FS8); //typedef enum _CVAR_DEF(D3DMULTISAMPLE_TYPE /* CVAR_DEF(D3DMULTISAMPLE_NONE, 0); CVAR_DEF(D3DMULTISAMPLE_NONMASKABLE, 1); CVAR_DEF(D3DMULTISAMPLE_2_SAMPLES, 2); CVAR_DEF(D3DMULTISAMPLE_3_SAMPLES, 3); CVAR_DEF(D3DMULTISAMPLE_4_SAMPLES, 4); CVAR_DEF(D3DMULTISAMPLE_5_SAMPLES, 5); CVAR_DEF(D3DMULTISAMPLE_6_SAMPLES, 6); CVAR_DEF(D3DMULTISAMPLE_7_SAMPLES, 7); CVAR_DEF(D3DMULTISAMPLE_8_SAMPLES, 8); CVAR_DEF(D3DMULTISAMPLE_9_SAMPLES, 9); CVAR_DEF(D3DMULTISAMPLE_10_SAMPLES,10); CVAR_DEF(D3DMULTISAMPLE_11_SAMPLES,11); CVAR_DEF(D3DMULTISAMPLE_12_SAMPLES,12); CVAR_DEF(D3DMULTISAMPLE_13_SAMPLES,13); CVAR_DEF(D3DMULTISAMPLE_14_SAMPLES,14); CVAR_DEF(D3DMULTISAMPLE_15_SAMPLES,15); CVAR_DEF(D3DMULTISAMPLE_16_SAMPLES,16); */ //typedef enum _D3DSWAPEFFECT CVAR_DEF(SWAP_DISCARD, D3DSWAPEFFECT_DISCARD); CVAR_DEF(SWAP_FLIP, D3DSWAPEFFECT_FLIP); CVAR_DEF(SWAP_COPY, D3DSWAPEFFECT_COPY); //PresentationIntervals /* CVAR_DEF(D3DPRESENT_INTERVAL_DEFAULT, 0); CVAR_DEF(D3DPRESENT_INTERVAL_ONE, 1); CVAR_DEF(D3DPRESENT_INTERVAL_TWO, 2); CVAR_DEF(D3DPRESENT_INTERVAL_THREE, 3); CVAR_DEF(D3DPRESENT_INTERVAL_FOUR, 4); CVAR_DEF(D3DPRESENT_INTERVAL_IMMEDIATE, -1); */ /* Register the definitions for the texture filter mode. */ CVAR_DEF(POINT, FILTER_POINT); CVAR_DEF(LINEAR, FILTER_LINEAR); CVAR_DEF(BILINEAR, FILTER_BILINEAR); CVAR_DEF(TRILINEAR, FILTER_TRILINEAR); CVAR_DEF(ANISOTROPIC, FILTER_ANISOTROPIC); /* CVAR_PhysEngineDef */ CVAR_DEF(PHYS_LEGACY, PHYS_ENGINE_LEGACY); CVAR_DEF(PHYS_NEWTON, PHYS_ENGINE_NEWTON); #if 0 CVAR_DEF(PHYS_PHYSX, PHYS_ENGINE_PHYSX); #endif /* To register a cvar: cvar=REGISTER_CVAR("cvar name", "cvar default value", flags) */ /* Which would be the same as REGCVAR "cvarname" "cvarvalue" [NOSAVE] [UPDATE]*/ /******************************************** Direct3D cvars, stuff that controls D3D. *********************************************/ //D3D Initialization stuff. CV_Register(CVAR_v_AdapterID, DEF_ADAPTER_DEFAULT, CVAR_SAVE); CV_Register(CVAR_v_DeviceType, DEF_HAL, 0); CV_Register(CVAR_v_VertexProc, DEF_SWVP, CVAR_SAVE); CV_Register(CVAR_v_FPU_Preserve, DEF_FALSE, 0); CV_Register(CVAR_v_MultiThread, DEF_FALSE, 0); CV_Register(CVAR_v_PureDevice, DEF_FALSE, 0); CV_Register(CVAR_v_DisableDriverManagement, DEF_FALSE, 0); CV_Register(CVAR_v_AdapterGroupDevice, DEF_FALSE, 0); CV_Register(CVAR_v_Managed, DEF_FALSE, 0); //D3DPRESENT_PARAMETERS CV_Register(CVAR_v_Width, "640", CVAR_SAVE); CV_Register(CVAR_v_Height, "480", CVAR_SAVE); CV_Register(CVAR_v_BitDepth, "16", CVAR_SAVE); CV_Register(CVAR_v_ScreenBuffers, "1", CVAR_SAVE); CV_Register(CVAR_v_FSAAQuality, "0", CVAR_SAVE); CV_Register(CVAR_v_SwapEffect, DEF_SWAP_DISCARD, 0); CV_Register(CVAR_v_Windowed, DEF_FALSE, CVAR_SAVE); CV_Register(CVAR_v_EnableAutoDepthStencil, DEF_TRUE, 0); CV_Register(CVAR_v_AutoDepthStencilFormat, DEF_FMT_D16, 0); //v_D3DPP_Flags: CV_Register(CVAR_v_LockableBackBuffer, DEF_FALSE, 0); CV_Register(CVAR_v_DiscardDepthStencil, DEF_FALSE, 0); CV_Register(CVAR_v_DeviceClip, DEF_FALSE, 0); CV_Register(CVAR_v_VideoHint, DEF_FALSE, 0); //More D3DPRESENT_PARAMETERS CV_Register(CVAR_v_RefreshRate, "0", CVAR_SAVE); CV_Register(CVAR_v_EnableVSync, DEF_FALSE, CVAR_SAVE); //Sampler CVars, the sampler cvars have the update attribute, so we will //see the results immediately. CV_Register(CVAR_v_TextureFilter, DEF_BILINEAR, CVAR_SAVE|CVAR_UPDATE); CV_Register(CVAR_v_MaxAnisotropy, "1", CVAR_SAVE|CVAR_UPDATE); //Texture loading related cvars. CV_Register(CVAR_tm_UseMipMaps, DEF_TRUE, CVAR_SAVE); //CV_Register(CVAR_tm_HWMipMaps, DEF_TRUE, CVAR_SAVE); //CV_Register(CVAR_tm_MipGenFilter, DEF_LINEAR, CVAR_SAVE); CV_Register(CVAR_tm_TextureSizeLimit, "0", CVAR_SAVE); CV_Register(CVAR_tm_Force16BitTextures, DEF_FALSE, CVAR_SAVE); /*v_32BitTextrueAlpha and v_16BitTextureAlpha are used to store information //as to whethere or not alpha textures are supported, these cvars shouldn't //be changed by the user, only by the application.*/ //CV_Register(CVAR_tm_32BitTextureAlpha, DEF_TRUE, CVAR_ROM); //CV_Register(CVAR_tm_16BitTextureAlpha, DEF_TRUE, CVAR_ROM); //Should have a cvar to determine which pool textures are loaded into. CV_Register(CVAR_tm_DefaultTexture, "/dbase/textures/default.tga", 0); //Debug cvars CV_Register(CVAR_v_DebugWireframe, DEF_FALSE, CVAR_UPDATE); /****************************************** Sound cvars, stuff that controls audio. *******************************************/ CV_Register(CVAR_s_Channels, "2", CVAR_SAVE); CV_Register(CVAR_s_Frequency, "22050", CVAR_SAVE); CV_Register(CVAR_s_BitsPerSample, "16", CVAR_SAVE); CV_Register(CVAR_s_MusicVolume, "100", CVAR_SAVE|CVAR_UPDATE); /************************************ Game cvars, stuff about the game. *************************************/ /* The path to the console background, note that this can only be changed by the user by modifying the cvar in the console and calling vrestart or setting a different path in the autoexec.cfg file. Same is true for the font.*/ CV_Register(CVAR_lc_UseLegacyFont, DEF_FALSE, CVAR_SAVE); CV_Register(CVAR_lc_BG, "/dbase/textures/console/conbg.tga", 0); CV_Register(CVAR_lc_Font, "fixedsys", 0); CV_Register(CVAR_lc_FontColor, "0xFFFF00", 0); CV_Register(CVAR_lc_LegacyFont, "/dbase/font/lfontsm.tga", 0); CV_Register(CVAR_lc_LegacyFontSizeInFile, "15X8", 0); //Format is (H)X(W) CV_Register(CVAR_lc_FontSize, "16X0", 0); //Format is (H)X(W) cv_l_ShouldQuit=CV_Register(CVAR_lg_ShouldQuit, DEF_FALSE, CVAR_UPDATE); cv_l_AverageFPS=CV_Register(CVAR_lg_AverageFPS, "0", 0); CV_Register(CVAR_lg_DumpDebugData, DEF_FALSE, CVAR_SAVE); /***************** Input cvars *** *****************/ CV_Register(CVAR_li_ExclusiveKB, DEF_FALSE, 0); CV_Register(CVAR_li_ExclusiveMouse, DEF_TRUE, 0); CV_Register(CVAR_li_DisableWinKey, DEF_TRUE, CVAR_SAVE); CV_Register(CVAR_li_MouseSmoothing, DEF_TRUE, CVAR_SAVE); //Server cvars CV_Register(CVAR_srv_MaxEntities, "10000", CVAR_ROM); CV_Register(CVAR_srv_Name, "Legacy", CVAR_SAVE); CV_Register(CVAR_srv_PhysEngine, DEF_PHYS_LEGACY, CVAR_ROM); //Additional game cvars CV_Register(CVAR_lg_MaxMeshes, "512", CVAR_ROM); CV_Register(CVAR_lg_MaxSkels, "2048", CVAR_ROM); CV_Register(CVAR_lg_MaxTex, "128", CVAR_ROM); CV_Register(CVAR_lg_MaxFx, "128", CVAR_ROM); CV_Register(CVAR_lg_MaxMtr, "128", CVAR_ROM); CV_Register(CVAR_lg_MaxSkin, "128", CVAR_ROM); CV_Register(CVAR_lg_GameLib, "game.dll", CVAR_ROM); //Effect manager cvars CV_Register(CVAR_fxm_DefaultFx, "/dbase/fx/basic_unlit.fx", 0); return; } <file_sep>/Misc/DBXExporter/DBXExporter/oedbx/library/oedbx/dbxFileHeader.h //*************************************************************************************** #ifndef DbxFileHeaderH #define DbxFileHeaderH //*************************************************************************************** #include <oedbx/dbxCommon.h> //*************************************************************************************** const int4 FileHeaderSize = 0x24bc; const int4 FileHeaderEntries = FileHeaderSize>>2; const int4 fhFileInfoLength = 0x07, fhFirstFolderListNode = 0x1b, fhLastFolderListNode = 0x1c, fhMessageConditionsPtr = 0x22, fhFolderConditionsPtr = 0x23, fhEntries = 0x31, fhTreeRootNodePtr = 0x39 ; class AS_EXPORT DbxFileHeader { public : DbxFileHeader(InStream ins); int4 GetValue(int4 index) const{return Buffer[index]; } bool isFolders() const { return (Buffer && (Buffer[1]==0x6f74fdc6)); } void ShowResults(OutStream outs) const; private : // this function is called from the constructor void readFileHeader(InStream ins); // stores the data int4 Buffer[FileHeaderEntries]; }; //*********************************************** #endif DbxFileHeaderH <file_sep>/samples/D3DDemo/code/MD3Base/MD3PlayerMesh.cpp #define D3D_MD3 #include <d3dx9.h> #include <stdio.h> #include "defines.h" #include "md3.h" CMD3PlayerMesh::CMD3PlayerMesh() { m_nLowerUpperTag=0; m_nUpperHeadTag=0; m_nUpperWeaponTag=0; m_skinUpper=NULL; m_skinLower=NULL; m_skinHead=NULL; m_dwNumSkins=0; m_dwDefaultSkin=0; m_szSkinName=NULL; m_lpDevice=NULL; m_bLoaded=FALSE; } CMD3PlayerMesh::~CMD3PlayerMesh() { Clear(); } HRESULT CMD3PlayerMesh::GetSkinRef(DWORD * lpRef, char szSkinName[]) { DWORD i=0; for(i=0; i<m_dwNumSkins; i++){ if(_strnicmp(szSkinName, m_szSkinName[i], strlen(m_szSkinName[i]))==0){ *lpRef=i+1; return S_OK; } } return E_FAIL; } HRESULT CMD3PlayerMesh::GetAnimation(DWORD dwAnimRef, MD3ANIMATION * lpAnimation) { return m_Animation.GetAnimation(dwAnimRef, lpAnimation, MD3ANIM_ADJUST); } HRESULT CMD3PlayerMesh::GetLink(CMD3Mesh * lpFirst, char szTagName[], WORD * lpTagRef) { LONG i=0; LONG lNumTags=0; char szTemp[MAX_QPATH]; lpFirst->GetNumTags(&lNumTags); for(i=1; i<=lNumTags; i++){ lpFirst->GetTagName(i, szTemp); if(_strnicmp(szTemp, szTagName, strlen(szTagName))==0){ *lpTagRef=(WORD)i; return S_OK; } } return E_FAIL; } HRESULT CMD3PlayerMesh::Invalidate() { if(m_bLoaded){ m_meshHead.Invalidate(); m_meshUpper.Invalidate(); m_meshLower.Invalidate(); } return S_OK; } HRESULT CMD3PlayerMesh::Validate() { if(m_bLoaded){ m_meshHead.Validate(); m_meshUpper.Validate(); m_meshLower.Validate(); } return S_OK; } HRESULT CMD3PlayerMesh::Render( LONG lUpperFirstFrame, LONG lUpperSecondFrame, FLOAT fUpperTime, LONG lLowerFirstFrame, LONG lLowerSecondFrame, FLOAT fLowerTime, DWORD dwSkinRef, CMD3WeaponMesh * lpWeapon, const D3DMATRIX& SavedWorldMatrix ) { if(!m_bLoaded) return 0; D3DXMATRIX WorldMatrix, Translation, Temp; DWORD dwRenderFlags=0;//MD3RENDER_WIREFRAME; //In order to render in the propper location it is necessary //to save the current World Matrix. Then create a rotation //matrix to get the mesh properly oriented, then apply the //world matrix that was previously saved. if(!m_bLoaded) return S_FALSE; if(dwSkinRef==SKIN_DEFAULT) dwSkinRef=m_dwDefaultSkin; if((dwSkinRef<1) || (dwSkinRef>m_dwNumSkins)) return E_FAIL; if(fUpperTime>1.0f) fUpperTime-=(LONG)fUpperTime; if(fLowerTime>1.0f) fLowerTime-=(LONG)fLowerTime; D3DXMatrixIdentity(&WorldMatrix); //Orient the model in the right direction. D3DXMatrixRotationX(&Translation, 1.5f*D3DX_PI); WorldMatrix*=Translation; D3DXMatrixRotationY(&Translation, 0.5f*D3DX_PI); WorldMatrix*=Translation; WorldMatrix*=SavedWorldMatrix; m_lpDevice->SetTransform(D3DTS_WORLD, &WorldMatrix); //Render the lower mesh. m_meshLower.Render( &m_skinLower[dwSkinRef-1], fLowerTime, lLowerFirstFrame, lLowerSecondFrame, dwRenderFlags); //Get and set the translation for the lower mesh. m_meshLower.GetTagTranslation( m_nLowerUpperTag, fLowerTime, lLowerFirstFrame, lLowerSecondFrame, &Translation); WorldMatrix=Translation*WorldMatrix; m_lpDevice->SetTransform(D3DTS_WORLD, &WorldMatrix); D3DMATRIX TaggedMatrix = WorldMatrix; //Render the upper mesh. m_meshUpper.Render( &m_skinUpper[dwSkinRef-1], fUpperTime, lUpperFirstFrame, lUpperSecondFrame, dwRenderFlags); //Render a weapon if one is set. if(lpWeapon) { Temp=TaggedMatrix; m_meshUpper.GetTagTranslation( m_nUpperWeaponTag, fUpperTime, lUpperFirstFrame, lUpperSecondFrame, &Translation); WorldMatrix=Translation*WorldMatrix; //We must derotate because the object will properly orient itself. D3DXMatrixRotationX(&Translation, 0.5f*D3DX_PI); WorldMatrix=Translation*WorldMatrix; D3DXMatrixRotationY(&Translation, 1.5f*D3DX_PI); WorldMatrix=Translation*WorldMatrix; m_lpDevice->SetTransform(D3DTS_WORLD, &WorldMatrix); //Find out if the weapon should perform the flash. LONG lShoot=0, lGauntlet=0; MD3ANIMATION Animation; m_Animation.GetAnimation(TORSO_ATTACK, &Animation, MD3ANIM_ADJUST); lShoot=Animation.lFirstFrame; m_Animation.GetAnimation(TORSO_ATTACK2, &Animation, MD3ANIM_ADJUST); lGauntlet=Animation.lFirstFrame; if(lUpperSecondFrame==(lShoot+1) || lUpperSecondFrame==(lGauntlet+2) || lUpperSecondFrame==(lGauntlet+3)) lpWeapon->Render(TRUE, WorldMatrix); else lpWeapon->Render(FALSE, WorldMatrix); WorldMatrix=Temp; } //Get and set translation for head mesh. m_meshUpper.GetTagTranslation( m_nUpperHeadTag, fUpperTime, lUpperFirstFrame, lUpperSecondFrame, &Translation); WorldMatrix=Translation*WorldMatrix; m_lpDevice->SetTransform(D3DTS_WORLD, &WorldMatrix); //Render the head mesh (time, and frame must be set to zero). m_meshHead.Render( &m_skinHead[dwSkinRef-1], 0.0f, 0, 0, dwRenderFlags); //Restore the original world matrix. m_lpDevice->SetTransform(D3DTS_WORLD, &SavedWorldMatrix); return S_OK; } HRESULT CMD3PlayerMesh::GetSkinsA(char szDir[]) { WIN32_FIND_DATA FindData; HANDLE hFind=NULL; DWORD dwNumSkins=0; HRESULT hr=0; DWORD i=0, j=0, k=0; DWORD dwLen=0; BOOL bFoundName=FALSE; char szHeadSkin[MAX_PATH]; char szUpperSkin[MAX_PATH]; char szLowerSkin[MAX_PATH]; char szFindString[MAX_PATH]; char szTemp[MAX_PATH]; //Basically my intent is to find out how many skins there //are. This can be done by finding out how many files with names //skin file begining with upper_ exist. We could use any bone //of the body, but upper will do nicely. ZeroMemory(&FindData, sizeof(WIN32_FIND_DATA)); strcpy(szFindString, szDir); strcat(szFindString, "upper_*.skin"); hFind=FindFirstFile( szFindString, &FindData); if(hFind==INVALID_HANDLE_VALUE) return E_FAIL; do{ dwNumSkins++; }while(FindNextFile(hFind, &FindData)); FindClose(hFind); m_dwNumSkins=dwNumSkins; //Allocate memory to all of the skin files. m_skinHead=new CMD3SkinFile[m_dwNumSkins]; if(m_skinHead==NULL) return E_FAIL; m_skinUpper=new CMD3SkinFile[m_dwNumSkins]; if(m_skinUpper==NULL){ SAFE_DELETE_ARRAY(m_skinHead); return E_FAIL; } m_skinLower=new CMD3SkinFile[m_dwNumSkins]; if(m_skinLower==NULL){ SAFE_DELETE_ARRAY(m_skinHead); SAFE_DELETE_ARRAY(m_skinUpper); return E_FAIL; } //Allocate memory for the string names. m_szSkinName=(char**)malloc(sizeof(char*)*m_dwNumSkins); if(m_szSkinName==NULL){ SAFE_DELETE_ARRAY(m_skinHead); SAFE_DELETE_ARRAY(m_skinLower); SAFE_DELETE_ARRAY(m_skinUpper); return E_FAIL; } for(i=0; i<m_dwNumSkins; i++){ m_szSkinName[i]=(char*)malloc(MAX_PATH*sizeof(char)); if(m_szSkinName[i]==NULL){ SAFE_DELETE_ARRAY(m_skinHead); SAFE_DELETE_ARRAY(m_skinLower); SAFE_DELETE_ARRAY(m_skinUpper); for(j=0; j<i; j++){ SAFE_DELETE_ARRAY(m_szSkinName[i]); } SAFE_DELETE_ARRAY(m_szSkinName); return E_FAIL; } } //Obtain the names of all the skins. hFind=FindFirstFile(szFindString, &FindData); if(hFind==INVALID_HANDLE_VALUE){ SAFE_DELETE_ARRAY(m_skinHead); SAFE_DELETE_ARRAY(m_skinLower); SAFE_DELETE_ARRAY(m_skinUpper); for(i=0; i<m_dwNumSkins; i++){ SAFE_DELETE_ARRAY(m_szSkinName[i]); } SAFE_DELETE_ARRAY(m_szSkinName); return E_FAIL; } for(i=0; i<m_dwNumSkins; i++){ strcpy(szTemp, FindData.cFileName); dwLen=strlen(szTemp); bFoundName=FALSE; //Find the first occurence of '_'. for(j=0, k=0; j<dwLen; j++){ if(szTemp[j]=='.'){ m_szSkinName[i][k]=0; if(strncmp(m_szSkinName[i], "default", 7)==0){ m_dwDefaultSkin=i+1; } break; } if(bFoundName){ m_szSkinName[i][k]=szTemp[j]; k++; } if(szTemp[j]=='_') bFoundName=TRUE; } FindNextFile(hFind, &FindData); } //We'll now go ahead and load all the skins. for(i=0; i<m_dwNumSkins; i++){ sprintf(szHeadSkin, "%s%s%s%s", szDir, "head_", m_szSkinName[i], ".skin"); sprintf(szUpperSkin, "%s%s%s%s", szDir, "upper_", m_szSkinName[i], ".skin"); sprintf(szLowerSkin, "%s%s%s%s", szDir, "lower_", m_szSkinName[i], ".skin"); hr=m_skinHead[i].LoadSkinA(m_lpDevice, szHeadSkin, MD3SKINCREATE_DYNAMICTEXDB, &m_TexDB); hr|=m_skinUpper[i].LoadSkinA(m_lpDevice, szUpperSkin, MD3SKINCREATE_DYNAMICTEXDB, &m_TexDB); hr|=m_skinLower[i].LoadSkinA(m_lpDevice, szLowerSkin, MD3SKINCREATE_DYNAMICTEXDB, &m_TexDB); if(FAILED(hr)){ for(j=0; j<i; j++){ m_skinHead[j].UnloadSkin(); m_skinUpper[j].UnloadSkin(); m_skinLower[j].UnloadSkin(); } for(j=0; j<m_dwNumSkins; j++){ SAFE_DELETE_ARRAY(m_szSkinName[i]); } SAFE_DELETE_ARRAY(m_szSkinName); return E_FAIL; } } //Set all the skin references for the model. for(i=0; i<m_dwNumSkins; i++){ m_meshHead.SetSkinRefs(&m_skinHead[i]); m_meshUpper.SetSkinRefs(&m_skinUpper[i]); m_meshLower.SetSkinRefs(&m_skinLower[i]); } return S_OK; } HRESULT CMD3PlayerMesh::GetSkinsW(WCHAR szDir[]) { return E_FAIL; } HRESULT CMD3PlayerMesh::LoadA(LPDIRECT3DDEVICE9 lpDevice, char szDir[], MD3DETAIL nDetail) { DWORD dwLen=0; HRESULT hr=0; char szDirectory[MAX_PATH]; char szHead[MAX_PATH]; char szUpper[MAX_PATH]; char szLower[MAX_PATH]; char szAnimation[MAX_PATH]; if(!lpDevice) return E_FAIL; Clear(); m_lpDevice=lpDevice; m_lpDevice->AddRef(); //First thing to do is attempt to acquire the actual md3's. strcpy(szDirectory, szDir); dwLen=strlen(szDirectory); //Insure that there is a backslash at the end of the directory. if(szDirectory[dwLen-1]!='\\'){ szDirectory[dwLen]='\\'; szDirectory[dwLen+1]=0; dwLen++; } switch(nDetail) { case DETAIL_HIGH: strcpy(szHead, szDirectory); strcpy(szUpper, szDirectory); strcpy(szLower, szDirectory); strcat(szHead, "head.md3"); strcat(szUpper, "upper.md3"); strcat(szLower, "lower.md3"); break; case DETAIL_MEDIUM: strcpy(szHead, szDirectory); strcpy(szUpper, szDirectory); strcpy(szLower, szDirectory); strcat(szHead, "head_1.md3"); strcat(szUpper, "upper_1.md3"); strcat(szLower, "lower_1.md3"); break; case DETAIL_LOW: strcpy(szHead, szDirectory); strcpy(szUpper, szDirectory); strcpy(szLower, szDirectory); strcat(szHead, "head_2.md3"); strcat(szUpper, "upper_2.md3"); strcat(szLower, "lower_2.md3"); break; }; hr=m_meshHead.LoadMD3A(szHead, NULL, lpDevice, D3DPOOL_DEFAULT); hr|=m_meshUpper.LoadMD3A(szUpper, NULL, lpDevice, D3DPOOL_DEFAULT); hr|=m_meshLower.LoadMD3A(szLower, NULL, lpDevice, D3DPOOL_DEFAULT); if(FAILED(hr)){ m_meshHead.ClearMD3(); m_meshUpper.ClearMD3(); m_meshLower.ClearMD3(); if( (nDetail==DETAIL_MEDIUM) || (nDetail==DETAIL_LOW)) { //Lower details may not exist of this model so //attempt to load at high detail. SAFE_RELEASE(m_lpDevice); return LoadA(lpDevice, szDir, DETAIL_HIGH); } SAFE_RELEASE(m_lpDevice); return hr; } //Attempt to load the animation. strcpy(szAnimation, szDirectory); strcat(szAnimation, "animation.cfg"); hr=m_Animation.LoadAnimationA(szAnimation); if(FAILED(hr)){ m_meshHead.ClearMD3(); m_meshUpper.ClearMD3(); m_meshLower.ClearMD3(); SAFE_RELEASE(m_lpDevice); return E_FAIL; } hr=GetSkinsA(szDirectory); if(FAILED(hr)){ m_dwNumSkins=0; m_meshHead.ClearMD3(); m_meshUpper.ClearMD3(); m_meshLower.ClearMD3(); SAFE_RELEASE(m_lpDevice); return hr; } //Get the link reference for all the md3 mesh's. GetLink(&m_meshLower, "tag_torso", &m_nLowerUpperTag); GetLink(&m_meshUpper, "tag_head", &m_nUpperHeadTag); GetLink(&m_meshUpper, "tag_weapon", &m_nUpperWeaponTag); m_bLoaded=TRUE; return S_OK; } HRESULT CMD3PlayerMesh::LoadW(LPDIRECT3DDEVICE9 lpDevice, WCHAR szDir[], MD3DETAIL nDetail) { return E_FAIL; } HRESULT CMD3PlayerMesh::Clear() { DWORD i=0; if(!m_bLoaded)return S_FALSE; m_meshHead.ClearMD3(); m_meshUpper.ClearMD3(); m_meshLower.ClearMD3(); m_TexDB.ClearDB(); for(i=0; i<m_dwNumSkins; i++){ m_skinHead[i].UnloadSkin(); m_skinUpper[i].UnloadSkin(); m_skinLower[i].UnloadSkin(); SAFE_FREE(m_szSkinName[i]); } SAFE_FREE(m_szSkinName); SAFE_DELETE_ARRAY(m_skinHead); SAFE_DELETE_ARRAY(m_skinLower); SAFE_DELETE_ARRAY(m_skinUpper); SAFE_RELEASE(m_lpDevice); m_dwNumSkins=0; m_dwDefaultSkin=0; m_bLoaded=FALSE; return S_OK; }<file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/lv_reset.c #include "common.h" #include "lv_reset.h" #include "lv_init.h" #include "lg_sys.h" /**************************************************************** LV_ValidateGraphics() & LV_InvalidateGraphics () These functions are called whenever the graphics in the game have to be reset, so any graphics that need to be loaded should be validated and invalidated here. Invalidating means removing the object as a Direct3D resource. D3DPOOL_MANAGED resources usually don't need to be invalidated or revalidated. Any object invalidated in LV_InvalidateGraphics, should be revalidated in LV_ValidateGraphics. *****************************************************************/ L_result LV_ValidateGraphics(L3DGame* lpGame) { VCon_Validate(lpGame->v.m_lpVCon, lpGame->v.m_lpDevice); LVT_ValidateInvalidate(lpGame->v.m_lpTestObj, lpGame->v.m_lpDevice, L_true); /* Reset the states. */ Err_Printf("Calling LV_SetStates..."); if(!LV_SetStates(lpGame)) Err_Printf("An error occured while setting sampler and render states."); return LG_OK; } L_result LV_InvalidateGraphics(L3DGame* lpGame) { VCon_Invalidate(lpGame->v.m_lpVCon); LVT_ValidateInvalidate(lpGame->v.m_lpTestObj, L_null, L_false); return LG_OK; } /******************************************************************* LV_Restart() Resets the video with the present parameters located in the cvar list. This is called from LV_ValidateDevice() when the device gets reset, or when the user sends the VRESTART command to the console. ********************************************************************/ L_result LV_Restart(L3DGame* lpGame) { D3DPRESENT_PARAMETERS pp; L_bool bBackSurface=L_false; L_result nResult=0; if(!lpGame) return -1; /* Invalidate all graphics. */ LV_InvalidateGraphics(lpGame); /* Reset the device. */ /* If there was a back surface invalidate it. */ if(lpGame->v.m_lpBackSurface) { lpGame->v.m_lpBackSurface->lpVtbl->Release(lpGame->v.m_lpBackSurface); lpGame->v.m_lpBackSurface=L_null; bBackSurface=L_true; } /* Reset the device. */ memset(&pp, 0, sizeof(pp)); LV_SetPPFromCVars(lpGame, &pp); /* Call reset. */ nResult=lpGame->v.m_lpDevice->lpVtbl->Reset(lpGame->v.m_lpDevice, &pp); Err_PrintDX("IDirect3DDevice9::Reset", nResult); if(L_failed(nResult)) { return LVERR_CANTRECOVER; } else { Err_Printf("Reset Device With the following Present Parameters:"); LV_PrintPP(&pp); if(bBackSurface) { nResult=lpGame->v.m_lpDevice->lpVtbl->GetBackBuffer( lpGame->v.m_lpDevice, 0, 0, D3DBACKBUFFER_TYPE_MONO, &(lpGame->v.m_lpBackSurface)); Err_PrintDX("IDirect3DDevice9::GetBackBuffer", nResult); } /* Finally validate the graphics. */ LV_ValidateGraphics(lpGame); } return LG_OK; } /******************************************************************************* LV_ValidateDevice() Called to make sure that the device is valid for rendering. This is called every frame before anything is rendered. If this funciton fails it means the device can't render right now, and in some cases it means the app should shut down. If it succeeds it means it is okay for the device to draw. ********************************************************************************/ L_result LV_ValidateDevice(L3DGame* lpGame) { L_result nResult=0; L_bool bGetBackSurface=L_false; if(!lpGame || !lpGame->v.m_lpDevice) { Err_Printf("No device to check validation on."); return LVERR_NODEVICE; } if(L_succeeded((nResult=lpGame->v.m_lpDevice->lpVtbl->TestCooperativeLevel(lpGame->v.m_lpDevice)))) return LG_OK; switch(nResult) { case D3DERR_DEVICELOST: /* We can't do anything if the device is lost, we have to wait for it to recover. */ return LVERR_DEVICELOST; case D3DERR_DEVICENOTRESET: { D3DPRESENT_PARAMETERS pp; memset(&pp, 0, sizeof(pp)); /* If the device is not reset it means that windows is giving control of the application back to us and we need to reset it. */ if(nResult=L_failed(LV_Restart(lpGame))) return nResult; return LVERR_DEVICERESET; } default: break; } return LVERR_DEVICELOST; }<file_sep>/games/Legacy-Engine/Source/engine/lp_legacy.cpp /* lp_legacy.cpp - The Legacy Physics engine, for additional remarks see lp_legacy.h Copyright (c) 2007 <NAME> */ #include "lp_legacy.h" #include "lg_err.h" #include "lg_func.h" #include "lw_entity.h" #include "lw_map.h" //#define ITERATIVE_METHOD void CLPhysLegacy::CollisionCheck() { //Loop through all bodies accordingly and adjust for collisions. //In the future should only check bodies that are in the same section //of the map, not just all subsequent bodies. for(CLListStack::LSItem* pBody1=m_AwakeBodies.m_pFirst; pBody1; pBody1=pBody1->m_pNext) { m_nClsns=0; //Check against other bodies: for(CLListStack::LSItem* pBody2=m_AwakeBodies.m_pFirst; pBody2; pBody2=pBody2->m_pNext) { BodyClsnCheck((CLPhysBody*)pBody1, (CLPhysBody*)pBody2); } for(CLListStack::LSItem* pBody2=m_AsleepBodies.m_pFirst; pBody2; pBody2=pBody2->m_pNext) { BodyClsnCheck((CLPhysBody*)pBody1, (CLPhysBody*)pBody2); } #ifndef ITERATIVE_METHOD //Check against the hulls that make up the world: for(lg_dword i=0; i<m_nHullCount; i++) { HullClsnCheck((CLPhysBody*)pBody1, &m_pGeoHulls[i]); } #endif ITERATIVE_METHOD } #ifdef ITERATIVE_METHOD for(CLListStack::LSItem* pBody1=m_AwakeBodies.m_pFirst; pBody1; pBody1=pBody1->m_pNext) { m_nClsns=0; //Check against the hulls that make up the world: for(lg_dword i=0; i<m_nHullCount; i++) { HullClsnCheck((CLPhysBody*)pBody1, &m_pGeoHulls[i]); } if(m_nClsns) { m_nClsns=0; //Check against the hulls that make up the world: for(lg_dword i=0; i<m_nHullCount; i++) { HullClsnCheck((CLPhysBody*)pBody1, &m_pGeoHulls[i]); } } if(m_nClsns) { CLPhysBody* pBdy=(CLPhysBody*)pBody1; pBdy->m_v3Vel=s_v3Zero; SetPostMoveAABB(pBdy); } } #endif ITERATIVE_METHOD //Should probably also check any bodies that were woken up. } void CLPhysLegacy::BodyClsnCheck(CLPhysBody* pBody1, CLPhysBody* pBody2) { if(pBody1==pBody2) return; //Check to see if there is any chance that the bodies collided. if(!ML_AABBIntersect(&pBody1->m_aabbMove, &pBody2->m_aabbMove, LG_NULL)) return; //We'll calculate by subtracting the velocity of body 1 from body 2 to //get a frame of reference where body 2 is not moving. static ML_VEC3 v3ScaleVel; static ML_VEC3 v3RefVel; ML_Vec3Subtract(&v3RefVel, &pBody1->m_v3Vel, &pBody2->m_v3Vel); //Adjust the velocity to reflect the actual amount of movement. ML_Vec3Scale(&v3ScaleVel, &v3RefVel, m_fTimeStep); static lg_float fColTime; //Now we'll find out when the collision occured. fColTime=ML_AABBIntersectMoving( &pBody1->m_aabbPreMove, &pBody2->m_aabbPreMove, &v3ScaleVel); //If we had a large collision time, then a collsion never really occured. if(fColTime>=1e30f) return; //Err_MsgPrintf("Collision"); lg_bool bElastic=LG_TRUE; if(bElastic) { //Elastic collision: #ifdef FORCE_METHOD //Since there was a collision we'll calculate the new velocities. lg_float fM1=(pBody1->m_fMass-pBody2->m_fMass)/(pBody1->m_fMass+pBody2->m_fMass); lg_float fM2=(pBody1->m_fMass*2)/(pBody1->m_fMass+pBody2->m_fMass); ML_Vec3Scale(&pBody1->m_v3Vel, &v3RefVel, fM1); ML_Vec3Scale(&v3RefVel, &v3RefVel, fM2); ML_Vec3Add(&pBody1->m_v3ClsnForces, &pBody2->m_v3Vel, &pBody1->m_v3Vel); ML_Vec3Add(&pBody2->m_v3ClsnForces, &pBody2->m_v3Vel, &v3RefVel); #else //Since there was a collision we'll calculate the new velocities. lg_float fM1=(pBody1->m_fMass-pBody2->m_fMass)/(pBody1->m_fMass+pBody2->m_fMass); lg_float fM2=(pBody1->m_fMass*2)/(pBody1->m_fMass+pBody2->m_fMass); ML_Vec3Scale(&pBody1->m_v3Vel, &v3RefVel, fM1); ML_Vec3Scale(&v3RefVel, &v3RefVel, fM2); ML_Vec3Add(&pBody1->m_v3Vel, &pBody2->m_v3Vel, &pBody1->m_v3Vel); ML_Vec3Add(&pBody2->m_v3Vel, &pBody2->m_v3Vel, &v3RefVel); //Should probably add some torque, but it should be based //on where the body's hit each other. //pBody1->m_v3AngVel.y+=1.0f; //pBody2->m_v3AngVel.y+=1.0f; #endif } else { //Inelastic Collison: //This is not an accurate check, but the idea //is that if the bodies were already colliding //we don't need to adjust the velocity. if(pBody1->m_nColBody=pBody2->m_nItemID) { //Just set the velocities equal pBody2->m_v3Vel=pBody1->m_v3Vel=v3RefVel; } else { //We'll use the laws of conservation of momentum: pBody1->m_nColBody=pBody2->m_nItemID; pBody2->m_nColBody=pBody1->m_nItemID; lg_float fM=pBody1->m_fMass/(pBody1->m_fMass+pBody2->m_fMass); pBody2->m_v3Vel.x=v3RefVel.x*fM; pBody2->m_v3Vel.y=v3RefVel.y*fM; pBody2->m_v3Vel.z=v3RefVel.z*fM; pBody1->m_v3Vel=pBody2->m_v3Vel; } } //We also need to calculate new AABBs SetPostMoveAABB(pBody1); SetPostMoveAABB(pBody2); } void CLPhysLegacy::HullClsnCheck(CLPhysBody* pBody, CLPhysHull* pHull) { //Do a quick check to see if the aabbs intersect. //Should probably start with a sphere check for additional //speed. if(!ML_AABBIntersect(&pBody->m_aabbMove, &pHull->m_aabbHull, LG_NULL)) return; //We'll calculate by subtracting the velocity of body 1 from body 2 to //get a frame of reference where body 2 is not moving. static ML_VEC3 v3ScaleVel; static ml_plane plnIsect; //Adjust the velocity to reflect the actual amount of movement. ML_Vec3Scale(&v3ScaleVel, &pBody->m_v3Vel, m_fTimeStep); if(AABBIntersectHull(&pBody->m_aabbPreMove,pHull,&v3ScaleVel,&plnIsect)) { m_nClsns++; #ifdef FORCE_METHOD //Applying forces rather than directly //manipulating: ml_vec3 v3Temp; ML_Vec3Scale( &v3Temp, (ml_vec3*)&plnIsect.a, ML_Vec3Dot((ml_vec3*)&plnIsect.a, &pBody->m_v3Vel)); ML_Vec3Subtract(&pBody->m_v3ClsnForces, &pBody->m_v3Vel, &v3Temp); #elif 1 //Inelastic collision: //From Lengyel (p. 125) //This is modified bounce code, rather than reflecting //this code flattens the movement onto the surface. ml_vec3 v3Temp; lg_float fDot; fDot=ML_Vec3Dot((ml_vec3*)&plnIsect.a, &pBody->m_v3Vel); ML_Vec3Scale(&v3Temp, (ml_vec3*)&plnIsect.a, fDot); ML_Vec3Subtract(&pBody->m_v3Vel, &pBody->m_v3Vel, &v3Temp); //We don't want the body to get progressively closer to the plane //it is intersecting, so we'll apply just a litte bit of elasticity. //This is especially important when the game is running at a high //frame rate, because on quick frames the object may not move very //far, whereas on other frames it will move a great distance. //We multiply this by the time step because ultimately the velocity //is going to get scaled by the time step so we want to make sure //that when the game run's at different framerates the amount of //overbounce isn't noticeable. ml_float fOverBounce=1.0f; ML_Vec3Scale(&v3Temp, (ml_vec3*)&plnIsect.a, m_fTimeStep*fOverBounce); ML_Vec3Add(&pBody->m_v3Vel, &v3Temp, &pBody->m_v3Vel); /* ML_Vec3Scale( &v3Temp, (ml_vec3*)&plnIsect.a, 2.0f*ML_Vec3Dot((ml_vec3*)&plnIsect.a, &pBody->m_v3Vel)); ML_Vec3Subtract(&pBody->m_v3Vel, &v3Temp, &pBody->m_v3Vel); */ #elif 0 //Just push in the oppisite direction: ML_Vec3Scale(&pBody->m_v3Vel, &pBody->m_v3Vel, -1.0f); #else //Elastic collision: //From Lengyel (p. 125) //This is just standard bounce, code, that would cause //a bounce at a reflection angle. ml_vec3 v3Temp; ML_Vec3Scale(&pBody->m_v3Vel, &pBody->m_v3Vel, -1.0f); ML_Vec3Scale( &v3Temp, (ml_vec3*)&plnIsect.a, 2.0f*ML_Vec3Dot((ml_vec3*)&plnIsect.a, &pBody->m_v3Vel)); ML_Vec3Subtract(&pBody->m_v3Vel, &v3Temp, &pBody->m_v3Vel); #endif ML_Vec3Scale(&v3ScaleVel, &pBody->m_v3Vel, m_fTimeStep); SetPostMoveAABB(pBody); } } lg_dword CLPhysLegacy::AABBIntersectHull( const ml_aabb* pAABB, const CLPhysHull* pHull, const ml_vec3* pVel, ml_plane* pIsctPlane) { static lg_float fTime; static lg_dword nType; static lg_bool bIsect; bIsect=LG_FALSE; for(lg_dword i=0; i<pHull->m_nNumFaces; i++) { nType=ML_AABBIntersectPlaneVelType( pAABB, &pHull->m_pFaces[i], pVel, &fTime); if(nType==ML_INTERSECT_ONPOS) { //If we ever find that we're on the positive side //of a plane, then we know for certain that there //wasn't a collision with this hull, so we can //end the function immediately. return 0; } else if(nType==ML_INTERSECT_HITPOS) { //If we intersected a plane, then we set the //intersection flag to true, and save the copy //of the plane that we intersected. Since hulls //are convex we can only hit one plane on the hull //we still need to continue to check the planes //because even if we hit a plane it is possible //that we are still on the positive side of //another one. bIsect=LG_TRUE; *pIsctPlane=pHull->m_pFaces[i]; } } //If we had an intersection we're done. if(bIsect)return 1; //If not, and we got here, then we probably hit a corner, and //we need to check against the bounding aabb. static ml_plane bounds[6]; ML_AABBToPlanes(bounds, (ml_aabb*)&pHull->m_aabbHull); //The following is pretty much exactly the same as above, //but we're writing it again, because I don't want to use //recursion to check this. bIsect=LG_FALSE; for(lg_dword i=0; i<6; i++) { nType=ML_AABBIntersectPlaneVelType( pAABB, &bounds[i], pVel, &fTime); if(nType==ML_INTERSECT_ONPOS) { return 0; } else if(nType==ML_INTERSECT_HITPOS) { bIsect=LG_TRUE; *pIsctPlane=bounds[i]; } } if(bIsect)return 1; //Technically we should never make it here, but it is a possibility. //And if we are here, then it means we were probably already inside //of the hull. return 0; } void CLPhysLegacy::SetPreMoveAABB(CLPhysBody* pBody) { #if 1 //The aabb is the base aabb adjusted by the objects //position, and center of gravity: ML_Vec3Add( &pBody->m_aabbPreMove.v3Min, &pBody->m_aabbBase.v3Min, (ML_VEC3*)&pBody->m_matPos._41); ML_Vec3Add( &pBody->m_aabbPreMove.v3Max, &pBody->m_aabbBase.v3Max, (ML_VEC3*)&pBody->m_matPos._41); #elif 0 ML_AABBTransform(&pBody->m_aabbPreMove, &pBody->m_aabbBase, &pBody->m_matPos); #endif } void CLPhysLegacy::SetPostMoveAABB(CLPhysBody* pBody) { #if 1 static ML_VEC3 v3Temp; ML_Vec3Scale(&v3Temp, &pBody->m_v3Vel, m_fTimeStep); ML_Vec3Add(&v3Temp, &v3Temp, (ML_VEC3*)&pBody->m_matPos._41); //Now save the new volume of the body: ML_Vec3Add( &pBody->m_aabbPostMove.v3Min, &pBody->m_aabbBase.v3Min, (ML_VEC3*)&v3Temp); ML_Vec3Add( &pBody->m_aabbPostMove.v3Max, &pBody->m_aabbBase.v3Max, (ML_VEC3*)&v3Temp); //We'll also created a catenated AABB which //represents the volume occupied by the move. ML_AABBCatenate(&pBody->m_aabbMove, &pBody->m_aabbPreMove, &pBody->m_aabbPostMove); #elif 0 ml_mat matTemp, matTemp2; ml_vec3 v3Temp; ML_Vec3Scale(&v3Temp, &pBody->m_v3Vel, m_fTimeStep); ML_MatTranslation(&matTemp, v3Temp.x, v3Temp.y, v3Temp.z); ML_MatRotationAxis(&matTemp2, &pBody->m_v3AngVel, m_fTimeStep*ML_Vec3Length(&v3Temp)); ML_MatMultiply(&matTemp, &matTemp2, &matTemp); ML_MatMultiply(&matTemp, &matTemp, &pBody->m_matPos); ML_AABBTransform(&pBody->m_aabbPostMove, &pBody->m_aabbBase, &matTemp); ML_AABBCatenate(&pBody->m_aabbMove, &pBody->m_aabbPreMove, &pBody->m_aabbPostMove); #endif } void CLPhysLegacy::ApplyWorldForces(CLPhysBody* pBody) { static ml_vec3 v3Temp; //Linear Drag: //We'll use (1/4)(surface area)(v^2) for drag. //We'll use m_fDrag as the surface area. lg_float fDrag=/*(0.25f)**/pBody->m_fSpeed*pBody->m_fSpeed*m_fDrag*m_fTimeStep; ML_Vec3Scale(&v3Temp, &pBody->m_v3Vel, fDrag); ML_Vec3Subtract(&pBody->m_v3Vel, &pBody->m_v3Vel, &v3Temp); //Angular drag: fDrag=pBody->m_fAngSpeed*pBody->m_fAngSpeed*m_fDrag*m_fTimeStep; ML_Vec3Scale(&v3Temp, &pBody->m_v3AngVel, fDrag); ML_Vec3Subtract(&pBody->m_v3AngVel, &pBody->m_v3AngVel, &v3Temp); //Add in the gravity force: //Note that technically the gravity force would //be m_fTimeStep*grav*mass*oneOverMass, but we //can just cancel out the mass. ML_Vec3Scale(&v3Temp, &m_v3Grav, m_fTimeStep); ML_Vec3Add(&pBody->m_v3Vel, &pBody->m_v3Vel, &v3Temp); #ifdef FORCE_METHOD //There may also have been forces carried over //from the collision detection, they get applied //directly: ML_Vec3Add(&pBody->m_v3Vel, &pBody->m_v3Vel, &pBody->m_v3ClsnForces); pBody->m_v3ClsnForces=s_v3Zero; #endif } void CLPhysLegacy::ProcessAwakeBodies() { static ML_VEC3 v3Temp; static ML_MAT matTemp, matTemp2; static lg_float fOneOverMass; //Only need to simulate for awake bodies. for(CLListStack::LSItem*pNode=m_AwakeBodies.m_pFirst; pNode; pNode=pNode->m_pNext) { //We'll loop through each body in the list stack of awake //bodies and process them. CLPhysBody* pBody=(CLPhysBody*)pNode; //Technically we only need to update the body if //it changed, and only awake bodies will change (or asleep //bodies that experienced a collision). //We need to update the body from the server, //this will get us the any server influenced physics //(such as thrust from an entity that is walking). UpdateFromSrv(pBody, (LEntitySrv*)pBody->m_pEnt); //Since we use 1/Mass quite frequenty we'll calcuate it fOneOverMass=1.0f/pBody->m_fMass; //Before moving the body, we'll save the volume of the body: //You'd think we could just set PreMove AABB to the PostMove //AABB, but this won't work cause those AABBs aren't set when //a body is created or if a body teleports, so we calculate them //on the spot. SetPreMoveAABB(pBody); //Apply forces exerted by the world (gravity, drag) ApplyWorldForces(pBody); //Apply forces exerted by the game engine (self propelled force, //i.e. if the object was walking, or got hit by a bullet and needs //to move or something). if(LG_CheckFlag(pBody->m_nFlags, AI_PHYS_DIRECT_LINEAR)) { //If the body is setup for a direct linear move, //we just add the thrust onto the position. ML_Vec3Add((ML_VEC3*)&pBody->m_matPos._41, (ML_VEC3*)&pBody->m_matPos._41, &pBody->m_v3Thrust); } else { #if 1 //If the body is not moving directly, we update the velocity //by calculating the acceleration and adding that to the velocity. //The first thing we'll do is update the velocity (this is done //using standard calculus for physics, the acceleration is //simly (Force/Mass), then we just add that //acceleration onto the velocity. ML_Vec3Scale(&v3Temp, &pBody->m_v3Thrust, fOneOverMass*m_fTimeStep); //a*t=(F/M)*t ML_Vec3Add(&pBody->m_v3Vel, &pBody->m_v3Vel, &v3Temp); //V = V0 + a*t //We now have the velocity at which the object is moving (dV/dt) #else ML_Vec3Scale(&v3Temp, &pBody->m_v3Thrust, fOneOverMass); //ML_Vec3Add(&pBody->m_v3Accel, &pBody->m_v3Accel, &v3Temp); pBody->m_v3Accel=v3Temp; ML_Vec3Scale(&v3Temp, &pBody->m_v3Accel, m_fTimeStep); ML_Vec3Add(&pBody->m_v3Vel, &pBody->m_v3Vel, &v3Temp); #endif } if(LG_CheckFlag(pBody->m_nFlags, AI_PHYS_DIRECT_ANGULAR)) { ML_MatRotationAxis( &matTemp, &pBody->m_v3Torque, ML_Vec3Length(&pBody->m_v3Torque)); ML_MatMultiply(&pBody->m_matPos, &matTemp, &pBody->m_matPos); } else { //Update the angular velocity: //Typical physics torque/mass = angular acceleration. ML_Vec3Scale(&v3Temp, &pBody->m_v3Torque, m_fTimeStep*fOneOverMass); //(alpha)*t=(T/m)*(delta t) //w=w0+(alpha)*t ML_Vec3Add( &pBody->m_v3AngVel, &pBody->m_v3AngVel, &v3Temp); } //We'll now calculate a new AABB to reflect the potential move. SetPostMoveAABB(pBody); } //Do collision detection: //AABBs will be update an objects will //adjust their velocities as necessary. CollisionCheck(); //Now update everything, and do some additional calcuations: for(CLListStack::LSItem*pNode=m_AwakeBodies.m_pFirst; pNode; pNode=pNode->m_pNext) { CLPhysBody* pBody=(CLPhysBody*)pNode; #ifdef FORCE_METHOD if(ML_Vec3Length(&pBody->m_v3ClsnForces)>0.0f) { pBody->m_v3Vel=s_v3Zero; } #endif //Save some values: pBody->m_fAngSpeed=ML_Vec3Length(&pBody->m_v3AngVel); //Angular speed. pBody->m_fSpeed=ML_Vec3Length(&pBody->m_v3Vel); //Linear speed. //Update the position: //The position is updated by simply adding the velocity to the position. ML_Vec3Scale(&v3Temp, &pBody->m_v3Vel, m_fTimeStep); ML_Vec3Add((ML_VEC3*)&pBody->m_matPos._41, (ML_VEC3*)&pBody->m_matPos._41, &v3Temp); //Update the orientation: //For torque we simply rotate about the torque axis, //according to the magnitude of the torque (speed). //Technically for a matrix rotation about an axis we //should normalize the vector, but the ML_MatRotationAxis //normalizes it for us, we should also insure that //the angle is > 0, but ML_MatRotationAxis also checks //that for us. //We want to rotate around the body's center of graity. //Translate to the center of gravity: ML_MatTranslation(&matTemp, pBody->m_v3Center.x, pBody->m_v3Center.y, pBody->m_v3Center.z); //Do the rotation: ML_MatRotationAxis( &matTemp2, &pBody->m_v3AngVel, pBody->m_fAngSpeed*m_fTimeStep); //Catenate matricies: ML_MatMultiply(&matTemp, &matTemp2, &matTemp); //Translate from the center of gravity: ML_MatTranslation(&matTemp2, -pBody->m_v3Center.x, -pBody->m_v3Center.y, -pBody->m_v3Center.z); //Catenate: ML_MatMultiply(&matTemp, &matTemp2, &matTemp); //Apply transformation: ML_MatMultiply(&pBody->m_matPos, &matTemp, &pBody->m_matPos); UpdateToSrv(pBody, pBody->m_pEnt); } } /* CLPhysLegacy::Init() */ void CLPhysLegacy::Init(lg_dword nMaxBodies) { m_nHullCount=0; m_pGeoPlaneList=LG_NULL; m_pGeoHulls=LG_NULL; m_UnusedBodies.Clear(); m_AwakeBodies.Clear(); m_AsleepBodies.Clear(); Err_Printf("Initializing Legacy Physics Engine..."); //Should probably set max bodies as a parameter to init. m_nMaxBodies=nMaxBodies; Err_Printf("Creating body list of %u bodies...", m_nMaxBodies); //Create the bodie list and put it in the unused stack. m_pBodyList=new CLPhysBody[m_nMaxBodies]; Err_Printf( "%u bytes allocated (%u MB).", m_nMaxBodies*sizeof(CLPhysBody), m_nMaxBodies*sizeof(CLPhysBody)/1048576); //Initialize all the bodies into the unused list. m_UnusedBodies.Init(m_pBodyList, m_nMaxBodies, sizeof(*m_pBodyList)); #if 0 //Create the lists. m_pSleepingBodies=new CLList<CLPhysBody*>(m_nMaxBodies); m_pAwakeBodies=new CLList<CLPhysBody*>(m_nMaxBodies); //To estimate the memory usage we take sizeof(lg_void*) //or the size of a pointer and multiply it by 3 (because //in the lists there are prev, next, and object pointers). //We know the object is a pointer because in the template //we specified it as (CLPhysBody*) not (CLPhysBody). Err_Printf( "Awake and sleeping lists created using %u bytes (%u MB)", (sizeof(lg_void*)*3)*m_nMaxBodies*2, (sizeof(lg_void*)*3)*m_nMaxBodies*2/1048576); #endif //Set some default values... m_v3Grav.x=m_v3Grav.y=m_v3Grav.z=0.0f; m_fDrag=0.0f;//0.1f; m_fTimeStep=0; } /* Shutdown PRE: Init should have been called. POST: Memory allocated to the physics engine is released, after this method is called any created bodies that might still ahve references on the server should not be used. */ void CLPhysLegacy::Shutdown() { Err_Printf("Shutting down Legacy Physics Engine..."); //Delete the lists. #if 0 delete m_pSleepingBodies; delete m_pAwakeBodies; delete m_pBodyStack; #endif m_AsleepBodies.Clear(); m_AwakeBodies.Clear(); m_UnusedBodies.Clear(); LG_SafeDeleteArray(m_pBodyList); SetupWorld(LG_NULL); } /* AddBody PRE: pEnt should be an entity in the server world, pInfo should be set with all information about the body to be created. POST: A new body is added to the world (or if a new body could not be added, null is returned. Note that the return value is a pointer that should be used whenever updates by the server need to be applied to the physics engine. */ lg_void* CLPhysLegacy::AddBody(lg_void* pEnt, lp_body_info* pInfo) { CLPhysBody* pBodyNew = (CLPhysBody*)m_UnusedBodies.Pop();//m_pBodyStack->Pop(); if(!pBodyNew) { Err_Printf("CLPhysLegacy::AddBody ERROR: Could not obtain a new body."); return LG_NULL; } pBodyNew->m_pEnt=pEnt; pBodyNew->m_fMass=pInfo->m_fMass; pBodyNew->m_matPos=pInfo->m_matPos; pBodyNew->m_v3Thrust=s_v3Zero; pBodyNew->m_v3Vel=s_v3Zero; pBodyNew->m_v3Torque=s_v3Zero; pBodyNew->m_v3AngVel=s_v3Zero; pBodyNew->m_nFlags=pInfo->m_nAIPhysFlags; pBodyNew->m_nColBody=0; pBodyNew->m_nNumRegions=0; pBodyNew->m_v3Center.x=pInfo->m_fMassCenter[0]; pBodyNew->m_v3Center.y=pInfo->m_fMassCenter[1]; pBodyNew->m_v3Center.z=pInfo->m_fMassCenter[2]; pBodyNew->m_fAngSpeed=0.0f; pBodyNew->m_fSpeed=0.0f; #ifdef FORCE_METHOD pBodyNew->m_v3ClsnForces=s_v3Zero; #endif LG_SetFlag(pBodyNew->m_nFlags, CLPhysBody::PHYS_BODY_AWAKE); //pBodyNew->m_nFlags=CLPhysBody::PHYS_BODY_AWAKE; pBodyNew->m_aabbBase=pInfo->m_aabbBody; //We always start a body in the awake list. m_AwakeBodies.Push(pBodyNew); return pBodyNew; } void CLPhysLegacy::RemoveBody(lg_void* pBody) { CLPhysBody* pBodyA=(CLPhysBody*)pBody; if(LG_CheckFlag(pBodyA->m_nFlags, CLPhysBody::PHYS_BODY_AWAKE)) { m_AwakeBodies.Remove(pBodyA); } else { m_AsleepBodies.Remove(pBodyA); } m_UnusedBodies.Push(pBodyA); } void CLPhysLegacy::SetupWorld(lg_void* pWorldMap) { //We always clear the old data: LG_SafeDeleteArray(m_pGeoPlaneList); LG_SafeDeleteArray(m_pGeoHulls); m_nHullCount=0; CLMap* pMap=(CLMap*)pWorldMap; if(!pMap || !pMap->IsLoaded()) return; m_nHullCount=pMap->m_nGeoBlockCount; m_pGeoHulls=new CLPhysHull[m_nHullCount]; m_pGeoPlaneList=new ml_plane[pMap->m_nGeoFaceCount]; for(lg_dword i=0; i<m_nHullCount; i++) { m_pGeoHulls[i].m_nFirstFace=pMap->m_pGeoBlocks[i].nFirstFace; m_pGeoHulls[i].m_nNumFaces=pMap->m_pGeoBlocks[i].nFaceCount; m_pGeoHulls[i].m_aabbHull=pMap->m_pGeoBlocks[i].aabbBlock; m_pGeoHulls[i].m_pFaces=&m_pGeoPlaneList[m_pGeoHulls[i].m_nFirstFace]; } for(lg_dword i=0; i<pMap->m_nGeoFaceCount; i++) { m_pGeoPlaneList[i]=pMap->m_pGeoFaces[i]; } } void CLPhysLegacy::SetGravity(ML_VEC3* pGrav) { m_v3Grav=*pGrav; } /* Simulate PRE: Everything needs to be initialized, fTimeStepSec >= 0.0f and represents how many seconds have elapsed since the last update (usually a small number such as 1/30 seconds (at 30 fps) etc.). POST: The physics engine simulates all physical interactions. This method updates the entities on the server. After it finishes any changes in a body's velocity, torque, position, etc. will already be updated on the server, so there is no need to loop through all the ents on the server and update their physical information. Note that the server's entity's thrust and torque are set to zero, this is because if an entity wants to continue accelerating it needs to keep setting the forces (that is in order to speed up forces need to be applied over time, remember that forces imply acceleration, but if the object only accelerates a little then it will not have a big velocity, and if there is a significant amount of friction, then the veloctiy will be reduced to zero very quickly). Future Notes: Additionally if a body's veloctiy becomes extremely low, that body will be put to sleep and will not be effected by calls to UpdateBody. If another bodies collides with a sleeping body it will then become awake. Note that AI controlled bodies should be set to never fall asleep, only dumb objects. */ void CLPhysLegacy::Simulate(lg_float fTimeStepSec) { /* if(fTimeStepSec>=1.0f) { m_fTimeStep=0.0f; } */ //We'll clamp the elapsed time to less than //1 second (if we're at 1 frame per second //we've go serious problems anyway). m_fTimeStep=LG_Clamp(fTimeStepSec, 0.001f, 0.25f); //m_fTimeStep=fTimeStepSec>=0.25f?0.0f:fTimeStepSec; ProcessAwakeBodies(); } void CLPhysLegacy::SetBodyFlag(lg_void* pBody, lg_dword nFlagID, lg_dword nValue) { } void CLPhysLegacy::SetBodyVector(lg_void* pBody, lg_dword nVecID, ML_VEC3* pVec) { } void CLPhysLegacy::SetBodyFloat(lg_void* pBody, lg_dword nFloatID, lg_float fValue) { } /* SetBodyPosition PRE: pBody must point to a body created by the phys engine. POST: The new position is set, and the server's entity's m_v3Face and m_v3Pos is updated as well (so it does not need to be updated on the server side). NOTES: This should rarely be called, it may need to be called in the case of teleports of some kind, or in the case that precise rotation needs to be specifed (as in the case of a first person shooter, if we just had the mouse do a certain amount of torque rotation might not be as smooth as directly updating the rotation, but in that case the translation part of the matrix should not be changed, only the rotation part). */ void CLPhysLegacy::SetBodyPosition(lg_void* pBody, ML_MAT* pMat) { CLPhysBody* pPhysBody=(CLPhysBody*)pBody; LEntitySrv* pEntSrv=(LEntitySrv*)pPhysBody->m_pEnt; pPhysBody->m_matPos=*pMat; pEntSrv->m_matPos=*pMat; //Calculate the face vectors, we set up face vector's for //ai purposes. These aren't really usefull for inert objects //but intelligent objects can use them to decide what direction //they want to move, etc. In the future it may be decided to //update these vectors only when the object is flagged as //intelligent. ML_Vec3TransformNormalArray( pEntSrv->m_v3Face, sizeof(ML_VEC3), s_v3StdFace, sizeof(ML_VEC3), pMat, 3); } lg_void* CLPhysLegacy::GetBodySaveInfo(lg_void* pBody, lg_dword* pSize) { return LG_NULL; } lg_void* CLPhysLegacy::LoadBodySaveInfo(lg_void* pData, lg_dword nSize) { return LG_NULL; } void CLPhysLegacy::UpdateFromSrv(CLPhysBody* pPhysBody, lg_void* pEntSrv) { static ml_vec3 v3Temp; LEntitySrv* pEnt=(LEntitySrv*)pEntSrv; //ML_Vec3Add(&pPhysBody->m_v3Thrust, &pPhysBody->m_v3Thrust, &pEnt->m_v3Thrust); pPhysBody->m_v3Thrust=pEnt->m_v3Thrust; pPhysBody->m_v3Torque=pEnt->m_v3Torque; ML_Vec3Scale(&v3Temp, &pEnt->m_v3Impulse, 1.0f/m_fTimeStep); ML_Vec3Add(&pPhysBody->m_v3Thrust, &pPhysBody->m_v3Thrust, &v3Temp); //Set torque and thrust to zero, so they don't carry over to the next frame. pEnt->m_v3Torque=s_v3Zero; pEnt->m_v3Thrust=s_v3Zero; pEnt->m_v3Impulse=s_v3Zero; } void CLPhysLegacy::UpdateToSrv(CLPhysBody* pPhysBody, lg_void* pEntSrv) { LEntitySrv* pEnt=(LEntitySrv*)pEntSrv; //We need to update the position, velocities pEnt->m_v3Vel=pPhysBody->m_v3Vel; pEnt->m_v3AngVel=pPhysBody->m_v3AngVel; pEnt->m_matPos=pPhysBody->m_matPos; //Calculate the face vectors. ML_Vec3TransformNormalArray( pEnt->m_v3Face, sizeof(ML_VEC3), s_v3StdFace, sizeof(ML_VEC3), &pEnt->m_matPos, 3); //Set the AABB (we use the PostMove AABB because this represents where the object is now: pEnt->m_aabbBody=pPhysBody->m_aabbPostMove; //Call the post physics AI routine. pEnt->m_pAI->PostPhys(pEnt); } <file_sep>/games/Legacy-Engine/Source/engine/lg_err_ex.cpp #include <stdio.h> #include <stdarg.h> #include "lg_err_ex.h" #include "lg_func.h" #include "common.h" typedef char ERR_TEXT[32]; ERR_TEXT g_szErr[LG_ERR_ERRCOUNT]={ "UNKNOWN ERROR", "DEFAULT ERROR", "OUT OF MEMORY", "ASSERTION ERROR"}; #if 0 CLError::CLError(): m_nErrorCode(LG_ERR_UNKNOWN) { m_szError[0]=0; } #endif CLError::CLError(LG_ERR nErrorCode, char* szFile, lg_dword nLine, char* szMsg): m_nErrorCode(nErrorCode) { _snprintf(m_szError, LG_ERR_MSG_SIZE, "ERROR 0x%08X (%s) %s (LINE %d)", nErrorCode, g_szErr[nErrorCode], szFile, nLine); if(szMsg) L_strncat(m_szError, szMsg, LG_ERR_MSG_SIZE); } /* CLError::CLError(char *szError, lg_dword nErrorCode): m_nErrorCode(nErrorCode) { LG_strncpy(this->m_szError, szError, LG_ERR_MSG_SIZE); this->m_nErrorCode=nErrorCode; } CLError::CLError(lg_str szError, lg_dword nErrorCode, lg_str szFile, lg_dword nLine) { _snprintf(m_szError, LG_ERR_MSG_SIZE, "ERROR 0x%08X: %s %s (LINE %d)", nErrorCode, szError, szFile, nLine); } */ void CLError::Catenate(LG_ERR nErrorCode, char* szFile, lg_dword nLine, char* szMsg) { lg_char szTemp[LG_ERR_MSG_SIZE+1]; LG_strncpy(szTemp, m_szError, LG_ERR_MSG_SIZE); _snprintf(m_szError, LG_ERR_MSG_SIZE, "%s >>\nERROR 0x%08X: %s %s (LINE %d)", szTemp, nErrorCode, g_szErr[nErrorCode], szFile, nLine); if(szMsg) L_strncat(m_szError, szMsg, LG_ERR_MSG_SIZE); } void CLError::Catenate(lg_str format, ...) { char szTemp[LG_ERR_MSG_SIZE+1]; LG_strncpy(szTemp, m_szError, LG_ERR_MSG_SIZE); va_list arglist=LG_NULL; va_start(arglist, format); _vsnprintf(m_szError, LG_ERR_MSG_SIZE, format, arglist); L_strncat(m_szError, " -->\n", LG_ERR_MSG_SIZE); L_strncat(m_szError, szTemp, LG_ERR_MSG_SIZE); va_end(arglist); } lg_cstr CLError::GetMsg() { return m_szError; } <file_sep>/games/Legacy-Engine/Source/lc_sys2/lc_def_UNICODE.cpp #if 0 #include <stdio.h> #include <string.h> #include "lc_sys2.h" #include "common.h" class CDefsU { friend class CConsoleU; private: struct DEF_VALUE{ lg_float f; lg_int u; }; struct DEF{ lg_wchar szDef[LC_MAX_DEF_LEN+1]; DEF_VALUE nValue; DEF* pHashNext; lg_bool bDefined; }; private: DEF* m_pHashList; lg_dword m_nDefCount; lg_dword GenDefHash(const lg_wchar* def); lg_bool AddDef(const lg_wchar* szDef, DEF_VALUE* pValue, lg_dword Flags=0); DEF_VALUE* GetDef(const lg_wchar* szDef); public: CDefsU(); ~CDefsU(); lg_bool AddDef(const lg_wchar* szDef, lg_float value, lg_dword Flags=0); lg_bool AddDef(const lg_wchar* szDef, lg_dword value, lg_dword Flags=0); lg_bool AddDef(const lg_wchar* szDef, lg_long value, lg_dword Flags=0); void Clear(); lg_dword GetDefUnsigned(const lg_wchar* def, lg_bool* bGot); lg_long GetDefSigned(const lg_wchar* def, lg_bool* bGot); lg_float GetDefFloat(const lg_wchar* def, lg_bool* bGot); }; CDefsU::CDefsU(): m_pHashList(LG_NULL), m_nDefCount(0) { m_pHashList=new DEF[LC_DEF_HASH_SIZE]; for(lg_dword i=0; i<LC_DEF_HASH_SIZE; i++) { m_pHashList[i].bDefined=LG_FALSE; } } CDefsU::~CDefsU() { Clear(); if(m_pHashList) { delete[]m_pHashList; } //printf("%d definitions.\n", m_nDefCount); } CDefsU::DEF_VALUE* CDefsU::GetDef(const lg_wchar* szDef) { lg_dword nHash=GenDefHash(szDef)%LC_DEF_HASH_SIZE; if(!m_pHashList[nHash].bDefined) return LG_NULL; DEF* pDef=&m_pHashList[nHash]; while(pDef) { if(wcsnicmp((wchar_t*)pDef->szDef, (wchar_t*)szDef, LC_MAX_DEF_LEN)==0) return &pDef->nValue; pDef=pDef->pHashNext; } return LG_NULL; } lg_dword CDefsU::GetDefUnsigned(const lg_wchar* def, lg_bool* bGot) { DEF_VALUE* pValue=GetDef(def); if(bGot) *bGot=pValue?LG_TRUE:LG_FALSE; if(pValue) return (lg_dword)pValue->u; return 0; } lg_long CDefsU::GetDefSigned(const lg_wchar* def, lg_bool* bGot) { DEF_VALUE* pValue=GetDef(def); if(bGot) *bGot=pValue?LG_TRUE:LG_FALSE; if(pValue) return (lg_long)pValue->u; return 0; } lg_float CDefsU::GetDefFloat(const lg_wchar* def, lg_bool* bGot) { DEF_VALUE* pValue=GetDef(def); if(bGot) *bGot=pValue?LG_TRUE:LG_FALSE; if(pValue) return (lg_float)pValue->f; return 0.0f; } lg_bool CDefsU::AddDef(const lg_wchar* szDef, DEF_VALUE* pValue, lg_dword Flags) { //First check to see if the definition has already been defined. DEF_VALUE* val=GetDef(szDef); if(val) { if(L_CHECK_FLAG(Flags, LC_DEF_NOREDEFINE)) { //printf("Can't redifine.\n"); return LG_FALSE; } else { //printf("Redefining.\n"); *val=*pValue; return LG_TRUE; } } lg_dword nHash=GenDefHash(szDef)%LC_DEF_HASH_SIZE; //LC_Printf("The hash for %s is %d", szDef, nHash); if(!m_pHashList[nHash].bDefined) { //If there is no definition in the hash slot we just //stick the definition in the hash slot. m_pHashList[nHash].bDefined=LG_TRUE; m_pHashList[nHash].nValue=*pValue; m_pHashList[nHash].pHashNext=LG_NULL; wcsncpy((wchar_t*)m_pHashList[nHash].szDef, (wchar_t*)szDef, LC_MAX_DEF_LEN); } else { //Add the new item (we know it isn't a redefinition because we //already checked). DEF* pNew=new DEF; if(!pNew) return LG_FALSE; pNew->bDefined=LG_TRUE; pNew->nValue=*pValue; pNew->pHashNext=LG_NULL; wcsncpy((wchar_t*)pNew->szDef, (wchar_t*)szDef, LC_MAX_DEF_LEN); pNew->pHashNext=m_pHashList[nHash].pHashNext; m_pHashList[nHash].pHashNext=pNew; } m_nDefCount++; return LG_TRUE; } lg_bool CDefsU::AddDef(const lg_wchar *szDef, lg_dword nValue, lg_dword Flags) { DEF_VALUE v={(lg_float)nValue, nValue}; return AddDef(szDef, &v, Flags); } lg_bool CDefsU::AddDef(const lg_wchar *szDef, lg_long nValue, lg_dword Flags) { DEF_VALUE v={(lg_float)nValue, nValue}; return AddDef(szDef, &v, Flags); } lg_bool CDefsU::AddDef(const lg_wchar *szDef, lg_float fValue, lg_dword Flags) { DEF_VALUE v={fValue, (lg_long)fValue}; return AddDef(szDef, &v, Flags); } void CDefsU::Clear() { if(!m_pHashList) return; for(lg_dword i=0; i<LC_DEF_HASH_SIZE; i++) { //If the slot doesn't have a definition //then there are no child subsequient definitions //with the same hash value, so it is safe to continue //down the list. if(!m_pHashList[i].bDefined) continue; DEF* pDef=m_pHashList[i].pHashNext; while(pDef) { DEF* pTemp=pDef->pHashNext; delete pDef; pDef=pTemp; m_nDefCount--; } m_pHashList[i].bDefined=LG_FALSE; m_nDefCount--; } } lg_dword CDefsU::GenDefHash(const lg_wchar* def) { lg_dword nLen=LG_Min(wcslen((wchar_t*)def), LC_MAX_DEF_LEN); lg_dword nHash=0; lg_dword i=0; lg_wchar c; for(i=0; i<nLen; i++) { c=def[i]; //Insure that the hash value is case insensitive //by capitalizing lowercase letters. if((c>='a') && (c<='z')) c-='a'-'A'; nHash+=c; nHash+=(nHash<<10); nHash^=(nHash>>6); } nHash+=(nHash<<3); nHash^=(nHash>>11); nHash+=(nHash<<15); return nHash; } #endif<file_sep>/games/Legacy-Engine/Source/LMEdit/AnimDialog.cpp // AnimDialog.cpp : implementation file // #include "stdafx.h" #include "LMEdit.h" #include "AnimDialog.h" #include "lg_func.h" // CAnimDialog dialog IMPLEMENT_DYNAMIC(CAnimDialog, CDialog) CAnimDialog::CAnimDialog(CWnd* pParent /*=NULL*/) : CDialog(CAnimDialog::IDD, pParent) , m_pSkel(NULL) { } CAnimDialog::~CAnimDialog() { } void CAnimDialog::DoDataExchange(CDataExchange* pDX) { if(pDX->m_bSaveAndValidate) { ModifySkeleton(); } CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_ANIMS, m_ListCtrl); DDX_Control(pDX, IDC_LOOPTYPE, m_cLoopBox); } BEGIN_MESSAGE_MAP(CAnimDialog, CDialog) ON_WM_CREATE() ON_BN_CLICKED(IDC_ADD_ANIM, &CAnimDialog::OnBnClickedAddAnim) ON_BN_CLICKED(IDC_DELETE_ANIM, &CAnimDialog::OnBnClickedDeleteAnim) END_MESSAGE_MAP() // CAnimDialog message handlers BOOL CAnimDialog::OnInitDialog() { CDialog::OnInitDialog(); CListCtrl* pCtrl=(CListCtrl*)GetDlgItem(IDC_ANIMS); pCtrl->InsertColumn(ANIM_NAME, _T("Name"), LVCFMT_LEFT, 100); pCtrl->InsertColumn(ANIM_FIRST_FRAME, _T("First Frame"), LVCFMT_LEFT, 75); pCtrl->InsertColumn(ANIM_NUM_FRAMES, _T("Frame Count"), LVCFMT_LEFT, 75); pCtrl->InsertColumn(ANIM_LOOPING_FRAMES, _T("Looping Frames"), LVCFMT_LEFT, 90); pCtrl->InsertColumn(ANIM_RATE, _T("Framerate"), LVCFMT_LEFT, 75); m_ListCtrl.InsertColumn(ANIM_FLAGS, _T("Flags"), LVCFMT_LEFT, 75); if(!m_pSkel || !m_pSkel->IsLoaded()) { MessageBox( "You need to load a skeleton before\n you can edit the animations!", 0, MB_ICONINFORMATION); CButton* pOkButton=(CButton*)GetDlgItem(IDOK); pOkButton->EnableWindow(FALSE); EndDialog(-1); return TRUE; } for(lg_long i=m_pSkel->GetNumAnims()-1; i>=0; i--) { const CLSkel2::SkelAnim* pAnim=m_pSkel->GetAnim(i); AddAnimation(pAnim); } /* for(lg_dword i=0; i<m_pSkel->GetNumAnims(); i++) { LSKEL_ANIM* pAnim=m_pSkel->GetAnim(i); AddAnimation(pAnim); } */ CString szTemp; szTemp.Format("%d", m_pSkel->GetNumFrames()); GetDlgItem(IDC_AVAILABLEFRAMES)->SetWindowText(szTemp); //Set some initial values for the animations SetDlgItemText(IDC_ANIM_NAME, _T("")); SetDlgItemText(IDC_ANIM_FIRST_FRAME, _T("0")); SetDlgItemText(IDC_ANIM_NUM_FRAMES, _T("1")); SetDlgItemText(IDC_ANIM_LOOPING_FRAMES, _T("0")); SetDlgItemText(IDC_ANIM_RATE, _T("30.0")); m_cLoopBox.SetCurSel(0); //Set focus to the name control. GetDlgItem(IDC_ANIM_NAME)->SetFocus(); return FALSE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CAnimDialog::SetSkel(CLSkel2* pSkel) { m_pSkel=pSkel; } BOOL CAnimDialog::AddAnimation(const CLSkel2::SkelAnim* pAnim) { if(!pAnim) return FALSE; /* CListCtrl* pCtrl=(CListCtrl*)GetDlgItem(IDC_ANIMS); if(!pCtrl) return FALSE; */ CString szNumber; m_ListCtrl.InsertItem(0, pAnim->szName); szNumber.Format("%d", pAnim->nFirstFrame); m_ListCtrl.SetItemText(0, ANIM_FIRST_FRAME, szNumber); szNumber.Format("%d", pAnim->nNumFrames); m_ListCtrl.SetItemText(0, ANIM_NUM_FRAMES, szNumber); szNumber.Format("%d", pAnim->nLoopingFrames); m_ListCtrl.SetItemText(0, ANIM_LOOPING_FRAMES, szNumber); szNumber.Format("%f", pAnim->fRate); m_ListCtrl.SetItemText(0, ANIM_RATE, szNumber); szNumber=""; if(LG_CheckFlag(pAnim->nFlags, pAnim->ANIM_FLAG_LOOPBACK)) { szNumber.AppendChar('B'); } m_ListCtrl.SetItemText(0, ANIM_FLAGS, szNumber); return TRUE; } void CAnimDialog::OnBnClickedAddAnim() { CLSkel2::SkelAnim Anim; CListCtrl* pCtrl=(CListCtrl*)GetDlgItem(IDC_ANIMS); if(!pCtrl) return; CString szTemp; GetDlgItemText(IDC_ANIM_NAME, szTemp); if(szTemp.IsEmpty()) { MessageBox("A name must be specified for the animation!", 0, MB_ICONINFORMATION); GetDlgItem(IDC_ANIM_NAME)->SetFocus(); return; } for(int i=0; i<pCtrl->GetItemCount(); i++) { CString szName=pCtrl->GetItemText(i, ANIM_NAME); if(szTemp.CompareNoCase(szName)==0) { MessageBox("That name is already being used for an animation.\nPlease specify a different name.", 0, MB_ICONINFORMATION); GetDlgItem(IDC_ANIM_NAME)->SetFocus(); return; } } //_tcsncpy(Anim.szName, szTemp, LMESH_MAX_NAME); LG_strncpy(Anim.szName, szTemp, CLMBase::LM_MAX_NAME); Anim.nFirstFrame=GetDlgItemInt(IDC_ANIM_FIRST_FRAME); Anim.nNumFrames=GetDlgItemInt(IDC_ANIM_NUM_FRAMES); Anim.nLoopingFrames=GetDlgItemInt(IDC_ANIM_LOOPING_FRAMES); GetDlgItemText(IDC_ANIM_RATE, szTemp); Anim.fRate=(float)atof(szTemp); //Here is where we set all the flags. szTemp=""; Anim.nFlags=0; if(m_cLoopBox.GetCurSel()==1) { Anim.nFlags|=Anim.ANIM_FLAG_LOOPBACK;//szTemp.AppendChar('B'); } //Check to make sure the variables are within bounds. BOOL bError=FALSE; lg_dword nNumFrames=m_pSkel?m_pSkel->GetNumFrames():0; szTemp="Please correct the following problems with the animation:\n"; if(Anim.nFirstFrame>nNumFrames) { bError=TRUE; szTemp.Append("The first frame is out of range.\n"); } if((Anim.nFirstFrame+Anim.nNumFrames-1)>nNumFrames) { bError=TRUE; szTemp.Append("The number of frames is out of range.\n"); } if(Anim.nLoopingFrames>Anim.nNumFrames) { bError=TRUE; szTemp.Append("There are more looping frames than total frames in the animation.\n"); } if(bError) { MessageBox(szTemp, 0, MB_ICONINFORMATION); return; } //Clear all the entries and set the focus back to IDC_ANIM_NAME. SetDlgItemText(IDC_ANIM_NAME, _T("")); SetDlgItemText(IDC_ANIM_FIRST_FRAME, _T("0")); SetDlgItemText(IDC_ANIM_NUM_FRAMES, _T("1")); SetDlgItemText(IDC_ANIM_LOOPING_FRAMES, _T("0")); //SetDlgItemText(IDC_ANIM_RATE, _T("30.0")); m_cLoopBox.SetCurSel(0); GetDlgItem(IDC_ANIM_NAME)->SetFocus(); //Add the animation AddAnimation(&Anim); } void CAnimDialog::OnBnClickedDeleteAnim() { CListCtrl* pCtrl=(CListCtrl*)GetDlgItem(IDC_ANIMS); if(!pCtrl) return; int nSelection=pCtrl->GetSelectionMark(); if(nSelection==-1) return; pCtrl->DeleteItem(nSelection); } BOOL CAnimDialog::ModifySkeleton(void) { CLSkel2::SkelAnim* pAnims=new CLSkel2::SkelAnim[m_ListCtrl.GetItemCount()]; if(!pAnims) return FALSE; for(int i=0; i<m_ListCtrl.GetItemCount(); i++) { CString szTemp; m_ListCtrl.GetItemText(i, ANIM_NAME, pAnims[i].szName, CLMBase::LM_MAX_NAME); szTemp=m_ListCtrl.GetItemText(i, ANIM_FIRST_FRAME); pAnims[i].nFirstFrame=_ttol(szTemp); szTemp=m_ListCtrl.GetItemText(i, ANIM_NUM_FRAMES); pAnims[i].nNumFrames=_ttol(szTemp); szTemp=m_ListCtrl.GetItemText(i, ANIM_LOOPING_FRAMES); pAnims[i].nLoopingFrames=_ttol(szTemp); szTemp=m_ListCtrl.GetItemText(i, ANIM_RATE); pAnims[i].fRate=(float)atof(szTemp); szTemp=m_ListCtrl.GetItemText(i, ANIM_FLAGS); pAnims[i].nFlags=0; for(int j=0; j<szTemp.GetLength(); j++) { switch(szTemp[j]) { default: break; case 'B': case 'b': pAnims[i].nFlags|=pAnims[i].ANIM_FLAG_LOOPBACK; break; } } } CLSkelEdit* pSkel=(CLSkelEdit*)(m_pSkel); if(!pSkel->SetAnims(m_ListCtrl.GetItemCount(), pAnims)) MessageBox("An error occured while modifying the\nanimations, no changes were made!", 0, MB_ICONERROR); LG_SafeDeleteArray(pAnims); return TRUE; } <file_sep>/games/Legacy-Engine/Scrapped/old/lm_sys.h #if 0 #ifndef __LM_SYS_H__ #define __LM_SYS_H__ #include <common.h> #include "ML_lib.h" #ifdef LM_USE_LF2 #include "lf_sys2.h" #endif LM_USE_LF2 #define LMESH_ID (*(lg_dword*)"LMSH") #define LMESH_VERSION (122) //Final version will be 200. #define LMESH_MAX_NAME (32) #define LMESH_MAX_PATH (260) //The Structures: #pragma pack(1) typedef char LMESH_NAME[LMESH_MAX_NAME]; typedef char LMESH_PATH[LMESH_MAX_PATH]; typedef struct _LSKEL_JOINT{ LMESH_NAME szName; LMESH_NAME szParentBone; lg_dword nParentBone; float position[3]; float rotation[3]; }LSKEL_JOINT; typedef struct _LSKEL_JOINTEX: public LSKEL_JOINT{ ML_MAT Local; ML_MAT Final; lg_dword nJointRef; }LSKEL_JOINTEX; typedef struct _LSKEL_JOINTPOS{ float position[3]; float rotation[3]; }LSKEL_JOINTPOS; typedef struct _LSKEL_ANIM{ LMESH_NAME m_szName; lg_dword m_nFirstFrame; //First frame for the animation. lg_dword m_nNumFrames; //Number of frames in the animation. lg_dword m_nLoopingFrames; //Number of frames to loop in the animation. float m_fRate; //Recommendation for rate at which animation should be processed. lg_dword m_nFlags; }LSKEL_ANIM; #define LSKEL_ANIM_DEFAULT 0x00000000 #define LSKEL_ANIM_LOOPBACK 0x00000001 //After the animation completes it's sequence of frames it then does them in reverse. #pragma pack() #define LSKEL_ID (*(lg_dword*)"LSKL") #define LSKEL_VERSION 105 //The Format: class CLMesh; class CLSkel; class CLFrame; //The read/write function is pretty similar to fread and fwrite //the first paramter is the out buffer, the second and third //are the size and count, and the fourth is the file stream. //The return value is either the number of bytes written //or read. typedef lg_uint (__cdecl * LM_RW_FN)(void*,lg_uint,lg_uint,void*); class CLSkel { public: friend class CLMesh; friend class CLMeshD3D; friend class CLMeshAnim; public: CLSkel(); ~CLSkel(); lg_bool Load(void* file, LM_RW_FN read); lg_bool Save(void* file, LM_RW_FN write); #ifdef LM_USE_LF2 lg_bool Load(lf_path szFilename); #endif LM_USE_LF2 lg_bool CalcExData(); virtual lg_bool Unload(); lg_dword GetNumFrames(); lg_dword GetNumJoints(); lg_dword GetNumKeyFrames(); lg_dword GetNumAnims(); lg_dword GetParentBoneRef(lg_dword nBone); ML_MAT* GenerateJointTransform(ML_MAT* pOut, lg_dword nJoint, lg_dword nFrame1, lg_dword nFrame2, float t); ML_MAT* GenerateJointTransform(ML_MAT* pOut, lg_dword nJoint, lg_dword nFrame1, lg_dword nFrame2, float t, CLSkel* pSkel2); ML_AABB* GenerateAABB(ML_AABB* pOut, lg_dword nFrame1, lg_dword nFrame2, float t); const ML_MAT* GetBaseTransform(lg_dword nJoint); lg_dword GetFrameFromTime(lg_dword nAnim, float fTime, float* pFrameTime, lg_dword* pFrame2); const LSKEL_ANIM* GetAnim(lg_dword n); lg_bool IsLoaded(); lg_bool GetMinsAndMaxes( float* fXMin, float* fXMax, float* fYMin, float* fYMax, float* fZMin, float* fZMax); protected: lg_bool AllocateMemory(); void DeallocateMemory(); lg_bool Serialize( void* file, LM_RW_FN read_or_write, lg_bool bLoading); protected: lg_dword m_nID; lg_dword m_nVersion; LMESH_NAME m_szSkelName; lg_dword m_nNumJoints; lg_dword m_nNumKeyFrames; lg_dword m_nNumAnims; LSKEL_JOINTEX* m_pBaseSkeleton; CLFrame* m_pFrames; LSKEL_ANIM* m_pAnims; lg_bool m_bLoaded; public: static ML_MAT* EulerToMatrix(ML_MAT* pOut, float* pEuler); static lg_uint ReadLF2(void* buffer, lg_uint size, lg_uint count, void* stream); }; //The CLFrame class, stores information about the frames. class CLFrame { friend class CLSkel; public: lg_dword m_nNumJoints; LSKEL_JOINTPOS* LocalPos; ML_AABB aabbBox; ML_MAT* Local; ML_MAT* Final; public: CLFrame(); CLFrame(lg_dword nNumJoints); ~CLFrame(); lg_bool Initialize(lg_dword nNumJoints); lg_dword GetNumJoints(); const ML_MAT* GetFinalMat(lg_dword nJoint); const ML_MAT* GetLocalMat(lg_dword nJoint); lg_bool SetFinalMat(lg_dword nJoint, ML_MAT* pM); lg_bool SetLocalMat(lg_dword nJoint, ML_MAT* pM); lg_bool SetLocalMat(lg_dword nJoint, float* position, float* rotation); }; #endif #endif //__SM_SYS_H__<file_sep>/tools/ListingGen/MovieLister/resource.h //{{NO_DEPENDENCIES}} // Microsoft Developer Studio generated include file. // Used by MovieLister.rc // #define IDD_TITLEDESC 101 #define IDD_SYSREQ 102 #define IDD_SHIPPAY 103 #define IDD_TERMS 104 #define IDC_NEXT 1000 #define IDC_PREV 1001 #define IDC_ITEMNAME 1002 #define IDC_ITEMTYPE 1003 #define IDC_DESC1 1004 #define IDC_DESC2 1005 #define IDC_MOVIEDESC 1005 #define IDC_OS 1008 #define IDC_CPU 1009 #define IDC_RAM 1010 #define IDC_CD 1011 #define IDC_HDD 1012 #define IDC_VIDEO 1013 #define IDC_SOUND 1014 #define IDC_INPUT 1015 #define IDC_OTHER 1016 #define IDC_RECOMMENDED 1017 #define IDC_COST 1021 #define IDC_SHIPINFO 1022 #define IDC_PAYOPTION 1023 #define IDC_TERMSHIP 1026 #define IDC_TERMFEEDBACK 1027 #define IDC_TERMWARRANTY 1028 #define IDC_CONDITION 1029 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 105 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1030 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif <file_sep>/tools/PodSyncPrep/src/podsyncp/resources/WaitWindow.properties jLabel1.text=Please wait... <file_sep>/games/Legacy-Engine/Source/LMEdit/DlgSaveAs.cpp // DlgSaveAs.cpp : implementation file // #include "stdafx.h" #include "LMEdit.h" #include "DlgSaveAs.h" // CDlgSaveAs dialog IMPLEMENT_DYNAMIC(CDlgSaveAs, CDialog) CDlgSaveAs::CDlgSaveAs(CWnd* pParent /*=NULL*/) : CDialog(CDlgSaveAs::IDD, pParent) , m_szMeshFile(_T("")) , m_szSkelFile(_T("")) { } CDlgSaveAs::CDlgSaveAs(LPCTSTR szMesh, LPCTSTR szSkel, CWnd* pParent/* = NULL*/) : CDialog(CDlgSaveAs::IDD, pParent) , m_szMeshFile(szMesh) , m_szSkelFile(szSkel) { } CDlgSaveAs::~CDlgSaveAs() { } void CDlgSaveAs::DoDataExchange(CDataExchange* pDX) { DDX_Text(pDX, IDC_MESHFILE, m_szMeshFile); DDX_Text(pDX, IDC_SKELFILE, m_szSkelFile); CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CDlgSaveAs, CDialog) ON_BN_CLICKED(IDC_BROWSEMESH, &CDlgSaveAs::OnBnClickedBrowsemesh) ON_BN_CLICKED(IDC_BROWSESKEL, &CDlgSaveAs::OnBnClickedBrowseskel) END_MESSAGE_MAP() // CDlgSaveAs message handlers void CDlgSaveAs::OnBnClickedBrowsemesh() { CFileDialog dlgFile( FALSE, _T(".lmsh"), m_szMeshFile, OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT, _T("Legacy Mesh (*.lmsh)|*.lmsh|All Files (*.*)|*.*||")); if(dlgFile.DoModal()!=IDOK) return; SetDlgItemText(IDC_MESHFILE, dlgFile.GetPathName()); } void CDlgSaveAs::OnBnClickedBrowseskel() { CFileDialog dlgFile( FALSE, _T(".lskl"), m_szSkelFile, OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT, _T("Legacy Skeleton (*.lskl)|*.lskl|All Files (*.*)|*.*||")); if(dlgFile.DoModal()!=IDOK) return; SetDlgItemText(IDC_SKELFILE, dlgFile.GetPathName()); } BOOL CDlgSaveAs::OnInitDialog() { CDialog::OnInitDialog(); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } <file_sep>/games/Legacy-Engine/Source/engine/lg_xml.h #ifndef __LG_XML_H__ #define __LG_XML_H__ #include <expat.h> #ifdef __cplusplus extern "C" { #endif __cplusplus void* XML_Alloc(size_t size); void* XML_Realloc(void* ptr, size_t size); void XML_Free(void* ptr); XML_Parser XML_ParserCreate_LG(const XML_Char *encoding); #ifdef __cplusplus } #endif __cplusplus #endif __LG_XML_H__<file_sep>/Misc/DBXExporter/DBXExporter/oedbx/library/oedbx/dbxTree.h //*************************************************************************************** #ifndef dbxTreeH #define dbxTreeH //*************************************************************************************** #include <oedbx/dbxCommon.h> //*************************************************************************************** class AS_EXPORT DbxTree { public : DbxTree(InStream ins, int4 address, int4 values); ~DbxTree(); int4 GetValue(int4 index) const; void ShowResults(OutStream outs) const; private : void readValues(InStream ins, int4 parent, int4 address, int4 position, int4 values); // data int4 Address; int4 Values, *Array; }; //*********************************************** #endif dbxTreeH <file_sep>/tools/img_lib/TexView3/TexView3Doc.cpp // TexView3Doc.cpp : implementation of the CTexView3Doc class // #include "stdafx.h" #include "TexView3.h" #include "TexView3Doc.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CTexView3Doc IMPLEMENT_DYNCREATE(CTexView3Doc, CDocument) BEGIN_MESSAGE_MAP(CTexView3Doc, CDocument) END_MESSAGE_MAP() // CTexView3Doc construction/destruction CTexView3Doc::CTexView3Doc() : m_pImg(NULL) { } CTexView3Doc::~CTexView3Doc() { if(m_pImg) { IMG_Delete(m_pImg); m_pImg=NULL; } } BOOL CTexView3Doc::OnNewDocument() { if (!CDocument::OnNewDocument()) return FALSE; IMG_Delete(m_pImg); m_pImg = NULL; return TRUE; } // CTexView3Doc serialization void CTexView3Doc::Serialize(CArchive& ar) { CFile* pFile=ar.GetFile(); if (ar.IsStoring()) { // TODO: add storing code here } else { img_byte* pData=NULL; try { if(pFile->GetLength()>0x0A400000) throw CString(CString(AfxGetAppName())+_T(" will not load textures greater than 64MB!")); pData=(img_byte*)malloc((size_t)pFile->GetLength()); if(!pData) throw CString(_T("Could not allocate enough memory to load image!")); if(!pData) throw CString(_T("Could not allocate memory to open file!")); if(pFile->Read(pData, (UINT)pFile->GetLength())<pFile->GetLength()) throw CString("Could not read ")+pFile->GetFileName(); if(m_pImg) { IMG_Delete(m_pImg); m_pImg = NULL; } m_pImg = IMG_OpenMemory(reinterpret_cast<img_void*>(pData), (img_dword)pFile->GetLength()); if(!m_pImg) throw CString(_T("Could not open image, no valid image data found!")); } catch(CString szError) { AfxMessageBox(CString(_T("CTexView3Doc::Serialize Error: "))+szError); //Should close document. POSITION p=GetFirstViewPosition(); this->GetNextView(p)->GetParent()->PostMessage(WM_CLOSE); } //Free data. if(pData)free(pData); } } // CTexView3Doc diagnostics #ifdef _DEBUG void CTexView3Doc::AssertValid() const { CDocument::AssertValid(); } void CTexView3Doc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG // CTexView3Doc commands BOOL CTexView3Doc::CreateCBitmap(CBitmap* pBM, DWORD* cx, DWORD* cy, IMGFILTER filter, DWORD Flags) { this->BeginWaitCursor(); /* The idea behind converting an imaged to a DDB that can be used with windows is the get necessary data and use CreateDIBitmap with specified info. */ if(!m_pImg) return FALSE; HBITMAP hFinal=NULL; LPVOID lpImageData=NULL; BITMAPINFOHEADER bmih; BITMAPINFO bmi; IMG_DESC descript; unsigned char nExtra=255; BOOL bOpen=FALSE; //unsigned short finalwidth=0, finalheight=0; memset(&bmih, 0, sizeof(BITMAPINFOHEADER)); memset(&bmi, 0, sizeof(BITMAPINFO)); if(!m_pImg) { EndWaitCursor(); return FALSE; } IMG_GetDesc(m_pImg, &descript); *cx=*cx?*cx:descript.Width; *cy=*cy?*cy:descript.Height; lpImageData=malloc((*cx)*(*cy)*4); if(!lpImageData) { EndWaitCursor(); return FALSE; } //Set up the destination rect. IMG_DEST_RECT rcd={0}; rcd.nWidth=*cx; rcd.nHeight=*cy; rcd.nPitch=(*cx)*4; rcd.nFormat=IMGFMT_A8R8G8B8; rcd.nOrient=IMGORIENT_BOTTOMLEFT; rcd.rcCopy.top=0; rcd.rcCopy.left=0; rcd.rcCopy.right=*cx; rcd.rcCopy.bottom=*cy; rcd.pImage=(img_void*)lpImageData; IMG_CopyBits(m_pImg, &rcd, filter, NULL, 0xFF); int i=0; //If we want the alpha channel we simply copy the alpha //value into all other values. This will give us the gray //scale image we need. //DWORD nAlphaMode=CHECK_FLAG(Flags, BC_ACHANNEL)|CHECK_FLAG(Flags, BC_IMAGE); if(CHECK_FLAG(Flags, BC_ACHANNEL)) { ARGBVALUE colrBG={0, 0, 0, 0xFF}; DWORD bgclr=CHECK_FLAG(Flags, BC_USEAPPBG)?/*pdc->GetBkColor()*/BG_COLOR:0xFF000000; memcpy(&colrBG, &bgclr, 4); ARGBVALUE* pColVals=(ARGBVALUE*)lpImageData; for(i=0; i<((*cx)*(*cy)); i++) { //If we want to render both the image and the alpah channel //we do an alpha blend. if(CHECK_FLAG(Flags, BC_IMAGE)) { //newColor = backColor + (overlayColor – backColor) * (alphaByte div 255) pColVals[i].r=pColVals[i].r+(colrBG.r-pColVals[i].r)*(255-pColVals[i].a)/255; pColVals[i].g=pColVals[i].g+(colrBG.g-pColVals[i].g)*(255-pColVals[i].a)/255; pColVals[i].b=pColVals[i].b+(colrBG.b-pColVals[i].b)*(255-pColVals[i].a)/255; } else { //If not we use white as the image color and do the same alpha blend op. pColVals[i].r=255+(colrBG.r-255)*(255-pColVals[i].a)/255; pColVals[i].g=255+(colrBG.g-255)*(255-pColVals[i].a)/255; pColVals[i].b=255+(colrBG.b-255)*(255-pColVals[i].a)/255; } } } bmih.biSize=sizeof(BITMAPINFOHEADER); bmih.biWidth=*cx; bmih.biHeight=*cy; bmih.biPlanes=1; bmih.biBitCount=32; bmih.biCompression=BI_RGB; bmih.biSizeImage=(*cx)*(*cy)*4;//BI_RGB; bmih.biXPelsPerMeter=0; bmih.biYPelsPerMeter=0; bmih.biClrUsed=0; bmih.biClrImportant=0; bmi.bmiHeader=bmih; POSITION p=GetFirstViewPosition(); hFinal=CreateDIBitmap( GetNextView(p)->GetDC()->m_hDC, &bmih, CBM_INIT, lpImageData, &bmi, DIB_RGB_COLORS); free(lpImageData); pBM->DeleteObject(); pBM->m_hObject=hFinal; //UpdateAllViews(NULL); EndWaitCursor(); return TRUE; } <file_sep>/games/Legacy-Engine/Scrapped/UnitTests/VarTest/var_var.h #pragma once #include "var_types.h" namespace var_sys{ class CVar; typedef CVar& lg_var; class CVar { friend class CVarMgr; public: //This is a blank var, whose hash value hasn't come up. static const var_word F_EMPTY=0x00000001; //var can't be changed. static const var_word F_ROM=0x00000002; //var should be saved upon exit. static const var_word F_SAVE=0x00000004; //something should update immediately on change of var. static const var_word F_UPDATE=0x00000008; private: var_string m_strName; var_word m_nFlags; var_float m_fValue; var_long m_nValue; var_string m_strValue; private: __inline static void CopyString(var_char* out, const var_char* in); __inline static var_word HexToDword(const var_char* in); __inline static void StringToNumber(const var_char* in, var_float * fValue, var_long * nValue); private: void SetFlags(var_word flags); void Init(const var_char* name); private: CVar(void); ~CVar(void); public: var_float Float()const; var_word Word()const; var_long Long()const; const var_char* String()const; const var_char* Name()const; void Set(var_float value); void Set(var_word value); void Set(var_long value); void Set(const var_char* value); void Set(const CVar& rhs); void operator= (var_float value); void operator= (var_word value); void operator= (var_long value); void operator= (const var_char* value); void operator= (CVar& rhs); }; } //namespace var_sys <file_sep>/games/Legacy-Engine/Scrapped/plugins/lmsh3DWS/lmsh3DWS.cpp // lmsh3DWS.cpp : Defines the initialization routines for the DLL. // #include "stdafx.h" #include "lmsh3DWS.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // //TODO: If this DLL is dynamically linked against the MFC DLLs, // any functions exported from this DLL which call into // MFC must have the AFX_MANAGE_STATE macro added at the // very beginning of the function. // // For example: // // extern "C" BOOL PASCAL EXPORT ExportedFunction() // { // AFX_MANAGE_STATE(AfxGetStaticModuleState()); // // normal function body here // } // // It is very important that this macro appear in each // function, prior to any calls into MFC. This means that // it must appear as the first statement within the // function, even before any object variable declarations // as their constructors may generate calls into the MFC // DLL. // // Please see MFC Technical Notes 33 and 58 for additional // details. // // Clmsh3DWSApp BEGIN_MESSAGE_MAP(Clmsh3DWSApp, CWinApp) END_MESSAGE_MAP() // Clmsh3DWSApp construction Clmsh3DWSApp::Clmsh3DWSApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } // The one and only Clmsh3DWSApp object Clmsh3DWSApp theApp; // Clmsh3DWSApp initialization BOOL Clmsh3DWSApp::InitInstance() { CWinApp::InitInstance(); return TRUE; } #include <stdio.h> #include "lm_xexp.h" void WS_FUNC PluginMeshLoad(wsByte* pIn, wsDword nInSize, wsByte* pOut, wsDword nOutSize) { wsString szFilename=(wsString)pIn; //We are going to convert the file to the x format, //then use the x plugin to load the file, so //we need to first load the x library. HMODULE hSMF=LoadLibrary(_T("plugins\\x.dll")); if(!hSMF) { AfxMessageBox(_T("Could not load X plugin."), MB_ICONERROR); return; } WS_PLUGIN_FUNC pPluginMeshLoadX=(WS_PLUGIN_FUNC)GetProcAddress(hSMF, _T("PluginMeshLoad")); if(!pPluginMeshLoadX) { AfxMessageBox(_T("Could not get address of PluginMeshLoad."), MB_ICONERROR); return; } CLMeshXExp cMesh; #if 0 void* file=L_fopen(szFilename, LOPEN_OPEN_EXISTING, LOPEN_READ); if(!file) return; if(!cMesh.Load(file, L_fread, "")) { L_fclose(file); return; } L_fclose(file); #endif FILE* file=fopen(szFilename, "rb"); if(!file) return; lg_bool bResult=cMesh.Load(file, (LM_RW_FN)fread, ""); fclose(file); if(!bResult) return; //Create a temp file to save to. CString szPath, szTempFilename; GetTempPath(MAX_PATH, szPath.GetBuffer(MAX_PATH+1)); GetTempFileName(szPath, _T("xcn"), 0, szTempFilename.GetBuffer(MAX_PATH)); bResult=cMesh.SaveAsX(szTempFilename.GetBuffer()); cMesh.Unload(); if(!bResult) return; pPluginMeshLoadX((wsByte*)szTempFilename.GetBuffer(), szTempFilename.GetLength()+1, pOut, nOutSize); //Delete the temporary file. DeleteFile(szTempFilename); //Free the x plugin library. FreeLibrary(hSMF); return; } void WS_FUNC PluginClass(wsByte* pIn, wsDword nInSize, wsByte* pOut, wsDword nOutSize) { wsDword nType=PLUGIN_MESHLOAD; memcpy(pOut, &nType, 4); } void WS_FUNC PluginDescription(wsByte* pIn, wsDword nInSize, wsByte* pOut, wsDword nOutSize) { wsChar szTemp[]="Load Legacy meshes (*.lmsh)"" ("__DATE__" "__TIME__")"; memcpy(pOut, szTemp, sizeof(szTemp)); } void WS_FUNC PluginFileExtension(wsByte* pIn, wsDword nInSize, wsByte* pOut, wsDword nOutSize) { wsChar szTemp[]="lmsh"; memcpy(pOut, szTemp, sizeof(szTemp)); } /* void PluginExport(unsigned char* inbuffer, int insize, unsigned char* outbuffer, int outsize) { char buffer[1024]; unsigned char* MapData=(unsigned char*)*((unsigned int *)inbuffer); unsigned short* mapversion = (unsigned short*) MapData; unsigned char* mapflags = (unsigned char*) (MapData+2); int* name_count = (int*) (MapData+3); int* name_offset = (int*) (MapData+7); int* object_count = (int*) (MapData+11); int* object_offset = (int*) (MapData+15); char** NameTable=new char*[*name_count]; MapData=(unsigned char*)*((unsigned int *)inbuffer)+*name_offset; for(int i=0;i<*name_count;++i) { NameTable[i]=(char*)MapData; MapData+=strlen(NameTable[i])+1; sprintf(buffer,"%s",NameTable[i]); MessageBox(NULL,buffer,"PluginExport",MB_OK); } MapData=(unsigned char*)*((unsigned int *)inbuffer)+*object_offset; for(int i=0;i<*object_count;++i) { sprintf(buffer,"Object %d %s size %d",i, NameTable[*((unsigned int*)MapData)-1], *((int*)MapData+1)); MessageBox(NULL,buffer,"PluginExport",MB_OK); MapData+=(*((int*)MapData+1))+8; } FILE* exp = fopen((const char*)inbuffer+4,"wb"); fwrite((unsigned char*)*((unsigned int *)inbuffer)+*object_offset,sizeof(unsigned char),512,exp); fclose(exp); delete[] NameTable; } */ <file_sep>/games/Explor2002/Source/Game/Player.h #ifndef __PLAYER_H__ #define __PLAYER_H__ #include <windows.h> #include "defines.h" class CPlayerObject{ private: int m_nXLoc; int m_nYLoc; Direction m_nFace; public: CPlayerObject(int x, int y, Direction face); ~CPlayerObject(); BOOL Move(MoveType Move, int movedst); BOOL Turn(TurnType Turn); void SetFace(Direction newFace); void SetLocation(int x, int y); BOOL CopyTFront(USHORT src[TFRONT_SIZE]); int GetXLoc(); int GetYLoc(); Direction GetFace(); USHORT m_aTFront[TFRONT_SIZE]; }; #endif<file_sep>/games/Legacy-Engine/Scrapped/old/lw_sys.cpp #include "lg_malloc.h" #include "lg_sys.h" #include "lw_sys.h" #include "lg_err.h" #include "lg_err_ex.h" #include "lvf_sys.h" #include "le_test.h" #include "ld_sys.h" CLPhysics CLWorld::s_LegacyPhysics; CLWorld::CLWorld(): m_pEntities(LG_NULL), m_Camera() { Initialize(); } CLWorld::~CLWorld() { m_WorldMap.Unload(); //L_safe_release(m_pDevice); s_LegacyPhysics.RemoveAllBodies(); RemoveAllEntities(); Err_Printf("Destroying Newton Game Dynamics physics engine..."); CElementNewton::Shutdown(); CElementPhysX::Shutdown(); } void CLWorld::RemoveEntity(CLEntity* pEnt) { CLEntity* pTempEnt; if(pEnt==m_pEntities) { //Special case. pTempEnt=m_pEntities; m_pEntities=(CLBase3DEntity*)m_pEntities->GetNext(); delete pTempEnt; return; } pTempEnt=pEnt->GetPrev(); pTempEnt->SetNext(pEnt->GetNext()); pEnt->SetPrev(pTempEnt); delete pEnt; } void CLWorld::RemoveAllEntities() { for(CLBase3DEntity* pEnt=m_pEntities; pEnt; ) { CLBase3DEntity* pTemp=(CLBase3DEntity*)pEnt->GetNext(); //In the future we won't use delete, there will be a //set maximum entities and we will simply remove //entities from the linked list. delete pEnt; pEnt=pTemp; } } void CLWorld::Initialize() { if(!s_pDevice) throw CLError(LG_ERR_INVALID_PARAM, __FILE__, __LINE__, "CLWorld Initializion: No device specified."); //Create the newton world... Err_Printf("Initializing Newton Game Dynamics physics engine..."); CElementNewton::Initialize(); CLEntity::s_pWorldMap=&m_WorldMap; Err_Printf("Initializing PhysX physics engine..."); CElementPhysX::Initialize(); LoadLevel("dbase/scripts/levels/Cedar Hills.xml"); } lg_bool CLWorld::LoadMap(lf_path szFilename) { lg_bool bLoaded=m_WorldMap.LoadFromWS(szFilename, s_pDevice); //lg_bool bLoaded=m_WorldMap.Load(szFilename, s_pDevice); if(bLoaded) { Err_Printf("Setting up Newton Game Dynamics world geometry..."); CElementNewton::SetupWorld(&m_WorldMap); Err_Printf("Setting up PhysX world geometry..."); CElementPhysX::SetupWorld(&m_WorldMap); s_LegacyPhysics.SetWorld(&m_WorldMap); } else { CElementNewton::SetupWorld(LG_NULL); CElementPhysX::SetupWorld(LG_NULL); } return bLoaded; } lg_bool CLWorld::LoadLevel(lf_path szXMLFilename) { //This is just temporary, a real xml file will be loaded later on. //Some test stuff... //m_SkyBox.Load("/dbase/meshes/skybox/skybox.lmsh"); m_SkyBox.Load("/dbase/meshes/skybox/SkyMATTER3/SkyMATTER3.lmsh"); //lg_char szMap[]="/dbase/maps/solids_test.3dw"; //lg_char szMap[]="/dbase/maps/Cedar Hills.3dw"; //lg_char szMap[]="/dbase/maps/tri_test.3dw"; //lg_char szMap[]="/dbase/maps/thing.3dw"; lg_char szMap[]="/dbase/maps/room_test.3dw"; //lg_char szMap[]="/dbase/maps/block.3dw"; //lg_char szMap[]="/dbase/maps/house.3dw"; //lg_char szMap[]="/dbase/maps/simple_example.3dw"; //m_WorldMap.LoadFromWS(szMap, s_pDevice); LoadMap(szMap); //Create some entities. ML_VEC3 v3Pos={2.0f, 0.2f, -2.0f}; CLBase3DEntity* pNewEnt; pNewEnt=AddEntity(new CLJack()); pNewEnt->Initialize(&v3Pos); ML_VEC3 offset={0.0f, 1.2f, 0.0f}; //ML_VEC3 offset={0.0f, 1.5f*30.0f, 0.0f}; //m_Camera.AttachToObject(&m_Player, CLCamera::CLCAMERA_ATTACH_FOLLOW, &offset, 2.0f); m_Camera.AttachToObject( pNewEnt, CLCamera::CLCAMERA_ATTACH_FOLLOW, //CLCamera::CLCAMERA_ATTACH_EYE, &offset, 1.5f);//*30.0f); #if 1 v3Pos.x=2.0f; v3Pos.z=-1.0f; v3Pos.y=0.2f; pNewEnt=AddEntity(new CLBlaineEnt()); pNewEnt->Initialize(&v3Pos); v3Pos.x=1.0f; v3Pos.z=2.0f; v3Pos.y=1.0f; pNewEnt=AddEntity(new CLBarrelEnt()); pNewEnt->Initialize(&v3Pos); #endif //A test #if 0 CLVFont font; font.Load("/dbase/font/font2.xml"); #endif //Test stuff... //lg_str szTestSound="/dbase/music/singerstrangetheme.ogg"; //lg_str szTestSound="/dbase/music/LARGEWAVE01.wav"; lg_str szTestSound="InTown.ogg"; LC_SendCommandf("MUSIC_START \"%s\"", szTestSound); //UPdate the timer so the phsysics engine isn't way ahead. s_Timer.Update(); return LG_TRUE; } lg_bool CLWorld::LoadSky(lf_path szFilename) { m_SkyBox.Load(szFilename); return LG_TRUE; } void CLWorld::ProcessEntities() { //First things first is to process all the entitie's AI (processing //AI doesn't move the object, but it generates a proposoed movement //vector stored int m_v3Vel. for(CLEntity* pEnt=m_pEntities; pEnt; pEnt=pEnt->GetNext()) { pEnt->ProcessFrame(); } //Process Newton Game Dynamics physics engine. CElementNewton::Simulate(s_Timer.GetFElapsed()); //s_LegacyPhysics.Processes(s_Timer.GetElapsed()); //Update PhysX scene... CElementPhysX::Simulate(s_Timer.GetFElapsed()); this->s_LegacyPhysics.Processes(s_Timer.GetElapsed()); //Update the camera... m_Camera.Update(); } CLBase3DEntity* CLWorld::AddEntity(CLBase3DEntity* pEnt) { if(!pEnt) { Err_Printf("CLWorld::AddEntity ERROR: No entity specified."); return LG_NULL; } pEnt->SetPrev(LG_NULL); pEnt->SetNext(m_pEntities); if(m_pEntities) m_pEntities->SetPrev(pEnt); m_pEntities=pEnt; return pEnt; } void CLWorld::SetEntityLight(CLBase3DEntity* pEnt) { if(!m_WorldMap.m_bLoaded) return; //Right now we'll just get the first light //from the first region that the entity is in. LW_LIGHT lt; memset(&lt, 0, sizeof(LW_LIGHT)); if(pEnt->m_nNumRegions) { //if(m_WorldMap.m_pRegions[pEnt->m_nRegions[0]].nLightcount) lt=m_WorldMap.m_pRegions[pEnt->m_nRegions[0]].pLights[0]; } D3DLIGHT9 Light; Light.Type=D3DLIGHT_DIRECTIONAL; Light.Diffuse.r=lt.Color.r; Light.Diffuse.g=lt.Color.g; Light.Diffuse.b=lt.Color.b; Light.Diffuse.a=lt.Color.a; Light.Specular.a=Light.Specular.r=Light.Specular.g=Light.Specular.b=0.0f; Light.Ambient.a=Light.Ambient.r=Light.Ambient.g=Light.Ambient.b=0.3f; ML_Vec3Subtract((ML_VEC3*)&Light.Direction, &pEnt->m_v3Pos, &lt.v3Pos); #if 0 ML_AABB aabb; aabb.v3Min=lt.v3Pos; aabb.v3Max=aabb.v3Min; aabb.v3Max.x+=0.25f; aabb.v3Max.y+=0.25f; aabb.v3Max.z+=0.25f; LD_DrawAABB(s_pDevice, &aabb, 0xFF00FF00); #endif s_pDevice->SetLight(0, &Light); s_pDevice->LightEnable(0, TRUE); } void CLWorld::Render() { m_Camera.RenderForSkybox(); CLMeshD3D::SetSkyboxRenderStates(); m_SkyBox.Render(); m_Camera.Render(); s_pDevice->SetRenderState(D3DRS_ZENABLE, TRUE); s_pDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE); s_pDevice->SetRenderState(D3DRS_LIGHTING, FALSE); m_WorldMap.Render(); s_pDevice->SetRenderState(D3DRS_LIGHTING, TRUE); CLMeshD3D::SetRenderStates(); for(CLBase3DEntity* pEnt=m_pEntities; pEnt; pEnt=(CLBase3DEntity*)pEnt->GetNext()) { SetEntityLight(pEnt); pEnt->Render(); } #if 0 lg_bool bRenderBlockAABB=LG_TRUE; lg_bool bRenderRegionAABB=LG_TRUE; lg_bool bRenderEntAABB=LG_TRUE; //For debug purposes we can draw some bounding volumes.... s_pDevice->SetRenderState(D3DRS_LIGHTING, FALSE); //For debug draw all geo block bounding volumes for(lg_dword i=0; i<m_WorldMap.m_nGeoBlockCount && bRenderBlockAABB; i++) { LD_DrawAABB(s_pDevice, &m_WorldMap.m_pGeoBlocks[i].aabbBlock, 0xFF0000FF); } for(lg_dword i=0; i<m_WorldMap.m_nRegionCount && bRenderRegionAABB; i++) { LD_DrawAABB(s_pDevice, &m_WorldMap.m_pRegions[i].aabbAreaBounds, 0xFFFFFF00); } for(CLBase3DEntity* pEnt=m_pEntities; pEnt && bRenderEntAABB; pEnt=(CLBase3DEntity*)pEnt->GetNext()) { LD_DrawAABB(s_pDevice, &pEnt->m_aabbCurrent, 0xFFFF0000); } s_pDevice->SetRenderState(D3DRS_LIGHTING, TRUE); #endif } lg_bool CLWorld::Validate() { lg_bool bResult=LG_TRUE; bResult=bResult&&m_WorldMap.Validate(); return bResult; } void CLWorld::Invalidate() { m_WorldMap.Invalidate(); }<file_sep>/games/Explor2002/Source/Game/defines.h #ifndef __DEFINES_H__ #define __DEFINES_H__ #define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } } #define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } } #define NUM_TILES 3 #define NUM_TILE_SETS 2 #define SCREEN_WIDTH 640 //pixels wide #define SCREEN_HEIGHT 480 //pixels high #define VIEW_WIDTH 640 #define VIEW_HEIGHT 480 #define COLOR_DEPTH 16 //number of bits to store colors #define BACK_FUFFER_COUNT 1 #define TRANSPARENT_COLOR RGB(255,0,255) //transparent color enum Direction{NORTH=0, EAST, SOUTH, WEST}; enum MoveType{FORWARD, BACKWARD, STRAFE_LEFT, STRAFE_RIGHT}; enum TurnType{LEFT, RIGHT}; enum TileType{WALL, DOOR}; #define TFRONT_SIZE 25 #endif<file_sep>/games/Legacy-Engine/Source/engine/lt_sys.cpp #include "lt_sys.h" #include "lg_err_ex.h" #include <windows.h> //LT_GetTimeMS returns the number of milliseconds since the game was started. lg_dword LT_GetTimeMS() { static lg_bool bInit=LG_FALSE; static lg_dword dwBaseTime; if(!bInit) { dwBaseTime=timeGetTime(); bInit=LG_TRUE; } return timeGetTime()-dwBaseTime; } lg_dword LT_GetHPTimeMS() { static lg_bool bInit=LG_FALSE; static UINT64 nAdjFreq; static UINT64 nBaseTime; if(!bInit) { if(!QueryPerformanceFrequency((LARGE_INTEGER*)&nAdjFreq) || nAdjFreq==0) throw CLError(LG_ERR_DEFAULT, __FILE__, __LINE__, "Could not initialize high performance timer!"); //Adjust the freqency to milliseconds (we'll lose precision here). nAdjFreq/=1000; QueryPerformanceCounter((LARGE_INTEGER*)&nBaseTime); bInit=LG_TRUE; } UINT64 nTime; QueryPerformanceCounter((LARGE_INTEGER*)&nTime); return (lg_dword)((nTime-nBaseTime)/(nAdjFreq)); } //CLTimer class methods... CLTimer::CLTimer(): m_dwInitialTime(0), m_dwTime(0), m_dwLastTime(0), m_dwElapsed(0), m_fTime(0.0f), m_fLastTime(0.0f), m_fElapsed(0.0f) { } void CLTimer::Initialize() { m_dwInitialTime=LT_GetTimeMS(); m_dwLastTime=m_dwTime=0;//m_dwInitialTime-m_dwInitialTime/*(=0)*/; m_fTime=m_fLastTime=(lg_float)m_dwInitialTime; } void CLTimer::Update() { m_dwLastTime=m_dwTime; m_dwTime=LT_GetTimeMS()-m_dwInitialTime; m_dwElapsed=m_dwTime-m_dwLastTime; m_fLastTime=m_dwLastTime*0.001f; m_fTime=m_dwTime*0.001f; m_fElapsed=m_dwElapsed*0.001f; } lg_dword CLTimer::GetTime() { return m_dwTime; } //////////////////////////////////////////////// // CLTimer::GetElapsedTime returns the amount // of milliseconds since the last call to Update // so in effect this will report how much time // has passed between two frames. //////////////////////////////////////////////// lg_dword CLTimer::GetElapsed() { return m_dwElapsed; } //Note that the GetF methods return a floating //point time that represents a decimal number of //the seconds as opposed to milliseconds for the //Get methods. lg_float CLTimer::GetFTime() { return m_fTime; } lg_float CLTimer::GetFElapsed() { return m_fElapsed; } <file_sep>/games/Legacy-Engine/Source/engine/lg_err.c /********************************************************* File: lg_err.c Copyright (c) 2006, <NAME> Purpose: Contains various functions for initializing error reporting, and for reporting errors. *********************************************************/ #include "common.h" #include <windows.h> #include <stdio.h> #include <stdarg.h> #include <d3d9.h> #include "lg_err.h" //#include "dxerr9.h" #include "lg_sys.h" lg_dword g_nTabSize=0; /********************************************************* Err_Printf() Prints formatted text to the specifed console, or if a console has not been initialized reports to stdout. *********************************************************/ void Err_Printf(const char* format, ...) { char szOutput[MAX_ERR_MSG_LEN]; va_list arglist=LG_NULL; int nResult=0; for(lg_dword i=0; i<g_nTabSize; i++) { szOutput[i]=' '; } va_start(arglist, format); _vsnprintf(&szOutput[g_nTabSize], MAX_ERR_MSG_LEN-1-g_nTabSize, format, arglist); LC_Print(szOutput); #if defined(_DEBUG) OutputDebugString("CONSOLE: "); OutputDebugString(szOutput); OutputDebugString("\n"); #endif va_end(arglist); } void Err_IncTab() { g_nTabSize+=3; } void Err_DecTab() { if(g_nTabSize) g_nTabSize-=3; } void Err_MsgPrintf(const char* format, ...) { char szOutput[128]; char szMsg[128]; va_list arglist=LG_NULL; int nResult=0; va_start(arglist, format); _vsnprintf(szOutput, 127, format, arglist); va_end(arglist); _snprintf(szMsg, 127, "setmessage \"%s\"", szOutput); LC_SendCommand(szMsg); } void Err_PrintfDebug(const char* format, ...) { char szOutput[MAX_ERR_MSG_LEN]; va_list arglist=LG_NULL; int nResult=0; va_start(arglist, format); _vsnprintf(szOutput, MAX_ERR_MSG_LEN-1, format, arglist); OutputDebugString(szOutput); va_end(arglist); } /************************************************ Err_PrintDX() Prints a directx error code and description. ************************************************/ void Err_PrintDX(lg_cstr function, lg_result nResult) { Err_Printf( "%s returned %s (%s).", (lg_str)function, "Error", //DXGetErrorString9(nResult), "Desc");//DXGetErrorDescription9(nResult)); } void Err_PrintVersion() { Err_Printf(g_GameString); //Err_Printf("%s %s", LGAME_NAME, "BUILD "LGAME_VERSION" ("__DATE__" "__TIME__")"); } void Err_ErrBox(const char* format, ...) { char szOutput[1024]; va_list arglist=LG_NULL; int nResult=0; va_start(arglist, format); _vsnprintf(szOutput, 1024-1, format, arglist); MessageBox(0, szOutput, "Error Message", MB_OK); va_end(arglist); } void Err_PrintMatrix(void* pM1) { D3DMATRIX* pM=(D3DMATRIX*)pM1; Err_Printf("MATRIX:"); Err_Printf("| %f\t %f\t %f\t %f|", pM->_11, pM->_12, pM->_13, pM->_14); Err_Printf("| %f\t %f\t %f\t %f|", pM->_21, pM->_22, pM->_23, pM->_24); Err_Printf("| %f\t %f\t %f\t %f|", pM->_31, pM->_32, pM->_33, pM->_34); Err_Printf("| %f\t %f\t %f\t %f|", pM->_41, pM->_42, pM->_43, pM->_44); } //File system error reporting callback function void __cdecl Err_FSCallback(lg_cwstr szString) { char szOutput[512]; wcstombs(szOutput, (const wchar_t*)szString, 511); Err_Printf(szOutput); } <file_sep>/games/Legacy-Engine/Scrapped/libs/lf_sys1/lf_sys.c /**************************************************** File: lf_sys.c Copyright (c) 2006, <NAME> Purpose: Functions that control disk input (and possibly in the future, output) for the Legacy File System. Functions starting with LF_ are used to effect the usage of the file system. Functions starting with File_ are used to access files within the file system. ****************************************************/ #include "common.h" #include <stdio.h> #include <direct.h> #include <math.h> #include <memory.h> #include <malloc.h> #include "lf_sys.h" #include "lf_sys.h" #include <stdarg.h> /* A few global variables are used for the file system, one to indicate if the file system has been initialized another to store the current working directory, and also one to store the SEARCHPATHS. */ L_bool g_bFSInited=L_false; char g_szCurDir[MAX_F_PATH]; SEARCHPATHS* g_SearchPaths=L_null; L_bool g_bArchivesFirst=L_false; /********************************************************* The LF_* functions are used to manipulate the file system, they initialize, shutdown, and can change the working directory. **********************************************************/ /************************************************ LF_SetError() && LF_GetLastError() Get and set the error text. ************************************************/ char g_szErrorText[1024]; void LF_SetError(char* format, ...) { va_list arglist; va_start(arglist, format); _vsnprintf(g_szErrorText, 1023, format, arglist); va_end(arglist); } char* LF_GetLastError() { return g_szErrorText; } /********************************************************************** LF_GetPath() This function goes through the search paths until it finds the specified filename. If it finds it, it returns information about that file. If it doesn't it returns L_null. **********************************************************************/ SEARCHPATHS* LF_GetPath(const char* szFilename) { SEARCHPATHS* lpPath=L_null; for(lpPath=g_SearchPaths; lpPath; lpPath=lpPath->m_next) { if(L_strnicmp((char*)szFilename, lpPath->m_szNameInLibrary, 0)) return lpPath; } LF_SetError("LF_GetPath: No errors detected."); return L_null; } /********************************************************************** LF_BuildPath() This function builds a path by parsing ..s and .s. **********************************************************************/ char* LF_BuildPath(char* szOut, const char* szPath) { char szTemp[MAX_F_PATH]={0}; char szTemp2[MAX_F_PATH]={0}; int nLen=0; int i=0, j=0; //The path we are building needs to start with a '\\' if(szPath[0]=='.' && szPath[1]=='\\') { L_strncpy(szTemp, g_szCurDir, MAX_F_PATH); L_strncat(szTemp, &szPath[1], MAX_F_PATH); } else if(szPath[0]=='\\') { L_strncpy(szTemp, g_szCurDir, MAX_F_PATH); L_strncat(szTemp, szPath, MAX_F_PATH); } else if(szPath[1]==':') { L_strncpy(szTemp, szPath, MAX_F_PATH); } else { szTemp2[0]='\\'; szTemp2[1]=0; L_strncat(szTemp2, szPath, MAX_F_PATH); L_strncpy(szTemp, g_szCurDir, MAX_F_PATH); L_strncat(szTemp, szTemp2, MAX_F_PATH); } //Now process the concatenated path by processing .\s and ..\s. nLen=L_strlen(szTemp); for(i=2; i<nLen; i++) { if(szTemp[i]=='.' && szTemp[i-1]=='\\') { if(szTemp[i+1]=='.') { //.. for(j=i-2; j>=0; j--) { //If we reach the root, we don't go any lower. if(szTemp[j]==':') { szTemp[j+1]=0; break; } if(szTemp[j]=='\\') { L_strncpy(szTemp2, szTemp, j); szTemp2[j]=0; L_strncat(szTemp2, &szTemp[i+2], MAX_F_PATH); L_strncpy(szTemp, szTemp2, MAX_F_PATH); i=j; break; } } } else { //. L_strncpy(szTemp2, szTemp, i); szTemp2[i]=0; L_strncat(szTemp2, &szTemp[i+2], MAX_F_PATH); L_strncpy(szTemp, szTemp2, MAX_F_PATH); } } } L_strncpy(szOut, szTemp, MAX_F_PATH); return szOut; } /***************************************************************** LF_ShowPaths() Calls Err_Printf for all of the files contained within the various archives. This function is currently called when a console command is isued by the user. A search limit string is allowed which will limit the filenames that are displayed to those beginning with the limit. This takes an output function as the second parameter which would be compatible with printf or Err_Printf. ******************************************************************/ L_bool LF_ShowPaths(const char* szLimit, void (*OutputFunc)(const char*, ...)) { SEARCHPATHS* lpPath=L_null; L_bool bLimit=L_false; char szTemp[MAX_F_PATH]; FS_CHECK_EXIT bLimit=L_strlen(szLimit); for(lpPath=g_SearchPaths; lpPath; lpPath=lpPath->m_next) { if(L_strnicmp(lpPath->m_szFilename, g_szCurDir, L_strlen(g_szCurDir))) { L_strncpy(szTemp, &lpPath->m_szFilename[L_strlen(g_szCurDir)+1], MAX_F_PATH); } else L_strncpy(szTemp, lpPath->m_szFilename, MAX_F_PATH); if(L_strnicmp((char*)szLimit, szTemp, L_strlen(szLimit)) || !bLimit) { OutputFunc(" \"%s\", ARCHIVED\n", &szTemp[0]); } } LF_SetError("LF_ShowPaths: No problems detected."); return L_true; } /****************************************************************** LF_Init() Initializes the file system and sets the current directory to the sepecified path. ******************************************************************/ L_bool LF_Init(char* dir, L_dword Flags) { g_bFSInited=L_true; LF_ChangeDir(dir); if(L_CHECK_FLAG(Flags, LFINIT_CHECKARCHIVESFIRST)) g_bArchivesFirst=L_true; else g_bArchivesFirst=L_false; LF_SetError("LF_Init: File System created. Starting in \"%s\".", LF_GetDir(L_null, MAX_F_PATH)); return L_true; } /******************************************************** LF_Shutdown() Shuts down the file system, and deletes the archive index. ********************************************************/ L_bool LF_Shutdown() { FS_CHECK_EXIT LF_CloseAllArchives(); g_bFSInited=L_false; g_szCurDir[0]=0; LF_SetError("LF_Shutdown: No problems detected."); return L_true; } /********************************************************************** LF_AddArchive() This function opens a legacy pak file, and stores the name of all the files that are in it, that way when the File_Open function trys to open a file, it will check to see if it is in a pack first. **********************************************************************/ L_bool LF_AddArchive(L_lpstr szFilename) { HLARCHIVE hArchive=L_null; L_dword dwNumFiles=0; L_dword i=0; SEARCHPATHS* lpNewPath=L_null; char szFullFile[MAX_F_PATH]; FS_CHECK_EXIT hArchive=Arc_Open(szFilename); if(!hArchive) { LF_SetError("Could not add \"%s\" to search path.", szFilename); return L_false; } dwNumFiles=Arc_GetNumFiles(hArchive); for(i=1; i<=dwNumFiles; i++) { //Build the full filename LF_BuildPath(szFullFile, Arc_GetFilename(hArchive, i)); /* Check to see if there is a file already by that name in the search path, if there is we replace it with the new one. */ lpNewPath=LF_GetPath(Arc_GetFilename(hArchive, i)); if(lpNewPath) { L_strncpy(lpNewPath->m_szLibrary, szFilename, MAX_F_PATH); continue; } lpNewPath=malloc(sizeof(SEARCHPATHS)); if(lpNewPath) { L_strncpy(lpNewPath->m_szNameInLibrary, (char*)Arc_GetFilename(hArchive, i), MAX_F_PATH); L_strncpy(lpNewPath->m_szLibrary, szFilename, MAX_F_PATH); L_strncpy(lpNewPath->m_szFilename, szFullFile, MAX_F_PATH); lpNewPath->m_next=g_SearchPaths; g_SearchPaths=lpNewPath; } } Arc_Close(hArchive); LF_SetError("Added \"%s\" to search path.", szFilename); return L_true; } /************************************************************************ LF_CloseAllArchives() Deletes all of the search path information, this should usually be called from LF_Shutdown, but for various reasons could be called from elswhere in the code. ************************************************************************/ L_bool LF_CloseAllArchives() { SEARCHPATHS* lpPath=L_null; SEARCHPATHS* lpTemp=L_null; FS_CHECK_EXIT /* Just delete all the search paths. */ for(lpPath=g_SearchPaths; lpPath; ) { lpTemp=lpPath->m_next; free(lpPath); lpPath=lpTemp; } g_SearchPaths=L_null; LF_SetError("LF_CloseAllArchives: No errors detected."); return L_true; } /******************************************************* LF_ChangeDir() Changes the working directory to the specified one. *******************************************************/ L_bool LF_ChangeDir(const char* dirname) { FS_CHECK_EXIT _chdir(dirname); /* We need to call File_GetDir, to update our directory string. */ LF_GetDir(L_null, 0); LF_SetError("LF_ChangeDir: No errors detected."); return L_true; } /********************************************* LF_GetDir() Returns the current working directory. *********************************************/ char* LF_GetDir(char* buffer, int nMaxLen) { FS_CHECK_EXIT /* Whenever we get the dir we always renew it with _getdcwd, to make sure it is correct. */ if(!nMaxLen) nMaxLen=MAX_F_PATH; _getdcwd(_getdrive(), g_szCurDir, MAX_F_PATH); LF_SetError("LF_GetDir: No errors detected."); if(buffer) { L_strncpy(buffer, g_szCurDir, nMaxLen); return buffer; } else { return g_szCurDir; } } /********************************************** LF_mkdir() Makes a directory, including subdirectory. Makes dir until the last / or \ so if you specifiy a filename for szDir it will create the necessary path to that file, and not some wierd directory. **********************************************/ int LF_MkDir(const char* szDir) { char szFullDir[MAX_F_PATH]; L_dword dwLen=0, i=0; char c=0; char* szTemp; LF_BuildPath(szFullDir, szDir); dwLen=L_strlen(szFullDir); /* We use a cheat here so we can temporarily change the string. */ szTemp=(char*)szFullDir; if(!szFullDir) return L_false; /* The idea here is to go through the string, find each subdirectory, then create a directory till we get to the final folder. */ for(i=0; i<=dwLen; i++) { c=szFullDir[i]; if(c=='\\' || c=='/') { szTemp[i]=0; _mkdir(szFullDir); szTemp[i]=c; } } return L_true; } <file_sep>/games/Legacy-Engine/Source/engine/lg_mem_file.h #ifndef __LG_MEM_FILE_H__ #define __LG_MEM_FILE_H__ #include "lg_types.h" class CLMemFile { private: lg_byte* m_pMem; lg_dword m_nSize; lg_dword m_nPos; public: enum MEM_SEEK_TYPE { MEM_SEEK_CUR=0, MEM_SEEK_BEGIN, MEM_SEEK_END }; public: CLMemFile(lg_dword nSize); ~CLMemFile(); lg_dword Read(lg_void* pOut, const lg_dword nSize); lg_dword Write(const lg_void* const pIn, const lg_dword nSize); lg_dword Tell()const; lg_dword Size()const; void Open(lg_dword nSize); void Resize(lg_dword nSize); void Close(); void Seek(MEM_SEEK_TYPE type, lg_long distance); }; #endif __LG_MEM_FILE_H__<file_sep>/tools/QInstall/Source/Main.c /* Quick and Dirty Application installer Copyright (c) 2003 <NAME> */ #include "directoryex.h" #include <tchar.h> #include <windows.h> #include "resource.h" TCHAR szProgramName[MAX_PATH]; TCHAR szDefaultInstall[MAX_PATH]; TCHAR szInstallFrom[MAX_PATH]; TCHAR szAppToRun[MAX_PATH]; BOOL bRunApp=FALSE; typedef enum tagLINECOMMAND{ LC_NOCOMMAND=0, LC_NAME, LC_INSTALLTO, LC_INSTALLFROM, LC_APPTORUN }LINECOMMAND; #define WM_CONTINUEINSTALL (WM_USER+0x0001) #define PRODUCT_VERSION TEXT("version 0.50") BOOL InstallApp(LPTSTR szSource, LPTSTR szDest, HWND hwnd){ /* First we make see if the dest directory already exists. If it does we prompt if the user wants to copy over it. Then we go ahead and copy the directory. */ if(SetCurrentDirectory(szDest)){ int nMBResult=0; nMBResult=MessageBox( hwnd, TEXT("The specified directory already exists! Overwrite?"), TEXT("Notice"), MB_YESNO|MB_ICONEXCLAMATION); if(nMBResult == IDNO)return FALSE; } SetDlgItemText(hwnd, IDC_COPYINGWORD, TEXT("Copying: Please wait!")); if(SUCCEEDED(CopyDirectory(szSource, szDest, FILE_ATTRIBUTE_NORMAL))){ SetDlgItemText(hwnd, IDC_COPYINGWORD, TEXT("")); return TRUE; }else{ MessageBox( hwnd, TEXT("An error occured while attempting to copy the directory!"), TEXT("Notice"), MB_OK|MB_ICONERROR); return FALSE; } } BOOL ReadLine(LPTSTR szLine, HANDLE hFile){ /*Read until encounter ';', or there is no more file to read. */ int i=0; TCHAR cChar=0; DWORD dwBytesRead=0; BOOL bInQuotes=FALSE; DWORD dwCurrentPosition=0; do{ /* Here we make sure there is enough of the file left to read. If there isn't we return FALSE indicating the reading of the lines is done. */ dwCurrentPosition=SetFilePointer(hFile, 0, 0, FILE_CURRENT); if( dwCurrentPosition > (SetFilePointer(hFile, 0, 0, FILE_END)-sizeof(TCHAR)) ) return FALSE; SetFilePointer(hFile, dwCurrentPosition, 0, FILE_BEGIN); if(!ReadFile(hFile, &cChar, sizeof(TCHAR), &dwBytesRead, NULL)){ /*If can't read line we're probably at the end of the file */ _tcscpy(szLine, TEXT("")); return FALSE; } if((cChar == '"')){ if(bInQuotes)bInQuotes=FALSE; else bInQuotes=TRUE; } if( (cChar != '\n') && (cChar != '\r') && (cChar != '\t')){ if( !((!bInQuotes) && (cChar==' '))){ szLine[i]=cChar; i++; } } }while(cChar != L';'); szLine[i-1]=0; return TRUE; } /* GetString retrieves all data inside quotes in a string. */ BOOL GetString(TCHAR szLineOut[MAX_PATH], TCHAR szLineIn[MAX_PATH]){ TCHAR szFinalLine[MAX_PATH]; DWORD i=0, j=0; BOOL bInQuotes=FALSE; for(i=0, j=0; i<MAX_PATH; i++){ if(szLineIn[i]==0)break; if(szLineIn[i]=='"'){ if(bInQuotes) bInQuotes=FALSE; else bInQuotes=TRUE; continue; } if(bInQuotes){ szFinalLine[j]=szLineIn[i]; j++; } } szFinalLine[j]=0; _tcscpy(szLineOut, szFinalLine); return TRUE; } /* This changes a parsed string, into it's signal string. */ DWORD ConvertParsedString(TCHAR szLineOut[MAX_PATH], TCHAR szLineIn[MAX_PATH]){ /* Here we convert a parse command into a new string! */ TCHAR szFinal[MAX_PATH]; TCHAR szTemp[MAX_PATH]; if(_tcsicmp(szLineIn, TEXT("defaultdrive"))==0){ GetWindowsDirectory(szTemp, MAX_PATH); szFinal[0]=szTemp[0]; szFinal[1]=':'; szFinal[2]=0; }else if(_tcsicmp(szLineIn, TEXT("currentdir"))==0){ GetCurrentDirectory(MAX_PATH, szFinal); }else{ _tcscpy(szFinal, TEXT("")); } if(szFinal[_tcslen(szFinal)-1]==TEXT('\\')){ szFinal[_tcslen(szFinal)-1]=0; } _tcscpy(szLineOut, szFinal); return _tcslen(szLineOut); } /* This changes all parsed strings into their final strings. */ BOOL ParseCommandString(TCHAR szLineOut[MAX_PATH], TCHAR szLineIn[MAX_PATH]){ /* _tcscpy(szLineOut, TEXT("This string was parsed!")); */ /* To parse a string we change everything inside a %xxx% into it's equivilant string. */ DWORD i=0, j=0, k=0; TCHAR szParsedLine[MAX_PATH]; TCHAR szParseCommand[MAX_PATH]; DWORD dwParsedLen=0; for(i=0, j=0, k=0; i<MAX_PATH; i++, j++){ if(szLineIn[i]=='%'){ /* We need to parse */ do{ i++; szParseCommand[k]=szLineIn[i]; k++; }while (szLineIn[i]!='%'); szParseCommand[k-1]=0; /* Here we should parse the line */ dwParsedLen=ConvertParsedString(szParseCommand, szParseCommand); for(k=0; k<dwParsedLen; k++, j++){ szParsedLine[j]=szParseCommand[k]; } i++; } szParsedLine[j]=szLineIn[i]; if(szLineIn[i]==0)break; } szParsedLine[j]=0; _tcscpy(szLineOut, szParsedLine); return TRUE; } LINECOMMAND ProccessLine(TCHAR szLine[MAX_PATH]){ /* To find out what the command is, we read the line until we encounter a '=' or a 0 (zero). */ TCHAR szCommand[MAX_PATH]; DWORD i=0; DWORD nStringOffset; BOOL bString=FALSE; LINECOMMAND nCommand=0; for(i=0; i<MAX_PATH; i++){ if( (szLine[i]=='=') || (szLine[i]==0) ){ if(szLine[i]=='='){ bString=TRUE; nStringOffset=i+1; } szCommand[i]=0; break; } szCommand[i]=szLine[i]; } /* We now have the command, lets procces it */ if(_tcsicmp(szCommand, TEXT("name"))==0)nCommand =LC_NAME; else if(_tcsicmp(szCommand, TEXT("installto"))==0)nCommand = LC_INSTALLTO; else if(_tcsicmp(szCommand, TEXT("installfrom"))==0)nCommand = LC_INSTALLFROM; else if(_tcsicmp(szCommand, TEXT("runonexit"))==0)nCommand = LC_APPTORUN; else return LC_NOCOMMAND; GetString(szLine, szLine); /* We now have the command string. This string may need to be altered if it has a %condition%. */ /* Application name does not need to be parsed */ if(nCommand==LC_NAME)return nCommand; /* Application to run after installation does not need to be parsed */ if(nCommand==LC_APPTORUN)return nCommand; /* Install from needs to be parsed */ if(nCommand==LC_INSTALLFROM){ ParseCommandString(szLine, szLine); return nCommand; } /* Install to needs to be parsed */ if(nCommand==LC_INSTALLTO){ ParseCommandString(szLine, szLine); return nCommand; } return nCommand; } /* GetInfo opens install.ini and get's all install info from it. */ HRESULT GetInfo(){ HANDLE hFile=0; TCHAR szTemp[MAX_PATH]; hFile=CreateFile( TEXT("qinstall.ini"), GENERIC_READ, FILE_SHARE_READ, (LPSECURITY_ATTRIBUTES)NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, (HANDLE)NULL); if(hFile == INVALID_HANDLE_VALUE)return E_FAIL; while(ReadLine(szTemp, hFile)){ switch(ProccessLine(szTemp)) { case LC_NAME: _tcscpy(szProgramName, szTemp); break; case LC_INSTALLTO: _tcscpy(szDefaultInstall, szTemp); break; case LC_INSTALLFROM: _tcscpy(szInstallFrom, szTemp); break; case LC_APPTORUN: _tcscpy(szAppToRun, szTemp); break; default: break; } } CloseHandle(hFile); return S_OK; } /* Dialog procedure for the Finish dialog. */ BOOL CALLBACK FinishQueryProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam){ TCHAR szTemp[MAX_PATH]; switch(msg){ case WM_INITDIALOG: { SetDlgItemText(hwnd, IDC_PNAME2, szProgramName); _tcscpy(szTemp, TEXT("Run: ")); _tcscat(szTemp, szAppToRun); _tcscat(szTemp, TEXT("?")); SetDlgItemText(hwnd, IDC_RUNPROGRAM, szTemp); CheckDlgButton(hwnd, IDC_RUNPROGRAM, BST_CHECKED); return FALSE; } case WM_CLOSE: if(IsDlgButtonChecked(hwnd, IDC_RUNPROGRAM)) bRunApp=TRUE; SendMessage(GetParent(hwnd), WM_CLOSE, 0, 0); break; case WM_COMMAND: { switch(LOWORD(wParam)) { case IDC_CONTINUE: SendMessage(hwnd, WM_CLOSE, 0, 0); break; default: break; } break; } case WM_DESTROY: if(IsDlgButtonChecked(hwnd, IDC_RUNPROGRAM)) bRunApp=TRUE; break; default:return FALSE; } return TRUE; } /* DialogProcedure for the installation dialog. */ BOOL CALLBACK InstallProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam){ switch(msg){ case WM_INITDIALOG: SetDlgItemText(hwnd, IDC_PNAME, szProgramName); SetDlgItemText(hwnd, IDC_INSTALLPATH, szDefaultInstall); SetDlgItemText(hwnd, IDC_INSTALLFROM, szInstallFrom); return FALSE; case WM_CLOSE: SendMessage(GetParent(hwnd), WM_CLOSE, 0, 0); break; case WM_DESTROY: { break; } case WM_COMMAND: { switch(LOWORD(wParam)) { case IDC_QUIT: SendMessage(GetParent(hwnd), WM_CLOSE, 0, 0); break; case IDC_BROWSE:break; case IDC_INSTALL: { /* we first attempt to create the install to directory if we can't we go back to dialog loop */ TCHAR szInstallTo[MAX_PATH]; GetDlgItemText(hwnd, IDC_INSTALLPATH, szInstallTo, MAX_PATH); /*we successfully created directroy, now we need to copy the files */ if(!InstallApp(szInstallFrom, szInstallTo, hwnd)){ /*If we couldn't copy directory... */ break; } SetCurrentDirectory(szInstallTo); _tcscpy(szDefaultInstall, szInstallTo); /*We successfully copied the directoy so continue install.*/ SendMessage(GetParent(hwnd), WM_CONTINUEINSTALL, 0, 0); break; } } } default:return FALSE; } return TRUE; } /* Paints the background window all blue, and addes text to it. */ HRESULT PaintWindow(HWND hwnd){ HDC hDc=0; RECT rClient; PAINTSTRUCT ps; HPEN hp=0, hpt; HBRUSH hb=0, hbt; DWORD dwColor=RGB(0,0,125); LOGBRUSH logbrush; HFONT hfont, hfontt; TCHAR temp[]=TEXT("Quick Dirty Application Installer Copyright (c) 2002, 2003, <NAME>"); TEXTMETRIC tm; GetClientRect(hwnd, &rClient); logbrush.lbColor=dwColor; logbrush.lbHatch=0; logbrush.lbStyle=BS_SOLID; hp=CreatePen(PS_SOLID, 1, dwColor); hb=CreateBrushIndirect(&logbrush); hDc=BeginPaint(hwnd, &ps); hpt=(HPEN)SelectObject(hDc, hp); hbt=(HBRUSH)SelectObject(hDc, hb); Rectangle(hDc, rClient.left, rClient.top, rClient.right, rClient.bottom); DeleteObject(SelectObject(hDc, hpt)); DeleteObject(SelectObject(hDc, hbt)); SetBkColor(hDc, dwColor); SetTextColor(hDc, RGB(255,255,255)); hfont=CreateFont(35,0,0,0,FW_NORMAL, TRUE, FALSE, FALSE, ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, 0, NULL); hfontt=(HFONT)SelectObject(hDc, hfont); TextOut(hDc, 4, 4, szProgramName, _tcslen(szProgramName)); DeleteObject(SelectObject(hDc, hfontt)); GetTextMetrics(hDc, &tm); TextOut(hDc, 0, rClient.bottom-tm.tmHeight*2, temp, _tcslen(temp)); TextOut(hDc, 0, rClient.bottom-tm.tmHeight, PRODUCT_VERSION, _tcslen(PRODUCT_VERSION)); EndPaint(hwnd, &ps); return S_OK; } /* Main Window procedure, manages all other app dialogs and procedures. */ LRESULT CALLBACK MainWnd(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam){ static HWND hwndInstall=NULL; static HWND hwndFinishQuery=NULL; static BOOL bAppInstalled=FALSE; switch (msg){ case WM_CREATE: { RECT wrc, mwrc; int nWndWidth; int nWndHeight; int nWndX,nWndY; hwndInstall=CreateDialog( ((LPCREATESTRUCT)lParam)->hInstance, MAKEINTRESOURCE(IDD_MAINDLG), hwnd, InstallProc); hwndFinishQuery=CreateDialog( ((LPCREATESTRUCT)lParam)->hInstance, MAKEINTRESOURCE(IDD_RUNDIALOG), hwnd, FinishQueryProc); GetWindowRect(hwndInstall, &wrc); GetWindowRect(hwnd, &mwrc); nWndWidth=wrc.right-wrc.left; nWndHeight=wrc.bottom-wrc.top; nWndX=(mwrc.right/2) - (nWndWidth/2)-20; nWndY=(mwrc.bottom/2) - (nWndHeight/2)-20; MoveWindow( hwndInstall, nWndX, nWndY, nWndWidth, nWndHeight, FALSE); ShowWindow(hwndInstall, SW_SHOWNORMAL); UpdateWindow(hwndInstall); break; } case WM_DESTROY: { DestroyWindow(hwndInstall); DestroyWindow(hwndFinishQuery); if(bRunApp && bAppInstalled) PostQuitMessage(1); //1 indicates run app else PostQuitMessage(0); //0 indicates do not run app break; } case WM_CLOSE: { if(bAppInstalled){ SendMessage(hwndInstall, WM_COMMAND, MAKEWORD(IDC_CONTINUE, NULL), 0); } DestroyWindow(hwnd); break; } case WM_CONTINUEINSTALL: { RECT rcWnd; GetWindowRect(hwndInstall, &rcWnd); MoveWindow( hwndFinishQuery, rcWnd.left, rcWnd.top, rcWnd.right-rcWnd.left, rcWnd.bottom-rcWnd.top, FALSE); ShowWindow(hwndInstall, SW_HIDE); ShowWindow(hwndFinishQuery, SW_SHOWNORMAL); UpdateWindow(hwndFinishQuery); /*If we made it here the app is installed */ bAppInstalled=TRUE; break; } case WM_PAINT: { PaintWindow(hwnd); break; } default:return DefWindowProc(hwnd, msg, wParam, lParam); } return 0l; } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd){ WNDCLASS wc; TCHAR szAppName[]=TEXT("Quick and Dirty Application Installer"); MSG msg; HWND hwnd=NULL; /* First thing we do is read the initializer info. */ if(FAILED(GetInfo())){ MessageBox(NULL, TEXT("Failed to load installation file!"), TEXT("Quick Install"), MB_OK|MB_ICONERROR); return 2; } ZeroMemory(&wc, sizeof(wc)); wc.cbClsExtra =0; wc.cbWndExtra=0; wc.hbrBackground=(HBRUSH)GetStockObject(WHITE_BRUSH); wc.hCursor=LoadCursor(NULL, IDC_ARROW); wc.hIcon=LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1)); wc.hInstance=hInstance; wc.lpfnWndProc=MainWnd; wc.lpszClassName=szAppName; wc.lpszMenuName=NULL; wc.style=0; if(!RegisterClass(&wc)){ MessageBox( NULL, TEXT("This program requires Windows NT!"), szAppName, MB_OK|MB_ICONERROR); return 2; } hwnd = CreateWindow( szAppName, szAppName, WS_SYSMENU|WS_MINIMIZEBOX|WS_CAPTION, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), NULL, NULL, hInstance, 0); ShowWindow(hwnd, SW_SHOWNORMAL); UpdateWindow(hwnd); while(GetMessage(&msg, NULL, 0, 0)){ /*if(!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)){ */ TranslateMessage(&msg); DispatchMessage(&msg); /*}*/ } if(msg.wParam==1) { /*Should run selected program here. If run app is selected. */ SetCurrentDirectory(szDefaultInstall); WinExec(szAppToRun, SW_SHOWNORMAL); } return msg.wParam; }<file_sep>/samples/D3DDemo/code/MD3Base/MD3Animation.cpp #define D3D_MD3 #include "functions.h" #include "md3.h" #define PERR_FAIL 0x80000000l #define PERR_NOLINE 0x80000001l #define PERR_ANIMOUTOFRANGE 0x80000002l //////////////////////////////// // Constructor and Destructor // //////////////////////////////// CMD3Animation::CMD3Animation() { m_nHeadOffset[0]=m_nHeadOffset[1]=m_nHeadOffset[2]=0; m_nSex=MD3SEX_DEFAULT; m_nFootStep=MD3FOOTSTEP_DEFAULT; m_lLegOffset=0; ZeroMemory(m_Animations, sizeof(m_Animations)); } CMD3Animation::~CMD3Animation() { } ////////////////////// // Public Functions // ////////////////////// HRESULT CMD3Animation::LoadAnimationA(char szFilename[]) { HANDLE hFile=NULL; hFile=CreateFileA( szFilename, GENERIC_READ, FILE_SHARE_READ, (LPSECURITY_ATTRIBUTES)NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, (HANDLE)NULL); if(hFile==INVALID_HANDLE_VALUE) return E_FAIL; DWORD dwNumLines=GetNumLinesInFile(hFile); ReadAnimations(hFile, dwNumLines); CloseHandle(hFile); //Get the leg animation offset. if(m_Animations[TORSO_GESTURE].lFirstFrame != m_Animations[LEGS_WALKCR].lFirstFrame) { m_lLegOffset=m_Animations[LEGS_WALKCR].lFirstFrame-m_Animations[TORSO_GESTURE].lFirstFrame; } else m_lLegOffset=0; return S_OK; } HRESULT CMD3Animation::LoadAnimationW(WCHAR szFilename[]) { HANDLE hFile=NULL; hFile=CreateFileW( szFilename, GENERIC_READ, FILE_SHARE_READ, (LPSECURITY_ATTRIBUTES)NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, (HANDLE)NULL); if(hFile==INVALID_HANDLE_VALUE) return E_FAIL; DWORD dwNumLines=GetNumLinesInFile(hFile); ReadAnimations(hFile, dwNumLines); CloseHandle(hFile); if(m_Animations[TORSO_GESTURE].lFirstFrame != m_Animations[LEGS_WALKCR].lFirstFrame) { m_lLegOffset=m_Animations[LEGS_WALKCR].lFirstFrame-m_Animations[TORSO_GESTURE].lFirstFrame; } else m_lLegOffset=0; return S_OK; } HRESULT CMD3Animation::GetAnimation(DWORD dwRef, MD3ANIMATION * lpAnimation, DWORD dwFlags) { if(dwRef >= MD3_NUM_ANIMS) return E_FAIL; lpAnimation->lFirstFrame=m_Animations[dwRef].lFirstFrame; lpAnimation->lNumFrames=m_Animations[dwRef].lNumFrames; lpAnimation->lLoopingFrames=m_Animations[dwRef].lLoopingFrames; lpAnimation->lFramesPerSecond=m_Animations[dwRef].lFramesPerSecond; if( (dwRef >= LEGS_WALKCR) && (dwRef <= LEGS_TURN) && ((dwFlags&MD3ANIM_ADJUST)==MD3ANIM_ADJUST) ) { //The animation legs offset should be adjusted. lpAnimation->lFirstFrame -= m_lLegOffset; } return S_OK; } /////////////////////// // Private Functions // /////////////////////// HRESULT CMD3Animation::ReadAnimations(HANDLE hFile, DWORD dwNumLines) { DWORD i=0; HRESULT hr=0; DWORD dwAnimRef=0; char szLine[100]; for(i=0; i<dwNumLines; i++){ hr=ReadLine(hFile, szLine); if(FAILED(hr)) return hr; if(hr!=RLSUC_FINISHED){ ParseLine(NULL, szLine, &dwAnimRef); } } return S_OK; } HRESULT CMD3Animation::ParseLine(LPVOID lpDataOut, LPSTR szLineIn, DWORD * lpAnimRef) { DWORD dwLen=0; DWORD i=0, j=0; char szTemp[100]; char szFinal[100]; strcpy(szFinal, szLineIn); dwLen=strlen(szFinal); //The first thing to do is remove anything found after the double slash. for(i=0; i<dwLen; i++){ if(i < dwLen-1) if(szFinal[i]=='/' && szFinal[i+1]=='/') szFinal[i]=0; } dwLen=strlen(szFinal); if(dwLen==0) return PERR_NOLINE; //Convert all tabs into spaces. for(i=0; i<dwLen; i++){ if(szFinal[i]=='\t') szFinal[i]=' '; } //Determine the type of line by geting the first word. ReadWordFromLine(szTemp, szFinal, 0, &i); //Check if the line is an assignment or a animation. if(_strnicmp(szTemp, "sex", 3)==0){ //It's sex, so read second word to get the sex. ReadWordFromLine(szTemp, szFinal, i, &i); switch(szTemp[0]) { case 'm': m_nSex=MD3SEX_MALE; break; case 'f': m_nSex=MD3SEX_FEMALE; break; default: m_nSex=MD3SEX_OTHER; break; }; return S_OK; }else if(_strnicmp(szTemp, "headoffset", 10)==0){ //It is headoffset so we read three additional words. ReadWordFromLine(szTemp, szFinal, i, &i); m_nHeadOffset[0]=atoi(szTemp); ReadWordFromLine(szTemp, szFinal, i, &i); m_nHeadOffset[1]=atoi(szTemp); ReadWordFromLine(szTemp, szFinal, i, &i); m_nHeadOffset[2]=atoi(szTemp); return S_OK; }else if(_strnicmp(szTemp, "footsteps", 9)==0){ //It is footsteps so we read one more word. ReadWordFromLine(szTemp, szFinal, i, &i); if(_strnicmp(szTemp, "boot", 4)==0){ m_nFootStep=MD3FOOTSTEP_BOOT; }else if(_strnicmp(szTemp, "energy", 6)==0){ m_nFootStep=MD3FOOTSTEP_ENERGY; }else{ m_nFootStep=MD3FOOTSTEP_DEFAULT; } return S_OK; }else{ //We assume it is an animation configuration. if(*lpAnimRef>=MD3_NUM_ANIMS)return PERR_ANIMOUTOFRANGE; //Set the first frame to the current word. m_Animations[*lpAnimRef].lFirstFrame=atoi(szTemp); //Read the additional three words to get the rest of the info. ReadWordFromLine(szTemp, szFinal, i, &i); m_Animations[*lpAnimRef].lNumFrames=atoi(szTemp); ReadWordFromLine(szTemp, szFinal, i, &i); m_Animations[*lpAnimRef].lLoopingFrames=atoi(szTemp); ReadWordFromLine(szTemp, szFinal, i, &i); m_Animations[*lpAnimRef].lFramesPerSecond=atoi(szTemp); (*lpAnimRef)++; return S_OK; } } <file_sep>/games/Legacy-Engine/Source/engine/lg_mgr.h #ifndef __LG_MGR_H__ #define __LG_MGR_H__ #include "lg_mmgr.h" //Mesh & Skel manager. #include "lg_fxmgr.h" //FX Manager. #include "lg_tmgr.h" //Texture manager. #include "lg_mtr_mgr.h" //Material manager. #include "lg_skin_mgr.h" //Skin manager. class CLMgrs { protected: CLMMgr* m_pMMgr; //Mesh & skeleton manager. CLFxMgr* m_pFxMgr; //FX Manger. CLTMgr* m_pTexMgr; //Texture manager. CLMtrMgr* m_pMtrMgr; //Material manager. CLSkinMgr* m_pSkinMgr;//Skin Manager. protected: CLMgrs(); ~CLMgrs(); lg_void InitMgrs(IDirect3DDevice9* pDevice); lg_void ShutdownMgrs(); lg_void ValidateMgrs(); lg_void InvalidateMgrs(); }; #endif __LG_MGR_H__<file_sep>/tools/PodSyncPrep/src/podsyncp/resources/PodSyncPAboutBox.properties title = About: ${Application.title} ${Application.version} closeAboutBox.Action.text = &Close appDescLabel.text=Prepares mp3 files for synchronization with music player. versionLabel.text=Product Version\: vendorLabel.text=Vendor\: homepageLabel.text=Homepage\: <file_sep>/games/Legacy-Engine/Source/common/lg_string.h #ifndef __LG_STRING_H__ #define __LG_STRING_H__ #include "lg_types.h" #ifdef __cplusplus extern "C"{ #endif __cplusplus lg_int LG_StrNcCmpA(const lg_char* s1, const lg_char* s2, lg_long n); lg_int LG_StrNcCmpW(const lg_wchar* s1, const lg_wchar* s2, lg_long n); lg_dword LG_StrLenA(const lg_char* s); lg_dword LG_StrLenW(const lg_wchar* s); lg_char* LG_StrCopySafeA(lg_char* dest, const lg_char* src, lg_dword destsize); lg_wchar* LG_StrCopySafeW(lg_wchar* dest, const lg_wchar* src, lg_dword destsize); #ifdef __cplusplus } #endif __cplusplus #ifdef UNICODE #define LG_StrNcCmp LG_StrNcCmpW #define LG_StrLen LG_StrLenW #else !UNICODE #define LG_StrNcCmp LG_StrNcCmpA #define LG_StrLen LG_StrLenA #endif UNICODE #endif __LG_STRING_H__<file_sep>/games/Legacy-Engine/Source/3rdParty/ML_lib/ML_types.h #ifndef __ML_TYPES_H__ #define __ML_TYPES_H__ #ifdef ML_LIB_BYTEPACK #include <pshpack1.h> #endif ML_LIB_BYTEPACK /* Some types that we will use.*/ typedef unsigned char ml_byte; typedef signed char ml_sbyte; typedef unsigned short ml_word; typedef signed short ml_short; typedef unsigned long ml_dword; typedef signed long ml_long; typedef int ml_bool; typedef unsigned int ml_uint; typedef signed int ml_int; typedef void ml_void; typedef float ml_float; /* A few definitions. */ #define ML_TRUE (1) #define ML_FALSE (0) #define ML_Max(v1, v2) ((v1)>(v2))?(v1):(v2) #define ML_Min(v1, v2) ((v1)<(v2))?(v1):(v2) #define ML_Clamp(v1, min, max) ( (v1)>(max)?(max):(v1)<(min)?(min):(v1) ) #define ML_FUNC __cdecl /**************************************** Some constants for the math library. ****************************************/ #define ML_PI ((ml_float)3.141592654f) #define ML_2PI ((ml_float)3.141592654f*2.0f) #define ML_HALFPI ((ml_float)3.141592654f*0.5f) /************************************* Structures for the math functions. *************************************/ typedef struct _ML_MATRIX{ ml_float _11, _12, _13, _14; ml_float _21, _22, _23, _24; ml_float _31, _32, _33, _34; ml_float _41, _42, _43, _44; }ML_MATRIX, ML_MAT, ml_mat; typedef struct _ML_QUATERNION{ ml_float x, y, z, w; }ML_QUATERNION, ML_QUAT, ml_quat; typedef struct _ML_VECTOR2{ ml_float x, y; }ML_VECTOR2, ML_VEC2, ml_vec2; typedef struct _ML_VECTOR3{ ml_float x, y, z; }ML_VECTOR3, ML_VEC3, ml_vec3; typedef struct _ML_VECTOR4{ ml_float x, y, z, w; }LML_VECTOR4, ML_VEC4, ml_vec4; typedef struct _ML_PLANE{ ml_float a, b, c, d; }ML_PLANE, ml_plane; typedef struct _ML_AABB{ ML_VEC3 v3Min; ML_VEC3 v3Max; }ML_AABB, ml_aabb; #ifdef ML_LIB_BYTEPACK #include <poppack.h> #endif ML_LIB_BYTEPACK #endif __ML_TYPES_H__<file_sep>/games/Legacy-Engine/Source/lm_sys/lm_mesh_tree.h /* CLMeshTree - The mesh tree class. In the game an objects appearance may contain one or more meshes which are combined together in a tree, the hiearchy described in an XML file. Each mesh is required to have a base mesh (and only one base mesh) with all other meshes attached to the base mesh. There are limits on how many meshes a Mesh Tree can contain. Also Meshes can be changed on the fly (as in the case of switching weapons, etc.). This class is exclusively for the Legacy game, and not any other utilities or plugins. Note that when multiple instances of a mesh or skel are used they will refer to the same data (which was aquired from their respective resource managers), but each in game object should have it's own instance of a CLMeshTree class (that way they can be animated independantly). Copyright (c) 2008 <NAME> */ #ifndef __MESH_TREE_H__ #define __MESH_TREE_H__ #include "lm_mesh_lg.h" #include "lm_skel_lg.h" class CLMeshTree: public CLMBase { //Constants & flags: public: //Maximum number of nodes that can make up //a mesh tree: static const lg_dword MT_MAX_MESH_NODES=10; //Maximum number of skeletons to be used //by a tree (applies to all nodes). static const lg_dword MT_MAX_SKELS=10; private: /* The LM_FLAG_RASTER_READY indicates that the mesh is ready to be rendered (that is since Update was called, all the transformations have been carried out, if this flag isn't set and we want to render, then it is necessary to call DoTransform for each of the vertexes. */ static const lg_dword LM_FLAG_RASTER_READY=0x00010000; //Internally used structures: private: class MeshNode { friend class CLMeshTree; private: CLMeshLG* m_pMesh; //The mesh assiated with the node. CLSkin* m_pSkin; //The skin associated with this node's mesh. CLSkelLG* m_pDefSkel; //The default skel associated with the mesh. //Data that changes as the animation changes: //Current animation: CLSkelLG* m_pSkel; //Skel for the current animation. lg_dword m_nAnim; //Animation within skel for the current animation. lg_float m_fAnimProgress; //The time of the current animation (0.0f to 100.0f). lg_float m_fAnimSpeed; //Number of seconds to cycle through the animation. lg_float m_fElapsed; //Amount of time elapsed since an update (in seconds). //lg_long m_nTime; //Time store for animation purposes. //lg_dword m_nLastUpdate; //Time that the animation was last updated. //Transitioning animation: CLSkelLG* m_pPrevSkel; //The previous skel animation. lg_dword m_nPrevAnim; //The previous anim within the prev skel. lg_float m_fPrevAnimProgress; //Previous progress. lg_float m_fPostTransSpeed; //The speed of the animation after transitions occur. //Que for transitiong animations: //If we switch animations while transitioning, //we have to wait for the transition to complete //before transitioning again, so we store the //animation we are waiting to transition to, //in the following variable. CLSkelLG* m_pNextSkel; lg_dword m_nNextAnim; //Tree structures: lg_dword m_nNumChildren; MeshNode* m_pChildren[MT_MAX_MESH_NODES]; //Children of this node. lg_dword m_nParentJoint; //The reference to the joint of wich this node is attached. public: MeshNode(); ~MeshNode(); /* PRE: N/A. POST: Set's up the node with the default information specified. Set's animation information to default. */ lg_void Load(CLMeshLG* pMesh, CLSkin* pSkin, CLSkelLG* pSkel); /* PRE: N/A POST: Clears all information from the node. */ lg_void Clear(); /* PRE: N/A POST: Renders the node, and all children nodes in the heierarchy. */ lg_void Render(ml_mat* pMatWorldTrans); /* PRE: pChild should be a valid Node. Should only be called by CLMeshTree::Load. POST: The child is added to heirarchy. */ lg_void AddChild(MeshNode* pChild, lg_str szJoint); }; //Private data: private: //The nodes associated with the mesh, //note that m_MeshNodes[0] is always //the root node. MeshNode m_MeshNodes[MT_MAX_MESH_NODES]; lg_dword m_nNumNodes; //The skeletons that can be used by the //mesh nodes (these are used by all nodes, //not just the root node). CLSkelLG* m_pSkels[MT_MAX_SKELS]; lg_dword m_nNumSkels; //Base transform, this transform is always applied: ml_mat m_matBaseTrans; //User methods: public: CLMeshTree(); ~CLMeshTree(); /* PRE: N/A POST: Loads the tree as described in the XML files, returns LG_TRUE if it succeeded. */ lg_bool Load(lg_path szFile); /* PRE: pSrcTree must be a loaded mesh node. POST: Creates a mesh tree that is a duplicate of the source tree (it has the same meshes, skeletons, and skins, this is much faster than Load because it doesn't have to access the disk, or allocate memory. Note that some settings are set to default, and not the info from the source tree. Returns LG_TRUE if it succeeded. */ lg_bool Duplicate(CLMeshTree* pSrcTree); /* PRE: N/A POST: If a mesh tree was loaded, it will be unlaoded. */ lg_void Unload(); /* PRE: Mesh tree should be loaded. POST: Rasterizes the mesh based on the matrix passed. */ lg_void Render(ml_mat* pMatWorldTrans); /* PRE: Mesh tree should be loaded. fDeltaTime>0 fDeltaTimeSec represents the number of seconds that have passed since the last call to Update. POST: Generates the transform matricies for all of the meshes, based on how much time has passed. Does not carry out the transform, because if we don't need to render the tree there is no point in carrying out the transform as that would be a waste of time. Technically we don't need to call Update unless we are actually rendereing, but fDeltaTimeSec should be the amount of time elapsed since the last call to Update. */ lg_void Update(lg_float fDeltaTimeSec); /* PRE: The mesh tree should be loaded. nNode: specifies which node we want to set the animation for, only this node will be effected 0 based. nSkel: specifies which skel we want to use for the anim, 0 based. nAnim: specifies the animation within the skeleton that we want to use, 0 based. fSpeed: specifies the number of seconds that it takes to complete one cycle of the animation. fTransitionTime: specifies the number of seconds that it takes to transition from the current animation to the animation specified. 0.0f will make the transition immediate. POST: Subsequent calls to Update will use the new information to update the node specified. NOTES: Note that if SetAnimation is called on a MeshTree that is transitioning, then the transition isn't going to look verry smooth, because we don't store an entire buffer of transitions. It is best to just try to wait til a transition is complete til changing an animation. It might be a good idea to create another variable to set the next animation, that way if we are in a transition we can go to the next animation afterwards, or go right into it if we aren't. */ lg_void SetAnimation(lg_dword nNode, lg_dword nSkel, lg_dword nAnim, lg_float fSpeed, lg_float fTransitionTime); /* PRE: nFlags must have been prepared using the LWAI_SetAnim macro. POST: See above, and see lw_ai_sdk.h */ lg_void SetAnimation(lg_dword nFlags); /* PRE: nChild, should be a reference to on the the base nod's children. Should be called after Update. Also note that if the base node doesn't have children, we'll run into problems. POST: pOut is filled in with the joint transform for the specified node. */ lg_void GetAttachTransform(ml_mat* pOut, lg_dword nChild); private: /* PRE: N/A POST: N/A NOTES: Note used, but has to be overriden. */ lg_bool Serialize(lg_void* file, ReadWriteFn read_or_write, RW_MODE mode); }; #endif __MESH_TREE_H__<file_sep>/games/Legacy-Engine/Scrapped/old/ls_init.h /* ls_init.h - Header for audio initialization. */ #ifndef __LS_INIT_H__ #define __LS_INIT_H__ //#include "lg_sys.h" #ifdef __cplusplus extern "C"{ #endif /* __cplusplus */ L_result LS_Init(L3DGame* lpGame); L_result LS_Shutdown(L3DGame* lpGame); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __LS_INIT_H__ */<file_sep>/games/Legacy-Engine/Source/engine/lvf_sys.cpp #include <string.h> #include "lvf_sys.h" #include "lg_err.h" #include "common.h" #include "lg_func.h" #include <stdio.h> CLVFont::CLVFont() { } CLVFont::~CLVFont() { } lg_bool CLVFont::Load(lf_path szXMLFile) { #if 0 //Temp thing to create output LF_FILE3 fout=LF_Open("/dbase/font/font.xml", LF_ACCESS_WRITE, LF_CREATE_ALWAYS); char szLine[128]; LG_strncpy(szLine, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n", 127); LF_Write(fout, szLine, L_strlen(szLine)); LG_strncpy(szLine, "<lfont file=\"lfontsm.tga\">\r\n", 127); LF_Write(fout, szLine, L_strlen(szLine)); lg_dword x=0, y=0; for(lg_dword i=0; i<96; i++) { sprintf(szLine, "\t<c%d>%d %d %d %d</c%d> <!-- '%c' -->\r\n", i+32, x, y, 8, 15, i+32, i+32); LF_Write(fout, szLine, L_strlen(szLine)); x+=8; if(x>120) { x=0; y+=15; } } LG_strncpy(szLine, "</lfont>\r\n", 127); LF_Write(fout, szLine, L_strlen(szLine)); LF_Close(fout); #endif Err_Printf("Loading \"%s\" font...", szXMLFile); LF_FILE3 fileXML=LF_Open(szXMLFile, LF_ACCESS_READ|LF_ACCESS_MEMORY, LF_OPEN_EXISTING); if(!fileXML) { Err_Printf(" ERROR: Could not open XML file."); return LG_FALSE; } XML_Parser xmlParser=XML_ParserCreate_LG(LG_NULL); if(!xmlParser) { Err_Printf(" ERROR: Could not create XML parser."); LF_Close(fileXML); return LG_FALSE; } XML_SetCharacterDataHandler(xmlParser, xml_font_data_data); XML_SetElementHandler(xmlParser, xml_font_data_start, xml_font_data_end); XML_FIND_DATA sFindData; sFindData.bInChar=LG_FALSE; sFindData.c=0; sFindData.pCharData=m_CharData; sFindData.szFontFile[0]=0; memset(m_CharData, 0, sizeof(m_CharData)); XML_SetUserData(xmlParser, &sFindData); if(!XML_Parse(xmlParser, (const char*)LF_GetMemPointer(fileXML), LF_GetSize(fileXML), LG_TRUE)) { Err_Printf(" ERROR: Parse error at line %d: \"%s\"", XML_GetCurrentLineNumber(xmlParser), XML_ErrorString(XML_GetErrorCode(xmlParser))); XML_ParserFree(xmlParser); LF_Close(fileXML); return LG_FALSE; } XML_ParserFree(xmlParser); LF_Close(fileXML); if(sFindData.szFontFile[0]==0) { Err_Printf(" ERROR: Could not find font file."); return LG_FALSE; } //We now have information about all the characters... //Adjust the font to the same path as the tga file lf_path szTemp; LF_GetDirFromPath(szTemp, szXMLFile); L_strncat(szTemp, sFindData.szFontFile, LF_MAX_PATH); LG_strncpy(sFindData.szFontFile, szTemp, LF_MAX_PATH); for(lg_byte i=0; i<96; i++) { Err_Printf("x: %u y: %u w: %u h:%u", m_CharData[i].x, m_CharData[i].y, m_CharData[i].w, m_CharData[i].h); } Err_Printf("The font file is: %s", sFindData.szFontFile); return LG_TRUE; } void CLVFont::xml_font_data_start(void* userData, const XML_Char* name, const XML_Char** atrs) { XML_FIND_DATA* pFindData=(XML_FIND_DATA*)userData; const XML_Char* szFilename=LG_NULL; for(lg_dword i=0; atrs[i]; i+=2) { if(strcmp(atrs[i], "file")==0) szFilename=atrs[i+1]; } if(name[0]=='c') { lg_char c=(lg_char)L_atol((char*)&name[1]); pFindData->bInChar=LG_TRUE; pFindData->c=c; } if(stricmp(name, "lfont")==0) { if(!szFilename) { Err_Printf(" ERROR: lfont declared but no file specified"); return; } strncpy(pFindData->szFontFile, szFilename, LF_MAX_PATH); return; } } void CLVFont::xml_font_data_end(void* userData, const XML_Char* name) { XML_FIND_DATA* pFindData=(XML_FIND_DATA*)userData; if(name[0]=='c') pFindData->bInChar=LG_FALSE; } void CLVFont::xml_font_data_data(void* userData, const XML_Char*s, int len) { XML_FIND_DATA* pFindData=(XML_FIND_DATA*)userData; if(!pFindData->bInChar || !pFindData->szFontFile[0]) return; lg_char c=pFindData->c-32; if(c>=96) return; //Parse the data: lg_char szTemp[64]; LG_strncpy(szTemp, s, LG_Min(63, len+1)); pFindData->pCharData[c].x=(lg_word)L_atol(L_strtokA(szTemp, " \t", 0)); pFindData->pCharData[c].y=(lg_word)L_atol(L_strtokA(0, 0, 0)); pFindData->pCharData[c].w=(lg_word)L_atol(L_strtokA(0, 0, 0)); pFindData->pCharData[c].h=(lg_word)L_atol(L_strtokA(0, 0, 0)); pFindData->pCharData[c].c=pFindData->c; } <file_sep>/tools/CornerBin/CornerBin/CBTrayIcon.h #pragma once #include "CBSettings.h" class CCBTrayIcon { public: CCBTrayIcon(void); ~CCBTrayIcon(void); BOOL Init(HINSTANCE hInst, HWND hwndParent, CCBSettings* pSettings); private: enum ICON_TYPE { ICON_FILE, ICON_INDLL }; static const DWORD s_nUEID; static const GUID s_GUID; static const DWORD s_nVERSION = NOTIFYICON_VERSION; HICON m_IcoFull; HICON m_IcoEmpty; CCBSettings* m_pSettings; public: void Update(void); private: // Tracks if there are currently items in the RB BOOL m_bIsFull; public: static BOOL IsRBFull(void); public: HICON LoadIcon2(LPCTSTR strIcon); void LoadIcons(void); void UnInit(void); private: HWND m_hwndParent; }; <file_sep>/Misc/Guiness/Readme.txt Guin by <NAME> This folder includes: Guin.bas - Guin source code. Guin.exe - Guin executable. Readme.txt - This file. Note: This program will solve a 3 x 3 Magic Square using probably on of the worst methods possible: randomly picking numbers.<file_sep>/Misc/BRSaveTool/BRSaveTool.cpp // (c) 2019 <NAME> #include <stdio.h> #include <conio.h> #include <vector> #include <string> #include <iostream> #include <Windows.h> typedef unsigned char bm_byte; typedef wchar_t bm_char; typedef std::wstring bm_string; typedef std::vector<bm_byte> bm_bin_data; #define countof( _a_ ) (sizeof(_a_)/sizeof(0[_a_])) static bm_string BRSaveTool_GetDir() { bm_char DirBuffer[_MAX_PATH]; GetCurrentDirectoryW( countof(DirBuffer) , DirBuffer ); return DirBuffer; } static void BRSaveTool_ReadFile( const bm_string Filename , bm_bin_data& DataOut ) { std::wcout << L"Reading " << Filename << std::endl; HANDLE File = CreateFileW( Filename.c_str() ,GENERIC_READ , FILE_SHARE_READ , NULL , OPEN_EXISTING , 0 , NULL ); const DWORD FileSize = GetFileSize( File , NULL ); if( INVALID_HANDLE_VALUE != File ) { // std::wcout << L"The size is " << FileSize << " bytes " << std::endl; DataOut.resize( FileSize , 0 ); if( DataOut.size() == FileSize ) { DWORD BytesRead = 0; ReadFile( File , DataOut.data() , DataOut.size() , &BytesRead , NULL ); if( BytesRead == DataOut.size() ) { // std::wcout << L"Read all the data." << std::endl; } else { std::wcout << L"Did not read all the data." << std::endl; DataOut.clear(); } } else { std::wcout << L"Could not allocate memory." << std::endl; DataOut.clear(); } CloseHandle( File ); } else { std::wcout << L"Could not open the file." << std::endl; } } int wmain( int argc , wchar_t* argv[] ) { const std::vector<bm_string> AllFiles { L"3HHHH.SAV", L"3HRRR.SAV", L"H3HHR.SAV", L"H3HRH.SAV", L"H3HRH-2.SAV", L"HH3RR.SAV", L"HH3RR-2.SAV", L"R3HRR.SAV", L"R3RHH.SAV", L"RH3RR.SAV", }; const bm_string SavesDir = BRSaveTool_GetDir() + L"\\SAVES\\"; std::wcout << L"Working in: " << SavesDir << std::endl; std::vector<bm_bin_data> AllFileDatas; AllFileDatas.resize( AllFiles.size() ); if( AllFiles.size() == AllFileDatas.size() ) { for( DWORD i=0; i<AllFiles.size(); i++ ) { BRSaveTool_ReadFile( SavesDir + AllFiles[i] , AllFileDatas[i] ); } } const DWORD FileSize = [&AllFileDatas]() -> DWORD { const DWORD ExpectedSize = AllFileDatas.size() > 0 ? AllFileDatas[0].size() : -1; for( const bm_bin_data& File : AllFileDatas ) { if( File.size() != ExpectedSize ) { return 0; } } return ExpectedSize; }(); // We want to find any case where the two same ones are the same, but every other file is different. const DWORD Same1Idx = 3; const DWORD Same2Idx = 4; std::vector<DWORD> AnomolyIndexes; for( DWORD ByteIdx=0; ByteIdx<FileSize; ByteIdx++ ) { if( AllFileDatas[Same1Idx][ByteIdx] == AllFileDatas[Same2Idx][ByteIdx] ) { const bm_byte SameByte = AllFileDatas[Same1Idx][ByteIdx]; bool bAllDifferent = true; for( DWORD FileDataIdx=0; FileDataIdx<AllFileDatas.size(); FileDataIdx++ ) { // Skip the two datas that we know are the same. if( FileDataIdx == Same1Idx || FileDataIdx == Same2Idx ) { continue; } // Now check and if every other byte is different, log this one. const bm_byte Byte = AllFileDatas[FileDataIdx][ByteIdx]; if( Byte == SameByte ) { bAllDifferent = false; } } if( bAllDifferent ) { AnomolyIndexes.push_back( ByteIdx ); } } } wprintf( L"Found %d anomolies.\n" , AnomolyIndexes.size() ); for( const DWORD& Anom : AnomolyIndexes ) { wprintf( L"Anomoly found at %d\n" , Anom ); for( DWORD FileDataIdx=0; FileDataIdx<AllFileDatas.size(); FileDataIdx++ ) { wprintf( L"\tData %d: %02X (%s)\n" , FileDataIdx , AllFileDatas[FileDataIdx][Anom] , AllFiles[FileDataIdx].c_str() ); } } /* BRSaveTool_ReadFile( SavesDir + L"H3HRH.SAV" , Same1 ); BRSaveTool_ReadFile( SavesDir + L"H3HRH-2.SAV" , Same2 ); BRSaveTool_ReadFile( SavesDir + L"3HHHH.SAV" , Compare1 ); BRSaveTool_ReadFile( SavesDir + L"RH3RR.SAV" , Compare2 ); if( Same1.size() == Same2.size() && Same2.size() == Compare1.size() && Compare1.size() == Compare2.size() ) { const DWORD FileSize = Same1.size(); std::wcout << L"Analyzing " << FileSize << L" bytes across 4 files." << std::endl; // We just want to find any bytes where 2 and 3 are the same but 1 is different. DWORD NumFound = 0; for( DWORD i=0; i<FileSize; i++ ) { if( Same1[i] == Same2[i] && Compare1[i] != Same1[i] && Compare2[i] != Same2[i] ) { NumFound++; wprintf( L"Anomoly %04d: %06d S:%02X , 1:%02X , 2:%02X \n" , NumFound , i , Same1[i] , Compare1[i] , Compare2[i] ); } } } */ std::wcout << L"Press any key to continue." << std::endl; _getch(); return 0; }<file_sep>/tools/img_lib/TexView3/TexView3Doc.h // TexView3Doc.h : interface of the CTexView3Doc class // #pragma once #include "afxwin.h" class CTexView3Doc : public CDocument { protected: // create from serialization only CTexView3Doc(); DECLARE_DYNCREATE(CTexView3Doc) // Attributes public: static const DWORD BC_IMAGE=0x00000010; static const DWORD BC_ACHANNEL=0x00000020; static const DWORD BC_USEAPPBG=0x00000040; static const COLORREF BG_COLOR=RGB(128, 128, 128); private: typedef struct _ARGBVALUE{ BYTE b, g, r, a; }ARGBVALUE; // Operations public: // Overrides public: virtual BOOL OnNewDocument(); virtual void Serialize(CArchive& ar); // Implementation public: virtual ~CTexView3Doc(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // Generated message map functions protected: DECLARE_MESSAGE_MAP() private: HIMG m_pImg; private: //CBitmap m_bmImg; public: BOOL CreateCBitmap(CBitmap* pBM, DWORD* cx, DWORD* cy, IMGFILTER filter, DWORD Flags); private: //DWORD m_nWidth; private: //DWORD m_nHeight; public: //BOOL DrawBitmap(int x, int y, CDC* pdc); public: //void GetImageSize(int* px, int* py); private: //int m_nAlphaMode; public: //DWORD GetAlphaMode(void); }; <file_sep>/games/Legacy-Engine/Source/engine/lx_object.cpp #include "lx_sys.h" #include "lg_malloc.h" #include "lg_xml.h" #include "lg_err.h" #include "lg_stack.h" #include "lp_sys2.h" #include <memory.h> #include <string.h> typedef enum _LX_OBJ_MODE{ OBJ_MODE_NONE=0, OBJ_MODE_OBJECT, OBJ_MODE_MODEL, OBJ_MODE_SKELS, OBJ_MODE_SKEL, OBJ_MODE_AI, OBJ_MODE_PHYS, OBJ_MODE_MODES, OBJ_MODE_MODE }LX_OBJ_MODE; typedef struct _lx_obj_data{ lx_object* pObject; CLStack<LX_OBJ_MODE> stkMode; }lx_obj_data; void LX_ObjectStart(void* userData, const XML_Char* name, const XML_Char** atts); void LX_ObjectEnd(void* userData, const XML_Char* name); void LX_ObjectCharData(void* userData, const XML_Char*s, int len); lx_object* LX_LoadObject(const lf_path szXMLFile) { //First thing we need to do is open the file, //if the file is not available, then the object //cannot be loaded and null is returned. LF_FILE3 fileScript=LF_Open(szXMLFile, LF_ACCESS_READ|LF_ACCESS_MEMORY, LF_OPEN_EXISTING); if(!fileScript) { Err_Printf("LX_LoadObject ERROR: Could not open \"%s\" for parsing.", szXMLFile); return LG_NULL; } //We need a new instance of lx_object, to be filled as the //xml file is parsed. lx_object* pNew = (lx_object*)LG_Malloc(sizeof(lx_object)); memset(pNew, 0, sizeof(lx_object)); XML_Parser parser = XML_ParserCreate_LG(LG_NULL); if(!parser) { Err_Printf("LX_LoadObject ERROR: Could not create XML parser. (%s)", szXMLFile); LF_Close(fileScript); return LG_NULL; } //TODO: Parsing Goes Here lx_obj_data data; data.stkMode.Push(OBJ_MODE_NONE); data.pObject=pNew; XML_ParserReset(parser, LG_NULL); XML_SetUserData(parser, &data); XML_SetElementHandler(parser, LX_ObjectStart, LX_ObjectEnd); XML_SetCharacterDataHandler(parser, LX_ObjectCharData); //Do the parsing if(!XML_Parse(parser, (const char*)LF_GetMemPointer(fileScript), LF_GetSize(fileScript), LG_TRUE)) { Err_Printf("LX_LoadObject ERROR: Parse error at line %d: \"%s\"", XML_GetCurrentLineNumber(parser), XML_ErrorString(XML_GetErrorCode(parser))); LX_DestroyObject(pNew); LF_Close(fileScript); return LG_NULL; } //Destroy the parser, and close the file, then return the data. XML_ParserFree(parser); LF_Close(fileScript); #if 0 Err_Printf("Model File: %s", pNew->szModelFile); Err_Printf("AI Function: %s", pNew->szAiFunction); Err_Printf("Mass: %f", pNew->fMass); Err_Printf("Scale: %f", pNew->fScale); Err_Printf("PHYS Flags: 0x%08X", pNew->nPhysFlags); Err_Printf("Center: %f, %f, %f", pNew->fXC, pNew->fYC, pNew->fZC); Err_Printf("Mode Count: %d", pNew->nModeCount); for(lg_dword i=0; i<pNew->nModeCount; i++) { Err_Printf("Mode %i: %s", i+1, pNew->pModes[i].szName); } Err_Printf("Skel Count: %d", pNew->nNumSkels); for(lg_dword i=0; i<pNew->nNumSkels; i++) { Err_Printf("Skel %i: File: %s Mesh: %s", i+1, pNew->pSkelFiles[i], pNew->pSkelMeshes[i]); } #endif return pNew; } lg_void LX_DestroyObject(lx_object* pObject) { if(!pObject) return; if(pObject->pSkelFiles) LG_Free(pObject->pSkelFiles); if(pObject->pSkelMeshes) LG_Free(pObject->pSkelMeshes); if(pObject->pModes) LG_Free(pObject->pModes); if(pObject) LG_Free(pObject); } LX_OBJ_MODE LX_ObjectNameToMode(const XML_Char* name) { LX_OBJ_MODE nMode=OBJ_MODE_NONE; if(stricmp(name, "object")==0) nMode=OBJ_MODE_OBJECT; else if(stricmp(name, "model")==0) nMode=OBJ_MODE_MODEL; else if(stricmp(name, "ai")==0) nMode=OBJ_MODE_AI; else if(stricmp(name, "skels")==0) nMode=OBJ_MODE_SKELS; else if(stricmp(name, "skel")==0) nMode=OBJ_MODE_SKEL; else if(stricmp(name, "phys")==0) nMode=OBJ_MODE_PHYS; else if(stricmp(name, "modes")==0) nMode=OBJ_MODE_MODES; else if(stricmp(name, "mode")==0) nMode=OBJ_MODE_MODE; return nMode; } void LX_ObjectStart(void* userData, const XML_Char* name, const XML_Char** atts) { lx_obj_data* pData = (lx_obj_data*)userData; LX_OBJ_MODE nMode=LX_ObjectNameToMode(name); //We'll always push the mode onto the stack even it was invalid //that way when the values get popped off the stack they //will always match. pData->stkMode.Push(nMode); //Convert the tage to an integer value, if the value is //OBJ_MODE_NONE then it was an invalid tage and there //is nothing to do. if(nMode==OBJ_MODE_NONE) { Err_Printf("LX_Object Parse ERROR: Invalid object tag (%s).", name); return; } if(nMode==OBJ_MODE_MODEL) { for(lg_dword i=0; atts[i]; i+=2) { if(stricmp(atts[i], "file")==0) { strncpy(pData->pObject->szModelFile, atts[i+1], LF_MAX_PATH); pData->pObject->szModelFile[LF_MAX_PATH]=0; } } } else if(nMode==OBJ_MODE_SKELS) { for(lg_dword i=0; atts[i]; i+=2) { if(stricmp(atts[i], "count")==0) { pData->pObject->nNumSkels=atoi(atts[i+1]); } } if(pData->pObject->nNumSkels>0) { pData->pObject->pSkelFiles = (lf_path*)LG_Malloc(sizeof(lf_path)*pData->pObject->nNumSkels); pData->pObject->pSkelMeshes = (lx_name*)LG_Malloc(sizeof(lx_name)*pData->pObject->nNumSkels); } } else if(nMode==OBJ_MODE_SKEL) { lg_dword nID=0; lg_char* szFile=LG_NULL; lg_char* szMesh=LG_NULL; for(lg_dword i=0; atts[i]; i+=2) { if(stricmp(atts[i], "id")==0) nID=atoi(atts[i+1]); else if(stricmp(atts[i], "file")==0) szFile=(lg_char*)atts[i+1]; else if(stricmp(atts[i], "mesh")==0) szMesh=(lg_char*)atts[i+1]; } if(nID>0 && nID<=pData->pObject->nNumSkels) { strncpy(pData->pObject->pSkelFiles[nID-1], szFile, LF_MAX_PATH); pData->pObject->pSkelFiles[nID-1][LF_MAX_PATH]=0; strncpy(pData->pObject->pSkelMeshes[nID-1], szMesh, LF_MAX_PATH); pData->pObject->pSkelMeshes[nID-1][LF_MAX_PATH]=0; } } else if(nMode==OBJ_MODE_AI) { for(lg_dword i=0; atts[i]; i+=2) { if(stricmp(atts[i], "function")==0) { strncpy(pData->pObject->szAiFunction, atts[i+1], LF_MAX_PATH); pData->pObject->szAiFunction[LF_MAX_PATH]=0; } } } else if(nMode==OBJ_MODE_PHYS) { LX_START_ATTR LX_ATTR_FLOAT(pData->pObject->fHeight, height) LX_ATTR_FLOAT(pData->pObject->fRadius, radius) LX_ATTR_FLOAT3(pData->pObject->fShapeOffset, shape_offset) LX_ATTR_FLOAT3(pData->pObject->fMassCenter, mass_center) LX_ATTR_FLOAT(pData->pObject->fMass, mass) //LX_ATTR_FLOAT(pData->pObject->fScale, scale) LX_MISC_ATTR(shape) if(stricmp(atts[i+1], "capsule")==0) pData->pObject->nShape=PHYS_SHAPE_CAPSULE;//pData->pObject->nPhysFlags|=LX_OBJ_PHYS_SHAPE_CAPSULE; else if(stricmp(atts[i+1], "box")==0) pData->pObject->nShape=PHYS_SHAPE_BOX;//pData->pObject->nPhysFlags|=LX_OBJ_PHYS_SHAPE_BOX; else if(stricmp(atts[i+1], "sphere")==0) pData->pObject->nShape=PHYS_SHAPE_SPHERE;//pData->pObject->nPhysFlags|=LX_OBJ_PHYS_SHAPE_SPHERE; else if(stricmp(atts[i+1], "cylinder")==0) pData->pObject->nShape=PHYS_SHAPE_CYLINDER;//pData->pObject->nPhysFlags|=LX_OBJ_PHYS_SHAPE_CYLINDER; LX_END_MISC_ATTR LX_MISC_ATTR(bounds) if(stricmp(atts[i+1], "skel")==0) pData->pObject->nPhysFlags|=LX_OBJ_PHYS_BOUNDS_SKEL; else if(stricmp(atts[i+1], "mesh")==0) pData->pObject->nPhysFlags|=LX_OBJ_PHYS_BOUNDS_MESH; LX_END_MISC_ATTR LX_END_ATTR /* for(lg_dword i=0; atts[i]; i+=2) { if(stricmp(atts[i], "mass")==0) pData->pObject->fMass=(lg_float)atof(atts[i+1]); else if(stricmp(atts[i], "scale")==0) pData->pObject->fScale=(lg_float)atof(atts[i+1]); else if(stricmp(atts[i], "shape")==0) { if(stricmp(atts[i+1], "capsule")==0) pData->pObject->nPhysFlags|=LX_OBJ_PHYS_SHAPE_CAPSULE; else if(stricmp(atts[i+1], "box")==0) pData->pObject->nPhysFlags|=LX_OBJ_PHYS_SHAPE_BOX; else if(stricmp(atts[i+1], "sphere")==0) pData->pObject->nPhysFlags|=LX_OBJ_PHYS_SHAPE_SPHERE; else if(stricmp(atts[i+1], "cylinder")==0) pData->pObject->nPhysFlags|=LX_OBJ_PHYS_SHAPE_CYLINDER; } else if(stricmp(atts[i], "bounds")==0) { if(stricmp(atts[i+1], "skel")==0) pData->pObject->nPhysFlags|=LX_OBJ_PHYS_BOUNDS_SKEL; else if(stricmp(atts[i+1], "mesh")==0) pData->pObject->nPhysFlags|=LX_OBJ_PHYS_BOUNDS_MESH; } else if(stricmp(atts[i], "center")==0) { if(stricmp(atts[i+1], "auto")==0) pData->pObject->nPhysFlags|=LX_OBJ_PHYS_AUTO_CENTER; else { char* szTok=strtok((char*)atts[i+1], ", "); pData->pObject->fXC=szTok?(lg_float)atof(szTok):0.0f; szTok=strtok(LG_NULL, ", "); pData->pObject->fYC=szTok?(lg_float)atof(szTok):0.0f; szTok=strtok(LG_NULL, ", "); pData->pObject->fZC=szTok?(lg_float)atof(szTok):0.0f; } } } */ } else if(nMode==OBJ_MODE_MODES) { //If the nModeCount is set, then the modes have already been //declared an in that case, more modes cannot be declared. if(pData->pObject->nModeCount>0) { Err_Printf("LX_Object Parse ERROR: <modes> tag can only be used once."); return; } //Get the number of modes (count) and allocate memory to store //the modes. for(lg_dword i=0; atts[i]; i+=2) { if(stricmp(atts[i], "count")==0) { pData->pObject->nModeCount=atoi(atts[i+1]); } } if(pData->pObject->nModeCount>0) { pData->pObject->pModes=(lx_object_mode*)LG_Malloc(pData->pObject->nModeCount*sizeof(lx_object_mode)); } } else if(nMode==OBJ_MODE_MODE) { //A mode can only be declared if we are already inside //the <modes> tage, so make sure that that is the case. LX_OBJ_MODE nModeCurrent=pData->stkMode.Pop(); LX_OBJ_MODE nModePrev=pData->stkMode.Peek(); pData->stkMode.Push(nModeCurrent); if(nModePrev!=OBJ_MODE_MODES) { Err_Printf("LX_Object Parse ERROR: <mode> delcared outside <modes>."); return; } //Get the mode id and the name of the mode. lg_dword nID=0; lg_char* szName=LG_NULL; for(lg_dword i=0; atts[i]; i+=2) { if(stricmp(atts[i], "id")==0) nID=atoi(atts[i+1]); else if(stricmp(atts[i], "name")==0) szName=(lg_char*)atts[i+1]; } if(nID>0 && nID<=pData->pObject->nModeCount) { strncpy(pData->pObject->pModes[nID-1].szName, szName, LX_MAX_NAME); pData->pObject->pModes[nID-1].szName[LX_MAX_NAME]=0; } } } void LX_ObjectEnd(void* userData, const XML_Char* name) { lx_obj_data* pData = (lx_obj_data*)userData; LX_OBJ_MODE nMode=LX_ObjectNameToMode(name); LX_OBJ_MODE nPrevMode=pData->stkMode.Pop(); if(nPrevMode!=nMode){ Err_Printf("LX_Object Parse ERROR: Starting tag did not match end tag."); } } void LX_ObjectCharData(void* userData, const XML_Char*s, int len) { lx_obj_data* pData = (lx_obj_data*)userData; lg_char* szText=(lg_char*)LG_Malloc((len+1)*sizeof(lg_char)); memcpy(szText, s, len+1); szText[len]=0; if(pData->stkMode.Peek()==OBJ_MODE_MODE) { #if 0 Err_Printf(szText); #endif } LG_Free(szText); } <file_sep>/games/Legacy-Engine/Scrapped/old/lm_node.cpp #include "lm_node.h" /***************************************************************** *** The Mesh Node System is a method of frame hierarchy for *** rendering multi-part meshes. Note that this class doesn't *** allocate memory at all and any child nodes need to be kept *** track of by the user application. *** The usual way to do this is to create an array of nodes, and *** use the first node in the array as the topmost parent, then *** setup all the other nodes as necessary. See example. *****************************************************************/ CLMeshNode::CLMeshNode(): m_pMesh(LG_NULL), m_pDefSkel(LG_NULL), m_pNext(LG_NULL), m_pChildren(LG_NULL), m_pParent(LG_NULL), m_nParentJoint(0xFFFFFFFF), m_pSkel(LG_NULL), m_nAnim(0), m_nAnimSpeed(0), m_nTime(0), m_nLastUpdate(0), m_fTime(0.0f), m_pPrevSkel(LG_NULL), m_nPrevAnim(0), m_fPrevTime(0.0f), m_nTransTime(0) { } CLMeshNode::~CLMeshNode() { Unload(); } void CLMeshNode::SetCompatibleWith(CLSkelLG* pSkel) { if(m_pMesh && pSkel) m_pMesh->SetCompatibleWith((CLSkel2*)pSkel); } void CLMeshNode::UpdateTime(lg_dword nTime) { m_nTime=nTime; lg_long nMSPerAnim=m_pPrevSkel?m_nTransTime:m_nAnimSpeed; lg_dword nElapsed=nTime-m_nLastUpdate; if(nElapsed>(lg_dword)ML_absl(nMSPerAnim)) { m_nLastUpdate=nTime; m_pPrevSkel=LG_NULL; nElapsed=0; } m_fTime=(float)nElapsed/(float)nMSPerAnim*99.0f; //If the animation speed is negative we //reverse the animation by subtracting the time //only we add because m_fTime will be negative. //In this way the animation is backwards... if(nMSPerAnim<0) m_fTime=100.0f+m_fTime; //Now update all children for(CLMeshNode* pNode=m_pChildren; pNode; pNode=pNode->m_pNext) { pNode->UpdateTime(nTime); } } void CLMeshNode::SetAnimation(CLSkelLG* pSkel, lg_dword nAnim, lg_long nSpeed, lg_dword nTransTime) { //If we're setting the same animation, there is no need to transition. if((m_pSkel==pSkel) && (nAnim==m_nAnim) && (m_nAnimSpeed==nSpeed)) return; m_pPrevSkel=m_pSkel; m_nPrevAnim=m_nAnim; m_fPrevTime=m_fTime; m_pSkel=pSkel; m_nAnim=nAnim; m_nAnimSpeed=nSpeed; m_nTransTime=nTransTime; m_nLastUpdate=m_nTime; m_fTime=0.0f; UpdateTime(m_nTime); return; } void CLMeshNode::Load(CLMeshLG* pMesh) { //Clear currently loaded information. Unload(); m_pMesh=pMesh; } void CLMeshNode::AddChild(CLMeshNode* pNode, lg_cstr szJoint) { //Add child adds the node to a linked list child. pNode->m_pParent=this; if(this->m_pMesh) pNode->m_nParentJoint=this->m_pMesh->GetJointRef(szJoint); pNode->m_pNext=this->m_pChildren; this->m_pChildren=pNode; } void CLMeshNode::Unload() { m_pSkin=LG_NULL; m_pMesh=LG_NULL; m_pNext=LG_NULL; m_pChildren=LG_NULL; m_pParent=LG_NULL; m_nParentJoint=0xFFFFFFFF; m_pSkel=LG_NULL; m_nAnim=0; m_nAnimSpeed=0; m_nTime=0; m_nLastUpdate=0; m_fTime=0.0f; m_pPrevSkel=LG_NULL; m_nPrevAnim=0; m_fPrevTime=0.0f; } void CLMeshNode::Render(const ML_MAT* matTrans) { if(m_pMesh) { CLMeshLG::s_pDevice->SetTransform(D3DTS_WORLD, (D3DMATRIX*)matTrans); if(m_pPrevSkel) { m_pMesh->SetupFrame(m_nPrevAnim, m_fPrevTime, (CLSkel2*)m_pPrevSkel); } if(m_pPrevSkel && m_pSkel) { m_pMesh->TransitionTo(m_nAnim, m_fTime*0.01f, (CLSkel2*)m_pSkel); } else if(m_pSkel && !m_pPrevSkel) { m_pMesh->SetupFrame(m_nAnim, m_fTime, (CLSkel2*)m_pSkel); } else { m_pMesh->SetupDefFrame(); } m_pMesh->DoTransform(); m_pMesh->Render(m_pSkin); } #if 1 //Now Render all the children... If the children have any children //they will get rendered as well. for(CLMeshNode* pNode=m_pChildren; pNode; pNode=pNode->m_pNext) { ML_MAT matTransChild; if(pNode->m_nParentJoint!=0xFFFFFFFF) { ML_MatMultiply( &matTransChild, this->m_pMesh->GetJointAttachTransform(pNode->m_nParentJoint), matTrans); } else { matTransChild=*matTrans; } pNode->Render(&matTransChild); } #endif } const CLMeshNode* CLMeshNode::GetParent() { return m_pParent; } #include "lg_err.h" #include "lg_mmgr.h" #include "lg_xml.h" //Right now for the XML mesh script parsing there //are two parts, the first part counts how many meshes //there are, the second part, actually loads the mesh. //If the mesh count attribute is specified in the base //mesh then that number is used for the mesh count. typedef struct _XML_Mesh_Data{ lg_dword nMesh; lg_dword nMaxMesh; CLMeshNode* pNodes; CLMeshNode* pParent; lg_str szXMLFilename; }XML_Mesh_Data; lg_dword LM_CountNumMeshes(lg_path szXMLScriptFile); void XML_Mesh_Start(void* userData, const XML_Char* name, const XML_Char** atts); void XML_Mesh_End(void* userData, const XML_Char* name); //LE_LoadMeshNodes loads a set of mesh nodes from based on an XML script, //the return value is the said array of nodes, node 0 being the parent //node. The nNumMeshes pointer will contain the number of nodes loaded. //LE_DeleteMeshNodes is used to delete the array of mesh nodes, note that //LE_DeleteMeshNodes should be used as opposed to delete[] because it //insures that compatible memory freeing methods are used. These functions //are used for loading mesh sets for CLEntities. #include "lf_sys2.h" CLMeshNode* LM_LoadMeshNodes(lg_path szXMLScriptFile, lg_dword* nNumMeshes) { //To load a mesh we first need to open the script file, //we'll open it with LF_ACCESS_MEMORY so we can pass the buffer //to the parser. LF_FILE3 fileScript=LF_Open(szXMLScriptFile, LF_ACCESS_READ|LF_ACCESS_MEMORY, LF_OPEN_EXISTING); if(!fileScript) { Err_Printf("LoadMesh ERROR: Could not open \"%s\" for parsing.", szXMLScriptFile); return LG_NULL; } //Now we'll create the parser. XML_Parser parser=XML_ParserCreate_LG(LG_NULL); if(!parser) { Err_Printf("LoadMesh ERROR: Could not create XML parser. (%s)", szXMLScriptFile); LF_Close(fileScript); return LG_NULL; } XML_Mesh_Data data; data.nMaxMesh=0; data.nMesh=0; data.pParent=LG_NULL; data.pNodes=LG_NULL; data.szXMLFilename=szXMLScriptFile; XML_ParserReset(parser, LG_NULL); XML_SetUserData(parser, &data); XML_SetElementHandler(parser, XML_Mesh_Start, XML_Mesh_End); if(!XML_Parse(parser, (const char*)LF_GetMemPointer(fileScript), LF_GetSize(fileScript), LG_TRUE)) { Err_Printf("LoadMesh ERROR: Parse error at line %d: \"%s\"", XML_GetCurrentLineNumber(parser), XML_ErrorString(XML_GetErrorCode(parser))); data.nMesh=0; LG_SafeDeleteArray(data.pNodes); } LF_Close(fileScript); XML_ParserFree(parser); if(nNumMeshes) *nNumMeshes=data.nMesh; return data.pNodes; } void LM_DeleteMeshNodes(CLMeshNode* pNodes) { LG_SafeDeleteArray(pNodes); } void XML_Mesh_Start(void* userData, const XML_Char* name, const XML_Char** atts) { //If this isn't a mesh tag there is no reason to parse it. if(strcmp(name, "mesh")!=0) { Err_Printf("MeshLoad WARNING: <%s> is not a valid mesh loading tag.", name); return; } XML_Mesh_Data* pData=(XML_Mesh_Data*)userData; const XML_Char* szName=NULL; const XML_Char* szFile=NULL; const XML_Char* szSkinFile=NULL; const XML_Char* szParentJoint=NULL; const XML_Char* szDefSkel=LG_NULL; lg_dword nMeshCount=0; for(lg_dword i=0; atts[i]; i+=2) { if(strcmp(atts[i], "name")==0) szName=atts[i+1]; else if(strcmp(atts[i], "mesh_file")==0) szFile=atts[i+1]; else if(strcmp(atts[i], "skin_file")==0) szSkinFile=atts[i+1]; else if(strcmp(atts[i], "parent_joint")==0) szParentJoint=atts[i+1]; else if(strcmp(atts[i], "default_skel")==0) szDefSkel=atts[i+1]; else if(strcmp(atts[i], "mesh_count")==0) nMeshCount=(lg_dword)atol((char*)atts[i+1]); } if(pData->nMesh==0) { //If we are handling the first mesh, we need to allocate //memory for the mesh. if(pData->nMaxMesh || nMeshCount) { pData->nMaxMesh=LG_Max(pData->nMaxMesh, (lg_dword)nMeshCount); } else { Err_Printf("MeshLoad WARNING: Mesh count not specified, counting..."); //pData->bNeedToCount=LG_TRUE; pData->nMaxMesh=LM_CountNumMeshes(pData->szXMLFilename); } if(pData->nMaxMesh) pData->pNodes=new CLMeshNode[pData->nMaxMesh]; if(!pData->pNodes) { pData->nMaxMesh=0; Err_Printf("MeshLoad ERROR: Could not allocate memory for mesh nodes."); return; } } if((pData->nMesh>=pData->nMaxMesh)) { Err_Printf("MeshLoad ERROR: Exceeded the maximum number of meshes."); return; } //Load the mesh based off the filename. pData->pNodes[pData->nMesh].Load(CLMMgr::MM_LoadMesh((lf_char*)szFile, 0)); //If a default skeleton was specified for this node, //then set it. if(szDefSkel) { pData->pNodes[pData->nMesh].m_pDefSkel=CLMMgr::MM_LoadSkel((lf_char*)szDefSkel, 0); pData->pNodes[pData->nMesh].SetCompatibleWith(pData->pNodes[pData->nMesh].m_pDefSkel); } //Load the skin for the mesh if(szSkinFile) { pData->pNodes[pData->nMesh].m_pSkin=CLSkinMgr::SM_Load((lg_char*)&szSkinFile[0], 0); if(pData->pNodes[pData->nMesh].m_pSkin) { pData->pNodes[pData->nMesh].m_pSkin->MakeCompatibleWithMesh( pData->pNodes[pData->nMesh].m_pMesh); } } if(pData->pParent) pData->pParent->AddChild(&pData->pNodes[pData->nMesh], szParentJoint); pData->pParent=&pData->pNodes[pData->nMesh]; pData->nMesh++; } void XML_Mesh_End(void* userData, const XML_Char* name) { XML_Mesh_Data* pData=(XML_Mesh_Data*)userData; if(pData->pParent) pData->pParent=(CLMeshNode*)pData->pParent->GetParent(); } //The counter parsing methods simply count how many meshes are in the XML file //It's not really that fast to parse the XML file twice to find out how many meshes //there are, but it is the best way (memory wise, as a linked list could be created) //to get memory allocated for the file. void XML_Mesh_Start_Count(void* userData, const XML_Char* name, const XML_Char** atts) { //If this isn't a mesh tag there is no reason to parse it. if(strcmp(name, "mesh")!=0) { Err_Printf("MeshLoad WARNING: <%s> is not a valid mesh loading tag.", name); return; } XML_Mesh_Data* pData=(XML_Mesh_Data*)userData; pData->nMaxMesh++; } void XML_Mesh_End_Count(void* userData, const XML_Char* name){} lg_dword LM_CountNumMeshes(lg_path szXMLScriptFile) { //To load a mesh we first need to open the script file, //we'll open it with LF_ACCESS_MEMORY so we can pass the buffer //to the parser. LF_FILE3 fileScript=LF_Open(szXMLScriptFile, LF_ACCESS_READ|LF_ACCESS_MEMORY, LF_OPEN_EXISTING); if(!fileScript) { Err_Printf("LoadMesh ERROR: Could not open \"%s\" for parsing.", szXMLScriptFile); return 0; } //Now we'll create the parser. XML_Parser parser=XML_ParserCreate_LG(LG_NULL); if(!parser) { Err_Printf("LoadMesh ERROR: Could not create XML parser. (%s)", szXMLScriptFile); LF_Close(fileScript); return 0; } XML_Mesh_Data data; //First we count the meshes.. data.nMaxMesh=0; XML_SetUserData(parser, &data); XML_SetElementHandler(parser, XML_Mesh_Start_Count, XML_Mesh_End_Count); if(!XML_Parse(parser, (const char*)LF_GetMemPointer(fileScript), LF_GetSize(fileScript), LG_TRUE)) { Err_Printf("LoadMesh ERROR: Parse error at line %d: \"%s\"", XML_GetCurrentLineNumber(parser), XML_ErrorString(XML_GetErrorCode(parser))); data.nMesh=0; data.nMaxMesh=0; } if(data.nMaxMesh==0) { Err_Printf("LoadMesh ERROR: Could not find any meshes in \"%s\".", szXMLScriptFile); LF_Close(fileScript); XML_ParserFree(parser); return 0; } LF_Close(fileScript); XML_ParserFree(parser); return data.nMaxMesh; }<file_sep>/games/Legacy-Engine/Scrapped/old/lg_meshmgr.cpp #include "lf_sys2.h" #include "lg_meshmgr.h" #include "lg_err.h" #include "lg_err_ex.h" #include "lg_func.h" CLMeshMgr* CLMeshMgr::s_pMeshMgr=LG_NULL; CLMeshD3D* CLMeshMgr::GlobalLoadMesh(lf_path szFilename, lg_dword Flags) { if(s_pMeshMgr) return s_pMeshMgr->LoadMesh(szFilename, Flags); else { Err_Printf( "LG_LoadMesh ERROR: The Mesh Manager has not been initialized, cannot load \"%s\"", szFilename); return LG_NULL; } } CLSkel* CLMeshMgr::GlobalLoadSkel(lf_path szFilename, lg_dword Flags) { if(s_pMeshMgr) return s_pMeshMgr->LoadSkel(szFilename, Flags); else { Err_Printf( "LG_LoadSkel ERROR: The Mesh Manager has not been initialized, cannot load \"%s\"", szFilename); return LG_NULL; } } CLMeshMgr::CLMeshMgr(IDirect3DDevice9 *pDevice, lg_dword nMaxMesh, lg_dword nMaxSkel): m_nNumMeshes(0), m_pFirstMesh(LG_NULL), m_nNumSkels(0), m_pFirstSkel(LG_NULL) { //If the Mesh Manager already exists, then we have failed, because //it should only be initialized once. if(s_pMeshMgr) { throw new CLError( LG_ERR_DEFAULT, __FILE__, __LINE__, LG_TEXT("The Mesh Manager can only be initialized once.")); } //To initialze D3D we are going to save a reference to //the device for the purpose of loading meshes. //This function should be called before any meshes are //loaded or the meshes will not be able to get d3d //interfaces to render themselves with. Note that if //a null point is passed it effectively uninitializes //the device interace, but all meshes that have been //created so far will still have references to the //device they were created with. //L_safe_release(m_pDevice); //m_pDevice=pDevice; CLMeshD3D::InitMeshDevice(pDevice); s_pMeshMgr=this; } CLMeshMgr::~CLMeshMgr() { if(!UnloadAll(LMMGR_UNLOAD_FORCE_ALL)) OutputDebugString("CLMeshMgr::ERROR Was not able to delete all stored items!\n"); else OutputDebugString("CLMeshMgr::NOTE Was able to delete all stored items!\n"); if(m_nNumSkels>0) OutputDebugString("CLMeshMgr::ERROR There were skeletons left over!\n"); if(m_nNumMeshes>0) OutputDebugString("CLMeshMgr::ERROR There were meshes left over!\n"); CLMeshD3D::UnInitMeshDevice(); s_pMeshMgr=LG_NULL; } CLMeshD3D* CLMeshMgr::GetMesh(lg_char* szName) { LMESH_LINK* pLink=m_pFirstMesh; while(pLink) { if(L_strnicmp(szName, pLink->szName, LMESH_MAX_NAME)) return pLink->pMesh; pLink=pLink->pNext; } return LG_NULL; } CLMeshD3D* CLMeshMgr::LoadMesh(lf_path szFilename, lg_dword nFlags) { //The first thing we do is make sure that //the mesh isn't already loaded. Note that if two meshes //have the same name, even if they are different meshes only one //mesh will be loaded, for this reason no two meshes used //in a game should have the same name. lf_path szTemp; CLMeshD3D* pExistingMesh=GetMesh(LF_GetShortNameFromPath(szTemp, szFilename)); if(pExistingMesh) { //Err_Printf("CLMeshMgr::LoadMesh WARNING: \"%s\" mesh is already loaded (or if a different mesh is desired the filename may need to be changed).", szTemp); Err_Printf("\"%s\" mesh acquired (%s).", szTemp, pExistingMesh->Validate()?"D3D READY":"NO RENDER"); return pExistingMesh; } //Allocate memory for the new link in the chain... //Note that the new link will be placed at the //beginning of the chain, we are simply creating //a linked list here. LMESH_LINK* pNew=new LMESH_LINK; if(!pNew) { Err_Printf("CLMeshMgr::LoadMesh ERROR: Could not allocate memory for linked list."); return LG_NULL; } pNew->pMesh=new CLMeshD3D(); if(!pNew->pMesh) { delete pNew; Err_Printf("CLMeshMgr::LoadMesh ERROR: Could not allocate memory for CLMeshD3D."); return LG_NULL; } if(!pNew->pMesh->Load(szFilename)) { delete pNew->pMesh; delete pNew; Err_Printf("CLMeshMgr::LoadMesh ERROR: Could not load \"%s\".", szFilename); return LG_NULL; } //Set the flags for this mesh. pNew->nFlags=nFlags; //For now the name will simply be the short version of //the file without the extensions (in the future this will //actually be a name stored in he file itself). LF_GetShortNameFromPath(pNew->szName, szFilename); pNew->pNext=m_pFirstMesh; m_pFirstMesh=pNew; m_nNumMeshes++; lg_bool bD3D=pNew->pMesh->CreateD3DComponents(); Err_Printf("\"%s\" mesh loaded (%s).", pNew->szName, bD3D?"D3D READY":"NO RENDER"); return pNew->pMesh; } lg_bool CLMeshMgr::UnloadMesh(lg_char* szName) { LMESH_LINK* pNext,* pCur; LMESH_LINK* pNewList=LG_NULL; lg_bool bFound=LG_FALSE; //The easiest way to delete a mesh is to create //a new list (which will be in reverse ord) //and while so doing eliminate the desired mesh. pCur=m_pFirstMesh; while(pCur) { pNext=pCur->pNext; if(bFound || !L_strnicmp(pCur->szName, szName, LMESH_MAX_NAME)) { pCur->pNext=pNewList; pNewList=pCur; } else { OutputDebugString("Removing ");OutputDebugString(pCur->szName);OutputDebugString(" mesh.\n"); Err_Printf("\"%s\" mesh unloaded.", pCur->szName); L_safe_delete(pCur->pMesh); delete pCur; bFound=LG_TRUE; m_nNumMeshes--; } pCur=pNext; } m_pFirstMesh=pNewList; return bFound; } lg_bool CLMeshMgr::UnloadAll(lg_dword nFlags) { lg_bool bResult; bResult=UnloadMeshes(nFlags); bResult=bResult&&UnloadSkels(nFlags); return bResult; } lg_bool CLMeshMgr::UnloadMeshes(lg_dword nFlags) { LMESH_LINK* pItem=m_pFirstMesh,* pTemp=LG_NULL; LMESH_LINK* pNewList=LG_NULL, *pNewItem=LG_NULL; while(pItem) { pTemp=pItem; pItem=pTemp->pNext; //If the model needs to be saved we will put it in the new list. if(L_CHECK_FLAG(pTemp->nFlags, LMMGR_LOAD_RETAIN) && !L_CHECK_FLAG(nFlags, LMMGR_UNLOAD_FORCE_ALL)) { pNewItem=pNewList; pNewList=pTemp; pNewList->pNext=pNewItem; continue; } OutputDebugString("Removing ");OutputDebugString(pTemp->szName);OutputDebugString(" Mesh.\n"); Err_Printf("\"%s\" mesh unloaded.", pTemp->szName); L_safe_delete(pTemp->pMesh); delete pTemp; m_nNumMeshes--; } m_pFirstMesh=pNewList; return LG_TRUE; } lg_bool CLMeshMgr::UnloadSkels(lg_dword nFlags) { LSKEL_LINK* pItem=m_pFirstSkel,* pTemp=LG_NULL; LSKEL_LINK* pNewList=LG_NULL, *pNewItem=LG_NULL; while(pItem) { pTemp=pItem; pItem=pTemp->pNext; //If the model needs to be saved we will put it in the new list. if(L_CHECK_FLAG(pTemp->nFlags, LMMGR_LOAD_RETAIN) && !L_CHECK_FLAG(nFlags, LMMGR_UNLOAD_FORCE_ALL)) { pNewItem=pNewList; pNewList=pTemp; pNewList->pNext=pNewItem; continue; } OutputDebugString("Removing ");OutputDebugString(pTemp->szName);OutputDebugString(" skeleton.\n"); Err_Printf("\"%s\" skeleton unloaded.", pTemp->szName); L_safe_delete(pTemp->pSkel); delete pTemp; m_nNumSkels--; } m_pFirstSkel=pNewList; return LG_TRUE; } lg_bool CLMeshMgr::UnloadSkel(lg_char* szName) { LSKEL_LINK* pNext,* pCur; LSKEL_LINK* pNewList=LG_NULL; lg_bool bFound=LG_FALSE; //The easiest way to delete a mesh is to create //a new list (which will be in reverse ord) //and while so doing eliminate the desired mesh. pCur=m_pFirstSkel; while(pCur) { pNext=pCur->pNext; if(bFound || !L_strnicmp(pCur->szName, szName, LMESH_MAX_NAME)) { pCur->pNext=pNewList; pNewList=pCur; } else { OutputDebugString("Removing ");OutputDebugString(pCur->szName);OutputDebugString(" skeleton.\n"); Err_Printf("\"%s\" skeleton unloaded.", pCur->szName); L_safe_delete(pCur->pSkel); delete pCur; bFound=LG_TRUE; m_nNumMeshes--; } pCur=pNext; } m_pFirstSkel=pNewList; return bFound; } void CLMeshMgr::InvalidateMeshes() { LMESH_LINK* pLink=m_pFirstMesh; while(pLink) { pLink->pMesh->Invalidate(); pLink=pLink->pNext; } } lg_bool CLMeshMgr::ValidateMeshes() { LMESH_LINK* pLink=m_pFirstMesh; lg_bool bResult=LG_TRUE; while(pLink) { bResult=bResult&&pLink->pMesh->Validate(); pLink=pLink->pNext; } return bResult; } CLSkel* CLMeshMgr::LoadSkel(lf_path szFilename, lg_dword nFlags) { //The first thing we do is make sure that //the mesh isn't already loaded. Note that if two meshes //have the same name, even if they are different meshes only one //mesh will be loaded, for this reason no two meshes used //in a game should have the same name. lf_path szTemp; CLSkel* pExistingSkel=GetSkel(LF_GetShortNameFromPath(szTemp, szFilename)); if(pExistingSkel) { //Err_Printf("CLMeshMgr::LoadSkel WARNING: \"%s\" skeleton is already loaded (or if a different mesh is desired the filename may need to be changed).", szTemp); Err_Printf("\"%s\" skeleton acquired.", szTemp); return pExistingSkel; } //Allocate memory for the new link in the chain... //Note that the new link will be placed at the //beginning of the chain, we are simply creating //a linked list here. LSKEL_LINK* pNew=new LSKEL_LINK; if(!pNew) { Err_Printf("CLMeshMgr::LoadSkel ERROR: Could not allocate memory for linked list."); return LG_NULL; } //Load the skel (if it exists). pNew->pSkel=new CLSkel(); if(!pNew->pSkel) { delete pNew; Err_Printf("CLMeshMgr::LoadSkel ERROR: Could not allocate memory for CLSkel."); return LG_NULL; } if(!pNew->pSkel->Load(szFilename)) { delete pNew->pSkel; delete pNew; Err_Printf("CLMeshMgr::LoadSkel ERROR: Could not load \"%s\".", szFilename); return LG_NULL; } //Set the flags for this skeleton. pNew->nFlags=nFlags; //For now the name will simply be the short version of //the file without the extensions (in the future this will //actually be a name stored int he file itself). LF_GetShortNameFromPath(pNew->szName, szFilename); pNew->pNext=m_pFirstSkel; m_pFirstSkel=pNew; m_nNumSkels++; Err_Printf("\"%s\" skeleton loaded.", pNew->szName); return pNew->pSkel; } CLSkel* CLMeshMgr::GetSkel(lg_char* szName) { LSKEL_LINK* pLink=m_pFirstSkel; while(pLink) { if(L_strnicmp(szName, pLink->szName, LMESH_MAX_NAME)) return pLink->pSkel; pLink=pLink->pNext; } return LG_NULL; }<file_sep>/samples/Project5/src/bcol/BQueue.java /* <NAME> CS 2420-002 BQueue - Generic Queue for data collections. */ package bcol; public class BQueue <T>{ protected BList <T> m_listQ; /* PRE: N/A POST: Createa a new instance of BQueue. */ public BQueue() { m_listQ = new BList<T>(); } /* PRE: N/A POST: Returns true if the queue is empty, else false. */ public boolean isEmpty(){ return m_listQ.isEmpty(); } /* PRE: obj != null POST: Inserts the specified object in the queue (queues it up) */ public void enqueue(T obj){ m_listQ.insert(obj); } /* PRE: isEmpty returns false. POST: returns the next item from the queue (does not dequeue it though). */ public T next() throws BColException{ if(m_listQ.isEmpty()){ throw new BColException("Queue is empty."); } return m_listQ.getLast(); } /* PRE: isEmpty() returns false. POST: REturns the next item to be dequeued then dequeueus that item. */ public T dequeue() throws BColException{ T obj = next(); m_listQ.remove(obj); return obj; } /* PRE: N/A POST: Returns a string representation of the queue. */ public String toString(){ String s; if(m_listQ.isEmpty()){ s = "===EMPTY QUEUE==="; }else{ s = "===QUEUE===\n"; T obj = m_listQ.getLast(); Integer num = 1; while(obj != null){ s += num.toString() + ": " + obj.toString() + '\n'; obj = m_listQ.getPrev(); num++; } s += "===========\n"; } return s; //return m_listQ.toString(); } } <file_sep>/games/Sometimes-Y/SometimesY/resource.h //{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by SometimesY.rc // #define IDM_ABOUTBOX 0x0010 #define IDD_ABOUTBOX 100 #define IDS_ABOUTBOX 101 #define IDD_SOMETIMESY_DIALOG 102 #define IDR_MAINFRAME 128 #define IDR_MENU1 129 #define IDR_MENU_INSERT 129 #define ID_INSERT_A 32771 #define ID_INSERT_E 32772 #define ID_INSERT_I 32773 #define ID_INSERT_O 32774 #define ID_INSERT_U 32775 #define ID_INSERT_Y 32776 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 130 #define _APS_NEXT_COMMAND_VALUE 32777 #define _APS_NEXT_CONTROL_VALUE 1000 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif <file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/lv_con.h /* lv_con.h - the graphical console. */ #ifndef __LV_CON_H__ #define __LV_CON_H__ #include "common.h" #include "lv_font2.h" #include "lv_img2d.h" #include <lc_sys.h> #ifdef __cplusplus extern "C"{ #endif /* __cplusplus */ typedef struct _LVCON{ LV2DIMAGE* lpBackground; /* The background image. */ void* lpFont; /* The font. */ L_dword dwViewHeight; /* The view height. */ L_dword dwFontHeight; HLCONSOLE hConsole; /* Pointer to the console. */ IDirect3DDevice9* lpDevice; /* The device that created teh console. */ L_bool bActive; /* Whether or not the console is receiving input. */ L_bool bDeactivating;/* If the console is in the process of deactivating (scrolling up).*/ float fPosition; /* The position of the console. */ long nScrollPos; /* Where the console is rendering output. */ L_dword dwLastUpdate; /* The last time the console position was updated. */ L_bool bCaretOn; L_dword dwLastCaretChange; L_bool bFullMode; }LVCON, *LPLVCON; LVCON* VCon_Create( HLCONSOLE hConsole, HCVARLIST cvars, IDirect3DDevice9* lpDevice); L_bool VCon_Delete( LVCON* lpVCon); L_bool VCon_Render( LVCON* lpVCon, IDirect3DDevice9* lpDevice); L_bool VCon_Validate( LVCON* lpVCon, IDirect3DDevice9* lpDevice); L_bool VCon_Invalidate( LVCON* lpVCon); L_bool VCon_OnChar( LVCON* lpVCon, char c); #ifdef __cplusplus } #endif /* __cplusplus */ #endif __LV_CON_H__<file_sep>/games/Legacy-Engine/Source/engine/lvf_sys.h #ifndef __LVF_SYS_H__ #define __LVF_SYS_H__ #include "lf_sys2.h" #include "lg_types.h" #include "lg_xml.h" class CLVFont { private: struct CHAR_DATA{ lg_char c; lg_word x, y, w, h; }; struct XML_FIND_DATA{ lf_path szFontFile; CHAR_DATA* pCharData; lg_char c; lg_bool bInChar; }; public: CLVFont(); ~CLVFont(); CHAR_DATA m_CharData[96]; lg_bool Load(lf_path szXMLFilename); private: static void xml_font_data_start(void* userData, const XML_Char* name, const XML_Char** atrs); static void xml_font_data_end(void* userData, const XML_Char* name); static void xml_font_data_data(void* userData, const XML_Char*s, int len); }; #endif __LVF_SYS_H__<file_sep>/games/Legacy-Engine/Scrapped/UnitTests/ML_demo/ML_demo_mat.c #include <stdio.h> #include <d3dx9.h> #include <ML_lib.h> #include <math.h> #define DO_ALT_TEST void MatIdentTest(ML_MAT* pMM, ML_MAT* pMD); void MatMulTest(ML_MAT* pT, ML_MAT* pM1, ML_MAT* pM2); void MatRotXTest(ML_MAT* pT, float fA); void MatRotYTest(ML_MAT* pT, float fA); void MatRotZTest(ML_MAT* pT, float fA); void MatFromQuatTest(ML_MAT* pM, ML_QUAT* pQ); void MatInverseTest(ML_MAT* pMT, ML_MAT* pM); void QuatFromMatTest(ML_QUAT* pQT, ML_MAT* pM); void QuatSlerpTest(ML_QUAT* pQT, ML_QUAT* pQ1, ML_QUAT* pQ2, float t); void MatDetTest(ML_MAT* pM); void MatFovPerspectiveTest(ML_MAT* pMT); void MatLookAtTest(ML_MAT* pM, ML_VEC3* pEye, ML_VEC3* pAt, ML_VEC3* pUp); void MatYawPitchRollTest(ML_MAT* pM, float Yaw, float Pitch, float Roll); void PrintMat(void*); void PrintVec4(void*); /* ML_QUAT* ML_FUNC ML_QuatRotationMat2(ML_QUAT* pOut, ML_MAT* pM) { float fTrace=pM->_11+pM->_22+pM->_33+1.0f; if(fTrace > 0.00000001f) { //MessageBox(0, "W", 0, 0); pOut->w=sqrtf(fTrace)*0.5f; fTrace=0.25f/pOut->w; pOut->x=(pM->_23-pM->_32)*fTrace; pOut->y=(pM->_31-pM->_13)*fTrace; pOut->z=(pM->_12-pM->_21)*fTrace; return pOut; } if( (pM->_11>pM->_22) && (pM->_11>pM->_33)) { //MessageBox(0, "X", 0, 0); pOut->x=sqrtf(pM->_11-pM->_22-pM->_33+1.0f)*0.5f; fTrace=0.25f/pOut->x; pOut->w=(pM->_23-pM->_32)*fTrace; pOut->y=(pM->_12+pM->_21)*fTrace; pOut->z=(pM->_31+pM->_13)*fTrace; return pOut; } else if(pM->_22>pM->_33) { //MessageBox(0, "Y", 0, 0); pOut->y=sqrtf(pM->_22-pM->_11-pM->_33+1.0f)*0.5f; fTrace=0.25f/pOut->y; pOut->w=(pM->_31-pM->_13)*fTrace; pOut->x=(pM->_12+pM->_21)*fTrace; pOut->z=(pM->_23+pM->_32)*fTrace; return pOut; } else { //MessageBox(0, "Z", 0, 0); pOut->z=sqrtf(pM->_33-pM->_11-pM->_22+1.0f)*0.5f; fTrace=0.25f/pOut->z; pOut->w=(pM->_12-pM->_21)*fTrace; pOut->x=(pM->_31+pM->_13)*fTrace; pOut->y=(pM->_23+pM->_32)*fTrace; return pOut; } } */ void MatTest() { ML_MAT MT; ML_MAT M1={32.2f, 56.7f, -2.0f, 3.5f, 5.6f, 7.0f, 8.0f, 90.0f, 10.0f, -785.0f, 4.3f, 2.1f, 3.0f, 4.0f, 5.0f, -7.0f}; ML_MAT M2={500.23f, 6.0f, 7.0f, 20.2f, 13.0f, -2.56f, -7.5f, 2.1f, 5.6f, 7.0f, 1.0f, -2.0f, 7.0f, -5.6f, 7.0f, 2.4f}; ML_MAT M3={-5.0f, 6.0f, 7.0f, 20.2f, 13.0f, 1.0f, -7.5f, 2.1f, 5.6f, 7.0f, 2.0f, -2.0f, 7.0f, -5.6f, 7.0f, 2.4f}; ML_MAT M4={-5.0f, 6.0f, 7.0f, 0.2f, 13.0f, 1.0f, -7.5f, 0.0f, 5.6f, 7.0f, 2.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f}; ML_QUAT Q1={345.21f, 78.65f, 21.20f, 34.56f}; ML_QUAT Q2={23.23f, -2.4f, 34.4f, 0.56f}; ML_QUAT QT={0.0f, 0.0f, 0.0f, 0.0f}; ML_VEC3 v1={0.0f, 0.0f, -1.0f}; ML_VEC3 v2={0.0f, 0.0f, 1.0f}; ML_VEC3 v3={0.0f, 1.0f, 0.0f}; ML_MatIdentity(&MT); printf("MT:\n");PrintMat(&MT); printf("M1:\n");PrintMat(&M1); printf("M2:\n");PrintMat(&M2); printf("M3:\n");PrintMat(&M3); printf("Q1:\t");PrintVec4(&Q1); printf("Q2:\t");PrintVec4(&Q2); printf("\n\n"); #if 1 MatIdentTest(&MT, &MT); MatMulTest(&MT, &M1, &M2); MatRotXTest(&MT, 3.76f); MatRotYTest(&MT, 3.76f); MatRotZTest(&MT, 3.76f); MatFromQuatTest(&MT, &Q1); QuatFromMatTest(&QT, &M3); MatDetTest(&M4); #endif MatInverseTest(&MT, &M4); #if 1 MatFovPerspectiveTest(&MT); QuatSlerpTest(&QT, &Q1, &Q2, 1.24f); MatLookAtTest(&MT, &v1, &v2, &v3); MatYawPitchRollTest(&MT, 3.012f, 1.24f, 4.566f); #endif } void MatYawPitchRollTest(ML_MAT* pM, float Yaw, float Pitch, float Roll) { printf("YawPitchRoll Test:\n"); printf("ML_lib:\n"); PrintMat((void*)ML_MatRotationYawPitchRoll(pM, Yaw, Pitch, Roll)); printf("D3DX:\n"); PrintMat((void*)D3DXMatrixRotationYawPitchRoll(pM, Yaw, Pitch, Roll)); printf("\n\n"); } void MatLookAtTest(ML_MAT* pM, ML_VEC3* pEye, ML_VEC3* pAt, ML_VEC3* pUp) { printf("MatLookAt Test:\n"); printf("ML_lib:\n"); PrintMat((void*)ML_MatLookAtLH(pM, pEye, pAt, pUp)); printf("D3DX:\n"); PrintMat((void*)D3DXMatrixLookAtLH(pM, pEye, pAt, pUp)); printf("\n\n"); } void MatFovPerspectiveTest(ML_MAT* pMT) { printf("MatPerspectiveFovLH Test:\n"); printf("ML_lib:\n"); PrintMat((void*)ML_MatPerspectiveFovLH(pMT, 3.14159f*0.25f, 4.0f/3.0f, 1.0f, 1000.0f)); printf("D3DX:\n"); PrintMat((void*)D3DXMatrixPerspectiveFovLH((ML_MAT*)pMT, 3.14159f*0.25f, 4.0f/3.0f, 1.0f, 1000.0f)); printf("\n\n"); } void MatInverseTest(ML_MAT* pMT, ML_MAT* pM) { printf("MatInverse Test:\n"); printf("ML_lib:\n"); PrintMat((void*)ML_MatInverse((void*)pMT, (void*)0, pM)); printf("D3DX:\n"); PrintMat((void*)D3DXMatrixInverse((void*)pMT, (void*)0, pM)); printf("\n\n"); } void MatDetTest(ML_MAT* pM) { printf("MatDet Test:\n"); //ML_MatRotationX(pM, 3.5f); printf("ML_lib: %f\n", ML_MatDeterminant(pM)); printf("D3DX: %f\n", D3DXMatrixDeterminant(pM)); printf("\n\n"); } void QuatSlerpTest(ML_QUAT* pQT, ML_QUAT* pQ1, ML_QUAT* pQ2, float t) { printf("QuatSlerp Test:\n"); printf("ML_lib:\t"); PrintVec4((void*)ML_QuatSlerp(pQT, pQ1, pQ2, t));//(pQT, pM)); printf("D3DX:\t"); PrintVec4((void*)D3DXQuaternionSlerp((void*)pQT, (void*)pQ1, (void*)pQ2, t)); printf("\n\n"); } void QuatFromMatTest(ML_QUAT* pQT, ML_MAT* pM) { printf("QuatFromMat Test:\n"); printf("ML_lib:\t"); PrintVec4((void*)ML_QuatRotationMat(pQT, pM)); printf("D3DX:\t"); PrintVec4((void*)D3DXQuaternionRotationMatrix((void*)pQT, (void*)pM)); printf("\n\n"); } void MatFromQuatTest(ML_MAT* pM, ML_QUAT* pQ) { printf("MatFromQuat Test:\n"); printf("ML_lib:\n"); PrintMat((void*)ML_MatRotationQuat(pM, pQ)); printf("D3DX:\n"); PrintMat((void*)D3DXMatrixRotationQuaternion((void*)pM, (void*)pQ)); printf("\n\n"); } void MatIdentTest(ML_MAT* pMM, ML_MAT* pMD) { printf("MatIdentity Test:\n"); printf("ML_lib:\n"); PrintMat(ML_MatIdentity(pMM)); printf("D3DX:\n"); PrintMat(D3DXMatrixIdentity((void*)pMD)); printf("\n\n"); } void MatMulTest(ML_MAT* pMT, ML_MAT* pM1, ML_MAT* pM2) { printf("MatMultiply Test:\n"); printf("ML_lib:\n"); PrintMat(ML_MatMultiply(pMT, pM1, pM2)); #ifdef DO_ALT_TEST printf("PEQU1:\n"); memcpy(pMT, pM1, sizeof(ML_MAT)); PrintMat(ML_MatMultiply(pMT, pMT, pM2)); printf("PEQU2:\n"); memcpy(pMT, pM2, sizeof(ML_MAT)); PrintMat(ML_MatMultiply(pMT, pM1, pMT)); #endif printf("D3DX:\n"); PrintMat((ML_MAT*)D3DXMatrixMultiply((void*)pMT, (void*)pM1, (void*)pM2)); printf("\n\n"); } void MatRotXTest(ML_MAT* pT, float fA) { printf("MatRotateX Test:\n"); printf("ML_lib:\n"); PrintMat(ML_MatRotationX(pT, fA)); printf("D3DX:\n"); PrintMat((ML_MAT*)D3DXMatrixRotationX((void*)pT, fA)); printf("\n\n"); } void MatRotYTest(ML_MAT* pT, float fA) { printf("MatRotateY Test:\n"); printf("ML_lib:\n"); PrintMat(ML_MatRotationY(pT, fA)); printf("D3DX:\n"); PrintMat((ML_MAT*)D3DXMatrixRotationY((void*)pT, fA)); printf("\n\n"); } void MatRotZTest(ML_MAT* pT, float fA) { printf("MatRotateZ Test:\n"); printf("ML_lib:\n"); PrintMat(ML_MatRotationY(pT, fA)); printf("D3DX:\n"); PrintMat((ML_MAT*)D3DXMatrixRotationY((void*)pT, fA)); printf("\n\n"); }<file_sep>/games/Legacy-Engine/Source/3rdParty/ML_lib/ML_vec3_F.c #include "ML_vec3.h" #include "ML_lib.h" /** ML_VEC3 FPU FUNCTIONS *** *** *** *** ML_Vec3Add *** *** ML_Vec3Subtract *** *** ML_Vec3Cross *** *** ML_Vec3Dot *** *** ML_Vec3Length *** *** ML_Vec3LengthSq *** *** ML_Vec3Normalize *** *** ML_Vec3Scale *** *** ML_Vec3Distance *** *** ML_Vec3DistanceSq *** *** ML_Vec3Transform *** *** ML_Vec3TransformCoord *** *** ML_Vec3TransformNormal *** ******************************/ ml_vec3* ML_FUNC ML_Vec3Add_F(ml_vec3* pOut, const ml_vec3* pV1, const ml_vec3* pV2) { pOut->x=pV1->x+pV2->x; pOut->y=pV1->y+pV2->y; pOut->z=pV1->z+pV2->z; return pOut; } ml_vec3* ML_FUNC ML_Vec3Subtract_F(ml_vec3* pOut, const ml_vec3* pV1, const ml_vec3* pV2) { pOut->x=pV1->x-pV2->x; pOut->y=pV1->y-pV2->y; pOut->z=pV1->z-pV2->z; return pOut; } ml_vec3* ML_FUNC ML_Vec3Cross_F(ml_vec3* pOut, const ml_vec3* pV1, const ml_vec3* pV2) { ml_vec3 v3Res; v3Res.x=pV1->y*pV2->z - pV1->z*pV2->y; v3Res.y=pV1->z*pV2->x - pV1->x*pV2->z; v3Res.z=pV1->x*pV2->y - pV1->y*pV2->x; *pOut=v3Res; return pOut; } ml_float ML_FUNC ML_Vec3Dot_F(const ml_vec3* pV1, const ml_vec3* pV2) { return pV1->x*pV2->x + pV1->y*pV2->y + pV1->z*pV2->z; } ml_float ML_FUNC ML_Vec3Length_F(const ml_vec3* pV) { return ML_sqrtf(pV->x*pV->x + pV->y*pV->y + pV->z*pV->z); } ml_float ML_FUNC ML_Vec3LengthSq_F(const ml_vec3* pV) { return pV->x*pV->x + pV->y*pV->y + pV->z*pV->z; } ml_vec3* ML_FUNC ML_Vec3Normalize_F(ml_vec3* pOut, const ml_vec3* pV) { ml_float fLen=1.0f/ML_Vec3Length(pV); pOut->x=pV->x*fLen; pOut->y=pV->y*fLen; pOut->z=pV->z*fLen; return pOut; } ml_vec3* ML_FUNC ML_Vec3Scale_F(ml_vec3* pOut, const ml_vec3* pV, ml_float s) { pOut->x=pV->x*s; pOut->y=pV->y*s; pOut->z=pV->z*s; return pOut; } ml_float ML_FUNC ML_Vec3Distance_F(const ml_vec3* pV1, const ml_vec3* pV2) { ml_vec3 v3T; v3T.x=pV1->x - pV2->x; v3T.y=pV1->y - pV2->y; v3T.z=pV1->z - pV2->z; return ML_Vec3Length(&v3T); } ml_float ML_FUNC ML_Vec3DistanceSq_F(const ml_vec3* pV1, const ml_vec3* pV2) { ml_vec3 v3T; v3T.x=pV1->x - pV2->x; v3T.y=pV1->y - pV2->y; v3T.z=pV1->z - pV2->z; return ML_Vec3LengthSq(&v3T); } ml_vec4* ML_FUNC ML_Vec3Transform_F(ml_vec4* pOut, const ml_vec3* pV, const ml_mat* pM) { //Just do pM * (pV, 1.0) //We know that pOut can't be pV, so we don't need to worry about //making room on the stack, but we will because one might cast //pV from a ml_vec4, also this function is rarely used anyway. ml_vec4 v4Res; v4Res.x = pM->_11*pV->x + pM->_21*pV->y + pM->_31*pV->z + pM->_41*1.0f; v4Res.y = pM->_12*pV->x + pM->_22*pV->y + pM->_32*pV->z + pM->_42*1.0f; v4Res.z = pM->_13*pV->x + pM->_23*pV->y + pM->_33*pV->z + pM->_43*1.0f; v4Res.w = pM->_14*pV->x + pM->_24*pV->y + pM->_34*pV->z + pM->_44*1.0f; *pOut=v4Res; return pOut; } ml_vec3* ML_FUNC ML_Vec3TransformCoord_F(ml_vec3* pOut, const ml_vec3* pV, const ml_mat* pM) { ml_vec3 v3Res; ml_float w; //We'll calculat w first, so that we can divide right away (we'll use 1.0f/w) w = 1.0f/(pM->_14*pV->x + pM->_24*pV->y + pM->_34*pV->z + pM->_44*1.0f); v3Res.x = (pM->_11*pV->x + pM->_21*pV->y + pM->_31*pV->z + pM->_41*1.0f)*w; v3Res.y = (pM->_12*pV->x + pM->_22*pV->y + pM->_32*pV->z + pM->_42*1.0f)*w; v3Res.z = (pM->_13*pV->x + pM->_23*pV->y + pM->_33*pV->z + pM->_43*1.0f)*w; *pOut=v3Res; return pOut; } ml_vec3* ML_FUNC ML_Vec3TransformNormal_F(ml_vec3* pOut, const ml_vec3* pV, const ml_mat* pM) { //Transform normal is only concerned with the rotation portion of the matrix: ml_vec3 v3Res; v3Res.x = (pM->_11*pV->x + pM->_21*pV->y + pM->_31*pV->z); v3Res.y = (pM->_12*pV->x + pM->_22*pV->y + pM->_32*pV->z); v3Res.z = (pM->_13*pV->x + pM->_23*pV->y + pM->_33*pV->z); *pOut=v3Res; return pOut; } ml_vec4* ML_FUNC ML_Vec3TransformArray(ml_vec4* pOut, ml_uint nOutStride, const ml_vec3* pV, ml_uint nInStride, const ML_MAT* pM, ml_uint nNum) { ml_uint i; for(i=0; i<nNum; i++) ML_Vec3Transform((ml_vec4*)((ml_byte*)pOut+i*nOutStride), (ml_vec3*)((ml_byte*)pV+i*nInStride), pM); return pOut; } ml_vec3* ML_FUNC ML_Vec3TransformCoordArray(ml_vec3* pOut, ml_uint nOutStride, const ml_vec3* pV, ml_uint nInStride, const ML_MAT* pM, ml_uint nNum) { ml_uint i; for(i=0; i<nNum; i++) ML_Vec3TransformCoord((ml_vec3*)((ml_byte*)pOut+i*nOutStride), (ml_vec3*)((ml_byte*)pV+i*nInStride), pM); return pOut; } ml_vec3* ML_FUNC ML_Vec3TransformNormalArray(ml_vec3* pOut, ml_uint nOutStride, const ml_vec3* pV, ml_uint nInStride, const ML_MAT* pM, ml_uint nNum) { ml_uint i; for(i=0; i<nNum; i++) ML_Vec3TransformNormal((ml_vec3*)((ml_byte*)pOut+i*nOutStride), (ml_vec3*)((ml_byte*)pV+i*nInStride), pM); return pOut; } <file_sep>/samples/MASMTest/Main.c /* Filename: Main.c */ #include <stdio.h> #ifdef __cplusplus extern "C" { #endif void MasmSub(char *, short *, long *); int __cdecl power2(int num, char power); #ifdef __cplusplus } #endif char chararray[4]="abc"; short shortarray[3]={1,2,3}; long longarray[3]={32768, 32769, 32770}; int main(void) { printf("%s\n", chararray); printf("%d %d %d\n", shortarray[0], shortarray[1], shortarray[2]); printf("%ld %ld %ld\n", longarray[0], longarray[1], longarray[2]); MasmSub(chararray, shortarray, longarray); printf("%s\n", chararray); printf("%d %d %d\n", shortarray[0], shortarray[1], shortarray[2]); printf("%ld %ld %ld\n", longarray[0], longarray[1], longarray[2]); //printf("The result is: %i\n", power2(3, 5)); return 0; }<file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/lg_err.c /********************************************************* File: lg_err.c Copyright (c) 2006, <NAME> Purpose: Contains various functions for initializing error reporting, and for reporting errors. *********************************************************/ #include "common.h" #include <windows.h> #include <stdio.h> #include <stdarg.h> #include <d3d9.h> #include <lc_sys.h> #include "lg_err.h" #include "dxerr9.h" #include "lg_sys.h" HLCONSOLE g_console=L_null; /* Global, stores the console that will receive error reports.*/ /****************************************************** Err_InitReporting() Initialized error reporting by setting the console to report to. ******************************************************/ void Err_InitReporting(HLCONSOLE hConsole) { g_console=hConsole; } /********************************************************* Err_Printf() Prints formatted text to the specifed console, or if a console has not been initialized reports to stdout. *********************************************************/ L_int Err_Printf(const char* format, ...) { char szOutput[MAX_ERR_MSG_LEN]; va_list arglist=L_null; int nResult=0; va_start(arglist, format); _vsnprintf(szOutput, MAX_ERR_MSG_LEN-1, format, arglist); if(g_console) nResult=Con_SendMessage(g_console, szOutput); else nResult=printf(szOutput); va_end(arglist); return nResult; } /************************************************ Err_PrintDX() Prints a directx error code and description. ************************************************/ L_int Err_PrintDX(const char* function, L_result nResult) { char szOutput[MAX_ERR_MSG_LEN]; _snprintf( szOutput, MAX_ERR_MSG_LEN-1, "%s returned %s (%s).", (char*)function, DXGetErrorString9(nResult), DXGetErrorDescription9(nResult)); return Con_SendMessage(g_console, szOutput); } L_int Err_PrintVersion() { return Err_Printf("%s %s", LGAME_NAME, "BUILD "LGAME_VERSION" ("__DATE__" "__TIME__")"); } void Err_ErrBox(const char* format, ...) { char szOutput[1024]; va_list arglist=L_null; int nResult=0; va_start(arglist, format); _vsnprintf(szOutput, 1024-1, format, arglist); MessageBox(0, szOutput, "Error Message", MB_OK); va_end(arglist); } void Err_PrintMatrix(D3DMATRIX* pM) { Err_Printf("| %f\t %f\t %f\t %f|", pM->_11, pM->_12, pM->_13, pM->_14); Err_Printf("| %f\t %f\t %f\t %f|", pM->_21, pM->_22, pM->_23, pM->_24); Err_Printf("| %f\t %f\t %f\t %f|", pM->_31, pM->_32, pM->_33, pM->_34); Err_Printf("| %f\t %f\t %f\t %f|", pM->_41, pM->_42, pM->_43, pM->_44); } <file_sep>/games/Legacy-Engine/Source/engine/li_sys.h #ifndef __LI_SYS_H__ #define __LI_SYS_H__ #include <dinput.h> #include "common.h" typedef enum _LI_COMMAND{ COMMAND_MOVEFORWARD=0, COMMAND_MOVEBACK, COMMAND_MOVERIGHT, COMMAND_MOVELEFT, COMMAND_TURNRIGHT, COMMAND_TURNLEFT, COMMAND_MOVEUP, //Jumping, or swimming/flying up. COMMAND_MOVEDOWN, //Ducking or swimming/flying down. COMMAND_SPEED, COMMAND_PRIMARY_WEAPON, COMMAND_COUNT, }LI_COMMAND; typedef enum _LI_INPUTDEVICE{ DEV_KB=0, DEV_MOUSE, DEV_JOYSTICK, }LI_INPUTDEVICE; class LG_CACHE_ALIGN CLICommand { friend class CLInput; private: LI_COMMAND m_nCommand; LI_INPUTDEVICE m_nDevice; lg_byte m_nButton; lg_bool m_bActive; lg_bool m_bWasActivated; lg_bool m_bWillDeactivate; public: CLICommand(): m_nCommand(COMMAND_MOVEFORWARD), m_nDevice(DEV_KB), m_nButton(0), m_bActive(0), m_bWasActivated(0), m_bWillDeactivate(0) { } lg_bool IsActive(){return m_bActive;} lg_bool Activated(){return m_bWasActivated;} void Init(LI_COMMAND cmd, LI_INPUTDEVICE dev, lg_byte nButton) { m_nCommand=cmd; m_nDevice=dev; m_nButton=nButton; } }; class CLAxis { public: CLAxis():nY(0),nX(0){} const lg_long nX; const lg_long nY; }; class CElementInput { public: static CLICommand* s_pCmds; static CLAxis* s_pAxis; }; class CLInput: public CElementInput { private: //DirectInput interfaces (we always have a mouse and keyboard) IDirectInput8* m_pDI; IDirectInputDevice8* m_pKB; lg_bool m_bExclusiveKB; lg_byte m_kbData[256]; //Keyboard_data. lg_byte m_nConKey; lg_float m_fXSense; //X axis sensitivity. lg_float m_fYSense; //y axis " ". IDirectInputDevice8* m_pMouse; lg_bool m_bExclusiveMouse; lg_bool m_bSmoothMouse; DIMOUSESTATE2 m_mouseState; //Mouse Data LONG m_nLastX, m_nLastY; HWND m_hwnd; lg_bool m_bInitialized; CLICommand m_Commands[COMMAND_COUNT]; CLAxis m_Axis; //The axis movment. //The following is a compact way to store commands, //rather than have an individual structure all commands //are store inside of flags, see examples for usage. public: lg_dword m_nCmdsActive[COMMAND_COUNT/32+1]; lg_dword m_nCmdsPressed[COMMAND_COUNT/32+1]; lg_float m_fAxis[2]; private: void InitCommands(); public: CLInput(); ~CLInput(); #define LINPUT_EXCLUSIVEKB 0x00000001 #define LINPUT_EXCLUSIVEMOUSE 0x00000002 #define LINPUT_DISABLEWINKEY 0x00000004 #define LINPUT_SMOOTHMOUSE 0x00000008 lg_bool LI_Init(HWND hwnd, lg_dword nFlags, lg_byte nConKey); void LI_Shutdown(); #define LIS_OK 0x00000001 #define LIS_CONSOLE 0x00000002 #define LIERR_FAIL 0x10000000 #define LI_UPDATE_MOUSE 0x00000001 #define LI_UPDATE_KB 0x00000002 #define LI_UPDATE_GP 0x00000004 #define LI_UPDATE_ALL 0x0000000F lg_result LI_Update(lg_dword Flags); //Update all input device (should be called once per frame before AI is processed). const lg_byte* GetKBData(); const DIMOUSESTATE2* GetMouseData(); CLICommand* GetCommand(LI_COMMAND cmd); CLICommand* GetCommands(); CLAxis* GetAxis(); void LI_ResetStates(); private: __inline void LI_InitKB(lg_dword Flags); __inline void LI_InitMouse(lg_dword Flags); void UpdateCommands(); }; #endif __LI_SYS_H__<file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/ls_load.c #include "common.h" #include <dsound.h> #include "lg_err.h" #include "lg_sys.h" #include "ls_wav.h" #include "ls_ogg.h" #include "ls_load.h" L_result LS_FillBuffer( SNDCALLBACKS* pCB, IDirectSound8* lpDS, IDirectSoundBuffer8** lppBuffer, L_dword dwBufferFlags, char* szFilename) { IDirectSoundBuffer* lpTempBuffer=L_null; DSBUFFERDESC desc; void* lpLockedBuffer=L_null; L_dword dwBufferBytes=0; L_dword dwBytesRead=0; void* lpSnd=L_null; L_result nResult=0; if(!pCB || !lpDS) return LG_FAIL; lpSnd=pCB->Snd_CreateFromDisk(szFilename); if(!lpSnd) return LG_FAIL; memset(&desc, 0, sizeof(desc)); desc.dwSize=sizeof(DSBUFFERDESC); desc.dwFlags=dwBufferFlags; desc.dwBufferBytes=pCB->Snd_GetSize(lpSnd); desc.lpwfxFormat=pCB->Snd_GetFormat(lpSnd, L_null); nResult=lpDS->lpVtbl->CreateSoundBuffer(lpDS, &desc, &lpTempBuffer, L_null); if(L_failed(nResult)) { pCB->Snd_Delete(lpSnd); Err_PrintDX("IDirectSound8::CreateSoundBuffer", nResult); return LG_FAIL; } lpTempBuffer->lpVtbl->QueryInterface( lpTempBuffer, &IID_IDirectSoundBuffer8, (void**)lppBuffer); IDirectSoundBuffer_Release(lpTempBuffer); nResult=IDirectSoundBuffer8_Lock( (*lppBuffer), 0, 0, &lpLockedBuffer, &dwBufferBytes, L_null, L_null, DSBLOCK_ENTIREBUFFER); if(L_failed(nResult)) { Err_PrintDX("IDirectSoundBuffer8::Lock", nResult); pCB->Snd_Delete(lpSnd); IDirectSoundBuffer8_Release((*lppBuffer)); return LG_FAIL; } dwBytesRead=pCB->Snd_Read(lpSnd, (void*)lpLockedBuffer, dwBufferBytes); if(dwBytesRead<1) { pCB->Snd_Delete(lpSnd); IDirectSoundBuffer8_Release((*lppBuffer)); return LG_FAIL; } nResult=IDirectSoundBuffer8_Unlock((*lppBuffer), lpLockedBuffer, dwBufferBytes, L_null, 0); pCB->Snd_Delete(lpSnd); if(L_failed(nResult)) { Err_PrintDX("IDirectSoundBuffer8::Unlock", nResult); /* Not sure what to do if we can't unlock it. */ } return LG_OK; } L_result LS_LoadSound( IDirectSound8* lpDS, IDirectSoundBuffer8** lppBuffer, L_dword dwBufferFlags, char* szFilename) { L_dword dwLen=0; L_dword i=0; char *szExt=szFilename; dwLen=L_strlen(szFilename); for(i=dwLen; i>0; i--) { if(szFilename[i]=='.') { szExt=&szFilename[i+1]; break; } } if(L_strnicmp(szExt, "ogg", 0)) return LS_FillBuffer( LS_GetCallbacks("ogg"), lpDS, lppBuffer, dwBufferFlags, szFilename); else /* We just try as a wave if, it isn't a previous type. */ return LS_FillBuffer( LS_GetCallbacks("wav"), lpDS, lppBuffer, dwBufferFlags, szFilename); return LG_OK; } SNDCALLBACKS* LS_GetCallbacks(char* szType) { static SNDCALLBACKS cbOgg={ Ogg_CreateFromDisk, /*Ogg_CreateFromData,*/ Ogg_Delete, Ogg_Read, Ogg_Reset, Ogg_GetFormat, Ogg_GetSize, Ogg_IsEOF}; static SNDCALLBACKS cbWav={ Wav_CreateFromDisk, /*Wav_CreateFromData,*/ Wav_Delete, Wav_Read, Wav_Reset, Wav_GetFormat, Wav_GetSize, Wav_IsEOF}; if(L_strnicmp(szType, "ogg", 0)) return &cbOgg; else if(L_strnicmp(szType, "wav", 0)) return &cbWav; return L_null; } <file_sep>/tools/img_lib/img_lib2/img_lib/img_gif.c #include <memory.h> #include <malloc.h> #include "img_private.h" #include "ungif-4x\gif_lib.h" int DGifSlurp(GifFileType * GifFile); IMG_CALLBACKS* g_pCB=NULL; int __cdecl ReadGif(GifFileType * pGifFile, GifByteType * pBuffer, int nSize) { return g_pCB->read(pBuffer, 1, nSize, pGifFile->UserData); } HIMG IMG_LoadGIFCallbacks(img_void* stream, IMG_CALLBACKS* lpCB) { IMAGE_S* pImage=IMG_NULL; GifFileType* pGifFile=IMG_NULL; ColorMapObject* pCM=IMG_NULL; g_pCB=lpCB; //Seek to the beginning of the file. lpCB->seek(stream, 0, IMG_SEEK_SET); pGifFile=DGifOpen(stream, ReadGif); if(!pGifFile) { return IMG_NULL; } //We have a valid GIF, lets decode it. if(DGifSlurp(pGifFile)!=GIF_OK) { DGifCloseFile(pGifFile); return IMG_NULL; } pImage=malloc(sizeof(IMAGE_S)); if(!pImage) { DGifCloseFile(pGifFile); return IMG_NULL; } pCM=pGifFile->SavedImages[0].ImageDesc.ColorMap?pGifFile->SavedImages[0].ImageDesc.ColorMap:pGifFile->SColorMap; memset(pImage, 0, sizeof(IMAGE_S)); pImage->nWidth=pGifFile->SavedImages[0].ImageDesc.Width;//pGifFile->Image.Width; pImage->nHeight=pGifFile->SavedImages[0].ImageDesc.Height; pImage->nBitDepth=8; pImage->nDataFmt=IMGFMT_PALETTE; pImage->nOrient=IMGORIENT_TOPLEFT; pImage->nPaletteBitDepth=24; pImage->nPaletteFmt=IMGFMT_B8G8R8; pImage->nPaletteEntries=pCM->ColorCount; pImage->nPaletteSize=pImage->nPaletteEntries*pImage->nPaletteBitDepth/8; pImage->nDataSize=pImage->nWidth*pImage->nHeight*pImage->nBitDepth/8; pImage->pImage=malloc(pImage->nDataSize); pImage->pPalette=malloc(pImage->nPaletteSize); if(!pImage->pImage || !pImage->pPalette) { IMG_SAFE_FREE(pImage->pImage); IMG_SAFE_FREE(pImage->pPalette); IMG_SAFE_FREE(pImage); DGifCloseFile(pGifFile); return IMG_NULL; } memcpy(pImage->pPalette, pCM->Colors, pImage->nPaletteSize); if(!pGifFile->SavedImages[0].ImageDesc.Interlace) { memcpy(pImage->pImage, pGifFile->SavedImages[0].RasterBits, pImage->nDataSize); } else { //De-Interlace. img_dword i=0, j=0; img_byte* pSrcBits=(img_byte*)pGifFile->SavedImages[0].RasterBits; img_byte* pDestBits=(img_byte*)pImage->pImage; for(i=0,j=0; i<pImage->nHeight; i+=8,j++) { memcpy(pDestBits+i*pImage->nWidth, pSrcBits+j*pImage->nWidth, pImage->nWidth*pImage->nBitDepth/8); } for(i=4; i<pImage->nHeight; i+=8, j++) { memcpy(pDestBits+i*pImage->nWidth, pSrcBits+j*pImage->nWidth, pImage->nWidth*pImage->nBitDepth/8); } for(i=2; i<pImage->nHeight; i+=4, j++) { memcpy(pDestBits+i*pImage->nWidth, pSrcBits+j*pImage->nWidth, pImage->nWidth*pImage->nBitDepth/8); } for(i=1; i<pImage->nHeight; i+=2, j++) { memcpy(pDestBits+i*pImage->nWidth, pSrcBits+j*pImage->nWidth, pImage->nWidth*pImage->nBitDepth/8); } } DGifCloseFile(pGifFile); return pImage; } int DGifSlurp(GifFileType * GifFile) { int ImageSize; GifRecordType RecordType; SavedImage *sp; GifByteType *ExtData; SavedImage temp_save; temp_save.ExtensionBlocks = NULL; temp_save.ExtensionBlockCount = 0; do { if (DGifGetRecordType(GifFile, &RecordType) == GIF_ERROR) return (GIF_ERROR); switch (RecordType) { case IMAGE_DESC_RECORD_TYPE: if (DGifGetImageDesc(GifFile) == GIF_ERROR) return (GIF_ERROR); sp = &GifFile->SavedImages[GifFile->ImageCount - 1]; ImageSize = sp->ImageDesc.Width * sp->ImageDesc.Height; sp->RasterBits = (unsigned char *)malloc(ImageSize * sizeof(GifPixelType)); if (sp->RasterBits == NULL) { return GIF_ERROR; } if (DGifGetLine(GifFile, sp->RasterBits, ImageSize) == GIF_ERROR) return (GIF_ERROR); if (temp_save.ExtensionBlocks) { sp->ExtensionBlocks = temp_save.ExtensionBlocks; sp->ExtensionBlockCount = temp_save.ExtensionBlockCount; temp_save.ExtensionBlocks = NULL; temp_save.ExtensionBlockCount = 0; /* FIXME: The following is wrong. It is left in only for * backwards compatibility. Someday it should go away. Use * the sp->ExtensionBlocks->Function variable instead. */ sp->Function = sp->ExtensionBlocks[0].Function; } break; case EXTENSION_RECORD_TYPE: if (DGifGetExtension(GifFile, &temp_save.Function, &ExtData) == GIF_ERROR) return (GIF_ERROR); while (ExtData != NULL) { /* Create an extension block with our data */ if (AddExtensionBlock(&temp_save, ExtData[0], &ExtData[1]) == GIF_ERROR) return (GIF_ERROR); if (DGifGetExtensionNext(GifFile, &ExtData) == GIF_ERROR) return (GIF_ERROR); temp_save.Function = 0; } break; case TERMINATE_RECORD_TYPE: break; default: /* Should be trapped by DGifGetRecordType */ break; } } while (RecordType != TERMINATE_RECORD_TYPE); /* Just in case the Gif has an extension block without an associated * image... (Should we save this into a savefile structure with no image * instead? Have to check if the present writing code can handle that as * well.... */ if (temp_save.ExtensionBlocks) FreeExtension(&temp_save); return (GIF_OK); }<file_sep>/tools/CornerBin/CornerBin/IconDlg/README.TXT Welcome to CIconDialog, A freeware MFC dialog class to select an icon. This is based on the dialog that appears when you choose to change the icon for a shortcut in the Windows 95 / NT 4 shell. The actual appearance of the dialog is based on the new look dialog in IE4 PP2 which uses a larger list box to display the icons. Have a look on my web site or run the supplied sample to see what it looks like. Included is a simple dialog based application which shows how to use it. The class would be used in your application as follows: CIconDialog dlg(this); dlg.SetIcon(m_sFilename, m_nIconIndex); if (dlg.DoModal() == IDOK) dlg.GetIcon(m_sFilename, m_nIconIndex); The variables m_sFilename and m_nIconIndex would be managed by your application. To use CIconDialog in your project simply include icondlg.cpp, the 5 string resources and the dialog resource IDD_CHOOSE_ICON from the test application in your application. Then just #include "icondlg.h" in which ever class needs to use it. Happy coding. CONTACTING THE AUTHOR <NAME> Email: <EMAIL> Web: http://www.naughter.com 12th April 2000 <file_sep>/games/Sometimes-Y/README.md Sometimes-Y =========== A scrapped game project by Beem Software. IP is open, if you want to read the game documentation and make an iPhone game with this and become a millionaire off of it, be my guest.<file_sep>/games/readme.txt QBasic-Games ============ Beem Software's early QBasic code including games! Beem's first game every was also a QBasic game but it isn't featured in this repository. The game was called Castle, and it evolved to a Windows game, so it has it's own repository at https://github.com/beemfx/Castle Bomb (Bomb) =========== Beem's first game that featured graphics. A first person shooter. Archer (Archer) =============== Beem's second first person shooter. Sort of a sequel to Bomb except this time you actually had to aim at the enemy, and you could be killed. Joe's Copter (Joes) =================== Beem's first side scroller game. This was to be followed up by Joe's Copter 2 which was never completed. Night Killers 2 (Night2) ======================== After StarCraft came out I was excited for StarCraft 2, so I made an intro video to SCII. Then thinking that that might be a copyright violation I changed the title of my video to Night Killers 2. Making a video in code isn't easy. Huckleberry's Adventure (Huckl) =============================== In the 10th grade I had to do a project on the Twain's The Adventures of Huckleberry Finn. It was a personal choice project. Knowing a thing or two about programming, I decided to make a video game. This is that game. One of my friends mentioned to me that the teacher had said that the game didn't really meet the requirements of the project, but because it was a video game it was so freaking cool that I got an A anyway. Dice Exposition (Dicexpo) ========================= A dice based gambling game. Never completed. Misc Code (Misc) ================ Various QBasic code I've written. No games.<file_sep>/games/Legacy-Engine/Source/engine/lg_hash_mgr.h /* lg_hash_mgr.h - The Hash Item Manager. Copyright (c) 2008 <NAME>. The Legacy engine uses quite a few managers to manage resources. Hashing seems to be one of the fastest ways to store and locate resources. I had developed three hash managers already, and it occured to me that I'd be developing more, so I decided to create a base template class, that could be used for multiple hash managers, that way I didn't have to duplicate code, if I found that there was a problem with a manager's hashing then I'd only have to change it in one class and so forth. The idea behind this class is that it is inherited by a parent class, at which time the parent indicates the type of item stored in the hash. This class is primarily designed to store resources with an associated filename, and the filename can be used to locate the resource needed. When overriding it is necessary to realize that The base class will allocate and deallocate memory, but any resources that have been loaded need to be deleted, or released, before the destructor of this base class is called. Further DoLoad and DoDestroy must be overloaded as they specify how a resource should be loaded and destroyed (or released). All items are obtained by reference. That is the manager returns an unsigned long (hm_item) that can then be used to reference the item obtained. Individual classes may have a method such as GetInterface that might retrun and actual interface or class, or they may have methods such as SetTexture which works only internally to Set the current rendering texture, for instance (See the CLTMgr class). See the comments before each method, for more specific usage, the user important methods are located at the bottom of the class. Currently this is used for: CLTMgr CLFxMgr Should be used for: CLSkelMgr CLMeshMgr */ #ifndef __LG_HASH_MGR_H__ #define __LG_HASH_MGR_H__ #include "lg_func.h" #include "lg_types.h" #include "lg_err.h" #include "lg_err_ex.h" //All items are represented by hm_item, in this way //they are used by reference rather than by the actual //item. Only the hash manager itself should do //anything with the items. typedef unsigned long hm_item; template<class T> class CLHashMgr { //Constants and flags: protected: //Internally Used Values: //Empty node is used to specify a hash location //that currently does not have an item associated //with it. const static lg_dword HM_EMPTY_NODE=0xFFFFFFFF; //A memory node is one in which an item exists at //that hash location, but it doesn't have a hash //code associated with it, can be used in classes //that which too, but it is not used in the base //class. const static lg_dword HM_MEMORY_NODE=0xFFFFFFD; //Null is an item with a zero reference. This //is never returned by the Load method, as eve //if an item could not be laoded, HM_DEFAULT_ITEM //is returned. const static hm_item HM_NULL_ITEM=0x00000000; //The default item, note that it is item 1, //in that way it is the first item in the list. //Default items must be specified in the parent //classes constructor. By default it is just //a NULL item. const static hm_item HM_DEFAULT_ITEM=0x00000001; //Internal structures: protected: //A list of item node structures is where all the //data is stored. LG_CACHE_ALIGN struct ItemNode{ T* pItem; //The pointer to the item stored. lg_void* pExtra; //Any extra data that the manager may want to use. lg_path szName; //The name of the item, usually the filename, but can be anything. lg_dword nFlags; //Flags associated with the item, passed to the DoLoad function. lg_dword nHashCode; //The hash code associated with this item. lg_dword nHashCount; //The hash count associated with the spot in the list (may want to change this to nNextMatchingHash instead). }; //Internal data: protected: lg_string m_szMgrName; //Stores the name of the manager, for debugging. const lg_dword m_nMaxItems; //Maximum number of items allowed in the list, unchangeable. ItemNode* m_pItemList; //The hash list of items, note that m_pItemList[0] is reserved for the default item. //Internal methods: protected: /* PRE: Constructor: Should be called from the inherited class's constructor. POST: Memory is allocated for the items, all items set to empty. */ CLHashMgr(lg_dword nMaxItem, lg_string szMgrName) : m_nMaxItems(nMaxItem) { //Allocate memory for the hash list, and throw a memory //exception if we are out. m_pItemList=new ItemNode[m_nMaxItems]; if(!m_pItemList) { throw LG_ERROR(LG_ERR_OUTOFMEMORY, "Ran out of memory!"); } //Start by setting all the items to empty, //and setting the hashcount to 0 for all of them. for(lg_dword i=0; i<m_nMaxItems; i++) { m_pItemList[i].nHashCode=HM_EMPTY_NODE; m_pItemList[i].nHashCount=0; } //Save the name of the manager, this is used in error messages. LG_strncpy(m_szMgrName, szMgrName, LG_MAX_STRING); //Setup some stuff for the default item. //Note that it's hash code is 0, and no other //functions should ever be hashed as zero. m_pItemList[0].nHashCode=0; m_pItemList[0].nHashCount=1; m_pItemList[0].nFlags=0; m_pItemList[0].pItem=LG_NULL; m_pItemList[0].pExtra=LG_NULL; m_pItemList[0].szName[0]=0; } /* PRE: N/A POST: Destroys everything, unloads all items, and deallocates memory associated. */ ~CLHashMgr() { LG_SafeDeleteArray(m_pItemList); } //Internal use only methods: private: /* PRE: Called only from LoadItem. POST: Basically a check to see if an item is already loaded in the manager. If it is, it is returned and LoadItem method ends quickly. If it isn't The manager knows it must load the item. 0 means the item does not exist. */ hm_item GetItem(lg_path szFilename, lg_dword* pHash) { //First get the hash for the item, then see if it is loaded. //The hash should limit the items to be from 1 to m_nMaxItems-1. //This way location 0 is always reserved for the default itme. *pHash=LG_HashFilename(szFilename)%(m_nMaxItems-1)+1; //If the hash count for the hash is 0 then there is no //matching hash, and we know the item isn't loaded. if(m_pItemList[*pHash].nHashCount==0) { return HM_NULL_ITEM; } //Since the hash index is not empty we'll search until we either //find a matching node, or exhaust the search. //For each index in the hash list we keep a count of how //many nodes use that hash, this speeds up the search, so //we don't have to loop through the entire list to find //our node, we just need to search through till we find //all the nodes that have the mathcing hash. lg_dword nSearchCount=m_pItemList[*pHash].nHashCount; //We keep track of the location we are currently searching, //naturally we start with the current hash, hopefully this //is where the item we want is actually stored, then our //method will return quickly. lg_dword nSearchLoc=*pHash; //Now we do a loop, where we continue to search for a mathcing //node, or until we've searched and found all the nodes that //matched the hash, but didn't find the node we wanted. while(nSearchCount>0) //If the search count drops to zero we've found all matching hashes, and didn't find the node. { //If the item we're searching at has a matching hash //we need to do a specific check. if(m_pItemList[nSearchLoc].nHashCode==*pHash) { //POTENTIAL EXIT POINT: if(strncmp(m_pItemList[nSearchLoc].szName, szFilename, LG_MAX_PATH)==0) return nSearchLoc+1; //Add one so we don't have a zero reference. else nSearchCount--; //If the hash didn't match the node, we have one less node to search for. } //We now move our search to the next index, note that //our indexes wrap around, so if we get to the maximum hash //we simply wrap around, that is why our increment is not simply //nSearchLoc++, this does mean that if we loop we'll //end up going through the default item, but the search should //still be quick. nSearchLoc=(nSearchLoc+1)%m_nMaxItems; //The following is just a check to make sure, our code is correct. //If we loop all the way around to the initial node, then it means //that the number stored in m_ItemList[*pHash].nHashCount was //incorrect, and that means that there was an error somewhere in //our code. if(nSearchLoc==*pHash) { throw LG_ERROR(LG_ERR_UNKNOWN, LG_TEXT("HashMgr ERROR: Looped through list and didn't exhaust search. Check Code.")); } } //If we exhausted the search, and didn't find anything we //return 0 for empty. return HM_NULL_ITEM; } /* User methods, these are the methods that are used in an individual manager, or that need to be overridden. The user also has access to the list, the maximum items avaailabe, and the default item. These variables can be used, but should generally not be altered. */ //Private Ones: private: /* PRE: Called only from the LoadItem method. POST: Loads the item, flags can be used to specify how the item is loaded. Notes: Must be overridden, typically should use the filename to laod some kind of resource, and flags are specific to the class. This is called when the Load method returns a new resource, but it can be called for any reason the user may see fit, such as for validating D3D objects, loading the default item, etc. */ virtual T* DoLoad(lg_path szFilename, lg_dword nFlags)=0; /* PRE: Called only from the UnloadItems method. POST: Should destroy the item, deallocate, or release it. Nost: Must be overridden, should destroy the item obtained, by DoLoad, deallocate any memory associated, or release the item, etc. Called whenever an item is unloaded, as in UnloadItems, but may be called for other reasons as well (such as destroying the default item). */ virtual void DoDestroy(T* pItem)=0; //Public ones: public: /* PRE: Used to load an item, calls DoLoad() which must be overridden. Flags are pass to DoLoad and are used there, they can also be used in the UnloadItems. POST: If the filename was not a valid item, then the default item will be returned. Notes: Called only to load an item, should not be overriden, and should not be modified. */ hm_item Load(lg_path szFilename, lg_dword nFlags) { //We first attempt to get the item, if we find it //we can return it. lg_dword nHash; hm_item itemOut=GetItem(szFilename, &nHash); if(itemOut) { Err_Printf(LG_TEXT("%s: Obtained \"%s\"."), m_szMgrName, szFilename); return itemOut; } //If not we need to load it: //So first we need to find an empty spot in our list: lg_dword nLoc=nHash; while(m_pItemList[nLoc].nHashCode!=HM_EMPTY_NODE) { //Search through the list in a circular manner. nLoc=(nLoc+1)%m_nMaxItems; //If wee looped through the entire list then we don't //have any more room. if(nLoc==nHash) { //POTENTIAL EXIT POINT: Err_Printf(LG_TEXT("%s ERROR: Max textures laoded. Can't load \"%s\"."), m_szMgrName, szFilename); Err_Printf(LG_TEXT("%s: Obtained default texure instead."), m_szMgrName); return HM_DEFAULT_ITEM; } } //We found a spot so let's do the load procedure: T* pOut=DoLoad(szFilename, nFlags); //If we ended up obtaining the default item //then we'll update that data. if(!pOut) { Err_Printf(LG_TEXT("%s: Obtained default item."), m_szMgrName); return HM_DEFAULT_ITEM; } else { //Increase the item count under the correct hash m_pItemList[nHash].nHashCount++; //Everything else is updated under the location m_pItemList[nLoc].nFlags=nFlags; m_pItemList[nLoc].nHashCode=nHash; LG_strncpy(m_pItemList[nLoc].szName, szFilename, LG_MAX_PATH); m_pItemList[nLoc].pItem=pOut; Err_Printf(LG_TEXT("%s: Loaded \"%s\" %i@%i"), m_szMgrName, szFilename, nHash, nLoc); } return nLoc+1; //We add 1 so the reference so 0 can be null. } /* PRE: item, must be an item in the list. POST: Removes the item from the manager, calling the DoDestroy method. Notes: This method isn't typically used as the point of the manager, is that it can find resources as needed without reloading them. Typically resources would be unloaded and relaoding between map loads, where different resources are used. */ void Unload(hm_item item) { //Can't remove the default item, or a null item if(item<=HM_DEFAULT_ITEM) { Err_Printf( "%s ERROR: Attempted to either Unload the default item, or a null item.", m_szMgrName); return; } //Decrease the reference of the item to match it //with the hash list. item--; //If the node isn't a memory object (e.g. a lightmap) //then we need to decrease the hash count, see above //for remarks concerning HM_MEMORY_NODE. if(m_pItemList[item].nHashCode!=HM_MEMORY_NODE) m_pItemList[m_pItemList[item].nHashCode].nHashCount--; //Zero out the information and Destroy the item. m_pItemList[item].nHashCode=HM_EMPTY_NODE; DoDestroy(m_pItemList[item].pItem); m_pItemList[item].pItem=LG_NULL; Err_Printf("%s: Unloaded \"%s\".", m_szMgrName, m_pItemList[item].szName); m_pItemList[item].szName[0]=0; } /* PRE: N/A POST: Unloads all items, except the default item. Notes: Will call teh DoDestroy method for every item stored in the manager. Should be called in the overriding class' destructor. The default item should also be destroyed in the destructor as well. */ void UnloadItems() { //We start at 1 in order to skip the default //item. for(lg_dword i=1; i<m_nMaxItems; i++) { if(m_pItemList[i].nHashCode!=HM_EMPTY_NODE) { if(m_pItemList[i].nHashCode!=HM_MEMORY_NODE) m_pItemList[m_pItemList[i].nHashCode].nHashCount--; m_pItemList[i].szName[0]=0; m_pItemList[i].nHashCode=HM_EMPTY_NODE; DoDestroy(m_pItemList[i].pItem); m_pItemList[i].pItem=LG_NULL; } } } /* PRE: N/A POST: Prints debug info about the items in the list, the default item is in spot 0. */ void PrintDebugInfo() { for(lg_dword i=0; i<m_nMaxItems; i++) { if(m_pItemList[i].nHashCode==CLHashMgr::HM_EMPTY_NODE) Err_Printf("%i Empty (%i)", i+1, m_pItemList[i].nHashCount); else if(m_pItemList[i].nHashCode==CLHashMgr::HM_MEMORY_NODE) Err_Printf("%i MEMORY (%i)", i+1, m_pItemList[i].nHashCount); else Err_Printf("%i \"%s\" %i@%i (%i)", i+1, m_pItemList[i].szName, m_pItemList[i].nHashCode, i, m_pItemList[i].nHashCount); } } }; #endif __LG_HASH_MGR_H__<file_sep>/games/Explor2002/Source/Game/Ddsetup.cpp #include <windows.h> #include <windowsx.h> #include <ddraw.h> #include "defines.h" #include "ddsetup.h" #include "resource.h" extern LPDIRECTDRAW lpDirectDrawObject; extern LPDIRECTDRAWSURFACE lpPrimary; extern LPDIRECTDRAWSURFACE lpSecondary; extern LPDIRECTDRAWSURFACE lpBackground; extern DWORD g_dwTransparentColor; extern HWND g_hwnd; extern int g_nColorDepth; extern int g_nScreenWidth, g_nScreenHeight; //Sets Transparent Color DWORD color(COLORREF rgb, LPDIRECTDRAWSURFACE surface){ DWORD dw=CLR_INVALID; COLORREF rgbT; HDC hDc; DDSURFACEDESC ddsd; HRESULT hres; if(rgb!=CLR_INVALID&&SUCCEEDED(surface->GetDC(&hDc))){ rgbT=GetPixel(hDc, 0, 0); SetPixel(hDc, 0, 0, rgb); surface->ReleaseDC(hDc); } ddsd.dwSize=sizeof(ddsd); while((hres=surface->Lock(NULL, &ddsd, 0, NULL))==DDERR_WASSTILLDRAWING); if(SUCCEEDED(hres)){ dw=*(DWORD*)ddsd.lpSurface; if(ddsd.ddpfPixelFormat.dwRGBBitCount!=32) dw&=(1<<ddsd.ddpfPixelFormat.dwRGBBitCount)-1; surface->Unlock(NULL); } if(rgb!=CLR_INVALID&&SUCCEEDED(surface->GetDC(&hDc))){ SetPixel(hDc, 0, 0, rgbT); surface->ReleaseDC(hDc); } return dw; } BOOL InitSurfaces(HWND hWnd){ DDSURFACEDESC ddsd; ddsd.dwSize=sizeof(ddsd); ddsd.dwFlags=DDSD_CAPS|DDSD_BACKBUFFERCOUNT; ddsd.ddsCaps.dwCaps=DDSCAPS_PRIMARYSURFACE|DDSCAPS_FLIP|DDSCAPS_COMPLEX; ddsd.dwBackBufferCount=BACK_FUFFER_COUNT; if(FAILED(lpDirectDrawObject->CreateSurface(&ddsd, &lpPrimary, NULL)))return FALSE; DDSCAPS ddscaps; ddscaps.dwCaps=DDSCAPS_BACKBUFFER; if(FAILED(lpPrimary->GetAttachedSurface(&ddscaps, &lpSecondary)))return FALSE; ddsd.dwSize=sizeof(ddsd); ddsd.dwFlags=DDSD_CAPS|DDSD_HEIGHT|DDSD_WIDTH; ddsd.ddsCaps.dwCaps=DDSCAPS_OFFSCREENPLAIN; ddsd.dwHeight=g_nScreenHeight; ddsd.dwWidth=g_nScreenWidth; if(FAILED(lpDirectDrawObject->CreateSurface(&ddsd,&lpBackground,NULL)))return FALSE; LPDIRECTDRAWCLIPPER lpClipper; if(FAILED(lpDirectDrawObject->CreateClipper(NULL,&lpClipper,NULL)))return FALSE; if(FAILED(lpClipper->SetHWnd(NULL,hWnd)))return FALSE; if(FAILED(lpSecondary->SetClipper(lpClipper)))return FALSE; g_dwTransparentColor=color(TRANSPARENT_COLOR,lpPrimary); return TRUE; } BOOL InitDirectDraw(HWND hWnd){ if(FAILED(DirectDrawCreate(NULL,&lpDirectDrawObject, NULL)))return FALSE; if(FAILED(lpDirectDrawObject->SetCooperativeLevel(hWnd,DDSCL_EXCLUSIVE| DDSCL_FULLSCREEN)))return FALSE; if(FAILED(lpDirectDrawObject->SetDisplayMode(g_nScreenWidth, g_nScreenHeight, g_nColorDepth)))return FALSE; if(!InitSurfaces(g_hwnd))return FALSE; return TRUE; } HWND CreateDefaultWindow(char *name, HINSTANCE hInstance){ WNDCLASS wndClass; wndClass.style=CS_HREDRAW|CS_VREDRAW; wndClass.lpfnWndProc=WindowProc; wndClass.cbClsExtra=wndClass.cbWndExtra=0; wndClass.hInstance=hInstance; wndClass.hIcon=LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1)); wndClass.hCursor=LoadCursor(hInstance, IDC_ARROW); wndClass.hbrBackground=NULL; wndClass.lpszMenuName=NULL; wndClass.lpszClassName=name; RegisterClass(&wndClass); return CreateWindowEx(WS_EX_TOPMOST, name, name, WS_POPUP,0,0,CW_USEDEFAULT, CW_USEDEFAULT,//GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CXSCREEN), NULL, NULL, hInstance, NULL); }<file_sep>/games/Sometimes-Y/SometimesY/WndGameView.cpp // WndGameView.cpp : implementation file // #include "stdafx.h" #include "SometimesY.h" #include "WndGameView.h" // CWndGameView IMPLEMENT_DYNAMIC(CWndGameView, CWnd) CWndGameView::CWndGameView(CSYGame* pGame) : m_pGame(pGame) { m_Font.CreateFont(36, 0, 0, 0, FW_BOLD, 0,0,0, ANSI_CHARSET,OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,DEFAULT_QUALITY, FF_DONTCARE, _T("Courier New")); m_mnuInsert.LoadMenu(IDR_MENU_INSERT); } CWndGameView::~CWndGameView() { } BEGIN_MESSAGE_MAP(CWndGameView, CWnd) ON_WM_PAINT() ON_WM_LBUTTONDOWN() ON_WM_RBUTTONDOWN() END_MESSAGE_MAP() // CWndGameView message handlers void CWndGameView::OnPaint() { CPaintDC dc(this); // device context for painting CFont* fntOld; CBrush* brshOld; dc.SetBkMode(TRANSPARENT); CBrush brshWhite(RGB(255, 255, 255)); CBrush brshBlack(RGB(0, 0, 0)); CBrush brshPlaced(RGB(200, 0, 0)); CBrush brshPlacedValid(RGB(0, 200, 0)); CBrush brshFixed(RGB(150, 150, 0)); CBrush brshFixedValid(RGB(255, 255, 0)); // TODO: Add your message handler code here // Do not call CWnd::OnPaint() for painting messages CRect rc; GetClientRect(&rc); brshOld=dc.SelectObject(&brshWhite); dc.Rectangle(&rc); fntOld=dc.SelectObject(&m_Font); //dc.TextOut(1, 2, CString(_T("Hi"))); DWORD sx, sy; m_pGame->GetSize(sx, sy); for(DWORD x=0; x<sx; x++) { for(DWORD y=0; y<sy; y++) { const CSYGame::Block* pBlk=m_pGame->GetBlock(x, y); TCHAR cBlock=0; switch(pBlk->nType) { case CSYGame::BLOCK_UNUSABLE: cBlock='X'; break; case CSYGame::BLOCK_A: cBlock='A'; break; case CSYGame::BLOCK_E: cBlock='E'; break; case CSYGame::BLOCK_I: cBlock='I'; break; case CSYGame::BLOCK_O: cBlock='O'; break; case CSYGame::BLOCK_U: cBlock='U'; break; case CSYGame::BLOCK_Y: cBlock='Y'; break; case CSYGame::BLOCK_EMPTY: cBlock=' '; break; } if(pBlk->nStatus==CSYGame::STATUS_PLACED) { dc.SelectObject((pBlk->bValid)?&brshPlacedValid:&brshPlaced); } else if(pBlk->nStatus==CSYGame::STATUS_FIXED) { dc.SelectObject(pBlk->bValid?&brshFixedValid:&brshFixed); } else dc.SelectObject(&brshWhite); rc.SetRect(x*40, y*40, x*40+40, y*40+40); if(cBlock=='X') { dc.SelectObject(&brshBlack); dc.Rectangle(rc); } else { dc.Rectangle(rc); dc.TextOutA(1+x*40+9, 1+y*40, CString(cBlock)); } } } //Draw the letters available: DWORD nCounts[6]; m_pGame->GetAvailLetters(nCounts); CString strOut; strOut.Format(_T("A - %d"), nCounts[0]); dc.TextOut(420, 50, strOut); strOut.Format(_T("E - %d"), nCounts[1]); dc.TextOut(420, 90, strOut); strOut.Format(_T("I - %d"), nCounts[2]); dc.TextOut(420, 130, strOut); strOut.Format(_T("O - %d"), nCounts[3]); dc.TextOut(420, 170, strOut); strOut.Format(_T("U - %d"), nCounts[4]); dc.TextOut(420, 210, strOut); strOut.Format(_T("Y - %d"), nCounts[5]); dc.TextOut(420, 250, strOut); dc.SelectObject(fntOld); dc.SelectObject(brshOld); } void CWndGameView::OnLButtonDown(UINT nFlags, CPoint point) { DWORD x=m_pntLastBlock.x = point.x/40; DWORD y=m_pntLastBlock.y = point.y/40; CString str; DWORD nCounts[6]; m_pGame->GetAvailLetters(nCounts); //str.Format(_T("You cliked box (%i, %i)"), x, y); //MessageBox(str); if(m_pGame->GetBlock(x, y)->nStatus!=m_pGame->STATUS_EMPTY) return; CMenu* pMenuLetters=m_mnuInsert.GetSubMenu(0); for(DWORD i=0; i<6; i++) { CString str; TCHAR c; switch(i){ case 0:c='A';break; case 1:c='E';break; case 2:c='I';break; case 3:c='O';break; case 4:c='U';break; case 5:c='Y';break; default:c='X';break; } str.Format(_T("%c: %i"), c, nCounts[i]); pMenuLetters->ModifyMenu(i, MF_BYPOSITION, ID_INSERT_A+i, str.GetBuffer()); pMenuLetters->EnableMenuItem(i, MF_BYPOSITION|(nCounts[i]>0?MF_ENABLED:MF_DISABLED)); } this->ClientToScreen(&point); pMenuLetters->TrackPopupMenu(TPM_LEFTALIGN |TPM_RIGHTBUTTON, point.x, point.y, this); CWnd::OnLButtonDown(nFlags, point); } void CWndGameView::OnRButtonDown(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default DWORD x = point.x/40; DWORD y = point.y/40; this->m_pGame->RemoveLetter(x, y); this->Invalidate(); CWnd::OnRButtonDown(nFlags, point); } BOOL CWndGameView::OnCommand(WPARAM wParam, LPARAM lParam) { switch(LOWORD(wParam)) { case ID_INSERT_A: m_pGame->PlaceLetter(CSYGame::BLOCK_A, this->m_pntLastBlock.x, m_pntLastBlock.y, NULL); Invalidate(); break; case ID_INSERT_E: m_pGame->PlaceLetter(CSYGame::BLOCK_E, this->m_pntLastBlock.x, m_pntLastBlock.y, NULL); Invalidate(); break; case ID_INSERT_I: m_pGame->PlaceLetter(CSYGame::BLOCK_I, this->m_pntLastBlock.x, m_pntLastBlock.y, NULL); Invalidate(); break; case ID_INSERT_O: m_pGame->PlaceLetter(CSYGame::BLOCK_O, this->m_pntLastBlock.x, m_pntLastBlock.y, NULL); Invalidate(); break; case ID_INSERT_U: m_pGame->PlaceLetter(CSYGame::BLOCK_U, this->m_pntLastBlock.x, m_pntLastBlock.y, NULL); Invalidate(); break; case ID_INSERT_Y: m_pGame->PlaceLetter(CSYGame::BLOCK_Y, this->m_pntLastBlock.x, m_pntLastBlock.y, NULL); Invalidate(); break; } return CWnd::OnCommand(wParam, lParam); } <file_sep>/games/Legacy-Engine/Scrapped/UnitTests/VarTest/Main.cpp #include <stdio.h> #include <conio.h> #include "var_mgr.h" using namespace var_sys; int main() { CVarMgr varMgr(30); varMgr.Register<var_word>(_T("var1"), 1, 0); varMgr.Register<var_word>(_T("var2"), 1, 0); varMgr.Register<var_word>(_T("var3"), 1, 0); varMgr.Register<var_word>(_T("var4"), 1, 0); varMgr.Register<var_word>(_T("var5"), 1, 0); varMgr.Register<var_word>(_T("var6"), 1, 0); varMgr.Register<var_word>(_T("var7"), 1, 0); varMgr.Register<var_word>(_T("var8"), 1, 0); varMgr.Register<var_word>(_T("var9"), 1, 0); varMgr.Register<var_word>(_T("var10"), 1, 0); varMgr.Register<var_word>(_T("var11"), 1, 0); varMgr.Register<var_float>(_T("var12"), 5.0f, CVar::F_ROM); varMgr.Register<var_long>(_T("var13"), -20, 0); varMgr.Register<var_word>(_T("var14"), 1, 0); varMgr.Register<var_word>(_T("var15"), 1, 0); varMgr.Register<var_word>(_T("var16"), 1, 0); varMgr.Register<var_word>(_T("var17"), 1, 0); varMgr.Register<var_word>(_T("var18"), 1, 0); varMgr.Register<var_word>(_T("var19"), 1, 0); varMgr.Register<var_word>(_T("var20"), 1, 0); varMgr.Register(_T("m_NewVar"), _T("Hello"), 0); varMgr.Register<var_word>(_T("var21"), 1, 0); varMgr.Define(_T("TRUE"), (var_word)1); varMgr.Define(_T("FALSE"), (var_word)0); varMgr.Define(_T("TEN"), (var_word)10); varMgr[_T("var1")].Set(_T("Hi")); lg_var var = varMgr[_T("var20")]; //This should not be able to register since it's already registered. lg_var othervar = varMgr.Register<var_word>(_T("var20"), 30, 0); var = _T("True"); var = varMgr[_T("m_NEwVar")]; var = _T("Ten"); wprintf(_T("The value of %s is: (%f) (%i) (%u) (0x%08X) (%s)\n"), var.Name(), var.Float(), var.Long(), var.Word(), var.Word(), var.String()); varMgr.DebugPrintList(); _getch(); return 0; } <file_sep>/games/Legacy-Engine/Source/LMEdit/LMEditDoc.h // LMEditDoc.h : interface of the CLMEditDoc class // #pragma once #include "lm_mesh_edit.h" #include "lm_skel_edit.h" class CLMEditDoc : public CDocument { friend class CLMEditView; protected: // create from serialization only CLMEditDoc(); DECLARE_DYNCREATE(CLMEditDoc) //Document input output for callbacks: static int CLMEditDoc::Doc_Close(void* stream); static lg_uint CLMEditDoc::Doc_Read(void* buffer, lg_uint size, lg_uint count, void* stream); static lg_uint CLMEditDoc::Doc_Write(void* buffer, lg_uint size, lg_uint count, void* stream); static long CLMEditDoc::Doc_Tell(void* stream); static int CLMEditDoc::Doc_Seek(void* stream, long offset, int origin); // Attributes public: // Operations public: // Overrides public: virtual BOOL OnNewDocument(); virtual void Serialize(CArchive& ar); // Implementation public: virtual ~CLMEditDoc(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // Generated message map functions protected: DECLARE_MESSAGE_MAP() CLMeshEdit m_cMesh; CString m_szMeshFilename; CLSkelEdit m_cSkel; CString m_szSkelFilename; public: virtual void OnCloseDocument(); BOOL SetDevice(IDirect3DDevice9* lpDevice); IDirect3DDevice9* m_pDevice; afx_msg void OnAnimationEditanimations(); public: afx_msg void OnAnimationImportframes(); public: virtual BOOL OnSaveDocument(LPCTSTR lpszPathName); public: virtual BOOL OnOpenDocument(LPCTSTR lpszPathName); public: virtual BOOL DoSave(LPCTSTR lpszPathName, BOOL bReplace = TRUE); public: BOOL OnSaveSkel(LPCTSTR lpszPathName); public: BOOL OnSaveMesh(LPCTSTR lpszPathName); public: virtual void SetTitle(LPCTSTR lpszTitle); public: afx_msg void OnAnimationCalculateaabb(); }; <file_sep>/samples/D3DDemo/code/MD3Base/MD3File.c /* MD3File.c - Functions for reading an MD3 file. Copyright (c) 2003 <NAME> */ #include "Defines.h" #include "MD3.h" #include "MD3File.h" BOOL ReadMD3File( HANDLE hFile, LPVOID lpBuffer, LPDWORD lpNumBytesRead, LPOVERLAPPED lpOverlapped) { LONG lHeaderOffset=0; BOOL bSuccess=FALSE; DWORD dwBytesRead=0; LPMD3FILE lpFile=NULL; LONG i=0; *lpNumBytesRead=0; lHeaderOffset=FindMD3Header(hFile, lpOverlapped); if(hFile==NULL)return FALSE; SetFilePointer(hFile, lHeaderOffset, 0, FILE_BEGIN); if(FAILED(GetLastError()))return FALSE; lpFile=(LPMD3FILE)lpBuffer; /* Begin by reading the MD3 File Header. */ bSuccess=ReadMD3Header( hFile, &(lpFile->md3Header), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0) )return FALSE; *lpNumBytesRead+=dwBytesRead; /* We have the header so lets make sure the information is correct. */ if( ( lpFile->md3Header.dwID != MD3_ID) )return FALSE; if( ( lpFile->md3Header.lVersion != MD3_VERSION) )return FALSE; /* Initialize and read frame data. */ lpFile->md3Frame=malloc(lpFile->md3Header.lNumFrames * sizeof(MD3FRAME)); if(lpFile->md3Frame == NULL)return FALSE; /* Set file pointer to appropriate location, then read the data. */ SetFilePointer(hFile, lpFile->md3Header.lFrameOffset+lHeaderOffset, 0, FILE_BEGIN); for(i=0; i<lpFile->md3Header.lNumFrames; i++){ if(!ReadMD3Frame(hFile, &(lpFile->md3Frame[i]), &dwBytesRead, lpOverlapped)){ SAFE_FREE(lpFile->md3Frame); return FALSE; } *lpNumBytesRead+=dwBytesRead; } /* Initialzie and read tag data. */ lpFile->md3Tag=malloc(lpFile->md3Header.lNumTags * lpFile->md3Header.lNumFrames * sizeof(MD3TAG) ); if(lpFile->md3Tag == NULL){ SAFE_FREE(lpFile->md3Frame); return FALSE; } /* Set file pointer to appropriate location. */ SetFilePointer(hFile, lpFile->md3Header.lTagOffset + lHeaderOffset, 0, FILE_BEGIN); for(i=0; i<lpFile->md3Header.lNumTags * lpFile->md3Header.lNumFrames; i++){ if(!ReadMD3Tag(hFile, &(lpFile->md3Tag[i]), &dwBytesRead, lpOverlapped)){ SAFE_FREE(lpFile->md3Frame); SAFE_FREE(lpFile->md3Tag); return FALSE; } *lpNumBytesRead+=dwBytesRead; } /* Next up Meshes need to be read. */ /* Allocate memory for meshes. */ lpFile->md3Mesh=malloc(lpFile->md3Header.lNumMeshes * sizeof(MD3MESH)); if(lpFile->md3Mesh == NULL){ SAFE_FREE(lpFile->md3Frame); SAFE_FREE(lpFile->md3Tag); return FALSE; } /* Set file pointer to appropriate position, then read the meshes. */ SetFilePointer(hFile, lpFile->md3Header.lMeshOffset + lHeaderOffset, 0, FILE_BEGIN); for(i=0; i<lpFile->md3Header.lNumMeshes; i++){ if(!ReadMD3Mesh(hFile, /*&md3Mesh*/&(lpFile->md3Mesh[i]), &dwBytesRead, lpOverlapped)){ SAFE_FREE(lpFile->md3Frame); SAFE_FREE(lpFile->md3Tag); /* Here I need to release any meshes that were created. */ for(i= (i-1); i>=0; i--){ DeleteMD3Mesh(&(lpFile->md3Mesh[i])); } SAFE_FREE((lpFile->md3Mesh)); return FALSE; } //DeleteMD3Mesh(&md3Mesh); *lpNumBytesRead+=dwBytesRead; } return TRUE; } BOOL DeleteMD3File( LPVOID lpFile) { LONG i=0; LPMD3FILE lpMd3File = (LPMD3FILE)lpFile; if(!lpFile)return FALSE; /* Free frame and tag data. */ SAFE_FREE( ( ((LPMD3FILE)lpFile)->md3Frame ) ); SAFE_FREE( ( ((LPMD3FILE)lpFile)->md3Tag ) ); /* Free each of the meshes. */ if( ((LPMD3FILE)lpFile)->md3Mesh){ for(i=0; i<((LPMD3FILE)lpFile)->md3Header.lNumMeshes; i++){ DeleteMD3Mesh( &( ((LPMD3FILE)lpFile)->md3Mesh[i] ) ); } /* Free the mesh array. */ SAFE_FREE( ( ((LPMD3FILE)lpFile)->md3Mesh ) ); } return TRUE; } BOOL ReadMD3Mesh( HANDLE hFile, LPVOID lpBuffer, LPDWORD lpNumBytesRead, LPOVERLAPPED lpOverlapped) { LONG lMeshOffset=0; LONG i=0; LPMD3MESH lpMesh=NULL; BOOL bSuccess=FALSE; DWORD dwBytesRead=0; *lpNumBytesRead=dwBytesRead; lMeshOffset=SetFilePointer(hFile, 0, NULL, FILE_CURRENT); lpMesh=(LPMD3MESH)lpBuffer; /* First read the mesh header. */ bSuccess=ReadMD3MeshHeader( hFile, &(lpMesh->md3MeshHeader), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0))return FALSE; *lpNumBytesRead+=dwBytesRead; if(lpMesh->md3MeshHeader.dwID != MD3_ID)return FALSE; /* Prepare shader data. */ lpMesh->md3Shader=malloc(lpMesh->md3MeshHeader.lNumShaders * sizeof(MD3SHADER)); if(lpMesh->md3Shader == NULL)return FALSE; /* Read shader. */ SetFilePointer(hFile, lMeshOffset+lpMesh->md3MeshHeader.lShaderOffset, 0, FILE_BEGIN); for(i=0; i<lpMesh->md3MeshHeader.lNumShaders; i++){ bSuccess=ReadMD3Shader( hFile, &(lpMesh->md3Shader[i]), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0) ){ SAFE_FREE(lpMesh->md3Shader); return FALSE; } *lpNumBytesRead+=dwBytesRead; } /* Prepare triangle data. */ lpMesh->md3Triangle=malloc(lpMesh->md3MeshHeader.lNumTriangles * sizeof(MD3TRIANGLE)); if(lpMesh->md3Triangle == NULL){ SAFE_FREE(lpMesh->md3Shader); return FALSE; } /* Read shader. */ SetFilePointer(hFile, lMeshOffset+lpMesh->md3MeshHeader.lTriangleOffset, 0, FILE_BEGIN); for(i=0; i<lpMesh->md3MeshHeader.lNumTriangles; i++){ bSuccess=ReadMD3Triangle( hFile, &(lpMesh->md3Triangle[i]), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0)){ SAFE_FREE(lpMesh->md3Shader); SAFE_FREE(lpMesh->md3Triangle); return FALSE; } *lpNumBytesRead+=dwBytesRead; } /* Prepare Texture coordinates. */ lpMesh->md3TexCoords=malloc(lpMesh->md3MeshHeader.lNumVertices * sizeof(MD3TEXCOORDS)); if(lpMesh->md3TexCoords == NULL){ SAFE_FREE(lpMesh->md3Shader); SAFE_FREE(lpMesh->md3Triangle); return FALSE; } /* Read texture coordinates. */ SetFilePointer(hFile, lMeshOffset+lpMesh->md3MeshHeader.lTexCoordOffset, 0, FILE_BEGIN); for(i=0; i<lpMesh->md3MeshHeader.lNumVertices; i++){ bSuccess=ReadMD3TexCoords( hFile, &(lpMesh->md3TexCoords[i]), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0) ){ SAFE_FREE(lpMesh->md3Shader); SAFE_FREE(lpMesh->md3Triangle); SAFE_FREE(lpMesh->md3TexCoords); return FALSE; } *lpNumBytesRead+=dwBytesRead; } /* Prepare vertex data. */ lpMesh->md3Vertex=malloc(lpMesh->md3MeshHeader.lNumVertices * lpMesh->md3MeshHeader.lNumFrames * sizeof(MD3VERTEX)); if(lpMesh->md3Vertex == NULL){ SAFE_FREE(lpMesh->md3Shader); SAFE_FREE(lpMesh->md3Triangle); SAFE_FREE(lpMesh->md3TexCoords); return FALSE; } /* Read vertex data. */ SetFilePointer(hFile, lMeshOffset+lpMesh->md3MeshHeader.lVertexOffset, 0, FILE_BEGIN); for(i=0; i<lpMesh->md3MeshHeader.lNumVertices * lpMesh->md3MeshHeader.lNumFrames; i++){ bSuccess=ReadMD3Vertex( hFile, &(lpMesh->md3Vertex[i]), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0) ){ SAFE_FREE(lpMesh->md3Shader); SAFE_FREE(lpMesh->md3Triangle); SAFE_FREE(lpMesh->md3TexCoords); SAFE_FREE(lpMesh->md3Vertex); return FALSE; } *lpNumBytesRead+=dwBytesRead; } /* Set the file pointer to the end of this surface. */ SetFilePointer(hFile, lpMesh->md3MeshHeader.lMeshDataSize+lMeshOffset, 0, FILE_BEGIN); return TRUE; } BOOL DeleteMD3Mesh( LPVOID lpMesh) { if(lpMesh==NULL)return FALSE; /* Free shader, vertex, texcoords, and triangle data. */ SAFE_FREE( ( ((LPMD3MESH)lpMesh)->md3Shader ) ); SAFE_FREE( ( ((LPMD3MESH)lpMesh)->md3Triangle ) ); SAFE_FREE( ( ((LPMD3MESH)lpMesh)->md3TexCoords ) ); SAFE_FREE( ( ((LPMD3MESH)lpMesh)->md3Vertex ) ); return TRUE; } LONG FindMD3Header( HANDLE hFile, LPOVERLAPPED lpOverlapped) { /* This function should seach through the file byte by byte until "IDP3", and MD3_VERSION are found. */ return 0; } BOOL ReadMD3Vertex( HANDLE hFile, LPVOID lpBuffer, LPDWORD lpNumBytesRead, LPOVERLAPPED lpOverlapped) { BOOL bSuccess=FALSE; DWORD dwBytesRead=0; MD3VERTEX md3Vertex; ZeroMemory(&md3Vertex, sizeof(MD3VERTEX)); *lpNumBytesRead=0; if(hFile==NULL)return FALSE; bSuccess=ReadFile( hFile, &(md3Vertex.x), sizeof(SHORT), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0) )return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3Vertex.y), sizeof(SHORT), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0) )return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3Vertex.z), sizeof(SHORT), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0) )return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3Vertex.nNormal), sizeof(SHORT), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0) )return FALSE; *lpNumBytesRead+=dwBytesRead; memcpy(lpBuffer, &md3Vertex, sizeof(MD3VERTEX)); return TRUE; } BOOL ReadMD3TexCoords( HANDLE hFile, LPVOID lpBuffer, LPDWORD lpNumBytesRead, LPOVERLAPPED lpOverlapped) { BOOL bSuccess=FALSE; DWORD dwBytesRead=0; MD3TEXCOORDS md3TexCoords; ZeroMemory(&md3TexCoords, sizeof(MD3TEXCOORDS)); *lpNumBytesRead=0; if(hFile==NULL)return FALSE; bSuccess=ReadFile( hFile, &(md3TexCoords.tu), sizeof(FLOAT), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0) )return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3TexCoords.tv), sizeof(FLOAT), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0) )return FALSE; *lpNumBytesRead+=dwBytesRead; memcpy(lpBuffer, &md3TexCoords, sizeof(MD3TEXCOORDS)); return TRUE; } BOOL ReadMD3Triangle( HANDLE hFile, LPVOID lpBuffer, LPDWORD lpNumBytesRead, LPOVERLAPPED lpOverlapped) { BOOL bSuccess=FALSE; DWORD dwBytesRead=0; MD3TRIANGLE md3Triangle; ZeroMemory(&md3Triangle, sizeof(MD3TRIANGLE)); *lpNumBytesRead=0; if(hFile==NULL)return FALSE; bSuccess=ReadFile( hFile, &(md3Triangle.nIndexes[0]), sizeof(LONG), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0) )return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3Triangle.nIndexes[1]), sizeof(LONG), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0) )return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3Triangle.nIndexes[2]), sizeof(LONG), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0) )return FALSE; *lpNumBytesRead+=dwBytesRead; memcpy(lpBuffer, &md3Triangle, sizeof(MD3TRIANGLE)); return TRUE; } BOOL ReadMD3Shader( HANDLE hFile, LPVOID lpBuffer, LPDWORD lpNumBytesRead, LPOVERLAPPED lpOverlapped) { BOOL bSuccess=FALSE; DWORD dwBytesRead=0; MD3SHADER md3Shader; ZeroMemory(&md3Shader, sizeof(MD3SHADER)); *lpNumBytesRead=0; if(hFile==NULL)return FALSE; bSuccess=ReadFile( hFile, &(md3Shader.szShaderName), MAX_QPATH, &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0) )return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3Shader.lShaderNum), sizeof(LONG), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0) )return FALSE; *lpNumBytesRead+=dwBytesRead; memcpy(lpBuffer, &md3Shader, sizeof(MD3SHADER)); return TRUE; } BOOL ReadMD3MeshHeader( HANDLE hFile, LPVOID lpBuffer, LPDWORD lpNumBytesRead, LPOVERLAPPED lpOverlapped) { BOOL bSuccess=FALSE; DWORD dwBytesRead=0; MD3MESHHEADER md3MeshHeader; ZeroMemory(&md3MeshHeader, sizeof(MD3MESHHEADER)); *lpNumBytesRead=0; if(hFile==NULL)return FALSE; bSuccess=ReadFile( hFile, &(md3MeshHeader.dwID), sizeof(DWORD), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0))return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3MeshHeader.szMeshName), MAX_QPATH, &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0))return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3MeshHeader.lFlags), sizeof(LONG), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0))return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3MeshHeader.lNumFrames), sizeof(LONG), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0))return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3MeshHeader.lNumShaders), sizeof(LONG), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0))return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3MeshHeader.lNumVertices), sizeof(LONG), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0))return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3MeshHeader.lNumTriangles), sizeof(LONG), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0))return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3MeshHeader.lTriangleOffset), sizeof(LONG), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0))return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3MeshHeader.lShaderOffset), sizeof(LONG), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0))return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3MeshHeader.lTexCoordOffset), sizeof(LONG), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0))return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3MeshHeader.lVertexOffset), sizeof(LONG), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0))return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3MeshHeader.lMeshDataSize), sizeof(LONG), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0))return FALSE; *lpNumBytesRead+=dwBytesRead; memcpy(lpBuffer, &md3MeshHeader, sizeof(MD3MESHHEADER)); return TRUE; } BOOL ReadMD3Tag( HANDLE hFile, LPVOID lpBuffer, LPDWORD lpNumBytesRead, LPOVERLAPPED lpOverlapped) { BOOL bSuccess=FALSE; DWORD dwBytesRead=0; MD3TAG md3Tag; ZeroMemory(&md3Tag, sizeof(MD3TAG)); *lpNumBytesRead=0; if(hFile==NULL)return FALSE; bSuccess=ReadFile( hFile, &(md3Tag.szName), MAX_QPATH, &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0))return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadMD3Vector( hFile, &(md3Tag.vPosition), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0))return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadMD3Vector( hFile, &(md3Tag.vAxis[0]), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0))return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadMD3Vector( hFile, &(md3Tag.vAxis[1]), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0))return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadMD3Vector( hFile, &(md3Tag.vAxis[2]), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0))return FALSE; *lpNumBytesRead+=dwBytesRead; memcpy(lpBuffer, &md3Tag, sizeof(MD3TAG)); return TRUE; } BOOL ReadMD3Frame( HANDLE hFile, LPVOID lpBuffer, LPDWORD lpNumBytesRead, LPOVERLAPPED lpOverlapped) { BOOL bSuccess=FALSE; DWORD dwBytesRead=0; MD3FRAME md3Frame; ZeroMemory(&md3Frame, sizeof(MD3FRAME)); *lpNumBytesRead=0; if(hFile==NULL)return FALSE; bSuccess=ReadMD3Vector( hFile, &(md3Frame.vMin), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0) )return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadMD3Vector( hFile, &(md3Frame.vMax), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0) )return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadMD3Vector( hFile, &(md3Frame.vOrigin), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0) )return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3Frame.fRadius), sizeof(FLOAT), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0))return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3Frame.szName), 16, &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0))return FALSE; *lpNumBytesRead+=dwBytesRead; memcpy(lpBuffer, &md3Frame, sizeof(MD3FRAME)); return TRUE; } BOOL ReadMD3Vector( HANDLE hFile, LPVOID lpBuffer, LPDWORD lpNumBytesRead, LPOVERLAPPED lpOverlapped) { BOOL bSuccess=FALSE; DWORD dwBytesRead=0; MD3VECTOR md3Vector; ZeroMemory(&md3Vector, sizeof(MD3VECTOR)); *lpNumBytesRead=0; if(hFile==NULL)return FALSE; bSuccess=ReadFile( hFile, &(md3Vector.x), sizeof(FLOAT), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0))return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3Vector.y), sizeof(FLOAT), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0))return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3Vector.z), sizeof(FLOAT), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0))return FALSE; *lpNumBytesRead+=dwBytesRead; memcpy(lpBuffer, &md3Vector, sizeof(MD3VECTOR)); return TRUE; } BOOL ReadMD3Header( HANDLE hFile, LPVOID lpBuffer, LPDWORD lpNumBytesRead, LPOVERLAPPED lpOverlapped) { BOOL bSuccess=FALSE; DWORD dwBytesRead=0; MD3HEADER md3Header; ZeroMemory(&md3Header, sizeof(MD3HEADER)); *lpNumBytesRead=0; if(hFile==NULL)return FALSE; bSuccess=ReadFile( hFile, &(md3Header.dwID), sizeof(DWORD), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0) )return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3Header.lVersion), sizeof(LONG), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0) )return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3Header.szFileName), MAX_QPATH, &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0) )return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3Header.lFlags), sizeof(LONG), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0) )return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3Header.lNumFrames), sizeof(LONG), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0) )return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3Header.lNumTags), sizeof(LONG), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0) )return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3Header.lNumMeshes), sizeof(LONG), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0) )return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3Header.lNumSkins), sizeof(LONG), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0) )return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3Header.lFrameOffset), sizeof(LONG), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0) )return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3Header.lTagOffset), sizeof(LONG), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0) )return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3Header.lMeshOffset), sizeof(LONG), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0) )return FALSE; *lpNumBytesRead+=dwBytesRead; bSuccess=ReadFile( hFile, &(md3Header.lFileSize), sizeof(LONG), &dwBytesRead, lpOverlapped); if( (!bSuccess) || (dwBytesRead==0) )return FALSE; *lpNumBytesRead+=dwBytesRead; memcpy(lpBuffer, &md3Header, sizeof(MD3HEADER)); return TRUE; }<file_sep>/games/Legacy-Engine/Source/lm_sys/lm_mesh_ms.cpp #include <windows.h> #include <stdio.h> #include <stdarg.h> #include <math.h> #include "lm_ms.h" #include "lg_func.h" #include "msLib\\msLib.h" lg_uint __cdecl MSWrite(lg_void *file, lg_void *buffer, lg_uint size) { return fwrite(buffer, 1, size, (FILE*)file); } extern "C" void ErrorBox(char* format, ...) { char szOutput[1024]; va_list arglist=LG_NULL; int nResult=0; va_start(arglist, format); _vsnprintf(szOutput, 1024-1, format, arglist); MessageBoxA(0, szOutput, "Error Message", MB_OK); va_end(arglist); } float vertex_length(float* pv) { return sqrt(pv[0]*pv[0]+pv[1]*pv[1]+pv[2]*pv[2]); } CLMeshMS::CLMeshMS(void* pModel, char* szName): CLMesh2() { this->LoadFromMS(pModel, szName); } lg_bool CLMeshMS::LoadFromMS(void* pModelParam, char* szName) { Unload(); //Make sure that nothing is currently loaded. lg_dword i=0, j=0; msModel* pModel=(msModel*)pModelParam; this->Unload(); m_nID=LM_MESH_ID; m_nVer=LM_MESH_VER; LG_strncpy(m_szMeshName, szName, LM_MAX_NAME); m_nNumSubMesh=msModel_GetMeshCount(pModel); m_nNumMtrs=msModel_GetMaterialCount(pModel); m_nNumBones=msModel_GetBoneCount(pModel); //To get the total number of vertices, we have to find //out how many vertices are in each mesh, to optomize //things just a bit we also find out some of the material //information. //Milkshape to L3DM steps: //Step 1: Set all the variables and allocate memory: m_nID=LM_MESH_ID; m_nVer=LM_MESH_VER; m_nNumSubMesh=msModel_GetMeshCount(pModel); m_nNumMtrs=msModel_GetMaterialCount(pModel); for(i=0, m_nNumVerts=0, m_nNumTris=0; i<m_nNumSubMesh; i++) { msMesh* pMesh=msModel_GetMeshAt(pModel, i); m_nNumVerts+=msMesh_GetVertexCount(pMesh); m_nNumTris+=msMesh_GetTriangleCount(pMesh); } //char szTemp[1024]; //sprintf(szTemp, "There are %d triangles", m_nNumTris); //MessageBox(0, szTemp, 0, 0); //Allocate the memory: if(!AllocateMemory()) return LG_FALSE; //Now load the vertices. //Step 2: Load the vertices and indexes: lg_word v=0, indexAt=0; for(i=0, v=0, indexAt=0; i<m_nNumSubMesh; i++) { msMesh* pMesh=msModel_GetMeshAt(pModel, i); //Some temp stuff. m_pSubMesh[i].nFirstIndex=indexAt; m_pSubMesh[i].nNumTri=msMesh_GetTriangleCount(pMesh); for(j=0; j<(lg_dword)msMesh_GetVertexCount(pMesh); j++, v++) { msVec3 Normal; msVertex* pVertex=msMesh_GetVertexAt(pMesh, j); msMesh_GetVertexNormalAt(pMesh, j, Normal); //? //Copy vertex (note that z must be made negative) m_pVerts[v].x=pVertex->Vertex[0]; m_pVerts[v].y=pVertex->Vertex[1]; m_pVerts[v].z=-pVertex->Vertex[2]; //Copy normals(again z is negative and the base vertex is added). //The normals will get set later. m_pVerts[v].nx=0.0f; m_pVerts[v].ny=0.0f; m_pVerts[v].nz=0.0f; //Copy tex coordinates. m_pVerts[v].tu=pVertex->u; m_pVerts[v].tv=pVertex->v; //For each vertex we save the bone index in the bone index list: m_pVertBoneList[v]=pVertex->nBoneIndex; } lg_word nOffset=v-msMesh_GetVertexCount(pMesh); for(j=0; j<(lg_dword)msMesh_GetTriangleCount(pMesh); j++, indexAt+=3) { lg_word nIndices[3], nNormalIndices[3]; msVec3 Normal; msTriangle* pTriangle=msMesh_GetTriangleAt(pMesh, j); msTriangle_GetVertexIndices(pTriangle, nIndices); msTriangle_GetNormalIndices(pTriangle, nNormalIndices); //Note that we reverse the order of the indices, so that //we can cull the way we want to. for(int k=0; k<3; k++) { m_pIndexes[indexAt+k]=nIndices[2-k]+nOffset; //Here is where we set the normals, note that //the actual normals may be affected multiply //times, but in the end a valid set of normals //should be available. lg_word nIndex=m_pIndexes[indexAt+k]; msMesh_GetVertexNormalAt(pMesh, nNormalIndices[2-k], Normal); m_pVerts[nIndex].nx=Normal[0]; m_pVerts[nIndex].ny=Normal[1]; m_pVerts[nIndex].nz=-Normal[2]; } } } //Step 2.5: Save all the bone names: for(i=0; i<m_nNumBones; i++) { msBone* pBone=msModel_GetBoneAt(pModel, i); LG_strncpy(m_pBoneNameList[i], pBone->szName, LM_MAX_NAME); } //Step 3: Load the meshes. for(i=0; i<m_nNumSubMesh; i++) { //We've already loaded the start vertex, and //number of vertexes from above. msMesh* pMesh=msModel_GetMeshAt(pModel, i); LG_strncpy(m_pSubMesh[i].szName, pMesh->szName, LM_MAX_NAME); m_pSubMesh[i].nMtrIndex=pMesh->nMaterialIndex; } //Step 4: Load the material. for(i=0; i<m_nNumMtrs; i++) { msMaterial* pMaterial=msModel_GetMaterialAt(pModel, i); LG_strncpy(m_pMtrs[i].szName, pMaterial->szName, LM_MAX_NAME); //We want to get rid of the path information: int nPos=0; char* szPtr=pMaterial->szDiffuseTexture; nPos=strlen(szPtr); for( ; nPos>0; --nPos) { if(szPtr[nPos]=='/' || szPtr[nPos]=='\\') { nPos++; break; } } LG_strncpy(m_pMtrs[i].szFile, &szPtr[nPos], LM_MAX_PATH); //ErrorBox("The file is: \"%s\" from \"%s\" %d", m_pMtrs[i].szFile, szPtr, nPos); } //Calculate the AABB m_AABB.v3Min.x=m_pVerts[0].x; m_AABB.v3Min.y=m_pVerts[0].y; m_AABB.v3Min.z=m_pVerts[0].z; m_AABB.v3Max.x=m_pVerts[0].x; m_AABB.v3Max.y=m_pVerts[0].y; m_AABB.v3Max.z=m_pVerts[0].z; for(i=0; i<m_nNumVerts; i++) { m_AABB.v3Min.x=LG_Min(m_AABB.v3Min.x, m_pVerts[i].x); m_AABB.v3Min.y=LG_Min(m_AABB.v3Min.y, m_pVerts[i].y); m_AABB.v3Min.z=LG_Min(m_AABB.v3Min.z, m_pVerts[i].z); m_AABB.v3Max.x=LG_Max(m_AABB.v3Max.x, m_pVerts[i].x); m_AABB.v3Max.y=LG_Max(m_AABB.v3Max.y, m_pVerts[i].y); m_AABB.v3Max.z=LG_Max(m_AABB.v3Max.z, m_pVerts[i].z); } m_nFlags=LM_FLAG_LOADED; return LG_TRUE; } lg_bool CLMeshMS::Load(LMPath szFile) { //We only load using the converter. return LG_FALSE; } lg_bool CLMeshMS::Save(LMPath szFile) { FILE* fout=fopen(szFile, "wb"); if(!fout) return LG_FALSE; lg_bool bRes=Serialize(fout, MSWrite, RW_WRITE); fclose(fout); return bRes; } //////////////////////////////////////////////////////////////// /// Legacy Skeleton Milkshape loading. ///////////////////////// //////////////////////////////////////////////////////////////// CLSkelMS::CLSkelMS(void* pModel, char* szName): CLSkel2() { this->LoadFromMS(pModel, szName); } lg_bool CLSkelMS::LoadFromMS(void* pModelParam, char* szName) { msModel* pModel=(msModel*)pModelParam; lg_dword i=0, j=0; m_nID=LM_SKEL_ID; m_nVersion=LM_SKEL_VER; LG_strncpy(m_szSkelName, szName, LM_MAX_NAME); m_nNumJoints=msModel_GetBoneCount(pModel); m_nNumKeyFrames=msModel_GetTotalFrames(pModel); m_nNumAnims=0; //Animations have to be added using a different utility. if(m_nNumJoints<1) { //No skeleton. m_nID=0; m_nVersion=0; m_nNumJoints=0; m_nNumKeyFrames=0; m_nFlags=0; return LG_FALSE; } if(!AllocateMemory()) return LG_FALSE; #define MINUS(a) (-a) #define MINUSR(a) (-a) //Load the base skeleton. for(i=0; i<m_nNumJoints; i++) { msBone* pBone=msModel_GetBoneAt(pModel, i); LG_strncpy(m_pBaseSkeleton[i].szName, pBone->szName, LM_MAX_NAME); LG_strncpy(m_pBaseSkeleton[i].szParent, pBone->szParentName, LM_MAX_NAME); m_pBaseSkeleton[i].fPos[0]=pBone->Position[0]; m_pBaseSkeleton[i].fPos[1]=pBone->Position[1]; m_pBaseSkeleton[i].fPos[2]=MINUS(pBone->Position[2]); m_pBaseSkeleton[i].fRot[0]=pBone->Rotation[0]; m_pBaseSkeleton[i].fRot[1]=pBone->Rotation[1]; m_pBaseSkeleton[i].fRot[2]=MINUSR(pBone->Rotation[2]); } //We now need to find all the indexes for the parent bones. for(i=0; i<m_nNumJoints; i++) { m_pBaseSkeleton[i].nParent=0; //If there is no parent the index for the parent bone is 0, //note that the index for bones is not zero based. In other //words bone 1 would be m_pBaseSkeleton[0]. if(strlen(m_pBaseSkeleton[i].szParent)<1) { m_pBaseSkeleton[i].nParent=0; continue; } for(j=1; j<=m_nNumJoints; j++) { if(stricmp(m_pBaseSkeleton[i].szParent, m_pBaseSkeleton[j-1].szName)==0) { m_pBaseSkeleton[i].nParent=j; break; } } } //Now we will write the keyframe information, //in the MS3D format only joints that are actually operated on //are saved, but in the legacy format we want every rotation //for every joint every frame. This can be calculated by finding //the most previous joint position. //Find the total number of keyframes. float fPosition[3]; float fRotation[3]; for(i=0; i<m_nNumJoints; i++) { msBone* pBone=msModel_GetBoneAt(pModel, i); //Set the position and rotation values of the //first frame. msPositionKey* pPos=msBone_GetPositionKeyAt(pBone, 0); msRotationKey* pRot=msBone_GetRotationKeyAt(pBone, 0); if(pPos) { fPosition[0]=pPos->Position[0]; fPosition[1]=pPos->Position[1]; fPosition[2]=MINUS(pPos->Position[2]); } else { fPosition[0]=0.0f; fPosition[1]=0.0f; fPosition[2]=0.0f; } if(pRot) { fRotation[0]=pRot->Rotation[0]; fRotation[1]=pRot->Rotation[1]; fRotation[2]=MINUSR(pRot->Rotation[2]); } else { fRotation[0]=0.0f; fRotation[1]=0.0f; fRotation[2]=0.0f; } m_pFrames[0].SetLocalMat(i, fPosition, fRotation); for(j=0; j<m_nNumKeyFrames; j++) { //We'll zero out the bounding boxes, //they will need to be set using LMEdit or //some other method. ML_VEC3 Zero={0.0f, 0.0f, 0.0f}; m_pFrames[j].aabbBox.v3Min=Zero; m_pFrames[j].aabbBox.v3Max=Zero; /* m_pKeyFrames[j].pJointPos[i].position[0]=0.0f; m_pKeyFrames[j].pJointPos[i].position[1]=0.0f; m_pKeyFrames[j].pJointPos[i].position[2]=0.0f; m_pKeyFrames[j].pJointPos[i].rotation[0]=0.0f; m_pKeyFrames[j].pJointPos[i].rotation[1]=0.0f; m_pKeyFrames[j].pJointPos[i].rotation[2]=0.0f; */ //If we are dealing with the first frame set it //to zero in case there is no first frame, for //any other frames we simply set it to the previous //frame if there is no frame. /* if(j==0) { fPosition[0]=0.0f; fPosition[1]=0.0f; fPosition[2]=0.0f; fRotation[0]=0.0f; fRotation[1]=0.0f; fRotation[2]=0.0f; m_pFrames[j].SetLocalMat(i, fPosition, fRotation); } */ lg_word k=0; lg_bool bFound=LG_FALSE; for(k=0; k<pBone->nNumPositionKeys; k++) { msPositionKey* pPos=msBone_GetPositionKeyAt(pBone, k); msRotationKey* pRot=msBone_GetRotationKeyAt(pBone, k); if((lg_dword)pPos->fTime==(j+0)) { fPosition[0]=pPos->Position[0]; fPosition[1]=pPos->Position[1]; fPosition[2]=MINUS(pPos->Position[2]); fRotation[0]=pRot->Rotation[0]; fRotation[1]=pRot->Rotation[1]; fRotation[2]=MINUSR(pRot->Rotation[2]); m_pFrames[j].SetLocalMat(i, &fPosition[0], &fRotation[0]); bFound=LG_TRUE; break; } } if(!bFound && j!=0) { fPosition[0]=m_pFrames[j-1].LocalPos[i].fPos[0]; fPosition[1]=m_pFrames[j-1].LocalPos[i].fPos[1]; fPosition[2]=m_pFrames[j-1].LocalPos[i].fPos[2]; fRotation[0]=m_pFrames[j-1].LocalPos[i].fRot[0]; fRotation[1]=m_pFrames[j-1].LocalPos[i].fRot[1]; fRotation[2]=m_pFrames[j-1].LocalPos[i].fRot[2]; m_pFrames[j].SetLocalMat(i, &fPosition[0], &fRotation[0]); } } } m_nFlags=LM_FLAG_LOADED; return LG_TRUE; } lg_bool CLSkelMS::Load(LMPath szFile) { return LG_FALSE; } lg_bool CLSkelMS::Save(CLMBase::LMPath szFile) { FILE* fout=fopen(szFile, "wb"); if(!fout) return LG_FALSE; lg_bool bRes=Serialize(fout, MSWrite, RW_WRITE); fclose(fout); return bRes; } <file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/lm_skel.cpp #include <stdio.h> #include "lm_sys.h" //Alright here is the skeleton class. //Further this needs to support some kind of //mechanism for pointing out different animations //based on a range of animations. //Also need to change the way the model gets rendered. //Either CLegacyMesh needs to have a RenderWithSkel funciton. //Or CLegacySkeleton needs to have a RenderModel functions. CLegacySkeleton::CLegacySkeleton(): m_nID(0), m_nVersion(0), m_nNumJoints(0), m_nNumKeyFrames(0), m_pBaseSkeleton(L_null), m_pKeyFrames(L_null), m_nTotalSize(0), m_bLoaded(L_false) { } CLegacySkeleton::~CLegacySkeleton() { Unload(); } L_bool CLegacySkeleton::Unload() { this->DeallocateMemory(); m_nID=0; m_nVersion=0; m_nNumJoints=0; m_nNumKeyFrames=0; m_nTotalSize=0; m_bLoaded=L_false; return L_true; } L_bool CLegacySkeleton::Load(void* file, LMESH_CALLBACKS* pcb) { L_dword i=0, j=0; LMESH_CALLBACKS cb; cb.close=(int (__cdecl*)(void*))fclose; cb.read=(unsigned int (__cdecl *)(void *,unsigned int,unsigned int,void *))fread; cb.seek=(int (__cdecl *)(void *,long,int))fseek; cb.tell=(int (__cdecl *)(void *))ftell; if(!pcb) { pcb=&cb; } //Unload in case a skeleton is already loaded. Unload(); //Read the header. pcb->read(&m_nID, 4, 1, file); pcb->read(&m_nVersion, 4, 1, file); pcb->read(&m_nNumJoints, 4, 1, file); pcb->read(&m_nNumKeyFrames, 4, 1, file); if(m_nID!=LSKEL_ID || m_nVersion!=LSKEL_VERSION) { pcb->close(file); return L_false; } //Allocate memory for the frames and base skeleton. if(!AllocateMemory()) return L_false; //Read the base skeleton. for(i=0; i<m_nNumJoints; i++) { //Note that we only read the size of LMESH_JOINT because that //is all that is stored. The rest of the information (namely //the rotatoin matrix) is built afterwards when CalcExData is //called. pcb->read(&m_pBaseSkeleton[i], sizeof(LMESH_JOINT), 1, file); } //Read the key frames. for(i=0; i<m_nNumKeyFrames; i++) { for(j=0; j<m_nNumJoints; j++) { //We only read the size of LMESH_JOINTPOS cause that is all that is //stored. The rest of the structure is built when CalcExData is called. pcb->read(&this->m_pKeyFrames[i].pJointPos[j], sizeof(LMESH_JOINTPOS), 1, file); } } pcb->close(file); m_bLoaded=L_true; //We will now get all the calculations for the extra data (the local //and final matrices for the base skeleton and keyframes). //this->CalcExData(); this->CalcExData(); return m_bLoaded; } L_bool CLegacySkeleton::Save(char* szFilename, L_bool bAppend) { FILE* fout=L_null; char mode[4]; L_dword i=0; if(!bAppend) L_strncpy(mode, "wb", 4); else L_strncpy(mode, "rb+", 4); if(!m_bLoaded) return L_false; if(!m_pBaseSkeleton || !m_pKeyFrames) return L_false; fout=fopen(szFilename, mode); if(!fout) return L_false; //Seek to the end of the file (in case we are appending). fseek(fout, 0, SEEK_END); //Write the header fwrite(&m_nID, 4, 1, fout); fwrite(&m_nVersion, 4, 1, fout); fwrite(&m_nNumJoints, 4, 1, fout); fwrite(&m_nNumKeyFrames, 4, 1, fout); //Write the base skeleton. for(i=0; i<m_nNumJoints; i++) { //We only write the size of LMESH_JOINT because the other //data is built when we load the model. fwrite(&this->m_pBaseSkeleton[i], sizeof(LMESH_JOINT), 1, fout); } //Write the key frames. L_dword j=0; for(i=0; i<m_nNumKeyFrames; i++) { for(j=0; j<m_nNumJoints; j++) { fwrite(&this->m_pKeyFrames[i].pJointPos[j], sizeof(LMESH_JOINTPOS), 1, fout); } } //Write the footer (which is the total size of the skeleton then the ID again). m_nTotalSize=16+m_nNumJoints*sizeof(LMESH_JOINT)+m_nNumJoints*m_nNumKeyFrames*sizeof(LMESH_JOINTPOS)+8; fwrite(&m_nTotalSize, 4, 1, fout); fwrite(&m_nID, 4, 1, fout); fclose(fout); m_bLoaded=L_true; return L_true; } L_bool CLegacySkeleton::AllocateMemory() { L_dword i=0, j=0; //Allocate memory for the frames and base skeleton. m_pKeyFrames=new LMESH_KEYFRAME[m_nNumKeyFrames]; if(!m_pKeyFrames) return L_false; for(i=0; i<m_nNumKeyFrames; i++) { m_pKeyFrames[i].pJointPos=new LMESH_JOINTPOSEX[m_nNumJoints]; if(!m_pKeyFrames[i].pJointPos) { for(j=i-1; j>0; j--) { L_safe_delete_array(m_pKeyFrames[j].pJointPos); } L_safe_delete_array(m_pKeyFrames); return L_false; } } m_pBaseSkeleton=new LMESH_JOINTEX[m_nNumJoints]; if(!m_pBaseSkeleton) { for(i=0; i<m_nNumKeyFrames; i++) { L_safe_delete_array(m_pKeyFrames[i].pJointPos); } L_safe_delete_array(m_pKeyFrames); return L_false; } return L_true; } void CLegacySkeleton::DeallocateMemory() { L_dword i=0; L_safe_delete_array(this->m_pBaseSkeleton); for(i=0; i<m_nNumKeyFrames; i++) { L_safe_delete_array(this->m_pKeyFrames[i].pJointPos); } L_safe_delete_array(this->m_pKeyFrames); } L_dword CLegacySkeleton::GetNumFrames() { return m_nNumKeyFrames; } L_bool CLegacySkeleton::CalcExData() { L_dword i=0, j=0; if(!m_bLoaded) return L_false; //Firstly we must convert Euler angles for the base skeleton and //keyframes to matrices. //Read the base skeleton. for(i=0; i<m_nNumJoints; i++) { //Now create the rotation matrixes (in the final format the rotation //matrices will probably be stored instead of the euler angles. LM_EulerToMatrix(&m_pBaseSkeleton[i].Local, (float*)&m_pBaseSkeleton[i].rotation); //Now stick the translation into the matrix. m_pBaseSkeleton[i].Local._41=m_pBaseSkeleton[i].position[0]; m_pBaseSkeleton[i].Local._42=m_pBaseSkeleton[i].position[1]; m_pBaseSkeleton[i].Local._43=m_pBaseSkeleton[i].position[2]; m_pBaseSkeleton[i].nJointRef=i; } //Read the key frames. for(i=0; i<m_nNumKeyFrames; i++) { for(j=0; j<m_nNumJoints; j++) { //pcb->read(&this->m_pKeyFrames[i].pJointPos[j], sizeof(LMESH_JOINTPOS), 1, file); LM_EulerToMatrix(&m_pKeyFrames[i].pJointPos[j].Local, (float*)&m_pKeyFrames[i].pJointPos[j].rotation); m_pKeyFrames[i].pJointPos[j].Local._41=m_pKeyFrames[i].pJointPos[j].position[0]; m_pKeyFrames[i].pJointPos[j].Local._42=m_pKeyFrames[i].pJointPos[j].position[1]; m_pKeyFrames[i].pJointPos[j].Local._43=m_pKeyFrames[i].pJointPos[j].position[2]; } } //Calculate the final matrices for the base skeleton. //This is simply a matter of multiplying each joint by //all of it's parent's matrices. for(i=0; i<m_nNumJoints; i++) { LMESH_JOINTEX* pTemp=&m_pBaseSkeleton[i]; m_pBaseSkeleton[i].Final=pTemp->Local; while(pTemp->nParentBone) { pTemp=&m_pBaseSkeleton[pTemp->nParentBone-1]; m_pBaseSkeleton[i].Final*=m_pBaseSkeleton[pTemp->nJointRef].Local; } } //We calculate the final transformation matrix for each joint for each //frame now, that way we don't have to calculate them on the fly. It //takes more memory this way, but the real time rendering is faster because //it isn't necessary to calculate each frames matrix every frame, it is only //necessary to interploate the joint matrixes for the given frame. //For each joint... for(i=0; i<m_nNumJoints; i++) { //For each frame for each joint... for(j=0; j<m_nNumKeyFrames; j++) { //1. Obtain the base joint for that joint. LMESH_JOINTEX* pTemp=&m_pBaseSkeleton[i]; //2. Start out by making the final translation for the frame the local frame joint //location multiplyed the by the local base joint. m_pKeyFrames[j].pJointPos[i].Final=m_pKeyFrames[j].pJointPos[i].Local*pTemp->Local; //3. Then if the joint has a parent... while(pTemp->nParentBone) { //3 (cont'd). It is necessary to multiply the final frame matrix //by the same calculation in step 2 (frame pos for the frame * local pos for the frame). pTemp=&m_pBaseSkeleton[pTemp->nParentBone-1]; m_pKeyFrames[j].pJointPos[i].Final*=m_pKeyFrames[j].pJointPos[pTemp->nJointRef].Local*pTemp->Local; } //4. Fianlly the final position needs to be multiplied by the //final base position's inverse so that the transformation is //relative to the joint's location and not to 0,0,0. D3DXMATRIX MI; D3DXMatrixInverse(&MI, L_null, &m_pBaseSkeleton[i].Final); m_pKeyFrames[j].pJointPos[i].Final=MI*m_pKeyFrames[j].pJointPos[i].Final; } } return L_true; } <file_sep>/Misc/DBXExporter/DBXExporter/oedbx/library/oedbx/dbxFileInfo.h //*************************************************************************************** #ifndef dbxFileInfoH #define dbxFileInfoH //*************************************************************************************** #include <oedbx/dbxCommon.h> //*************************************************************************************** class AS_EXPORT DbxFileInfo { public : DbxFileInfo(InStream ins, int4 address, int4 length); ~DbxFileInfo(); const char * GetFolderName() const; std::string GetFileInfoTime() const; void ShowResults(OutStream outs) const; private : void init(); void readFileInfo(InStream ins); //data int4 Address, Length; int1 * buffer; } ; //*********************************************** #endif dbxFileInfoH <file_sep>/games/Legacy-Engine/Scrapped/tools/Texview2/src/MainFrm.cpp // MainFrm.cpp : implementation of the CMainFrame class // #include "stdafx.h" #include "Texview2.h" #include "MainFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif DWORD __cdecl L_nextpow2_C(const DWORD n) { DWORD result = 1; if(n>=0x80000000) return 0x80000000; while(result<n) { result <<= 1; } return result; } ///////////////////////////////////////////////////////////////////////////// // CMainFrame IMPLEMENT_DYNAMIC(CMainFrame, CFrameWnd) BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) //{{AFX_MSG_MAP(CMainFrame) ON_WM_CREATE() ON_WM_SETFOCUS() ON_COMMAND(ID_FILE_OPEN, OnFileOpen) //}}AFX_MSG_MAP ON_COMMAND_RANGE(ID_TEXTURESIZE, ID_TEXTURESIZEMAX, OnViewSize) ON_COMMAND_RANGE(ID_VIEW_LINEARFILTER, ID_VIEW_POINTFILTER, OnFilterType) ON_COMMAND(ID_TOOLS_REGISTERFILETYPES, &CMainFrame::OnToolsRegisterfiletypes) END_MESSAGE_MAP() static UINT indicators[] = { ID_SEPARATOR, // status line indicator ID_INDICATOR_CAPS, ID_INDICATOR_NUM, ID_INDICATOR_SCRL, }; ///////////////////////////////////////////////////////////////////////////// // CMainFrame construction/destruction CMainFrame::CMainFrame() { // TODO: add member initialization code here this->m_bAutoMenuEnable=FALSE; } CMainFrame::~CMainFrame() { } int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CFrameWnd::OnCreate(lpCreateStruct) == -1) return -1; // create a view to occupy the client area of the frame if (!m_wndView.Create(NULL, NULL, AFX_WS_DEFAULT_VIEW|WS_VSCROLL|WS_HSCROLL, CRect(0, 0, 0, 0), this, AFX_IDW_PANE_FIRST, NULL)) { TRACE0("Failed to create view window\n"); return -1; } if (!m_wndStatusBar.Create(this) || !m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT))) { TRACE0("Failed to create status bar\n"); return -1; // fail to create } UpdateMenuTexSizes(0, 0); return 0; } BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) { if( !CFrameWnd::PreCreateWindow(cs) ) return FALSE; // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs cs.dwExStyle &= ~WS_EX_CLIENTEDGE; cs.lpszClass = AfxRegisterWndClass(0, 0, 0, AfxGetApp()->LoadIcon(_T("ICON_IMG"))); return TRUE; } ///////////////////////////////////////////////////////////////////////////// // CMainFrame diagnostics #ifdef _DEBUG void CMainFrame::AssertValid() const { CFrameWnd::AssertValid(); } void CMainFrame::Dump(CDumpContext& dc) const { CFrameWnd::Dump(dc); } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CMainFrame message handlers void CMainFrame::OnSetFocus(CWnd* pOldWnd) { // forward focus to the view window m_wndView.SetFocus(); } BOOL CMainFrame::OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo) { // let the view have first crack at the command if (m_wndView.OnCmdMsg(nID, nCode, pExtra, pHandlerInfo)) return TRUE; // otherwise, do default handling return CFrameWnd::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo); } void CMainFrame::OnFileOpen() { #define MFC_FILEDLG #ifdef MFC_FILEDLG CFileDialog fdOpen( TRUE, _T("tga"), NULL, OFN_EXPLORER|OFN_ENABLESIZING|OFN_NOCHANGEDIR, _T("Supported Images (*.tga; *.bmp; *.dib; *.jpg; *.gif; *.png)|*.tga;*.bmp;*.dib;*.jpg;*.gif;*.png;|All Files (*.*)|*.*||"), this); fdOpen.m_ofn.lpstrTitle=_T("Open Image..."); if(fdOpen.DoModal()==IDOK) LoadTexture(fdOpen.GetPathName().GetBuffer(0)); #else MFC_FILEDLG OPENFILENAME of; TCHAR szFilename[MAX_PATH]; ZeroMemory(&of, sizeof(OPENFILENAME)); szFilename[0]=0; of.lStructSize=sizeof(OPENFILENAME); of.hwndOwner=this->m_hWnd; of.hInstance=NULL; of.lpstrFilter=_T("Supported Images (*.tga; *.bmp; *.dib)\0*.tga;*.bmp;*.dib\0All Files (*.*)\0*.*\0"); of.lpstrCustomFilter=NULL; of.nMaxFile=MAX_PATH; of.lpstrTitle=_T("Open Image..."); of.lpstrDefExt=_T("tga"); of.lpstrFile=szFilename; if(GetOpenFileName(&of)) this->m_wndView.LoadTexture(szFilename); #endif MFC_FILEDLG } BOOL CMainFrame::LoadTexture(LPTSTR szFilename) { return m_wndView.LoadTexture(szFilename); } void CMainFrame::OnViewSize(UINT nID) { CMenu* menu=GetMenu(); DWORD i=0; for(i=0; i<=NUM_TEX_SIZES; i++) { if(nID==(ID_TEXTURESIZE+i)) menu->CheckMenuItem(ID_TEXTURESIZE+i, MF_CHECKED|MF_BYCOMMAND); else menu->CheckMenuItem(ID_TEXTURESIZE+i, MF_UNCHECKED|MF_BYCOMMAND); } if(nID==ID_TEXTURESIZE) { m_wndView.SetBitmapSize(0, 0); } else { DWORD size=nID-ID_TEXTURESIZE; //size=L_pow2((L_byte)size); size=1<<(size-1); m_wndView.SetBitmapSize(size, size); } menu->Detach(); } void CMainFrame::UpdateMenuTexSizes(int cx, int cy) { CMenu* parentmenu=GetMenu(); //parentmenu->InsertMenu(2, MF_BYPOSITION, MF_POPUP, "Texture"); CMenu* mnTexture=parentmenu->GetSubMenu(1); int i=0, j=0; for(i=0; i<NUM_TEX_SIZES; i++) mnTexture->DeleteMenu(ID_TEXTURESIZE+i+1, MF_BYCOMMAND); mnTexture->CheckMenuItem(ID_TEXTURESIZE, MF_CHECKED); if(!cx || !cy) { mnTexture->EnableMenuItem(ID_TEXTURESIZE, MF_BYCOMMAND|MF_GRAYED); mnTexture->Detach(); parentmenu->Detach(); return; } cx=L_nextpow2_C(cx); cy=L_nextpow2_C(cy); cx=MAX(cy, cx); cy=cx; TCHAR szTemp[100]; for(i=0,j=1; j<=cx && i<NUM_TEX_SIZES; i++, j*=2) { _stprintf(szTemp, _T("%ix%i"), j, j); mnTexture->InsertMenu(1, MF_BYPOSITION, ID_TEXTURESIZE+i+1, szTemp); } mnTexture->EnableMenuItem(ID_TEXTURESIZE, MF_BYCOMMAND|MF_ENABLED); mnTexture->Detach(); parentmenu->Detach(); DrawMenuBar(); } void CMainFrame::OnFilterType(UINT nID) { CMenu* menu=GetMenu(); if(nID==ID_VIEW_LINEARFILTER) m_wndView.SetFilter(IMGFILTER_LINEAR); else m_wndView.SetFilter(IMGFILTER_POINT); menu->CheckMenuItem(ID_VIEW_POINTFILTER, MF_BYCOMMAND|MF_UNCHECKED); menu->CheckMenuItem(ID_VIEW_LINEARFILTER, MF_BYCOMMAND|MF_UNCHECKED); menu->CheckMenuItem(nID, MF_BYCOMMAND|MF_CHECKED); menu->Detach(); } void CMainFrame::OnToolsRegisterfiletypes() { // TODO: Add your command handler code here RegisterFileType(".tga", "Targa.Image", "Truevision Targa Image", 1); RegisterFileType(".bmp", "Bitmap.Image", "Bitmap Image", 1); RegisterFileType(".jpg", "JPEG.Image", "JPEG Image", 1); RegisterFileType(".gif", "GIF.Image", "Graphics Interchange Format Image", 1); SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL); MessageBox(_T("File types are registered."), NULL, MB_ICONINFORMATION); } int CMainFrame::RegisterFileType(char* szExt, char* szDesc, char* szText, int nIcon) { HKEY hKey=NULL; DWORD dwType=0; char szValue[1024]; char szTemp[1024]; DWORD dwSize=0; DWORD dwDisp=0; char szModPath[MAX_PATH]; GetModuleFileNameA(NULL, szModPath, MAX_PATH); RegOpenKeyExA(HKEY_CLASSES_ROOT, szExt, 0, KEY_ALL_ACCESS, &hKey); //If the file type is already registers we will simply add the command to open //with texture viewer. if(hKey) { dwSize=1024; RegQueryValueExA(hKey, NULL, NULL, &dwType, (LPBYTE)szValue, &dwSize); RegCloseKey(hKey); sprintf(szTemp, "%s\\shell\\Open with Texture Viewer 2\\command", szValue); RegCreateKeyExA(HKEY_CLASSES_ROOT, szTemp, 0, NULL, 0, NULL, NULL, &hKey, &dwDisp); RegOpenKeyExA(HKEY_CLASSES_ROOT, szTemp, 0, KEY_ALL_ACCESS, &hKey); sprintf(szValue, "\"%s\" %%1", szModPath); RegSetValueExA(hKey, NULL, 0, REG_SZ, (LPBYTE)szValue, strlen(szValue)+1); RegCloseKey(hKey); } else { //Otherwise we need to create the file type. //REgister the extension. RegCreateKeyExA(HKEY_CLASSES_ROOT, szExt, 0, NULL, 0, NULL, NULL, &hKey, &dwDisp); RegOpenKeyExA(HKEY_CLASSES_ROOT, szExt, 0, KEY_ALL_ACCESS, &hKey); RegSetValueExA(hKey, NULL, 0, REG_SZ, (LPBYTE)szDesc, strlen(szDesc)+1); //sprintf(szTemp, "\"%s\", %d", szModPath, nIcoNum); //RegSetValueEx(hKey, "DefaultIcon", 0, REG_SZ, szTemp, strlen(szTemp)+1); RegCloseKey(hKey); //Register the file type. RegCreateKeyExA(HKEY_CLASSES_ROOT, szDesc, 0, NULL, 0, NULL, NULL, &hKey, &dwDisp); RegOpenKeyExA(HKEY_CLASSES_ROOT, szDesc, 0, KEY_ALL_ACCESS, &hKey); RegSetValueExA(hKey, NULL, 0, REG_SZ, (LPBYTE)szText, strlen(szText)+1); RegCloseKey(hKey); //Register the icon. sprintf(szTemp, "%s\\DefaultIcon", szDesc); RegCreateKeyExA(HKEY_CLASSES_ROOT, szTemp, 0, NULL, 0, NULL, NULL, &hKey, &dwDisp); RegOpenKeyExA(HKEY_CLASSES_ROOT, szTemp, 0, KEY_ALL_ACCESS, &hKey); sprintf(szTemp, "\"%s\",%d", szModPath, nIcon); RegSetValueExA(hKey, NULL, 0, REG_SZ, (LPBYTE)szTemp, strlen(szTemp)+1); RegCloseKey(hKey); //Register the command. sprintf(szTemp, "%s\\shell\\Open with Texture Viewer 2\\command", szDesc); RegCreateKeyExA(HKEY_CLASSES_ROOT, szTemp, 0, NULL, 0, NULL, NULL, &hKey, &dwDisp); RegOpenKeyExA(HKEY_CLASSES_ROOT, szTemp, 0, KEY_ALL_ACCESS, &hKey); sprintf(szTemp, "\"%s\" %%1", szModPath); RegSetValueExA(hKey, NULL, 0, REG_SZ, (LPBYTE)szTemp, strlen(szTemp)+1); RegCloseKey(hKey); } return 0; } <file_sep>/Misc/DBXExporter/DBXExporter/oedbx/library/dbxConditions.cpp //*************************************************************************************** #define AS_OE_IMPLEMENTATION #include <oedbx/dbxConditions.h> //*************************************************************************************** DbxConditions::DbxConditions(InStream ins, int4 address) { init(); Address = address; try { readConditions(ins); } catch(const DbxException & E) { delete[] Text; throw; } } DbxConditions::~DbxConditions() { delete[] Text; } void DbxConditions::init() { Length = 0; Text = 0; } void DbxConditions::readConditions(InStream ins) { int4 head[2]; ins.seekg(Address); ins.read((char *)head, 0x08); if(!ins) throw DbxException("Error reading object from input stream !"); if(Address!=head[0]) throw DbxException("Wrong object marker !"); Length = head[1]; if(Length) { Text = new char[Length]; ins.read(Text, Length); if(!ins) throw DbxException("Error reading object from input stream !"); } else throw DbxException("No text found !"); } //*************************************************************************************** void DbxConditions::ShowResults(OutStream outs) const { outs << std::endl << "Conditions : " << std::endl << " Position : 0x" << std::hex << Address << std::endl << " Length : 0x" << std::hex << Length << std::endl; if(Text) outs << Text << std::endl; } //*************************************************************************************** <file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/filesys/lf_sys.c /**************************************************** File: lf_sys.c Copyright (c) 2006, <NAME> Purpose: Functions that control disk input (and possibly in the future, output) for the Legacy File System. Functions starting with LF_ are used to effect the usage of the file system. Functions starting with File_ are used to access files within the file system. ****************************************************/ #include "common.h" #include <stdio.h> #include <direct.h> #include <math.h> #include <memory.h> #include <malloc.h> #include "lf_sys.h" #include "lf_sys.h" #include <windows.h> /* A few global variables are used for the file system, one to indicate if the file system has been initialized another to store the current working directory, and also one to store the SEARCHPATHS. */ L_bool g_bFSInited=L_false; char g_szCurDir[MAX_F_PATH]; SEARCHPATHS* g_SearchPaths=L_null; L_bool g_bArchivesFirst=L_false; /********************************************************* The LF_* functions are used to manipulate the file system, they initialize, shutdown, and can change the working directory. **********************************************************/ /************************************************ LF_SetError() && LF_GetLastError() Get and set the error text. ************************************************/ char g_szErrorText[1024]; void LF_SetError(char* format, ...) { va_list arglist; va_start(arglist, format); _vsnprintf(g_szErrorText, 1023, format, arglist); va_end(arglist); } char* LF_GetLastError() { return g_szErrorText; } /********************************************************************** LF_GetPath() This function goes through the search paths until it finds the specified filename. If it finds it, it returns information about that file. If it doesn't it returns L_null. **********************************************************************/ SEARCHPATHS* LF_GetPath(const char* szFilename) { SEARCHPATHS* lpPath=L_null; for(lpPath=g_SearchPaths; lpPath; lpPath=lpPath->m_next) { if(L_strnicmp((char*)szFilename, lpPath->m_szNameInLibrary, 0)) return lpPath; } LF_SetError("LF_GetPath: No errors detected."); return L_null; } /***************************************************************** LF_ShowPaths() Calls Err_Printf for all of the files contained within the various archives. This function is currently called when a console command is isued by the user. A search limit string is allowed which will limit the filenames that are displayed to those beginning with the limit. This takes an output function as the second parameter which would be compatible with printf or Err_Printf. ******************************************************************/ L_bool LF_ShowPaths(const char* szLimit, L_int (*OutputFunc)(const char*, ...)) { SEARCHPATHS* lpPath=L_null; L_bool bLimit=L_false; FS_CHECK_EXIT bLimit=L_strlen(szLimit); for(lpPath=g_SearchPaths; lpPath; lpPath=lpPath->m_next) { if(L_strnicmp((char*)szLimit, lpPath->m_szFilename, L_strlen(szLimit)) || !bLimit) OutputFunc(" \"%s\", ARCHIVED\n", lpPath->m_szFilename); } LF_SetError("LF_ShowPaths: No problems detected."); return L_true; } /****************************************************************** LF_Init() Initializes the file system and sets the current directory to the sepecified path. ******************************************************************/ L_bool LF_Init(char* dir, L_dword Flags) { g_bFSInited=L_true; LF_ChangeDir(dir); if(L_CHECK_FLAG(Flags, LFINIT_CHECKARCHIVESFIRST)) g_bArchivesFirst=L_true; else g_bArchivesFirst=L_false; LF_SetError("LF_Init: File System created. Starting in \"%s\".", LF_GetDir(L_null, MAX_F_PATH)); return L_true; } /******************************************************** LF_Shutdown() Shuts down the file system, and deletes the archive index. ********************************************************/ L_bool LF_Shutdown() { FS_CHECK_EXIT LF_CloseAllArchives(); g_bFSInited=L_false; g_szCurDir[0]=0; LF_SetError("LF_Shutdown: No problems detected."); return L_true; } /********************************************************************** LF_AddArchive() This function opens a legacy pak file, and stores the name of all the files that are in it, that way when the File_Open function trys to open a file, it will check to see if it is in a pack first. **********************************************************************/ L_bool LF_AddArchive(L_lpstr szFilename) { HLARCHIVE hArchive=L_null; L_dword dwNumFiles=0; L_dword i=0; L_dword nOffset=0; SEARCHPATHS* lpNewPath=L_null; FS_CHECK_EXIT hArchive=Arc_Open(szFilename); if(!hArchive) { LF_SetError("Could not add \"%s\" to search path.", szFilename); return L_false; } dwNumFiles=Arc_GetNumFiles(hArchive); for(i=1; i<=dwNumFiles; i++) { /* Check to see if there is a file already by that name in the search path, if there is we replace it with the new one. */ lpNewPath=LF_GetPath(Arc_GetFilename(hArchive, i)); if(lpNewPath) { L_strncpy(lpNewPath->m_szLibrary, szFilename, MAX_F_PATH); continue; } lpNewPath=malloc(sizeof(SEARCHPATHS)); if(lpNewPath) { L_strncpy(lpNewPath->m_szNameInLibrary, (char*)Arc_GetFilename(hArchive, i), MAX_F_PATH); L_strncpy(lpNewPath->m_szLibrary, szFilename, MAX_F_PATH); if(lpNewPath->m_szNameInLibrary[0]=='.') nOffset=2; else nOffset=0; L_strncpy(lpNewPath->m_szFilename, lpNewPath->m_szNameInLibrary+nOffset, MAX_F_PATH); lpNewPath->m_next=g_SearchPaths; g_SearchPaths=lpNewPath; } } Arc_Close(hArchive); LF_SetError("Added \"%s\" to search path.", szFilename); return L_true; } /************************************************************************ LF_CloseAllArchives() Deletes all of the search path information, this should usually be called from LF_Shutdown, but for various reasons could be called from elswhere in the code. ************************************************************************/ L_bool LF_CloseAllArchives() { SEARCHPATHS* lpPath=L_null; SEARCHPATHS* lpTemp=L_null; FS_CHECK_EXIT /* Just delete all the search paths. */ for(lpPath=g_SearchPaths; lpPath; ) { lpTemp=lpPath->m_next; free(lpPath); lpPath=lpTemp; } g_SearchPaths=L_null; LF_SetError("LF_CloseAllArchives: No errors detected."); return L_true; } /******************************************************* LF_ChangeDir() Changes the working directory to the specified one. *******************************************************/ L_bool LF_ChangeDir(const char* dirname) { FS_CHECK_EXIT _chdir(dirname); /* We need to call File_GetDir, to update our directory string. */ LF_GetDir(L_null, 0); LF_SetError("LF_ChangeDir: No errors detected."); return L_true; } /********************************************* LF_GetDir() Returns the current working directory. *********************************************/ char* LF_GetDir(char* buffer, int nMaxLen) { FS_CHECK_EXIT /* Whenever we get the dir we always renew it with _getdcwd, to make sure it is correct. */ if(!nMaxLen) nMaxLen=MAX_F_PATH; _getdcwd(_getdrive(), g_szCurDir, MAX_F_PATH); LF_SetError("LF_GetDir: No errors detected."); if(buffer) { L_strncpy(buffer, g_szCurDir, nMaxLen); return buffer; } else { return g_szCurDir; } } <file_sep>/games/Archer/Readme.txt Archer Deluxe v1.00b Copyright (C) 2000, <NAME> for Beem Software This folder contains Archer.exe - The executable program of Archer. Readme.txt - This File. Instructions: At the very beginning of the game you will be prompted as to the speed you wish to execute the program. 1 Will run fine on a 75Mhz computer about 20 for a 450Mhz computer. You'll have to guestimate for any other processor speeds. After that you will need to choose your difficulty level. Just type the letter of your choice. After selecting your difficulty level you will go to the view. You'll see your weapon at the base of the screen, and a man moving across the screen. Press space to fire as so as he is in the center of the screen to hit him. If you miss you will die and be prompted to begin again. If you hit him he will die and the game will end. ========================================================== === Version History === === for Archer Deluxe === ========================================================== v1.00b (July 10, 2000) Major fixes to the code. Created speed adjustment. Developed just push button rather than press enter. v0.03a (January 29, 1999) Minor fixes to the code. You can no longer tell when you will be able to hit the guy. v0.01a The original release. You had to press enter to make selections. You could tell when you could hit the enemy. Major visuall issues.<file_sep>/samples/D3DDemo/code/Main.cpp #include <d3d9.h> #include <d3dx9.h> #include <stdio.h> #include <tchar.h> #include <windows.h> #include "GFX3D9.h" #define D3D_MD3 #include "md3.h" #include "resource.h" #pragma comment(lib, "d3d9.lib") #if defined(_WIN64) #pragma comment(lib, "d3dx9_x64.lib") #else #pragma comment(lib, "d3dx9_x86.lib") #endif #pragma comment(lib, "winmm.lib") LPDIRECT3DDEVICE9 g_lpDevice=NULL; D3DPRESENT_PARAMETERS g_SavedPP; #define WM_USER_ACTIVEAPP (WM_USER+1) HBEEMCONSOLE BeemConsole=NULL; #define TESTLIGHT //#define TESTPRIM #ifdef TESTPRIM LPDIRECT3DTEXTURE9 g_lpTestPrimTexture=NULL; IDirect3DTexture9* g_lpTestPrimLM=NULL; LPDIRECT3DVERTEXBUFFER9 g_lpTestPrimVB=NULL; #endif //TESPRIM #define TESTMD3 #ifdef TESTMD3 CMD3PlayerMesh g_lpTestHuman; CMD3PlayerObject g_lpTestPlayer; CMD3WeaponMesh g_lpTestGun; #endif //TESTMD3 //#define TESTME #ifdef TESTME CMD3ObjectMesh g_lpMeTest; #endif TESTME #define TESTFONT #ifdef TESTFONT HD3DFONT TestFont=NULL; #endif //TESTFONT #define TESTIMAGE #ifdef TESTIMAGE HD3DIMAGE TestImage=NULL; HD3DIMAGE TestBG=NULL; #endif //TESTIMAGE typedef unsigned __int64 i64; static BOOL SyncTime( float* FrameTime ) { i64 CurrentTime = 0; static i64 LastUpdate = 0; static i64 Frequency = 0; QueryPerformanceCounter( reinterpret_cast<LARGE_INTEGER*>( &CurrentTime ) ); if( 0 == Frequency ) { QueryPerformanceFrequency( reinterpret_cast<LARGE_INTEGER*>( &Frequency ) ); LastUpdate = CurrentTime; } i64 Elapsed = CurrentTime - LastUpdate; double ElapsedSeconds = static_cast<double>(Elapsed)/Frequency; *FrameTime = static_cast<float>(ElapsedSeconds); if( *FrameTime > 1/120.f ) { LastUpdate = CurrentTime; return TRUE; } return FALSE; } BOOL ConsoleParse(LPSTR szCommand, LPSTR szParams, HBEEMCONSOLE hConsole) { char szOutputMessage[100]; BEGINCHOICE #ifdef TESTMD3 CHOICE(LOADWEAPON) char szFilename[100]; if(!BeemParseGetParam(szFilename, szParams, 1)){ SendBeemConsoleMessage(hConsole, "Usage: LOADWEAPON <string>"); }else{ if(!BeemParseGetString(szFilename, szFilename)){ SendBeemConsoleMessage(hConsole, "Usage: LOADWEAPON <string>"); }else{ if(SUCCEEDED(g_lpTestGun.Load(g_lpDevice, szFilename, DETAIL_HIGH))){ g_lpTestPlayer.SetWeapon(&g_lpTestGun); sprintf(szOutputMessage, "Successfully loaded \"%s\" weapon.", szFilename); SendBeemConsoleMessage(hConsole, szOutputMessage); }else SendBeemConsoleMessage(hConsole, "Could not load MD3 weapon file!"); } } CHOICE(LOADMD3) char szFilename[100]; if(!BeemParseGetParam(szFilename, szParams, 1)){ SendBeemConsoleMessage(hConsole, "Usage: LOADMD3 <string>"); }else{ if(!BeemParseGetString(szFilename, szFilename)){ SendBeemConsoleMessage(hConsole, "Usage: LOADMD3 <string>"); }else{ if((SUCCEEDED(g_lpTestHuman.LoadA(g_lpDevice, szFilename, DETAIL_HIGH)))){ g_lpTestPlayer.SetPlayerMesh(&g_lpTestHuman); g_lpTestPlayer.SetAnimation(TORSO_STAND, MD3SETANIM_WAIT, 2.0f); g_lpTestPlayer.SetAnimation(LEGS_IDLE, MD3SETANIM_WAIT, 2.0f); sprintf(szOutputMessage, "Successfully loaded \"%s\".", szFilename); SendBeemConsoleMessage(hConsole, szOutputMessage); }else SendBeemConsoleMessage(hConsole, "Could not load MD3 file!"); } } CHOICE(SETSKIN) char szSkinName[100]; if(BeemParseGetParam(szSkinName, szParams, 1)){ if(!BeemParseGetString(szSkinName, szSkinName)){ SendBeemConsoleMessage(hConsole, "Usage: SETSKIN <string>"); }else{ if(SUCCEEDED(g_lpTestPlayer.SetSkinByName(szSkinName))){ sprintf(szOutputMessage, "Successfully set skin to \"%s\".", szSkinName); SendBeemConsoleMessage(hConsole, szOutputMessage); }else{ SendBeemConsoleMessage(hConsole, "No such skin exists for this model!"); } } }else{ SendBeemConsoleMessage(hConsole, "Usage: SETSKIN <string>"); } #endif //TESTMD3 CHOICE(QUIT) SendBeemConsoleMessage(hConsole, "Quiting..."); SendMessage(g_SavedPP.hDeviceWindow, WM_CLOSE, 0, 0); CHOICE(CLS) BeemConsoleClearEntries(hConsole); CHOICE(ADD) LONG lValue[3]; if(BeemParseGetInt(&lValue[0], szParams, 1)){ if(BeemParseGetInt(&lValue[1], szParams, 2)){ lValue[2]=lValue[0]+lValue[1]; sprintf(szOutputMessage, "%i", lValue[2]); SendBeemConsoleMessage(hConsole, szOutputMessage); }else{ SendBeemConsoleMessage(hConsole, "Usage: ADD <value> <value>"); } }else{ SendBeemConsoleMessage(hConsole, "Usage: ADD <value> <value>"); } CHOICE(GETTEXMEM) sprintf(szOutputMessage, "%iMB Texture Memory", g_lpDevice->GetAvailableTextureMem()/1024/1024); SendBeemConsoleMessage(hConsole, szOutputMessage); CHOICE(CMDLIST) SendBeemConsoleMessage(hConsole, "ADD"); SendBeemConsoleMessage(hConsole, "QUIT"); SendBeemConsoleMessage(hConsole, "LOADMD3"); SendBeemConsoleMessage(hConsole, "SETSKIN"); SendBeemConsoleMessage(hConsole, "CLS"); SendBeemConsoleMessage(hConsole, "LOADWEAPON"); SendBeemConsoleMessage(hConsole, "GETTEXMEM"); INVALIDCHOICE sprintf(szOutputMessage, "Unknown command: \"%s\"", szCommand); SendBeemConsoleMessage(hConsole, szOutputMessage); ENDCHOICE return TRUE; } #ifdef TESTMD3 BOOL CreateAnimationString(char szAnimationString[100], CMD3PlayerObject * lpObject) { char szUpper[MAX_QPATH]; char szLower[MAX_QPATH]; DWORD dwLower=0, dwUpper=0; DWORD dwBoth=0; BOOL bBoth=FALSE; static DWORD dwLastUpper=0, dwLastLower=0; static char szLastString[100]; lpObject->GetAnimation(&dwUpper, &dwLower); if(dwLastUpper==dwUpper && dwLastLower==dwLower){ strcpy(szAnimationString, szLastString); return TRUE; } if(dwUpper==dwLower){ bBoth=TRUE; dwBoth=dwUpper; } if(!bBoth){ switch(dwUpper) { case TORSO_GESTURE: strcpy(szUpper, "TORSO_GESTURE"); break; case TORSO_ATTACK: strcpy(szUpper, "TORSO_ATTACK"); break; case TORSO_ATTACK2: strcpy(szUpper, "TORSO_ATTACK2"); break; case TORSO_DROP: strcpy(szUpper, "TORSO_DROP"); break; case TORSO_RAISE: strcpy(szUpper, "TORSO_RAISE"); break; case TORSO_STAND: strcpy(szUpper, "TORSO_STAND"); break; case TORSO_STAND2: strcpy(szUpper, "TORSO_STAND2"); break; default: strcpy(szUpper, "Invalid Torso Animation"); break; }; switch(dwLower) { case LEGS_WALKCR: strcpy(szLower, "LEGS_WALKCR"); break; case LEGS_WALK: strcpy(szLower, "LEGS_WALK"); break; case LEGS_RUN: strcpy(szLower, "LEGS_RUN"); break; case LEGS_BACK: strcpy(szLower, "LEGS_BACK"); break; case LEGS_SWIM: strcpy(szLower, "LEGS_SWIM"); break; case LEGS_JUMP: strcpy(szLower, "LEGS_JUMP"); break; case LEGS_LAND: strcpy(szLower, "LEGS_LAND"); break; case LEGS_JUMPB: strcpy(szLower, "LEGS_JUMPB"); break; case LEGS_LANDB: strcpy(szLower, "LEGS_LANDB"); break; case LEGS_IDLE: strcpy(szLower, "LEGS_IDLE"); break; case LEGS_IDLECR: strcpy(szLower, "LEGS_IDLECR"); break; case LEGS_TURN: strcpy(szLower, "LEGS_TURN"); break; default: strcpy(szLower, "Invalid Legs Animation"); break; }; }else{ switch(dwBoth) { case BOTH_DEATH1: strcpy(szUpper, "BOTH_DEATH1"); strcpy(szLower, "BOTH_DEATH1"); break; case BOTH_DEAD1: strcpy(szUpper, "BOTH_DEAD1"); strcpy(szLower, "BOTH_DEAD1"); break; case BOTH_DEATH2: strcpy(szUpper, "BOTH_DEATH2"); strcpy(szLower, "BOTH_DEATH2"); break; case BOTH_DEAD2: strcpy(szUpper, "BOTH_DEAD2"); strcpy(szLower, "BOTH_DEAD2"); break; case BOTH_DEATH3: strcpy(szUpper, "BOTH_DEATH3"); strcpy(szLower, "BOTH_DEATH3"); break; case BOTH_DEAD3: strcpy(szUpper, "BOTH_DEAD3"); strcpy(szLower, "BOTH_DEAD3"); break; }; } dwLastUpper=dwUpper; dwLastLower=dwLower; sprintf(szAnimationString, "Torso: %s Legs: %s", szUpper, szLower); strcpy(szLastString, szAnimationString); return TRUE; } BOOL CycleAnimation(DWORD dwBone, CMD3PlayerObject * lpObject) { DWORD dwUpper=0, dwLower=0; DWORD dwCycleType=MD3SETANIM_FRAME; BOOL bWasBoth=FALSE; lpObject->GetAnimation(&dwUpper, &dwLower); if(dwUpper==dwLower) bWasBoth=TRUE; switch(dwBone) { case 1: //Upper if(bWasBoth){ dwUpper=TORSO_STAND; dwLower=LEGS_IDLE; lpObject->SetAnimation(dwUpper, dwCycleType, 2.0f); lpObject->SetAnimation(dwLower, dwCycleType, 2.0f); }else{ dwUpper++; if(dwUpper > TORSO_STAND2) dwUpper=TORSO_GESTURE; lpObject->SetAnimation(dwUpper, dwCycleType, 2.0f); } return TRUE; case 2: //Legs if(bWasBoth){ dwUpper=TORSO_STAND; dwLower=LEGS_IDLE; lpObject->SetAnimation(dwUpper, dwCycleType, 2.0f); lpObject->SetAnimation(dwLower, dwCycleType, 2.0f); }else{ dwLower++; if(dwLower > LEGS_TURN) dwLower=LEGS_WALKCR; lpObject->SetAnimation(dwLower, dwCycleType, 2.0f); } return TRUE; case 3: //Both if(!bWasBoth){ dwUpper=BOTH_DEATH1; dwLower=BOTH_DEATH1; lpObject->SetAnimation(dwUpper, dwCycleType, 1.0f); }else{ dwUpper++; dwLower++; if(dwUpper > BOTH_DEAD3){ dwUpper=BOTH_DEATH1; dwLower=BOTH_DEATH1; } lpObject->SetAnimation(dwUpper, dwCycleType, 1.0f); } return TRUE; default: return FALSE; }; } #endif //TESTMD3 /* ReleasePoolResource() should release any resource in the default pool. This function is called during device validation. */ BOOL InvalidateDeviceResources() { /* Vertex Buffers need to be released. */ #ifdef TESTPRIM SAFE_RELEASE(g_lpTestPrimVB); #endif //TESTPRIM #ifdef TESTMD3 g_lpTestHuman.Invalidate(); g_lpTestGun.Invalidate(); #endif //TESTMD3 #ifdef TESTME g_lpMeTest.Invalidate(); #endif //TESTME #ifdef TESTIMAGE InvalidateD3DImage(TestImage); InvalidateD3DImage(TestBG); #endif //TESTIMAGE #ifdef TESTFONT InvalidateD3DFont(TestFont); #endif //TESTFONT InvalidateBeemConsole(BeemConsole); return TRUE; } /* RestoreDeviceResources() should reload and reinitialize any resources released in ReleaseDeviceResources. Addittionally it can be used to create resources during app initialization. */ BOOL RestoreDeviceResources() { /* During creation or device validation, the viewport, projection matix, view matrix, and other D3D states need to be set. */ SendBeemConsoleMessage(BeemConsole, "Validating Device Resources..."); SetViewPort(g_lpDevice, g_SavedPP.BackBufferWidth, g_SavedPP.BackBufferHeight); SetProjectionMatrix(g_lpDevice, g_SavedPP.BackBufferWidth, g_SavedPP.BackBufferHeight, 1.0f, 1000.0f); D3DXMATRIX ViewMatrix; //D3DXMatrixLookAtLH(&ViewMatrix, &D3DXVECTOR3(0.0f, 0.0f, -100.0f), &D3DXVECTOR3(0.0f, 0.0f, 0.0f), &D3DXVECTOR3(0.0f, 1.0f, 0.0f)); D3DXMatrixIdentity(&ViewMatrix); ViewMatrix._43=100.0f; #ifdef TESTME ViewMatrix._43=250.0f; #endif //TESTME g_lpDevice->SetTransform(D3DTS_VIEW, &ViewMatrix); ValidateBeemConsole(BeemConsole); SetTextureFilter(g_lpDevice, 0, D3DFILTER_TRILINEAR); SetTextureFilter(g_lpDevice, 1, D3DFILTER_TRILINEAR); g_lpDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); g_lpDevice->SetRenderState(D3DRS_LIGHTING, FALSE); #ifdef TESTFONT ValidateD3DFont(TestFont); #endif //TESTFONT #ifdef TESTLIGHT /* g_lpDevice->SetRenderState(D3DRS_LIGHTING, TRUE); D3DLIGHT9 TestLight; ZeroMemory(&TestLight, sizeof(D3DLIGHT9)); TestLight.Type=D3DLIGHT_DIRECTIONAL; TestLight.Diffuse.r=1.0f; TestLight.Diffuse.g=1.0f; TestLight.Diffuse.b=1.0f; TestLight.Diffuse.a=1.0f; TestLight.Specular.r=0.0f; TestLight.Specular.g=0.0f; TestLight.Specular.b=0.0f; TestLight.Specular.a=0.0f; TestLight.Ambient.r=0.0f; TestLight.Ambient.g=0.0f; TestLight.Ambient.b=0.0f; TestLight.Ambient.a=0.0f; TestLight.Position.x=0.0f; TestLight.Position.y=0.0f; TestLight.Position.z=0.0f; TestLight.Direction.x=0.0f; TestLight.Direction.y=0.0f; TestLight.Direction.z=1.0f; TestLight.Range=100.0f; TestLight.Falloff=1.0f; TestLight.Attenuation0=0.0f; TestLight.Attenuation1=1.0f; TestLight.Attenuation2=0.0f; TestLight.Theta=0.0f; TestLight.Phi=0.0f; g_lpDevice->SetLight(0, &TestLight); g_lpDevice->LightEnable(0, TRUE); //g_lpDevice->SetRenderState( D3DRS_AMBIENT, 0xff404040l); D3DMATERIAL9 mtrl; ZeroMemory( &mtrl, sizeof(mtrl) ); mtrl.Diffuse.r = mtrl.Ambient.r = 1.0f; mtrl.Diffuse.g = mtrl.Ambient.g = 1.0f; mtrl.Diffuse.b = mtrl.Ambient.b = 1.0f; mtrl.Diffuse.a = mtrl.Ambient.a = 1.0f; g_lpDevice->SetMaterial( &mtrl ); */ D3DLIGHT9 Light={ D3DLIGHT_DIRECTIONAL, //Type {1.0f, 1.0f, 1.0f, 0.0f},//Diffuse {0.0f, 0.0f, 0.0f, 0.0f},//Specular {0.0f, 0.0f, 0.0f, 0.0f},//Ambient {0.0f, 0.0f, 0.0f},//Position {0.0f, 0.0f, 1.0f},//Direction 0.0f,//Range 0.0f,//Falloff 0.0f,//Attenuation0 0.0f,//Attenuation1 0.0f,//Attenuation2 0.0f,//Theta 0.0f};//Phi g_lpDevice->SetLight(0, &Light); g_lpDevice->LightEnable(0, TRUE); D3DMATERIAL9 Material={ {1.0f, 1.0f, 1.0f, 1.0f},//Diffuse {1.0f, 1.0f, 1.0f, 1.0f},//Ambient {1.0f, 1.0f, 1.0f, 1.0f},//Specular {0.0f, 0.0f, 0.0f, 0.0f},//Emissive 0.0f}; //Power g_lpDevice->SetMaterial(&Material); #endif TESTLIGHT #ifdef TESTPRIM /* All vertices currently in existence should be (re)created. */ CUSTOMVERTEX vTestPrim[4]; vTestPrim[0]=CUSTOMVERTEX( -40.0f, -40.0f, 30.0f, //Position -40.0f, -40.0f, 20.0f, //Normal 0xFFFFFFFF,//0xFFFFFFFF, //Diffuse color 0XFFFFFFFF, //Specular color 1.0f, 1.0f); //Texture coordinates vTestPrim[1]=CUSTOMVERTEX( -40.0f, 40.0f, 30.0f, -40.0f, 40.0f, 20.0f, 0xFFFFFFFF, 0xFFFFFFFF, 1.0f, 0.0f); vTestPrim[2]=CUSTOMVERTEX( 40.0f, 40.0f, 30.0f, 40.0f, 40.0f, 20.0f, 0xFFFFFFFF, 0xFFFFFFFF, 0.0f, 0.0f); vTestPrim[3]=CUSTOMVERTEX( 40.0f, -40.0f, 30.0f, 40.0f, -40.0f, 20.0f, 0xFFFFFFFF, 0xFFFFFFFF, 0.0f, 1.0f); /* vTestPrim[0]=CUSTOMVERTEX( -40.0f, -40.0f, 30.0f, //Position -40.0f, -40.0f, 20.0f, //Normal 0xFFFFFFFF,//0xFFFFFFFF, //Diffuse color 0XFFFFFFFF, //Specular color 0.0f, 1.0f); //Texture coordinates vTestPrim[1]=CUSTOMVERTEX( 0.0f, 40.0f, 30.0f, 0.0f, 40.0f, 20.0f, 0xFFFFFFFF, 0xFFFFFFFF, 0.5f, 0.0f); vTestPrim[2]=CUSTOMVERTEX( 40.0f, -40.0f, 30.0f, 40.0f, -40.0f, 20.0f, 0xFFFFFFFF, 0xFFFFFFFF, 1.0f, 1.0f); */ g_lpDevice->CreateVertexBuffer( 4*sizeof(CUSTOMVERTEX), 0, CUSTOMVERTEX_TYPE, D3DPOOL_DEFAULT, &g_lpTestPrimVB, NULL); PVOID pVertices = 0; if(FAILED(g_lpTestPrimVB->Lock(0, sizeof(CUSTOMVERTEX)*4, &pVertices, 0))){ return E_FAIL; } memcpy(pVertices, &vTestPrim, sizeof(CUSTOMVERTEX)*4); g_lpTestPrimVB->Unlock(); #endif //TESTPRIM #ifdef TESTIMAGE ValidateD3DImage(TestImage); ValidateD3DImage(TestBG); #endif //TESTIMAGE #ifdef TESTMD3 g_lpTestHuman.Validate(); g_lpTestGun.Validate(); #endif //TESTMD3 #ifdef TESTME g_lpMeTest.Validate(g_lpDevice); #endif //TESTME SendBeemConsoleMessage(BeemConsole, "Device Resources Validated."); return TRUE; } BOOL GameInit(HWND hwnd, BOOL bWindowed, HINSTANCE hInstance) { LPDIRECT3D9 lpD3D=NULL; DWORD dwDeviceWidth=0, dwDeviceHeight=0; BOOL bResult=TRUE; char szTemp[200]; /* We start by creating Direct3D */ lpD3D=Direct3DCreate9(D3D_SDK_VERSION); if(!lpD3D) { MessageBox(hwnd, "This requires DirectX 9.0c", "D3DDemo", MB_OK); return FALSE; } /* CoInitialize(NULL); CoCreateInstance(CLSID_Direct3D9, NULL, CLSCTX_ALL, IID_IDirect3D9, &g_lpD3D); */ if(lpD3D==NULL) return FALSE; if(bWindowed){ dwDeviceWidth=800; dwDeviceHeight=600; }else{ dwDeviceWidth=1024; dwDeviceHeight=768; } /* We Initialize the Direct3D Device */ if(!InitD3D( hwnd, dwDeviceWidth, dwDeviceHeight, bWindowed, FALSE, //D3DFMT_R5G6B5, D3DFMT_X8R8G8B8, lpD3D, &g_lpDevice, NULL, &g_SavedPP)) { lpD3D->Release(); return FALSE; } lpD3D->Release(); CorrectWindowSize(hwnd, dwDeviceWidth, dwDeviceHeight, bWindowed, NULL); g_lpDevice->Clear( 0, 0, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0, 0, 200), 1.0f, 0); //#define CSYSTEMFONT #ifdef CSYSTEMFONT HD3DFONT Font=NULL; Font=CreateD3DFontFromFont( g_lpDevice, (HFONT)GetStockObject(SYSTEM_FONT), 0xFFFFFF00); BeemConsole=CreateBeemConsole(g_lpDevice, Font, NULL, ConsoleParse); DeleteD3DFont(Font); #else //CSYSTEMFONT BeemConsole=CreateBeemConsole(g_lpDevice, NULL, NULL, ConsoleParse); #endif //CSYSTEMFONT SendBeemConsoleMessage(BeemConsole, "Direct3DCreate9()"); SendBeemConsoleMessage(BeemConsole, "InitD3D()"); sprintf(szTemp, "Display Mode Set To: %ix%i", dwDeviceWidth, dwDeviceHeight); SendBeemConsoleMessage(BeemConsole, szTemp); SendBeemConsoleMessage(BeemConsole, "CorrectWindowSize()"); SendBeemConsoleMessage(BeemConsole, "IDirect3DDevice9::Clear()"); SendBeemConsoleMessage(BeemConsole, "CreateBeemConsole()"); #ifdef TESTMD3 SendBeemConsoleCommand(BeemConsole, "loadmd3 \"laracroft\""); SendBeemConsoleCommand(BeemConsole, "loadweapon \"machinegun\""); #endif //TESTMD3 #ifdef TESTME g_lpMeTest.Load(g_lpDevice, "me\\me_md3", DETAIL_HIGH); #endif //TESTME #ifdef TESTPRIM /* Load the texture from the file. */ D3DXCreateTextureFromFile(g_lpDevice, "test\\testtex.jpg", &g_lpTestPrimTexture); D3DXCreateTextureFromFile(g_lpDevice, "test\\testtexlm.jpg", &g_lpTestPrimLM); SendBeemConsoleMessage(BeemConsole, "D3DXCreateTextureFromFile(): texture.bmp"); #endif //TESTPRIM #ifdef TESTIMAGE TestImage=CreateD3DImageFromFile(g_lpDevice, "TestImage2.bmp", 100, 100, 0xFFFF00FF); SendBeemConsoleMessage(BeemConsole, "CreateD3DImageFromeFile(): TestImage2.bmp"); TestBG=CreateD3DImageFromFile(g_lpDevice, "bg.bmp", 256, 256, 0xFFFF00FF); SendBeemConsoleMessage(BeemConsole, "CreateD3DImageFromFile(): bg.bmp"); #endif //TESTIMAGE #ifdef TESTFONT TestFont=GetD3DFontDefault(g_lpDevice); SendBeemConsoleMessage(BeemConsole, "GetD3DFontDefault()"); #endif //TESTFONT RestoreDeviceResources(); SendBeemConsoleMessage(BeemConsole, "---"); return TRUE; } void GameShutdown() { /* Any COM interfaces that were created should be released. */ LPDIRECT3D9 lpD3D=NULL; SendBeemConsoleMessage(BeemConsole, "Shutting Down Game..."); g_lpDevice->GetDirect3D(&lpD3D); #ifdef TESTPRIM SAFE_RELEASE(g_lpTestPrimVB); SAFE_RELEASE(g_lpTestPrimTexture); SAFE_RELEASE(g_lpTestPrimLM); #endif //TESTPRIM #ifdef TESTMD3 g_lpTestHuman.Clear(); g_lpTestGun.Clear(); //CMD3SkinFile::ClearTexDB(); #endif //TESTMD3 #ifdef TESTME g_lpMeTest.Clear(); #endif //TESTME #ifdef TESTIMAGE DeleteD3DImage(TestImage); DeleteD3DImage(TestBG); #endif //TESTIMAGE #ifdef TESTFONT DeleteD3DFont(TestFont); #endif //TESTFONT DeleteBeemConsole(BeemConsole); //#define DEBUG_D3DSHUTDOWN #ifdef DEBUG_D3DSHUTDOWN LONG lDeviceLeft=0; char szDeviceLeft[100]; lDeviceLeft=g_lpDevice->Release(); sprintf(szDeviceLeft, "%i devices left", lDeviceLeft); MessageBox(0, szDeviceLeft, 0, 0); lDeviceLeft=lpD3D->Release(); sprintf(szDeviceLeft, "%i D3D's left", lDeviceLeft); MessageBox(0, szDeviceLeft, 0, 0); #else //DEBUG_D3DSHUTDOWN SAFE_RELEASE(g_lpDevice); SAFE_RELEASE(lpD3D); #endif //DEBUG_D3DSHUTDOWN //CoUninitialize(); } BOOL Render() { float DeltaTime = 0; BOOL Continue = SyncTime( &DeltaTime ); if( !Continue ) { return TRUE; } if(!ValidateDevice( &g_lpDevice, NULL,//&g_lpBackSurface, g_SavedPP, InvalidateDeviceResources, RestoreDeviceResources))return FALSE; if(!g_lpDevice)return FALSE; /* Clear the buffer */ g_lpDevice->Clear( 0, 0, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0, 0, 255), 1.0f, 0); g_lpDevice->BeginScene(); //All 3D Rendering goes here. #ifdef TESTIMAGE //RenderD3DImage(&TestBG, 0, 0, g_lpDevice); RenderD3DImageRelativeEx(TestBG, 0.0f, 0.0f, 100.0f, 100.0f, 0, 0, GetD3DImageWidth(TestBG), GetD3DImageHeight(TestBG)); #endif //TESTIMAGE #define TESTROTATE #ifdef TESTROTATE /* The following rotates the world around, just to show that the enviro is 3D */ static float Seconds = 0.f; Seconds += DeltaTime; if( Seconds > 5.f ) { Seconds = 0.f; } D3DXMATRIX WorldMatrix; D3DXMatrixRotationY(&WorldMatrix, (Seconds/5.f)*D3DX_PI*2.f); g_lpDevice->SetTransform(D3DTS_WORLD, &WorldMatrix); #endif //TESTROTATE #ifdef TESTPRIM //D3DXMatrixIdentity(&WorldMatrix); g_lpDevice->SetVertexShader(NULL); g_lpDevice->SetFVF(CUSTOMVERTEX_TYPE); #define MULTIPASS #ifdef MULTIPASS g_lpDevice->SetTexture(0, g_lpTestPrimTexture); g_lpDevice->SetStreamSource(0, g_lpTestPrimVB, 0, sizeof(CUSTOMVERTEX)); g_lpDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE); g_lpDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1); g_lpDevice->DrawPrimitive(D3DPT_TRIANGLEFAN, 0, 2); g_lpDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); g_lpDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ZERO); g_lpDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_SRCCOLOR); g_lpDevice->SetTexture(0, g_lpTestPrimLM); g_lpDevice->DrawPrimitive(D3DPT_TRIANGLEFAN, 0, 2); g_lpDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE); g_lpDevice->SetTexture(0, NULL); #else //MULTIPASS g_lpDevice->SetStreamSource(0, g_lpTestPrimVB, 0, sizeof(CUSTOMVERTEX)); g_lpDevice->SetTexture(0, g_lpTestPrimTexture); g_lpDevice->SetTexture(1, g_lpTestPrimLM); g_lpDevice->SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, 0); g_lpDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE); g_lpDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1); g_lpDevice->SetTextureStageState(1, D3DTSS_TEXCOORDINDEX, 0); g_lpDevice->SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_TEXTURE); g_lpDevice->SetTextureStageState(1, D3DTSS_COLORARG2, D3DTA_CURRENT); g_lpDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_MODULATE); g_lpDevice->DrawPrimitive(D3DPT_TRIANGLEFAN, 0, 2); g_lpDevice->SetTexture(1, NULL); g_lpDevice->SetTexture(0, NULL); #endif //MULTIPASS #endif #ifdef TESTMD3 g_lpTestPlayer.Render( WorldMatrix ); g_lpDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID); #ifdef TESTFONT char szAnimationString[100]; CreateAnimationString(szAnimationString, &g_lpTestPlayer); RenderD3DFontString(TestFont, 0, 0, szAnimationString); #endif //TESTFONT #endif //TESTMD3 #ifdef TESTME g_lpMeTest.Render(g_lpDevice); #endif //TESTME #ifdef TESTIMAGE POINT ps; GetCursorPos(&ps); ScreenToClient(g_SavedPP.hDeviceWindow, &ps); ps.x-=(GetD3DImageWidth(TestImage)/2); ps.y-=(GetD3DImageHeight(TestImage)/2); RenderD3DImage(TestImage, ps.x, ps.y); #endif //TESTIMAGE RenderBeemConsole(BeemConsole); g_lpDevice->EndScene(); //Present the BackBuffer g_lpDevice->Present(NULL, NULL, NULL, NULL); return TRUE; } BOOL GameLoop() { Render(); return TRUE; } LRESULT CALLBACK WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch(uMsg) { case WM_CREATE: break; case WM_ACTIVATEAPP: if(wParam){ PostMessage(hwnd, WM_USER_ACTIVEAPP, TRUE, 0); }else{ PostMessage(hwnd, WM_USER_ACTIVEAPP, FALSE, 0); } break; case WM_LBUTTONDOWN: #ifdef TESTMD3 CycleAnimation(1, &g_lpTestPlayer); #endif //TESTMD3 break; case WM_RBUTTONDOWN: #ifdef TESTMD3 CycleAnimation(2, &g_lpTestPlayer); #endif //TESTMD3 break; case WM_MBUTTONDOWN: #ifdef TESTMD3 CycleAnimation(3, &g_lpTestPlayer); #endif break; case WM_CHAR: BeemConsoleOnChar(BeemConsole, wParam); break; case WM_KEYDOWN: { switch(wParam) { case VK_ESCAPE: SendMessage(hwnd, WM_CLOSE, 0, 0); break; case VK_F11: ToggleActivateBeemConsole(BeemConsole); break; case VK_NEXT: ScrollBeemConsole(BeemConsole, -1); break; case VK_PRIOR: ScrollBeemConsole(BeemConsole, 1); break; default: break; } break; } case WM_CLOSE: DestroyWindow(hwnd); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hwnd, uMsg, wParam, lParam); } return 0l; } int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { HWND hwnd=NULL; MSG msg; WNDCLASSEX wc; BOOL bActiveApp=TRUE; /* Create the window's class */ static TCHAR szAppName[] = TEXT("D3DDemo"); wc.cbSize=sizeof(wc); wc.style = CS_HREDRAW|CS_VREDRAW|CS_OWNDC; wc.cbClsExtra=0; wc.cbWndExtra=0; wc.lpfnWndProc=WndProc; wc.hInstance=hInstance; wc.hbrBackground=(HBRUSH)GetStockObject(DKGRAY_BRUSH); wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hIconSm = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_DXICON)); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.lpszMenuName=NULL; wc.lpszClassName=szAppName; if(!RegisterClassEx(&wc)){ MessageBox( NULL, TEXT("This program requires Windows NT!"), szAppName, MB_OK|MB_ICONERROR); return 0; } /* Create the window */ hwnd = CreateWindowEx( 0, szAppName, szAppName, WS_CAPTION|WS_SYSMENU|WS_VISIBLE|WS_MINIMIZEBOX, CW_USEDEFAULT, CW_USEDEFAULT, 640, 480, NULL, NULL, hInstance, NULL); if(hwnd==NULL) return -1; SetCurrentDirectory( TEXT( "data" ) ); ShowWindow(hwnd, nShowCmd); UpdateWindow(hwnd); if(!GameInit(hwnd, TRUE, hInstance)) DestroyWindow(hwnd); while(TRUE){ if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)){ if(msg.message==WM_QUIT) break; if(msg.message==WM_USER_ACTIVEAPP) bActiveApp=msg.wParam; TranslateMessage(&msg); DispatchMessage(&msg); }else{ if(bActiveApp) GameLoop(); else WaitMessage(); } } GameShutdown(); return msg.wParam; }<file_sep>/games/Legacy-Engine/Source/lm_sys/lm_mesh_lg.cpp #include "lm_mesh_lg.h" #include <stdio.h> #include "lg_func.h" #include "lg_err.h" #include "lf_sys2.h" IDirect3DDevice9* CLMeshLG::s_pDevice=LG_NULL; CLMeshLG::CLMeshLG() : CLMeshAnim() , m_pVB(LG_NULL) , m_pIB(LG_NULL) , m_pTex(LG_NULL) { m_szMeshFilePath[0]=0; } CLMeshLG::~CLMeshLG() { Unload(); } lg_bool CLMeshLG::Load(LMPath szFile) { //Unload in case a mesh was already loaded. Unload(); //Open the file: LF_FILE3 fin=LF_Open(szFile, LF_ACCESS_READ, LF_OPEN_EXISTING); if(!fin) return LG_FALSE; //Serialize will take care of loading the model data. lg_bool bResult=Serialize(fin, ReadFn, RW_READ); //We're now done with the file. LF_Close(fin); //If we succeeded in loading the mesh we'll take aditional steps if(bResult) { //We'll set the flag to loaded (this will also clear any //other garbage that might have been left in the loaded flag. m_nFlags=LM_FLAG_LOADED; //We'll save the directory in which the mesh was located //so that we can get the default textures if we want. LF_GetDirFromPath(m_szMeshFilePath, szFile); m_pTex=new tm_tex[m_nNumMtrs]; for(lg_dword i=0; i<m_nNumMtrs; i++) { m_pTex[i]=0; } /* //We'll make our mesh d3d ready MakeD3DReady(); */ //We also want the animation data to be setup. InitAnimData(); } else { //If we couldn't load, we'll set m_nFlags to zero so that //if the LM_FLAG_LOADED flag was set it will be clear. m_nFlags=0; } return bResult; } lg_bool CLMeshLG::Save(CLMBase::LMPath szFile) { //No reason to be able to save meshes in the game. return LG_FALSE; } lg_void CLMeshLG::Unload() { //We won't bother to make sure a mesh is loaded, //we'll just delete everything anyway, and everything //that is empty should be set to null anyway. //We need to get rid of the anim data: DeleteAnimData(); //Get rid of all rasterization information: //We can just delete the texture array, //the texture manager will worry about getting //rid of the textures: LG_SafeDeleteArray(m_pTex); //Release Direct3D interfaces: LG_SafeRelease(m_pVB); LG_SafeRelease(m_pIB); //Call the base method unload: CLMeshAnim::Unload(); //Clear the flags (the base method should have set it, but just in case: m_nFlags=0; } lg_void CLMeshLG::MakeD3DReady(lg_dword flags) { //Check some flags to make sure we actually can or need to //creat the direct3d interfaces, if we don't have a mesh loaded //or the mesh is already D3D ready we're good, if there is no //device there is nothing we can do. if(!LG_CheckFlag(m_nFlags, LM_FLAG_LOADED) || LG_CheckFlag(m_nFlags, LM_FLAG_D3D_READY) || !s_pDevice) { Err_Printf("CLMeshLG ERROR: Could not make mesh D3D Ready."); return; } //If we want to load the default textures we'll load them //from the file, if(LG_CheckFlag(flags, D3DR_FLAG_LOAD_DEF_TEX)) { lf_path szTexPath; for(lg_dword i=0; i<m_nNumMtrs; i++) { _snprintf(szTexPath, LF_MAX_PATH, "%s%s", m_szMeshFilePath, m_pMtrs[i].szFile); szTexPath[LF_MAX_PATH]=0; m_pTex[i]=CLTMgr::TM_LoadTex(szTexPath, 0); } } //We can now call Validate to get everything D3D ready, //we'll know if the LM_FLAG_D3D_VALID flag is set afterwards //that we suceeded, we have to set the LM_FLAG_D3D_READY before //hand or validate will fail. LG_SetFlag(m_nFlags, LM_FLAG_D3D_READY); Validate(); //If we failed... if(!LG_CheckFlag(m_nFlags, LM_FLAG_D3D_VALID)) { //Unset the D3D_READY flag, and print an error message: LG_UnsetFlag(m_nFlags, LM_FLAG_D3D_READY); Err_Printf("CLMeshLG ERROR: Could not validate mesh!"); } //If we succeed we're good. } lg_void CLMeshLG::Validate() { const D3DPOOL nPool=D3DPOOL_MANAGED; //If the D3D_READY flag is set we know we are //good to validate, if the D3D_VALID flag is set //then we are already valid: if(LG_CheckFlag(m_nFlags, LM_FLAG_D3D_VALID) || !LG_CheckFlag(m_nFlags, LM_FLAG_D3D_READY)) return; //We don't need to worry about validating textures because //the texture manager does that. //We do need a vertex buffer, though: lg_result nResult; nResult=s_pDevice->CreateVertexBuffer( m_nNumVerts*sizeof(MeshVertex), D3DUSAGE_WRITEONLY, LM_VERTEX_FORMAT, nPool, &m_pVB, LG_NULL); if(LG_FAILED(nResult)) return; //We also need an index buffer: nResult=s_pDevice->CreateIndexBuffer( m_nNumTris*3*sizeof(*m_pIndexes), D3DUSAGE_WRITEONLY, D3DFMT_INDEX16, nPool, &m_pIB, LG_NULL); if(LG_FAILED(nResult)) { LG_SafeRelease(m_pVB); m_pIB=LG_NULL; return; } //Now we need to fill in the buffer with default data: lg_void* pBuffer=LG_NULL; nResult=m_pVB->Lock(0, m_nNumVerts*sizeof(MeshVertex), (void**)&pBuffer, 0); //If we couldn't lock we got serious issues: if(LG_FAILED(nResult)) { LG_SafeRelease(m_pVB); LG_SafeRelease(m_pIB); return; } //Just copy over the buffer: memcpy(pBuffer, m_pVerts, m_nNumVerts*sizeof(MeshVertex)); //And unlock the buffer: m_pVB->Unlock(); //Now fill the index buffer: nResult=m_pIB->Lock(0, m_nNumTris*3*sizeof(*m_pIndexes), &pBuffer, 0); //If we couldn't lock we got serious issues: if(LG_FAILED(nResult)) { LG_SafeRelease(m_pVB); LG_SafeRelease(m_pIB); return; } memcpy(pBuffer, m_pIndexes, m_nNumTris*3*sizeof(*m_pIndexes)); m_pIB->Unlock(); LG_SetFlag(m_nFlags, LM_FLAG_D3D_VALID); } lg_void CLMeshLG::Invalidate() { //Because the index and vertex buffers are managed //we don't need to do anything here. If they //weren't managed the code would look as follows. /* LG_SafeRelease(m_pVB); LG_SafeRelease(m_pIB) LG_UnsetFlag(m_nFlags, LM_FLAG_D3D_VALID); */ } lg_bool CLMeshLG::IsD3DReady() { return LG_CheckFlag(m_nFlags, LM_FLAG_D3D_READY); } CLMesh2::MeshVertex* CLMeshLG::LockTransfVB() { if(!LG_CheckFlag(m_nFlags, LM_FLAG_D3D_VALID)) return LG_NULL; lg_result nResult; MeshVertex* pBuffer; nResult=m_pVB->Lock(0, m_nNumVerts*sizeof(MeshVertex), (lg_void**)&pBuffer, 0); if(LG_FAILED(nResult)) return LG_NULL; return pBuffer; } void CLMeshLG::UnlockTransfVB() { m_pVB->Unlock(); } lg_void CLMeshLG::Render() { //This is the basic render method: //Can't render if we're not valid: if(!LG_CheckFlag(m_nFlags, LM_FLAG_D3D_VALID)) return; s_pDevice->SetFVF(LM_VERTEX_FORMAT); s_pDevice->SetStreamSource(0, m_pVB, 0, sizeof(MeshVertex)); s_pDevice->SetIndices(m_pIB); //Set the material for the mesh, in the future this might //be controlled by model properties, for now it is //just a default material. static D3DMATERIAL9 d3d9mtr={ {1.0f, 1.0f, 1.0f, 1.0f},//Diffuse {1.0f, 1.0f, 1.0f, 1.0f},//Ambient {1.0f, 1.0f, 1.0f, 1.0f},//Specular {0.0f, 0.0f, 0.0f, 0.0f},//Emissive 0.0f}; //Power s_pDevice->SetMaterial(&d3d9mtr); //The basic render method simply renders all the SubMeshes //with the default textures for(lg_dword i=0; i<m_nNumSubMesh; i++) { CLTMgr::TM_SetTexture(m_pSubMesh[i].nMtrIndex!=-1?m_pTex[m_pSubMesh[i].nMtrIndex]:0, 0); s_pDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, 0, m_nNumVerts, m_pSubMesh[i].nFirstIndex, m_pSubMesh[i].nNumTri); } } lg_void CLMeshLG::Render(const CLSkin *pSkin) { //The skinned render method: //This is the basic render method: if(!pSkin || !LG_CheckFlag(pSkin->m_nFlags, pSkin->LM_FLAG_LOADED)) { Render(); return; } //Can't render if we're not valid: if(!LG_CheckFlag(m_nFlags, LM_FLAG_D3D_VALID)) return; s_pDevice->SetFVF(LM_VERTEX_FORMAT); s_pDevice->SetStreamSource(0, m_pVB, 0, sizeof(MeshVertex)); s_pDevice->SetIndices(m_pIB); //Set the material for the mesh, in the future this might //be controlled by model properties, for now it is //just a default material. static D3DMATERIAL9 d3d9mtr={ {1.0f, 1.0f, 1.0f, 1.0f},//Diffuse {1.0f, 1.0f, 1.0f, 1.0f},//Ambient {1.0f, 1.0f, 1.0f, 1.0f},//Specular {0.0f, 0.0f, 0.0f, 0.0f},//Emissive 0.0f}; //Power s_pDevice->SetMaterial(&d3d9mtr); static D3DXMATRIX matTrans, matView, matProj; s_pDevice->GetTransform(D3DTS_PROJECTION, &matProj); s_pDevice->GetTransform(D3DTS_VIEW, &matView); s_pDevice->GetTransform(D3DTS_WORLD, &matTrans); matTrans=matTrans*matView*matProj; //The basic render method simply renders all the SubMeshes //with the default textures for(lg_dword i=0; i<m_nNumSubMesh; i++) { CLTMgr::TM_SetTexture(m_pSubMesh[i].nMtrIndex!=-1?m_pTex[m_pSubMesh[i].nMtrIndex]:0, 0); ID3DXEffect* pFx=LG_NULL; tm_tex txtr=0; CLMtrMgr::MTR_GetInterfaces(pSkin->m_pCmpRefs[i], &txtr, &pFx); UINT nPasses=0; CLTMgr::TM_SetTexture(txtr, 0); pFx->SetMatrix("matWVP", &matTrans); //pFx->SetInt("nTime", timeGetTime()); pFx->Begin(&nPasses, 0); for(lg_dword j=0; j<nPasses; j++) { pFx->BeginPass(j); s_pDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, 0, m_nNumVerts, m_pSubMesh[i].nFirstIndex, m_pSubMesh[i].nNumTri); pFx->EndPass(); } pFx->End(); } } lg_void CLMeshLG::LM_Init(IDirect3DDevice9* pDevice) { LM_Shutdown(); s_pDevice=pDevice; if(s_pDevice)s_pDevice->AddRef(); } lg_void CLMeshLG::LM_Shutdown() { LG_SafeRelease(s_pDevice); } lg_void CLMeshLG::LM_SetRenderStates() { if(!s_pDevice) return; s_pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); s_pDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); s_pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); s_pDevice->SetRenderState(D3DRS_NORMALIZENORMALS, TRUE); s_pDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); s_pDevice->SetRenderState(D3DRS_ZENABLE, TRUE); s_pDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE); s_pDevice->SetSamplerState( 0, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP); s_pDevice->SetSamplerState( 0, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP); } lg_void CLMeshLG::LM_SetSkyboxRenderStates() { if(!s_pDevice) return; D3DMATRIX m; s_pDevice->SetTransform(D3DTS_WORLD, D3DXMatrixIdentity((D3DXMATRIX*)&m)); LM_SetRenderStates(); s_pDevice->SetRenderState(D3DRS_ZENABLE, FALSE); s_pDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE); s_pDevice->SetRenderState(D3DRS_LIGHTING, FALSE); s_pDevice->SetSamplerState( 0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP); s_pDevice->SetSamplerState( 0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP); } lg_uint __cdecl CLMeshLG::ReadFn(lg_void* file, lg_void* buffer, lg_uint size) { return LF_Read(file, buffer, size); }<file_sep>/games/Explor2002/Source_Old/ExplorED DOS/Readme.txt The obsolete folder contains developmental portions of ExplorED that are no longer used or are obsolete. They are not used in the final release and there really isn't any reason (other than novelty) to keep them. I don't know what most of them are anymore but I will try to give some kind of explanation here. dosexplored: A dos version of explorED. With the release of the windows version this project was stopped completely. borland: Early development stage of ExplorED for windows. This one is compatible with borland based compilers (under a win32 api). It is now scrapped as the msvc version has all the same functionallity. mapconv: a lot of routines used to update obsolete map formats. None of them have any normal uses. obsfunc: some badly written source code for very early versions of the development. openmap: these funcitons were implemented into the dos version (which is now obsolete) and don't do much as standalone. These might still have some use depending on how a developer feels about them.<file_sep>/games/Legacy-Engine/Scrapped/tools/ms3dreader/ms3dreader.c #include <stdio.h> #include <memory.h> #include <malloc.h> #pragma pack(1) typedef struct _ms3d_vertex{ unsigned char flags; // SELECTED | SELECTED2 | HIDDEN float vertex[3]; // signed char boneId; // -1 = no bone unsigned char referenceCount; }ms3d_vertex; typedef struct _ms3d_triangle{ unsigned short flags; // SELECTED | SELECTED2 | HIDDEN unsigned short vertexIndices[3]; // float vertexNormals[3][3]; // float s[3]; // float t[3]; // unsigned char smoothingGroup; // 1 - 32 unsigned char groupIndex; // }ms3d_triangle; typedef struct { unsigned char flags; // SELECTED | HIDDEN signed char name[32]; // unsigned short numtriangles; // unsigned short* triangleIndices; // the groups group the triangles signed char materialIndex; // -1 = no material } ms3d_group_t; typedef struct _MILKSHAPE_FILE{ char id[10]; int version; unsigned short nNumVertices; ms3d_vertex* pVertices; unsigned short nNumTriangles; ms3d_triangle* pTriangles; unsigned short nNumGroups; ms3d_group_t* pGroups; }MILKSHAPE_FILE; int main() { MILKSHAPE_FILE msf; char szFile[]=".\\blaine\\me_skin.ms3d"; FILE* fin=NULL; int i=0, j=0; memset(&msf, 0, sizeof(MILKSHAPE_FILE)); fin=fopen(szFile, "rb"); if(!fin) return 0; printf("Openened \"%s\"\n", szFile); //Read the header. fread(&msf.id, 1, 10, fin); fread(&msf.version, 4, 1, fin); printf("id: %s\n", msf.id); printf("version: %i\n", msf.version); //Read the vertices fread(&msf.nNumVertices, 2, 1, fin); printf("Vertex Count: %i\n", msf.nNumVertices); msf.pVertices=malloc(msf.nNumVertices*sizeof(ms3d_vertex)); for(i=0; i<msf.nNumVertices; i++) { fread(&msf.pVertices[i], 1, 15, fin); printf("Vertex[%i]: f: %i; (%f, %f, %f); b: %i; r: %i\n", i+1, msf.pVertices[i].flags, msf.pVertices[i].vertex[0], msf.pVertices[i].vertex[1], msf.pVertices[i].vertex[2], msf.pVertices[i].boneId, msf.pVertices[i].referenceCount); } fread(&msf.nNumTriangles, 2, 1, fin); printf("Triangle Count: %i\n", msf.nNumTriangles); msf.pTriangles=malloc(msf.nNumTriangles*sizeof(ms3d_triangle)); for(i=0; i<msf.nNumTriangles; i++) { fread(&msf.pTriangles[i], 1, sizeof(ms3d_triangle), fin); //if(i>=0 && i<10) printf("Triangle[%i]: f: %i; (%i, %i, %i); [other traingle information]; sg: %i; g: %i\n", i+1, msf.pTriangles[i].flags, msf.pTriangles[i].vertexIndices[0], msf.pTriangles[i].vertexIndices[1], msf.pTriangles[i].vertexIndices[2], msf.pTriangles[i].smoothingGroup, msf.pTriangles[i].groupIndex); } fread(&msf.nNumGroups, 2, 1, fin); printf("Groups: %i\n", msf.nNumGroups); msf.pGroups=malloc(sizeof(ms3d_group_t)*msf.nNumGroups); for(i=0; i<msf.nNumGroups; i++) { char szTemp[32]; fread(&msf.pGroups[i].flags, 1, 1, fin); fread(&msf.pGroups[i].name, 1, 32, fin); printf("Name: %s\n", msf.pGroups[i].name); fread(&msf.pGroups[i].numtriangles, 2, 1, fin); printf("Triangles: %i\n", msf.pGroups[i].numtriangles); msf.pGroups[i].triangleIndices=malloc(msf.pGroups[i].numtriangles*2); for(j=0; j<msf.pGroups[i].numtriangles; j++) { fread(&msf.pGroups[i].triangleIndices[j], 2, 1, fin); //printf("Triangle[%i]: %i\n", j+1, msf.pGroups[i].triangleIndices[j]); } fread(&msf.pGroups[i].materialIndex, 1, 1, fin); printf("mi: %i\n", msf.pGroups[i].materialIndex); } fclose(fin); return 0; }<file_sep>/Misc/DBXExporter/DBXExporter/oedbx/examples/ex1.cpp #include <map> #pragma hdrstop #include <oedbx/dbxFileHeader.h> #include <oedbx/dbxTree.h> #include <oedbx/dbxFolderInfo.h> #include <oedbx/dbxMessageInfo.h> #include <oedbx/dbxMessage.h> #include "Ex1.h" //*************************************************************************************** void ExtractAllMessages(const char * fileName, const char * logFile) { // I presume that fileName stores the name of a message dbx file // The dbx file has to be opened in binary mode. std::ifstream ins(fileName, std::ios::binary); std::ofstream outf(logFile, std::ios::binary); DbxFileHeader fileHeader(ins); // Some const values like fhTreeRootNodePtr or fhEntries are defined // to allow easy access to the values stored in the DbxFileHeader int4 address = fileHeader.GetValue(fhTreeRootNodePtr), entries = fileHeader.GetValue(fhEntries ); if(address && entries) // if everything is OK { // The tree in the message dbx file stores the pointers to // all message infos objects // Read in the tree with all pointers DbxTree tree(ins,address,entries); // cycle through all values for(int4 j=0; j<entries; ++j) { // Get the address of the folder info address = tree.GetValue(j); // Read in the message info DbxMessageInfo messageInfo(ins,address); // Which indexes are used in the message info object int4 indexes = messageInfo.GetIndexes(); if(indexes&(1<<miiMessageAddress)) // Only if a message is stored { // Get the address of the message int4 messageAddress = messageInfo.GetValue(miiMessageAddress); // Extract the message DbxMessage message(ins, messageAddress); // output the result outf << "___Message___ : " << j << ((char)0x0d) << ((char)0x0a); outf << message.GetText(); } } } ins.close(); outf.close(); } //*************************************************************************************** typedef std::map<std::string, int> Histogramm; std::string GetDomain(const char * str) { std::string id(str), result; std::string::size_type pos = id.find_last_of("@"); if(pos==std::string::npos) result = ""; else result = id.substr(pos, id.size()-pos-1); // only between @...> return result; } void ShowAllDomains(const char * fileName, const char * logFile) { Histogramm histo; // I presume that fileName stores the name of a message dbx file // The dbx file has to be opened in binary mode. std::ifstream ins(fileName, std::ios::binary); std::ofstream outf(logFile); DbxFileHeader fileHeader(ins); // Some const values like fhTreeRootNodePtr or fhEntries are defined // to allow easy access to the values stored in the DbxFileHeader int4 address = fileHeader.GetValue(fhTreeRootNodePtr), entries = fileHeader.GetValue(fhEntries ); if(address && entries) // if everything is OK { // The tree in the message dbx file stores the pointers to // all message infos objects // Read in the tree with all pointers DbxTree tree(ins,address,entries); // cycle through all values for(int4 j=0; j<entries; ++j) { // Get the address of the folder info address = tree.GetValue(j); // Read in the message info DbxMessageInfo messageInfo(ins,address); // Which indexes are used in the message info object int4 indexes = messageInfo.GetIndexes(); if(indexes&(1<<0x07)) // Only if the message id is stored { // To store the length of the stored data. // This value is used if binary data is stored. int4 length; // To store the address of the stored data int1 * pointer; pointer = messageInfo.GetValue(0x07, &length); histo[GetDomain((char *)pointer)]++; //outf << pointer << std::endl; // Log the result } } } ins.close(); Histogramm::iterator pos = histo.begin(), end = histo.end(); while(pos!=end) { outf << std::setw(8) << (pos->second) << " : " << (pos->first) << std::endl; ++pos; } outf.close(); } //*************************************************************************************** void ShowAllLocaleFolders(const char * fileName, const char * logFile) { // I presume that fileName stores the name of a folders.dbx file // The dbx file has to be opened in binary mode. std::ifstream ins(fileName, std::ios::binary); std::ofstream outf(logFile); DbxFileHeader fileHeader(ins); // The third tree in the folders.dbx stores the pointers to // all folder infos of all subfolders of Outlook Express const int4 treeNumber=2; // Some const values like fhTreeRootNodePtr or fhEntries are defined // to allow easy access to the values stored in the DbxFileHeader int4 address = fileHeader.GetValue(fhTreeRootNodePtr+treeNumber), entries = fileHeader.GetValue(fhEntries +treeNumber); if(address && entries) // if everything is OK { // Read in the tree with all pointers DbxTree tree(ins,address,entries); outf << "Index Parent Name" << std::endl; // cycle through all values for(int4 j=0; j<entries; ++j) { // Get the address of the folder info address = tree.GetValue(j); // Read in the folder info DbxFolderInfo fInfo(ins,address); // Which indexes are used in the folder info object int4 indexes = fInfo.GetIndexes(); if(indexes&(1<<fiiName)) // Only if the name is stored { outf<< std::left<< std::setw(8)<< (fInfo.GetValue(fiiIndex)) << std::left<< std::setw(8)<< (fInfo.GetValue(fiiParentIndex)) << fInfo.GetString(fiiName) << std::endl; } } } ins.close(); outf.close(); } <file_sep>/Misc/Formulas/Readme.txt Equtions by <NAME> This folder includes: Euler.bas - Eulers Formula Souce code. Euler.exe - Executable. Quadrati.bas - Root solver source code. Quadratic.exe - Executable. Note: Euler determines whether an object is a real polygon. Quadrati determines the roots of a quadratic equation. <file_sep>/tools/img_lib/img_lib2/img_lib/img_tga.c /* img_tga.c - The functions for loading a TGA into an HIMG. Copyright (C) 2006, <NAME>. */ #include <string.h> #include <malloc.h> #include "img_private.h" /*************************************** Definitions and types used by TGAs. ***************************************/ #define TGA_IMAGE_ORIGIN(p) (((p)&0x30) >> 4) /*TGA Header*/ typedef struct _TGAHEADER{ img_byte nIDSize; img_byte nColorMapType; img_byte nImageType; /* Color Map Info. */ img_word nFirstCMIndex; img_word nNumCMEntries; img_byte nCMEntrySize; /* Image Specifications. */ img_word nXOrigin; img_word nYOrigin; img_word nWidth; img_word nHeight; img_byte nBitsPerPixel; img_byte nImageDesc; }TGAHEADER, *LPTGAHEADER; /*TGA Footer*/ typedef struct _TGAFOOTER{ img_dword nExtensionOffset; img_dword nDeveloperOffset; char szSignature[18]; }TGAFOOTER, *LPTGAFOOTER; /********************************************* Prototypes for some private TGA functions. *********************************************/ img_bool TGA_ReadHeaderAndFooter( img_void* stream, IMG_CALLBACKS* lpCB, TGAHEADER* pHeader, TGAFOOTER* pFooter); img_bool TGA_ReadRLEData( img_void* stream, IMG_CALLBACKS* lpCB, IMAGE_S* lpImage); HIMG IMG_LoadTGACallbacks(img_void* stream, IMG_CALLBACKS* lpCB) { IMAGE_S* lpImage=NULL; TGAHEADER Header; TGAFOOTER Footer; int bValid=0; char szImageID[255]; int bFooter=0; if(!stream || !lpCB) return NULL; lpImage=malloc(sizeof(IMAGE_S)); if(!lpImage) return IMG_NULL; memset(lpImage, 0, sizeof(IMAGE_S)); memset(&Header, 0, sizeof(TGAHEADER)); memset(&Footer, 0, sizeof(TGAFOOTER)); /* Read the header and footer, this funciton also insures that we have a valid tga file, so if it fails there is no TGA.*/ if(!TGA_ReadHeaderAndFooter(stream, lpCB, &Header, &Footer)) { free(lpImage); return IMG_NULL; } //Copy the data into our image structure. lpImage->nWidth=Header.nWidth; lpImage->nHeight=Header.nHeight; lpImage->nBitDepth=Header.nBitsPerPixel; lpImage->nPaletteBitDepth=Header.nCMEntrySize; lpImage->nOrient=TGA_IMAGE_ORIGIN(Header.nImageDesc); lpImage->nPaletteEntries=Header.nNumCMEntries; lpImage->nDataSize=Header.nWidth*Header.nHeight*Header.nBitsPerPixel/8; lpImage->nPaletteSize=Header.nNumCMEntries*Header.nCMEntrySize/8; // We assume a valid file now and read the id. lpCB->seek(stream, 18, IMG_SEEK_SET); lpCB->read( &szImageID, 1, Header.nIDSize, stream); // Now read the color map data if it exists. if(Header.nColorMapType) { lpImage->pPalette=malloc(lpImage->nPaletteEntries*lpImage->nPaletteBitDepth/8); if(lpImage->pPalette==IMG_NULL) { free(lpImage); return NULL; } lpCB->read( lpImage->pPalette, 1, lpImage->nPaletteEntries*lpImage->nPaletteBitDepth/8, stream); } // Read the image data. lpImage->pImage=malloc(lpImage->nWidth*lpImage->nHeight*lpImage->nBitDepth/8); if(!lpImage->pImage) { IMG_SAFE_FREE(lpImage->pPalette); IMG_SAFE_FREE(lpImage); return IMG_NULL; } // Read the data. If the data is compressed we need to decode. if((Header.nImageType >= 9) && (Header.nImageType <=11)) { TGA_ReadRLEData(stream, lpCB, lpImage); } else { lpCB->read( lpImage->pImage, 1, lpImage->nWidth*lpImage->nHeight*lpImage->nBitDepth/8, stream); } switch(Header.nBitsPerPixel) { case 8: { lpImage->nDataFmt=IMGFMT_PALETTE; switch(Header.nCMEntrySize) { case 16: lpImage->nPaletteFmt=IMGFMT_X1R5G5B5; break; case 24: lpImage->nPaletteFmt=IMGFMT_R8G8B8; break; case 32: lpImage->nPaletteFmt=IMGFMT_A8R8G8B8; break; default: lpImage->nPaletteFmt=IMGFMT_UNKNOWN; break; } break; } case 16: lpImage->nDataFmt=IMGFMT_X1R5G5B5; lpImage->nPaletteFmt=IMGFMT_NONE; break; case 24: lpImage->nDataFmt=IMGFMT_R8G8B8; lpImage->nPaletteFmt=IMGFMT_NONE; break; case 32: lpImage->nDataFmt=IMGFMT_A8R8G8B8; lpImage->nPaletteFmt=IMGFMT_NONE; break; default: lpImage->nDataFmt=IMGFMT_UNKNOWN; lpImage->nPaletteFmt=IMGFMT_UNKNOWN; break; } return (HIMG)lpImage; } /************************* *** Private Functions. *** *************************/ /* TGA_ReadHeaderAndFooter reads the header and footer (if it exists) of the TGA file. It then checks the data found in the header and footer to make sure that the file *is* actually a TGA file. If the file is not a TGA file it returns IMG_FALSE, if it is a TGA file it returns IMG_TRUE.*/ img_bool TGA_ReadHeaderAndFooter( img_void* stream, IMG_CALLBACKS* lpCB, TGAHEADER* pHeader, TGAFOOTER* pFooter) { img_bool bHasFooter=IMG_FALSE; img_bool bValid=IMG_FALSE; lpCB->seek(stream, 0, IMG_SEEK_SET); /* Read the Header info. */ lpCB->read(&pHeader->nIDSize, 1, 1, stream); lpCB->read(&pHeader->nColorMapType, 1, 1, stream); lpCB->read(&pHeader->nImageType, 1, 1, stream); /* Read the Color map info. */ lpCB->read(&pHeader->nFirstCMIndex, 2, 1, stream); lpCB->read(&pHeader->nNumCMEntries, 2, 1, stream); lpCB->read(&pHeader->nCMEntrySize, 1, 1, stream); /* Read the image specifications. */ lpCB->read(&pHeader->nXOrigin, 2, 1, stream); lpCB->read(&pHeader->nYOrigin, 2, 1, stream); lpCB->read(&pHeader->nWidth, 2, 1, stream); lpCB->read(&pHeader->nHeight, 2, 1, stream); lpCB->read(&pHeader->nBitsPerPixel, 1, 1, stream); lpCB->read(&pHeader->nImageDesc, 1, 1, stream); /* Read the footer, and check to seek if the file is a valid tga.*/ lpCB->seek(stream, -26, IMG_SEEK_END); lpCB->read(&pFooter->nExtensionOffset, 4, 1, stream); lpCB->read(&pFooter->nDeveloperOffset, 4, 1, stream); lpCB->read(&pFooter->szSignature, 1, 18, stream); /* If the file has the TRUEVISION-XFILE tag then it is a valid tga file.*/ if(_strnicmp("TRUEVISION-XFILE.", pFooter->szSignature, 17)==0) { bHasFooter=IMG_TRUE; bValid=IMG_TRUE; } else { pFooter->szSignature[0]=0; bHasFooter=IMG_FALSE; } //Do a series of tests to make sure the file //is a valid tga file. if(pHeader->nColorMapType==1) { if( (pHeader->nImageType==1) || (pHeader->nImageType==9)) bValid=IMG_TRUE; else bValid=IMG_FALSE; } else if(pHeader->nColorMapType==0) { if( (pHeader->nImageType==0) || (pHeader->nImageType==2) || (pHeader->nImageType==3) || (pHeader->nImageType==10) || (pHeader->nImageType==11)) bValid=IMG_TRUE; else bValid=IMG_FALSE; } else { bValid=IMG_FALSE; } //If the bits per pixel is not evenly divided by //8 we can't read the file. In theory 15 bit tga //images exist, but I haven't found one, and they //aren't supported by this library. if(pHeader->nBitsPerPixel%8) bValid=IMG_FALSE; return bValid; } /* TGAReadRLEData reads RLE data out of the file decompressing it as it goes along. lpImage->pImage needs to be allocated to the uncompressed size of the file. Or the function will probably cause a crash. */ img_bool TGA_ReadRLEData(img_void* stream, IMG_CALLBACKS* lpCB, IMAGE_S* lpImage) { img_byte nBPP=0; img_bool bCompressed=0; img_byte nLen=0; img_byte nCompress=0; img_dword nDecodePos=0; img_dword j=0; void * lpData=NULL; nBPP=lpImage->nBitDepth/8; /* Allocate some memory for the input data. */ lpData=malloc(nBPP); if(!lpData) return IMG_FALSE; nDecodePos=0; for(nDecodePos=0; nDecodePos<(unsigned long)(nBPP*lpImage->nWidth*lpImage->nHeight); ) { /* Read the encodeing byte. */ lpCB->read(&nCompress, 1, 1, stream); /* The compression mode is the last bit. */ bCompressed=(nCompress&0x80)>>7; /* The length of the data is the first 7 bits plus 1. */ nLen=(nCompress&0x7F)+1; if(bCompressed) { /* If compressed we decompress the data. */ /* Read the compressed data. */ lpCB->read(lpData, 1, nBPP, stream); for(j=0; j<nLen; j++) { /* Copy the data into the appropriate length of image. */ memcpy((void*)((unsigned int)lpImage->pImage+nDecodePos), lpData, nBPP); nDecodePos+=nBPP; } } else { /* Otherwize we simply read the data. */ for(j=0; j<nLen; j++) { lpCB->read(lpData, 1, nBPP, stream); memcpy((void*)((unsigned int)lpImage->pImage+nDecodePos), lpData, nBPP); nDecodePos+=nBPP; } } } /* Free the memory from the input. */ free(lpData); return IMG_TRUE; }<file_sep>/games/Legacy-Engine/Source/engine/lg_cmd.h //lg_cmd.h - This is where all console commands //should be registered, they allso need to be //registered in the CLGame::LGC_RegisterCommands function. #ifndef __LG_CMD_H__ #define __LG_CMD_H__ #define CONF_SET 0x00000001 #define CONF_GET 0x00000002 #define CONF_CLEAR 0x00000003 #define CONF_ECHO 0x00000004 #define CONF_CVARLIST 0x00000005 #define CONF_CMDLIST 0x00000006 #define CONF_CVARUPDATE 0x00000007 #define CONF_QUIT 0x00000010 #define CONF_VRESTART 0x00000020 #define CONF_DIR 0x00000030 #define CONF_EXTRACT 0x00000040 #define CONF_D3DCAPS 0x00000050 #define CONF_VIDMEM 0x00000060 //#define CONF_HARDVRESTART 0x00000070 #define CONF_TEXFORMATS 0x00000080 #define CONF_LOADMODEL 0x00000090 #define CONF_VERSION 0x000000A0 #define CONF_CONDUMP 0x000000B0 #define CONF_LOADCFG 0x000000C0 #define CONF_SAVECFG 0x000000D0 #define CONF_LOADMAP 0x000000E0 #define CONF_SETMESSAGE 0x000000F0 #define CONF_MUSIC_START 0x00000100 #define CONF_MUSIC_PAUSE 0x00000200 #define CONF_MUSIC_STOP 0x00000300 #define CONF_MUSIC_RESUME 0x00000400 #define CONF_SHOW_INFO 0x00000500 #define CONF_INIT_SRV 0x00000600 #define CONF_SHUTDOWN_SRV 0x00000700 #define CONF_CONNECT 0x00000800 #define CONF_DISCONNECT 0x00000900 #define CONF_PAUSE 0x00000A00 #define CONF_TEST 0x01000000 #endif /* __LG_CMD_H__ */<file_sep>/samples/D3DDemo/code/MD3Base/Functions.h #ifndef __FUNCTIONS_H__ #define __FUNCTIONS_H__ #include <windows.h> #include "MD3.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #ifdef UNICODE #define RemoveDirectoryFromString RemoveDirectoryFromStringW #define GetDirectoryFromString GetDirectoryFromStringW #else /* UNICODE */ #define RemoveDirectoryFromString RemoveDirectoryFromStringA #define GetDirectoryFromString GetDirectoryFromStringA #endif /* UNICODE */ BOOL RemoveDirectoryFromStringA(char szLineOut[], const char szLineIn[]); BOOL RemoveDirectoryFromStringW(WCHAR szLineOut[], const WCHAR szLineIn[]); BOOL GetDirectoryFromStringA(char szLineOut[], const char szLineIn[]); BOOL GetDirectoryFromStringW(WCHAR szLineOut[], const WCHAR szLineIn[]); BOOL DecodeNormalVector(LPMD3VECTOR lpOut, const LPMD3VERTEX lpVertex); #define RLERR_INVALIDFILE 0x80000001l #define RLERR_NOTALINE 0x80000002l #define RLSUC_READSUCCESS 0x0000000l #define RLSUC_EOF 0x00000001l #define RLSUC_FINISHED 0x00000002l DWORD GetNumLinesInFile(HANDLE hFile); HRESULT ReadLine(HANDLE hFile, LPSTR szLine); HRESULT ReadWordFromLine(LPSTR szLineOut, LPSTR szLine, DWORD dwStart, DWORD * dwEnd); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __FUNCTIONS_H__ */<file_sep>/tools/QInstall/Demo/QInstall.ini name = "QInstall Demo Application"; installto = "%defaultdrive%\DemoApp\"; installfrom = "%currentdir%\Data"; runonexit = "QTestApp.exe";<file_sep>/games/Legacy-Engine/readme.txt Legacy 3D Engine ================ Engineered by <NAME> (c) 2008 Beem Media The Legacy Engine was my first 3D engine. It's not very good and is not meant to be representative of my skills as an engineer. The engine was scrapped in 2008. It was developed before I knew anything about software engineering and so it has some really bad code. There are some good ideas in it, and it had some interesting tools (albeit unecessary), namely the LMEdit tool and various plugins. It also featured a math library written in assembly (but it was basically a less featured copy of d3dx9 math). The code never really came along far enough to even make a basic game demo in it. It supported various physics engines, the primary was meant to be PhysX though that is no longer supported by this source (since I'm not even sure what version of PhysX it was originally built with.) The provided code works with the Newton Game Dynamics physics engine and the in-house physics engine (though being that there is no gameplay, everything seems to be pretty chaotic in the demo). I'm keeping the code for novelty purposes, but it has been surpassed by the Emergence Engine (which is not open source at this time). The executables in the base directory work and were built with Visual Studio 2015 (except for LPaKager) so they'll require a recent version of the Visual C++ runtimes installed. The executable for LPaKager doesn't have source code any more, and it is the only version of the software that will open the game data in baseuncmp (besides the game client itself). The Scrapped directory has old version or obsolete code (or stuff I didn't want to build for this distribution). I didn't know about source control when I wrote this engine so I originally dumped old files into that directory. <file_sep>/games/Legacy-Engine/Source/engine/lw_skybox.cpp #include "lw_skybox.h" #include "lg_mmgr.h" CLSkybox3::CLSkybox3() : m_pSkyMesh(LG_NULL) , m_Skin() { } CLSkybox3::~CLSkybox3() { Unload(); } void CLSkybox3::Load(lg_path szMeshFile, lg_path szSkinFile) { m_pSkyMesh=CLMMgr::MM_LoadMesh(szMeshFile, 0); m_Skin.Load(szSkinFile); m_Skin.MakeCompatibleWithMesh((CLMesh2*)m_pSkyMesh); } void CLSkybox3::Unload() { m_pSkyMesh=LG_NULL; m_Skin.Unload(); } void CLSkybox3::Render() { if(m_pSkyMesh) m_pSkyMesh->Render(&m_Skin); } <file_sep>/games/Legacy-Engine/Scrapped/plugins/msLMEXP/msLMEXP.h // msMLEXP.h : main header file for the msMLEXP DLL // #pragma once #ifndef __AFXWIN_H__ #error "include 'stdafx.h' before including this file for PCH" #endif #include "resource.h" // main symbols // CmsMLEXPApp // See msMLEXP.cpp for the implementation of this class // class CmsMLEXPApp : public CWinApp { public: CmsMLEXPApp(); // Overrides public: virtual BOOL InitInstance(); DECLARE_MESSAGE_MAP() }; <file_sep>/games/Legacy-Engine/Scrapped/plugins/msL3DM/msL3DM.cpp //Milkshape Exporter for the Legacy3D Model Formal (L3DM). #include <windows.h> #include <stdio.h> #include "ML_lib.h" #include "msLib\\msPlugIn.h" #include "msLib\\msLib.h" #include "lm_ms.h" #pragma comment(lib, "msLib\\lib6\\msModelLib.lib") #pragma comment(lib, "ML_lib_s.lib") // ---------------------------------------------------------------------------------------------- class CLegacy3DExp:public cMsPlugIn { private: public: CLegacy3DExp(){} virtual ~CLegacy3DExp(){}; int GetType(){return cMsPlugIn::eTypeExport;} const char* GetTitle(){return "Legacy Engine Format";} int Execute(msModel* pModel); }; int CLegacy3DExp::Execute(msModel* pModel) { //Get a filename to export our data to. //Initialize the math library. ML_SetSIMDSupport(ML_INSTR_F); char szFile[MAX_PATH]; szFile[0]=0; OPENFILENAME sf; memset(&sf, 0, sizeof(OPENFILENAME)); sf.lStructSize=sizeof(OPENFILENAME); sf.lpstrFilter="Legacy Mesh Format (LMSH)\0*lmsh\0All Files\0*.*\0"; sf.lpstrFile=szFile; sf.nMaxFile=MAX_PATH; sf.lpstrTitle="Legacy Model Exporter"; sf.lpstrDefExt="lmsh"; if(!GetSaveFileName(&sf)) return -1; //Get the callbacks ready. fio_callbacks cb; cb.close=L_fclose; cb.read=L_fread; cb.seek=L_fseek; cb.write=L_fwrite; cb.tell=L_ftell; //All we need to to is load the mesh //from the milkshape model then call //the save function. //For now we are making the mesh name the same as //the filename, but without the lmsh or lskl extension L_char szName[MAX_PATH]; L_GetShortNameFromPath(szName, szFile); CLegacyMeshMS Mesh(pModel, szName); if(Mesh.IsLoaded()) { FILE* fout=fopen(szFile, "wb"); //Calling CLMesh::Save will close the file. //The same is not true for CLMesh::Open wich //will leave the file open. if(fout) Mesh.Save((void*)fout, &cb); } CLegacySkelMS Skel(pModel, szName); if(Skel.IsLoaded()) { //We change the filename to have a .lskl extension //for the skeleton. char szPath[MAX_PATH]; L_GetPathFromPath(szPath, szFile); _snprintf(szFile, MAX_PATH-1, "%s%s.lskl", szPath, szName); FILE* fout=fopen(szFile, "wb"); if(fout) Skel.Save((void*)fout,&cb); } msModel_Destroy(pModel); MessageBox( NULL, "Legacy Model Exported", "Legacy Model Exporter", MB_OK|MB_ICONINFORMATION); return 0; } //Our export function so milkshape can perform //the operations. cMsPlugIn *CreatePlugIn() { return new CLegacy3DExp; } <file_sep>/games/Explor2002/Source/Game/gMapboard.h #ifndef __MAPBOARD_H__ #define __MAPBOARD_H__ #include <windows.h> #include "defines.h" typedef unsigned short USHORT; typedef struct eMapHeader { char mapType[2]; unsigned short mapVersion; unsigned long mapFileSize; unsigned short mapReserved1; unsigned short mapReserved2; unsigned short mapWidth; unsigned short mapHeight; unsigned long mapDataSize; unsigned long mapTileDataSize; unsigned long mapPropertyDataSize; unsigned short mapNumProperty; } MAPHEADER; class CGameMap { private: BOOL mapLoaded; USHORT * tiles; USHORT * prop; MAPHEADER fileHeader; unsigned short tbase(int tx, int ty)const; char boardname[_MAX_PATH]; TileType m_nType[256]; public: CGameMap(); ~CGameMap(); //int saveMap(char openmap[_MAX_PATH]); //int resetBoard(void); int openMap(char openmap[_MAX_PATH]); //int boardEdit(int x, int y, unsigned int propnum, unsigned int newvalue); //int boardEdit(int x, int y); USHORT getTileStat(int x, int y, int propnum)const; USHORT getTileStat(int x, int y)const; USHORT getMapWidth(void)const; USHORT getMapHeight(void)const; USHORT getNumProperty(void)const; BOOL generateTFront(USHORT tfront[TFRONT_SIZE], const Direction FaceDirection, const int xloc, const int yloc); void SetTileType(int index, TileType newType); TileType GetTileType(int index); }; #endif <file_sep>/games/Legacy-Engine/Source/lm_sys/lm_skin.h #ifndef __LM_SKIN_H__ #define __LM_SKIN_H__ #include "lm_mesh.h" #include "lg_types.h" #include "lg_mtr_mgr.h" class CLSkin: public CLMBase { friend class CLMeshD3D; friend class CLMeshLG; private: LG_CACHE_ALIGN struct MtrGrp{ lg_dword nMtr; //Material associated with this group. LMName szName; //Name of this group (should match mesh group names). }; lg_dword m_nMtrCount; //The number of materials in the skin. lg_dword m_nGrpCount; //The number of groups assigned in the skin. lg_material* m_pMaterials; //List of materials (index 0 is material 1) MtrGrp* m_pGrps; //List of the groups and associated materials. lg_material* m_pCmpRefs; //References to translate mesh group ids to skin ids. lg_byte* m_pMem; public: CLSkin(); ~CLSkin(); /* PRE: N/A POST: Loads the skin, if the skin could not be loaded false is returned, otherwise true is returned. */ lg_bool Load(lg_path szFilename); /* PRE: N/A POST: Unloads the skin (freeing memory) if one was loaded. */ void Unload(); /* PRE: pMesh should be loaded. POST: The skin is compatible with the specified mesh. Note that skins should usually only be used with one mesh, so this call should be made with only one mesh. */ void MakeCompatibleWithMesh(CLMesh2* pMesh); //The loader method. static void LX_SkinStart(void* userData, const char* name, const char** atts); //Serialize method; lg_bool Serialize(lg_void* file, ReadWriteFn read_or_write, RW_MODE mode); }; #endif __LM_SKIN_H__<file_sep>/games/Legacy-Engine/Scrapped/UnitTests/ML_demo/ML_demo_vec3.c #include <stdio.h> #include <ML_lib.h> #include <d3dx9.h> /* Note: Both the SSE, SSE3, and F functions don't know how to normalize a 0.0f, 0.0f, 0.0f vector.*/ #define DO_ALT_TEST void Vec3AddTest(ML_VEC3* pVT, ML_VEC3* pV1, ML_VEC3* pV2); void Vec3CrossTest(ML_VEC3* pVT, ML_VEC3* pV1, ML_VEC3* pV2); void Vec3DotTest(ML_VEC3* pV1, ML_VEC3* pV2); void Vec3LengthTest(ML_VEC3* pV1); void Vec3NormalizeTest(ML_VEC3* pVT, ML_VEC3* pV1); void Vec3SubTest(ML_VEC3* pVT, ML_VEC3* pV1, ML_VEC3* pV2); void Vec3ScaleTest(ML_VEC3* pVT, ML_VEC3* pV1, float fS); void Vec3DistanceTest(ML_VEC3* pV1, ML_VEC3* pV2); void Vec3TransformTest(ML_VEC4* pVQ, ML_VEC3* pV, ML_MAT* pMT); void Vec3TransformCoordTest(ML_VEC3* pVT, ML_VEC3* pV, ML_MAT* pMT); void Vec3TransformNormalTest(ML_VEC3* pVT, ML_VEC3* pV, ML_MAT* pMT); void Vec3LengthSqTest(ML_VEC3* pV1); void PrintVec3(void* pVec3); void PrintVec4(void* pVec4); int Vec3Test() { ML_VEC4 VQ={0.0f, 0.0f, 0.0f}; ML_VEC3 VT={0.0f, 0.0f, 0.0f}; ML_VEC3 V1={12.34f, 45.67f, 89.1011f}; ML_VEC3 V2={343.324f, 765.443f, 78.45f}; ML_MAT M1={1.2f, 56.7f, 2.0f, 3.5f, 5.6f, 7.0f, 8.0f, 90.0f, 10.0f, 785.0f, 4.3f, 2.1f, 3.0f, 4.0f, 5.0f, 7.0f}; float fS=12.3f; printf("Data:\n"); printf("VT:\t");PrintVec3(&VT); printf("V1:\t");PrintVec3(&V1); printf("V2:\t");PrintVec3(&V2); printf("Scale:\t%f\n\n", fS); printf("Tests:\n\n"); Vec3AddTest(&VT, &V1, &V2); Vec3CrossTest(&VT, &V1, &V2); Vec3DotTest(&V1, &V2); Vec3LengthTest(&V1); Vec3NormalizeTest(&VT, &V1); Vec3SubTest(&VT, &V1, &V2); Vec3ScaleTest(&VT, &V1, fS); Vec3DistanceTest(&V1, &V2); Vec3TransformTest(&VQ, &V1, &M1); Vec3TransformCoordTest(&VT, &V1, &M1); Vec3TransformNormalTest(&VT, &V1, &M1); Vec3LengthSqTest(&V1); printf("\n"); return 0; } void Vec3TransformNormalTest(ML_VEC3* pVT, ML_VEC3* pV, ML_MAT* pMT) { printf("Vec3TransformNormal:\n"); printf("ML_lib:\t"); PrintVec3(ML_Vec3TransformNormal(pVT, pV, pMT)); #ifdef DO_ALT_TEST memcpy(pVT, pV, sizeof(ML_VEC3)); printf("PEQU:\t"); PrintVec3(ML_Vec3TransformNormal(pVT, pVT, pMT)); #endif printf("D3DX:\t"); PrintVec3((ML_VEC3*)D3DXVec3TransformNormal((void*)pVT, (void*)pV, (void*)pMT)); printf("\n\n"); } void Vec3TransformCoordTest(ML_VEC3* pVT, ML_VEC3* pV, ML_MAT* pMT) { printf("Vec3TransformCoord:\n"); printf("ML_lib:\t"); PrintVec3(ML_Vec3TransformCoord(pVT, pV, pMT)); #ifdef DO_ALT_TEST printf("PEQU:\t"); memcpy(pVT, pV, sizeof(ML_VEC3)); PrintVec3(ML_Vec3TransformCoord(pVT, pVT, pMT)); #endif printf("D3DX:\t"); PrintVec3((ML_VEC3*)D3DXVec3TransformCoord((void*)pVT, (void*)pV, (void*)pMT)); printf("\n\n"); } void Vec3TransformTest(ML_VEC4* pVQ, ML_VEC3* pV, ML_MAT* pMT) { ML_VEC4 V4; memcpy(&V4, pV, 12); printf("Vec3Transform:\n"); printf("ML_lib:\t"); PrintVec4(ML_Vec3Transform(pVQ, pV, pMT)); #ifdef DO_ALT_TEST printf("PEQU:\t"); memcpy(&V4, pV, sizeof(ML_VEC3)); PrintVec4(ML_Vec3Transform(&V4, (void*)&V4, pMT)); #endif printf("D3DX:\t"); PrintVec4((ML_VEC4*)D3DXVec3Transform((void*)pVQ, (void*)pV, (void*)pMT)); printf("\n\n"); } void Vec3AddTest(ML_VEC3* pVT, ML_VEC3* pV1, ML_VEC3* pV2) { printf("Vec3Add:\n"); printf("ML_lib:\t"); memcpy(pVT, pV1, sizeof(ML_VEC3)); PrintVec3(ML_Vec3Add(pVT, pV1, pV2)); #ifdef DO_ALT_TEST printf("PEQU1:\t"); memcpy(pVT, pV1, sizeof(ML_VEC3)); PrintVec3(ML_Vec3Add(pVT, pVT, pV2)); printf("PEQU2:\t"); memcpy(pVT, pV2, sizeof(ML_VEC3)); PrintVec3(ML_Vec3Add(pVT, pV1, pVT)); #endif printf("D3DX:\t"); PrintVec3((ML_VEC3*)D3DXVec3Add((void*)pVT, (void*)pV1, (void*)pV2)); printf("\n\n"); } void Vec3ScaleTest(ML_VEC3* pVT, ML_VEC3* pV1, float fS) { printf("Vec3Scale:\n"); printf("ML_lib:\t"); PrintVec3(ML_Vec3Scale(pVT, pV1, fS)); #ifdef DO_ALT_TEST printf("PEQU:\t"); memcpy(pVT, pV1, sizeof(ML_VEC3)); PrintVec3(ML_Vec3Scale(pVT, pVT, fS)); #endif printf("D3DX:\t"); PrintVec3((ML_VEC3*)D3DXVec3Scale((void*)pVT, (void*)pV1, fS)); printf("\n\n"); } void Vec3SubTest(ML_VEC3* pVT, ML_VEC3* pV1, ML_VEC3* pV2) { printf("Vec3Sub:\n"); printf("ML_lib:\t"); PrintVec3(ML_Vec3Subtract(pVT, pV1, pV2)); #ifdef DO_ALT_TEST printf("PEQU1:\t"); memcpy(pVT, pV1, sizeof(ML_VEC3)); PrintVec3(ML_Vec3Subtract(pVT, pVT, pV2)); printf("PEQU2:\t"); memcpy(pVT, pV2, sizeof(ML_VEC3)); PrintVec3(ML_Vec3Subtract(pVT, pV1, pVT)); #endif printf("D3DX:\t"); PrintVec3((ML_VEC3*)D3DXVec3Subtract((void*)pVT, (void*)pV1, (void*)pV2)); printf("\n\n"); } void Vec3CrossTest(ML_VEC3* pVT, ML_VEC3* pV1, ML_VEC3* pV2) { printf("Vec3Cross:\n"); printf("ML_lib:\t"); PrintVec3(ML_Vec3Cross(pVT, pV1, pV2)); #ifdef DO_ALT_TEST printf("PEQU1:\t"); memcpy(pVT, pV1, sizeof(ML_VEC3)); PrintVec3(ML_Vec3Cross(pVT, pVT, pV2)); printf("PEQU2:\t"); memcpy(pVT, pV2, sizeof(ML_VEC3)); PrintVec3(ML_Vec3Cross(pVT, pV1, pVT)); #endif printf("D3DX:\t"); PrintVec3((ML_VEC3*)D3DXVec3Cross((void*)pVT, (void*)pV1, (void*)pV2)); printf("\n\n"); } void Vec3DotTest(ML_VEC3* pV1, ML_VEC3* pV2) { printf("Vec3Dot:\n"); printf("ML_lib:\t"); printf("%f\n", ML_Vec3Dot(pV1, pV2)); printf("D3DX:\t"); printf("%f\n", D3DXVec3Dot((void*)pV1, (void*)pV2)); printf("\n\n"); } void Vec3LengthTest(ML_VEC3* pV1) { printf("Vec3Length:\n"); printf("ML_lib:\t"); printf("%f\n", ML_Vec3Length(pV1)); printf("D3DX:\t"); printf("%f\n", D3DXVec3Length((void*)pV1)); printf("\n\n"); } void Vec3LengthSqTest(ML_VEC3* pV1) { printf("Vec3LengthSq:\n"); printf("ML_lib:\t"); printf("%f\n", ML_Vec3LengthSq(pV1)); printf("D3DX:\t"); printf("%f\n", D3DXVec3LengthSq((void*)pV1)); printf("\n\n"); } void Vec3DistanceTest(ML_VEC3* pV1, ML_VEC3* pV2) { printf("Vec3Distance:\n"); printf("ML_lib:\t"); printf("%f\n", ML_Vec3Distance(pV1, pV2)); printf("D3DX:\t"); printf("%f\n", D3DXVec3Length(D3DXVec3Subtract((void*)pV1, (void*)pV1, (void*)pV2))); printf("\n\n"); } void Vec3NormalizeTest(ML_VEC3* pVT, ML_VEC3* pV1) { printf("Vec3Normalize:\n"); printf("ML_lib:\t"); PrintVec3(ML_Vec3Normalize(pVT, pV1)); #ifdef DO_ALT_TEST printf("PEQU:\t"); memcpy(pVT, pV1, sizeof(ML_VEC3)); PrintVec3(ML_Vec3Normalize(pVT, pVT)); #endif printf("D3DX:\t"); PrintVec3((ML_VEC3*)D3DXVec3Normalize((void*)pVT, (void*)pV1)); printf("\n\n"); } <file_sep>/games/Legacy-Engine/Scrapped/old/lg_meshmgr.h /* lg_meshmgr.h - The Legacy Game Mesh Manager is responsible for loading meshes, allowing objects to get meshes to use, cleaning up the meshes, etc, meshes should always be loaded using the game's instance of this class, though meshes themselves can be used however an object sees fit to use it. CLMeshMgr uses linked lists to store both meshes and skeletons. The manager also has validate and invalidate calls to validate and invalidate the Direct3D components, for this reason the objects that use the meshes don't need to worry about validatation at all, if because of the mesh manager a mesh is not valid if an in game object tries to render it, nothing will get rendered, but the game will not crash. Copyright (c) 2007 <NAME> */ #ifndef __LG_MESHMGR_H__ #define __LG_MESHMGR_H__ #include "lf_sys2.h" #include "lm_d3d.h" #include "lg_stack.h" //When a mesh or skel is loaded into the mesh manager the //LMMGR_LOAD_RETAIN flag may be set, if this flag is set //when UnloadMeshes is called any meshes that have this //flag set will survive the call to UnloadMeshes //unles UnloadMeshes has teh LMMGR_UNLOAD_FORCE_ALL flag //passed to it, in which case all meshes or skels will //be unloaded despite the RETAIN flag. The idea behind //retaining a mesh is in case a level is divided into //multiple part where certain meshes will always be //rendered (monster meshes for example) but some meshes are //not rendered (grass for example would only be rendered in //outdoor scenes, not indoors). Or if certain meshes //are used through the entire game (weapons, HUD stuff, etc) //and therefore have no reason to be unloaded. #define LMMGR_LOAD_RETAIN 0x00000001 #define LMMGR_UNLOAD_FORCE_ALL 0x00000001 //NOTES: In mesh (and skel) loading, unloading, and getting //the name is used. Because every time a mesh (or skel) is //loaded or loaded the order of the items in the list is subject //to change extensively. On an unload for example the order of //the list is completely reveresed (except for the removed mesh //which is no longer in the list at all). For that reason a //reference number cannot be used to get or delete a particular //mesh. Also note that a mesh (or skel) that has been gotten //with the GetMesh (or GetSkel) method is not independent of //the mesh manager, and if that mesh is deleted in the mesh manager //then the gotten pointer is no longer going to point at a valid //CLMeshD3D (unless a new mesh happens to be allocated in exactly //the same spot, and so anywhere that gets a mesh should be aware //of when that mesh is destroyed so that it no longer uses it. //Also note that before any meshes are loaded InitializeD3D should //be called with a reference to the games Direct3D device passed //to it, if this method is not called first then when LoadMesh //is called the meshes will never have their CreateD3DComponents //method called, and will not be renderable (unless a function that //calls GetMesh calls the CreateD3DComponents method on the mesh //that it has gotten. class CLMeshMgr { private: //LMESH_LINK and LSKEL_LINK are the link structures //for the linked lists of CLMeshD3Ds and CLSkels //within the Mesh Manager. typedef struct _LMESH_LINK { CLMeshD3D* pMesh; LMESH_NAME szName; lg_dword nFlags; lg_dword nHashCode; struct _LMESH_LINK* pNext; }LMESH_LINK; typedef struct _LSKEL_LINK { CLSkel* pSkel; LMESH_NAME szName; lg_dword nFlags; lg_dword nHashCode; struct _LSKEL_LINK* pNext; }LSKEL_LINK; private: lg_dword m_nNumMeshes; LMESH_LINK* m_pFirstMesh; lg_dword m_nNumSkels; LSKEL_LINK* m_pFirstSkel; public: CLMeshMgr(IDirect3DDevice9* pDevice, lg_dword nMaxMesh, lg_dword nMaxSkel); ~CLMeshMgr(); CLMeshD3D* LoadMesh(lf_path szFilename, lg_dword nFlags); CLMeshD3D* GetMesh(lg_char* szName); CLSkel* LoadSkel(lf_path szFilename, lg_dword nFlags); CLSkel* GetSkel(lg_char* szName); lg_bool UnloadMesh(lg_char* szName); lg_bool UnloadMeshes(lg_dword nFlags); lg_bool UnloadSkel(lg_char* szName); lg_bool UnloadSkels(lg_dword nFlags); lg_bool UnloadAll(lg_dword nFlags); lg_bool ValidateMeshes(); void InvalidateMeshes(); //The static mesh manager is so that meshes can be loaded //on demand without having access to the extablished mesh //manager within the game class. private: static CLMeshMgr* s_pMeshMgr; public: static CLMeshD3D* GlobalLoadMesh(lf_path szFilename, lg_dword Flags); static CLSkel* GlobalLoadSkel(lf_path szFilename, lg_dword Flags); }; //#define LG_LoadMesh CLMeshMgr::GlobalLoadMesh //#define LG_LoadSkel CLMeshMgr::GlobalLoadSkel #endif __LG_MESHMGR_H__<file_sep>/games/Legacy-Engine/Source/LMEdit/resource.h //{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by LMEdit.rc // #define ID_ANIM_DIALOG 9 #define IDD_ABOUTBOX 100 #define IDP_OLE_INIT_FAILED 100 #define IDR_MAINFRAME 128 #define IDR_LMEditTYPE 129 #define IDD_SAVEAS 133 #define IDC_ANIMS 1000 #define IDC_AVAILABLEFRAMES 1001 #define IDC_ANIM_NAME 1002 #define IDC_ANIM_FIRST_FRAME 1003 #define IDC_ANIM_NUM_FRAMES 1004 #define IDC_ANIM_LOOPING_FRAMES 1005 #define IDC_ANIM_RATE 1006 #define IDC_ADD_ANIM 1007 #define IDC_DELETE_ANIM 1008 #define IDC_LOOPTYPE 1009 #define IDC_MESHFILE 1011 #define IDC_SKELFILE 1012 #define IDC_BROWSEMESH 1013 #define IDC_BUTTON2 1014 #define IDC_BROWSESKEL 1014 #define ID_SKELETON_SHOWSKELETON 32771 #define ID_ANIMATION_SHOWSKELETON 32772 #define ID_MESH_WIREFRAME 32773 #define ID_MESH_TEXTURED 32774 #define ID_MESH_FLATSHADED 32775 #define ID_MESH_SMOOTHSHADED 32776 #define ID_ANIMATION_EDITANIMATIONS 32777 #define ID_ANIMATION_DEFAULTMESH 32778 #define ID_ANIMATION_IMPORTFRAMES 32780 #define ID_ANIMATION_CALCULATEAABB 32787 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 134 #define _APS_NEXT_COMMAND_VALUE 32788 #define _APS_NEXT_CONTROL_VALUE 1015 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif <file_sep>/Misc/DBXExporter/DBXExporter/oedbx/library/oedbx/dbxFolderInfo.h //*************************************************************************************** #ifndef dbxFolderInfoH #define dbxFolderInfoH //*************************************************************************************** #include <oedbx/dbxIndexedInfo.h> //*************************************************************************************** const int1 fiiIndex = 0x00, fiiParentIndex = 0x01, fiiName = 0x02, fiiFlags = 0x06; class AS_EXPORT DbxFolderInfo : public DbxIndexedInfo { public : DbxFolderInfo(InStream ins, int4 address) : DbxIndexedInfo(ins, address) { } const char * GetIndexText(int1 index) const; IndexedInfoDataType GetIndexDataType(int1 index) const; }; //*********************************************** #endif dbxFolderInfoH <file_sep>/games/Legacy-Engine/Scrapped/libs/ML_lib2008April/ML_plane.c #include "ML_lib.h" ml_float ML_FUNC ML_PlaneDotCoord(const ML_PLANE* pPlane, const ML_VEC3* pV) { return ML_Vec3Dot((ML_VEC3*)pPlane, pV)-pPlane->d; } ML_PLANE* ML_FUNC ML_PlaneScale(ML_PLANE* pOut, const ML_PLANE* pPlane, ml_float s) { pOut->a=pPlane->a; pOut->b=pPlane->b; pOut->c=pPlane->c; pOut->d=pPlane->d*s; return pOut; }<file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/ModelExporter/lm_ms.cpp #include <windows.h> #include <stdio.h> #include <stdarg.h> #include "lm_ms.h" #include "msLib\\msLib.h" extern "C" void ErrorBox(char* format, ...) { char szOutput[1024]; va_list arglist=L_null; int nResult=0; va_start(arglist, format); _vsnprintf(szOutput, 1024-1, format, arglist); MessageBox(0, szOutput, "Error Message", MB_OK); va_end(arglist); } float vertex_length(float* pv) { return sqrt(pv[0]*pv[0]+pv[1]*pv[1]+pv[2]*pv[2]); } CLegacyMeshMS::CLegacyMeshMS(void* pModel) { this->LoadFromMS(pModel); } L_bool CLegacyMeshMS::LoadFromMS(void* pModelParam) { //Make sure that nothing is currently loaded. L_dword i=0, j=0; msModel* pModel=(msModel*)pModelParam; this->Unload(); m_ID=LMESH_ID; m_nVersion=LMESH_VERSION; m_nNumMeshes=msModel_GetMeshCount(pModel); m_nNumMaterials=msModel_GetMaterialCount(pModel); //m_nNumJoints=msModel_GetBoneCount(pModel); //m_nNumKeyFrames=msModel_GetTotalFrames(pModel); //To get the total number of vertices, we have to find //out how many vertices are in each mesh, to optomize //things just a bit we also find out some of the material //information. m_pMeshes=new LMESH_SET[m_nNumMeshes]; if(!m_pMeshes) return L_false; /* //Allocate memory for the frames. m_pKeyFrames=new LMESH_KEYFRAME[m_nNumKeyFrames]; if(!m_pKeyFrames) { L_safe_delete_array(m_pMeshes); return L_false; } for(i=0; i<m_nNumKeyFrames; i++) { m_pKeyFrames[i].pJointPos=new LMESH_JOINTPOSEX[m_nNumJoints]; if(!m_pKeyFrames[i].pJointPos) { for(j=i-1; j>0; j--) { L_safe_delete_array(m_pKeyFrames[j].pJointPos); } L_safe_delete_array(m_pKeyFrames); L_safe_delete_array(m_pMeshes); return L_false; } } */ for(i=0, m_nNumVertices=0; i<m_nNumMeshes; i++) { msMesh* pMesh=msModel_GetMeshAt(pModel, i); //The location of the current number of vertices is //the index of the first vertex in the mesh. m_pMeshes[i].nFirstVertex=m_nNumVertices; //We have to multiply the number of triangles by three to get //the nubmer of vertices. m_pMeshes[i].nNumTriangles=msMesh_GetTriangleCount(pMesh); //Finally add the triangle count to get the total. m_nNumVertices+=(msMesh_GetTriangleCount(pMesh)*3); } //Now lets allocate memory for everything else. m_pVertices=new LMESH_VERTEX[m_nNumVertices]; m_pVertexBoneList=new L_dword[m_nNumVertices]; m_pMaterials=new LMESH_MATERIAL[m_nNumMaterials]; //m_pBaseSkeleton=new LMESH_JOINTEX[m_nNumJoints]; //m_pBones=new LMESH_BONE[m_nNumJoints]; if(!m_pVertices || !m_pMaterials || /*!m_pBaseSkeleton ||*/ !m_pVertexBoneList || !m_pMeshes) { L_safe_delete_array(m_pVertexBoneList); L_safe_delete_array(m_pMeshes); L_safe_delete_array(m_pVertices); L_safe_delete_array(m_pMaterials); /* L_safe_delete_array(m_pBaseSkeleton); for(i=0; i<m_nNumKeyFrames; i++) { L_safe_delete_array(m_pKeyFrames[i].pJointPos); } L_safe_delete_array(m_pKeyFrames); // L_safe_delete_array(m_pBones); */ return 0; } //Now load the vertices. L_dword v=0; for(i=0, v=0; i<m_nNumMeshes; i++) { msMesh* pMesh=msModel_GetMeshAt(pModel, i); L_dword nTrianlgeCount=(L_dword)msMesh_GetTriangleCount(pMesh); for(j=0; j<(L_dword)msMesh_GetTriangleCount(pMesh); j++, v+=3) { msTriangle* pTriangle=msMesh_GetTriangleAt(pMesh, j); L_word nIndices[3]; L_word nNormalIndices[3]; msTriangle_GetVertexIndices(pTriangle, nIndices); msTriangle_GetNormalIndices(pTriangle, nNormalIndices); for(int k=0; k<3; k++) { //We use 2-k to get the vertex, cause we want to reverse //the vertext order, because the Legacy engine's standard //mode for culling is counter-clockwise and Milkshapes is //clockwise. msVertex* pVertex=msMesh_GetVertexAt(pMesh, nIndices[2-k]); msVec3 pNormal; msMesh_GetVertexNormalAt(pMesh, nNormalIndices[2-k], pNormal); //Copy coordinates. m_pVertices[v+k].x=pVertex->Vertex[0]; m_pVertices[v+k].y=pVertex->Vertex[1]; //Note that z is negative. m_pVertices[v+k].z=-pVertex->Vertex[2]; //Copy normals. m_pVertices[v+k].nx=pNormal[0]+pVertex->Vertex[0]; m_pVertices[v+k].ny=pNormal[1]+pVertex->Vertex[1]; //Note that z is negative. m_pVertices[v+k].nz=-(pNormal[2]+pVertex->Vertex[2]); m_pVertices[v+k].tu=pVertex->u; m_pVertices[v+k].tv=pVertex->v; //Save the bone index. m_pVertexBoneList[v+k]=pVertex->nBoneIndex; /* static L_bool bFirst=6; if(bFirst) { bFirst--; float v3[3]; v3[0]=pNormal[0]-pVertex->Vertex[0]; v3[1]=pNormal[1]-pVertex->Vertex[1]; v3[2]=pNormal[2]-pVertex->Vertex[2]; //ErrorBox("Normal Index: %i", nIndices[2-k]); ErrorBox( "Vertex <%f, %f, %f> len: %f Normal: <%f, %f, %f> len: %f index: %i difference: %f", pVertex->Vertex[0], pVertex->Vertex[1], pVertex->Vertex[2], vertex_length(pVertex->Vertex), pNormal[0], pNormal[1], pNormal[2], vertex_length(pNormal), nNormalIndices[2-k], vertex_length(v3)); } */ } } } //Load the meshes. for(i=0; i<m_nNumMeshes; i++) { //We've already loaded the start vertex, and //number of vertexes from above. msMesh* pMesh=msModel_GetMeshAt(pModel, i); L_strncpy(m_pMeshes[i].szName, pMesh->szName, LMESH_MAX_NAME_LENGTH); m_pMeshes[i].nMaterialIndex=pMesh->nMaterialIndex; } //Load the material. for(i=0; i<m_nNumMaterials; i++) { msMaterial* pMaterial=msModel_GetMaterialAt(pModel, i); L_strncpy(m_pMaterials[i].szMaterialName, pMaterial->szName, LMESH_MAX_NAME_LENGTH); L_strncpy(m_pMaterials[i].szTexture, pMaterial->szDiffuseTexture, LMESH_MAX_PATH); } m_bLoaded=L_true; return L_true; } //////////////////////////////////////////////////////////////// /// Legacy Skeleton Milkshape loading. ///////////////////////// //////////////////////////////////////////////////////////////// CLegacySkelMS::CLegacySkelMS(void* pModel) { this->LoadFromMS(pModel); } L_bool CLegacySkelMS::LoadFromMS(void* pModelParam) { msModel* pModel=(msModel*)pModelParam; L_dword i=0, j=0; m_nID=LSKEL_ID; m_nVersion=LSKEL_VERSION; m_nNumJoints=msModel_GetBoneCount(pModel); m_nNumKeyFrames=msModel_GetTotalFrames(pModel); if(!AllocateMemory()) return L_false; //Load the base skeleton. for(i=0; i<m_nNumJoints; i++) { msBone* pBone=msModel_GetBoneAt(pModel, i); L_strncpy(m_pBaseSkeleton[i].szName, pBone->szName, LMESH_MAX_PATH); L_strncpy(m_pBaseSkeleton[i].szParentBone, pBone->szParentName, LMESH_MAX_PATH); m_pBaseSkeleton[i].position[0]=pBone->Position[0]; m_pBaseSkeleton[i].position[1]=pBone->Position[1]; m_pBaseSkeleton[i].position[2]=-pBone->Position[2]; m_pBaseSkeleton[i].rotation[0]=pBone->Rotation[0]; m_pBaseSkeleton[i].rotation[1]=pBone->Rotation[1]; m_pBaseSkeleton[i].rotation[2]=-pBone->Rotation[2]; } //We now need to find all the indexes for the parent bones. for(i=0; i<m_nNumJoints; i++) { m_pBaseSkeleton[i].nParentBone=0; //If there is no parent the index for the parent bone is 0, //note that the index for bones is not zero based. In other //words bone 1 would be m_pBaseSkeleton[0]. if(L_strlen(m_pBaseSkeleton[i].szParentBone)<1) { m_pBaseSkeleton[i].nParentBone=0; continue; } for(j=1; j<=m_nNumJoints; j++) { if(L_strnicmp(m_pBaseSkeleton[i].szParentBone, m_pBaseSkeleton[j-1].szName, 0)) { m_pBaseSkeleton[i].nParentBone=j; break; } } } //Now we will write the keyframe information, //in the MS3D format only joints that are actually operated on //are saved, but in the legacy format we want every rotation //for every joint every frame. This can be calculated by finding //the most previous joint position. //Find the total number of keyframes. for(i=0; i<m_nNumJoints; i++) { msBone* pBone=msModel_GetBoneAt(pModel, i); for(j=0; j<m_nNumKeyFrames; j++) { /* m_pKeyFrames[j].pJointPos[i].position[0]=0.0f; m_pKeyFrames[j].pJointPos[i].position[1]=0.0f; m_pKeyFrames[j].pJointPos[i].position[2]=0.0f; m_pKeyFrames[j].pJointPos[i].rotation[0]=0.0f; m_pKeyFrames[j].pJointPos[i].rotation[1]=0.0f; m_pKeyFrames[j].pJointPos[i].rotation[2]=0.0f; */ //If we are dealing with the first frame set it //to zero in case there is no first frame, for //any other frames we simply set it to the previous //frame if there is no frame. if(j==0) { m_pKeyFrames[j].pJointPos[i].position[0]=0.0f; m_pKeyFrames[j].pJointPos[i].position[1]=0.0f; m_pKeyFrames[j].pJointPos[i].position[2]=0.0f; m_pKeyFrames[j].pJointPos[i].rotation[0]=0.0f; m_pKeyFrames[j].pJointPos[i].rotation[1]=0.0f; m_pKeyFrames[j].pJointPos[i].rotation[2]=0.0f; } L_word k=0; L_bool bFound=L_false; for(k=0; k<pBone->nNumPositionKeys; k++) { if((L_dword)pBone->pPositionKeys[k].fTime==(j+1)) { m_pKeyFrames[j].pJointPos[i].position[0]=pBone->pPositionKeys[k].Position[0]; m_pKeyFrames[j].pJointPos[i].position[1]=pBone->pPositionKeys[k].Position[1]; m_pKeyFrames[j].pJointPos[i].position[2]=-pBone->pPositionKeys[k].Position[2]; m_pKeyFrames[j].pJointPos[i].rotation[0]=pBone->pRotationKeys[k].Rotation[0]; m_pKeyFrames[j].pJointPos[i].rotation[1]=pBone->pRotationKeys[k].Rotation[1]; m_pKeyFrames[j].pJointPos[i].rotation[2]=-pBone->pRotationKeys[k].Rotation[2]; bFound=L_true; break; } } if(!bFound && j!=0) { m_pKeyFrames[j].pJointPos[i].position[0]=m_pKeyFrames[j-1].pJointPos[i].position[0]; m_pKeyFrames[j].pJointPos[i].position[1]=m_pKeyFrames[j-1].pJointPos[i].position[1]; m_pKeyFrames[j].pJointPos[i].position[2]=m_pKeyFrames[j-1].pJointPos[i].position[2]; m_pKeyFrames[j].pJointPos[i].rotation[0]=m_pKeyFrames[j-1].pJointPos[i].rotation[0]; m_pKeyFrames[j].pJointPos[i].rotation[1]=m_pKeyFrames[j-1].pJointPos[i].rotation[1]; m_pKeyFrames[j].pJointPos[i].rotation[2]=m_pKeyFrames[j-1].pJointPos[i].rotation[2]; } } } m_bLoaded=L_true; return L_true; } <file_sep>/samples/Project5/src/bcol/BStack.java /* <NAME> CS 2420-002 BStack generic stack for reuse. */ package bcol; /* The BStack class containsa BList rather than extending it, to insure that BList methods cannot be called on a BStack. */ public class BStack <T>{ private BList<T> m_listStack; /* PRE: N/A POST: Creates a new instance of BStack. */ public BStack() { m_listStack=new BList<T>(); } /* PRE: N/A POST: Returns true if the stack is empty. */ public boolean isEmpty(){ return m_listStack.isEmpty(); } /*PRE: c is a character. POST: c is pushed onto the top of the stack. */ public void push(T c) { m_listStack.insert(c); } /* PRE: The stack is not empty. POST: The object on the top of the stack is removed and returned. */ public T pop() throws BColException{ T obj=peek(); m_listStack.remove(obj); return obj; } /* PRE: The stack is not empty. POST: The object on the top of the stack is returned, but is left on the top of the stack. */ public T peek() throws BColException{ T t=m_listStack.getFirst(); if(t==null){ throw new BColException("Empty Stack (Underflow)."); } return t; } /* PRE: N/A POST: A string representation of the stack is returned. */ public String toString(){ return m_listStack.toString(); } } <file_sep>/games/Legacy-Engine/Scrapped/UnitTests/ML_demo/ML_demo.c #include <math.h> #include <stdio.h> #include <conio.h> #include <d3d9.h> #include <d3dx9.h> #pragma warning(disable: 4267) #pragma warning(disable: 4996) #include "ML_lib.h" #pragma comment(lib, "d3dx9.lib") #pragma comment(lib, "winmm.lib") void PrintMat(ML_MAT* pM1); void PrintVec3(ML_VEC3* pV1); void PrintVec4(ML_VEC4* pV1); void CRT_Test(); void Vec3Test(); int main(void) { //SSEVersion(); //DoSomething(); int i=0; #define F_STACK_TEST #ifdef F_STACK_TEST float fValue=2.3f; __asm fld fValue #endif F_STACK_TEST //ML_SetSIMDSupport(ML_INSTR_F); ML_Init(ML_INSTR_F); //ML_SetFuncs(ML_INSTR_SSE3); //ML_SetFuncs(ML_INSTR_3DNOW); printf("Conducting tests...\n"); //#define TEXT_OUTPUT #ifdef TEXT_OUTPUT freopen("out.txt", "w", stdout); #endif TEST_OUTPUT Vec3Test(); MatTest(); CRT_Test(); #ifdef F_STACK_TEST __asm fstp fValue printf("FVALUE=%f\n", fValue); #endif F_STACK_TEST #ifdef TEXT_OUTPUT freopen( "CON", "w", stdout ); #endif TEXT_OUTPUT //MatTest(); printf("Tests complete.\nPress any key to exit.\n"); getch(); return 0; } void CRT_Test() { float f=2.5f; ml_float fSin, fCos; printf("ML_lib:\tcosf(%f)=%f\n", f, ML_cosf(f)); printf("CRT:\tcosf(%f)=%f\n", f, cosf(f)); printf("\n\n"); printf("ML_lib:\tsinf(%f)=%f\n", f, ML_sinf(f)); printf("CRT:\tsinf(%f)=%f\n", f, sinf(f)); printf("\n\n"); printf("ML_lib:\ttanf(%f)=%f\n", f, ML_tanf(f)); printf("CRT:\ttanf(%f)=%f\n", f, tanf(f)); printf("\n\n"); f=0.5f; printf("ML_lib:\tacosf(%f)=%f\n", f, ML_acosf(f)); printf("CRT:\tacosf(%f)=%f\n", f, acosf(f)); printf("\n\n"); printf("ML_lib:\tasinf(%f)=%f\n", f, ML_asinf(f)); printf("CRT:\tasinf(%f)=%f\n", f, asinf(f)); printf("\n\n"); //3.012f, 1.24f, 4.566f f=4.566f; fSin=ML_sincosf(f, &fCos); printf("ML_lib:\tsincosf(%f)=%f, %f\n", f, fSin, fCos); fSin=sinf(f); fCos=cosf(f); printf("CRT:\tsincosf(%f)=%f, %f\n", f, fSin, fCos); f=1.24f; fSin=ML_sincosf(f, &fCos); printf("ML_lib:\tsincosf(%f)=%f, %f\n", f, fSin, fCos); fSin=sinf(f); fCos=cosf(f); printf("CRT:\tsincosf(%f)=%f, %f\n", f, fSin, fCos); f=3.012f; fSin=ML_sincosf(f, &fCos); printf("ML_lib:\tsincosf(%f)=%f, %f\n", f, fSin, fCos); fSin=sinf(f); fCos=cosf(f); printf("CRT:\tsincosf(%f)=%f, %f\n", f, fSin, fCos); printf("\n\n"); } void PrintMat(ML_MAT* pM1) { printf("%f\t%f\t%f\t%f\n", pM1->_11, pM1->_12, pM1->_13, pM1->_14); printf("%f\t%f\t%f\t%f\n", pM1->_21, pM1->_22, pM1->_23, pM1->_24); printf("%f\t%f\t%f\t%f\n", pM1->_31, pM1->_32, pM1->_33, pM1->_34); printf("%f\t%f\t%f\t%f", pM1->_41, pM1->_42, pM1->_43, pM1->_44); printf("\n\n"); } void PrintVec3(ML_VEC3* pV1) { printf("%f\t%f\t%f\t", pV1->x, pV1->y, pV1->z); printf("\n"); } void PrintVec4(ML_VEC4* pV1) { printf("%f\t%f\t%f\t%f", pV1->x, pV1->y, pV1->z, pV1->w); printf("\n"); }<file_sep>/games/Legacy-Engine/Scrapped/UnitTests/lc_demo2/lc_demo2.c #include <stdio.h> #include <conio.h> #include <tchar.h> #include <windows.h> #include "lc_sys2.h" typedef struct _LCDEMO_INFO{ lg_bool bQuit; }LCDEMO_INFO; lg_bool LCDemoCmd(LC_CMD nCmd, lg_void* pParams, lg_void* pExtra) { LCDEMO_INFO* pInfo=(LCDEMO_INFO*)pExtra; switch(nCmd) { case 7: { const lg_char* szCvar=LC_GetArg(1, pParams); const lg_char* szValue=LC_GetArg(2, pParams); lg_cvar* cvar; if(!szCvar || !szValue) { LC_Printf("USAGE: set \"$cvarname$\" \"$value$\""); break; } cvar=CV_Get(szCvar); if(!cvar) { LC_Printf("\"%s\" is not a registered cvar.", szCvar); break; } CV_Set_s(cvar, szValue); LC_Printf("Set %s (\"%s\", %.2f, %d)", cvar->szName, cvar->szValue, cvar->fValue, cvar->nValue); break; } case 1: LC_Printf(TEXT("Quit command.")); pInfo->bQuit=1; break; case 2: LC_ListCommands(); break; case 3: LC_Printf(TEXT("List second command.")); break; case 4: { const lg_char* szString=LC_GetArg(1, pParams); if(!szString) LC_Printf(TEXT("USAGE: echo \"$string$\".")); else LC_Printf(TEXT("%s"), szString); return LG_TRUE; } case 9: LC_Clear(); break; case 6: LC_Print(TEXT("cvarlist command")); break; case 13: LC_Print(TEXT("Lose command")); break; default: return LG_FALSE; } return LG_TRUE; } void main() { LCDEMO_INFO info; lg_dword nMessage=0; lg_char szCmd[1024]; info.bQuit=0; LC_Init(); LC_Printf(TEXT("Cosole Tester v1.0")); LC_SetCommandFunc(LCDemoCmd, &info); LC_RegisterCommand(TEXT("quit"), 1, 0); LC_RegisterCommand(TEXT("cmdlist"), 2, 0); LC_RegisterCommand(TEXT("cmdlist"), 3, 0); LC_RegisterCommand(TEXT("echo"), 4, 0); LC_RegisterCommand(TEXT("extract"), 5, 0); LC_RegisterCommand(TEXT("cvarlist"), 6, 0); LC_RegisterCommand(TEXT("set"), 7, 0); LC_RegisterCommand(TEXT("get"), 8, 0); LC_RegisterCommand(TEXT("clear"), 9, 0); LC_RegisterCommand(TEXT("hello"), 10, 0); LC_RegisterCommand(TEXT("whatup"), 11, 0); LC_RegisterCommand(TEXT("win"), 12, 0); LC_RegisterCommand(TEXT("lose"), 13, 0); LC_RegisterCommand(TEXT("regcvar"), 14, 0); CV_Define_l("TRUE", 1); CV_Define_l("FALSE", 0); CV_Define_l("ONE", 1); CV_Define_l("TWO", 2); CV_Define_l("THREE", 3); CV_Register("v_Windowed", "TRUE", CVAR_SAVE|CVAR_ROM); CV_Register("v_VidSetting", "THREE", CVAR_SAVE); CV_Register("hi{}", "HI", CVAR_ROM); while(LG_TRUE) { const lg_char* szLine=LC_GetOldestLine(); system("cls"); while(szLine) { _tprintf(TEXT("%s\n"), szLine); szLine=LC_GetNextLine(); } _tprintf(TEXT("ct:> ")); _getts(szCmd); LC_SendCommand(szCmd); if(_tcsicmp(szCmd, TEXT("x"))==0) break; if(info.bQuit) break; } LC_Shutdown(); _tprintf(TEXT("press any key to exit\n")); getch(); }<file_sep>/samples/D3DDemo/code/MD3Base/MD3TexDB.cpp /* MD3TexDB.cpp - Source for MD3Texture Database implimentation. Copryight (c) 2003 <NAME> */ #define D3D_MD3 #include <d3dx9.h> #include "defines.h" #include "Functions.h" #include "md3.h" #include "md3texdb.h" /* CMD3Texture class methods. The CMD3Texture objects represent nodes in a linked-list. Each object can get the next item in the list by calling GetNext(). The last object in the list will have m_lpNext set to NULL. */ //Constructor simply sets all values to 0 or NULL. CMD3Texture::CMD3Texture() { m_Texture.lpTexture=NULL; m_Texture.szTextureName[0]=0; m_lpNext=NULL; } //Destructor releases the texture. CMD3Texture::~CMD3Texture() { if(m_Texture.lpTexture) m_Texture.lpTexture->Release(); } //Returns the next node in the linked-list CMD3Texture * CMD3Texture::GetNext() { return m_lpNext; } //Sets the next node in the list. void CMD3Texture::SetNext(CMD3Texture * lpNext) { m_lpNext=lpNext; } //Sets the texture data for the node. void CMD3Texture::SetTexture(MD3TEXTURE * lpTexture) { m_Texture.lpTexture=lpTexture->lpTexture; strcpy(m_Texture.szTextureName, lpTexture->szTextureName); } //Gets the texture data for the node. void CMD3Texture::GetTexture(MD3TEXTURE * lpTexture) { lpTexture->lpTexture=m_Texture.lpTexture; strcpy(lpTexture->szTextureName, m_Texture.szTextureName); } /* CMD3TextureDB class methods. The CMD3TextureDB object manages a linked list. The first object contains a pointer to the second object, which in turn has a pointer to the next object and so on. */ CMD3TextureDB::CMD3TextureDB(): m_dwNumTextures(0) { //Constructor simly sets the first link to NULL. m_lpFirst=NULL; } CMD3TextureDB::~CMD3TextureDB() { //Destructor insures that the database is clear. ClearDB(); } //Returns the number of textures HRESULT CMD3TextureDB::GetNumTextures(DWORD * dwNumTex) { *dwNumTex=m_dwNumTextures; return S_OK; } //Adds a texture from a filename, uses filename as texture name. HRESULT CMD3TextureDB::AddTexture(LPDIRECT3DDEVICE9 lpDevice, char szTexName[MAX_PATH]) { CMD3Texture * lpCurrent=NULL; CMD3Texture * lpNext=NULL; LPDIRECT3DTEXTURE9 lpTexture=NULL; MD3TEXTURE md3Texture; HRESULT hr=0; char szName[MAX_PATH]; ZeroMemory(&md3Texture, sizeof(MD3TEXTURE)); //Reomving the path directory from the filename gives a good //texture name. RemoveDirectoryFromString(szName, szTexName); //If the texture already exists we silently return. if(SUCCEEDED(GetTexture(szName, &lpTexture))){ lpTexture->Release(); return S_FALSE; } if(m_lpFirst==NULL){ //If there are currently no textures in the database //we create the first node. m_lpFirst=new CMD3Texture; if(m_lpFirst==NULL){ return E_FAIL; } m_lpFirst->SetNext(NULL); //Load the texture from file. hr=D3DXCreateTextureFromFileExA( lpDevice, szTexName, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, 0xFF000000L, NULL, NULL, &md3Texture.lpTexture); if(FAILED(hr)){ //If we failed we delete the node //and return an error. SAFE_DELETE(m_lpFirst); return E_FAIL; } //Copy over the texture name. strcpy(md3Texture.szTextureName, szName); //Put the texture in the node. m_lpFirst->SetTexture(&md3Texture); }else{ lpCurrent=m_lpFirst; //Go through the nodes until we find an empty one. while(lpCurrent->GetNext() != NULL){ lpCurrent=lpCurrent->GetNext(); } //Create the new node lpNext=new CMD3Texture; if(lpNext==NULL){ return E_FAIL; } lpNext->SetNext(NULL); //Create the texture from file hr=D3DXCreateTextureFromFileExA( lpDevice, szTexName, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, 0xFF000000L, NULL, NULL, &md3Texture.lpTexture); if(FAILED(hr)){ SAFE_DELETE(lpNext); return E_FAIL; } strcpy(md3Texture.szTextureName, szName); lpNext->SetTexture(&md3Texture); //Set the new node as the next node to the old last node. lpCurrent->SetNext(lpNext); } //Increment the number of textures. m_dwNumTextures++; return S_OK; } /* The code for this version of AddTexture works pretty much the same as the previous method except it uses the szTexName parameter as the texture name, and it merely obtains a pointer to the lpTexture parameter, instead of creating the file from disk. Note that it calls the AddRef function on the texture, so Release() will need to be called on any textures passed to this function before the program terminates. */ HRESULT CMD3TextureDB::AddTexture(LPDIRECT3DTEXTURE9 lpTexture, char szTexName[]) { //Se previous method for information on how this works. CMD3Texture * lpCurrent=NULL; CMD3Texture * lpNext=NULL; LPDIRECT3DTEXTURE9 lpTempTexture=NULL; MD3TEXTURE md3Texture; HRESULT hr=0; ZeroMemory(&md3Texture, sizeof(MD3TEXTURE)); if(lpTexture==NULL)return E_FAIL; //First we check to see if the texture already exists. if(SUCCEEDED(GetTexture(szTexName, &lpTexture))){ lpTexture->Release(); return S_FALSE; } if(m_lpFirst==NULL){ m_lpFirst=new CMD3Texture; if(m_lpFirst==NULL){ return E_FAIL; } m_lpFirst->SetNext(NULL); md3Texture.lpTexture=lpTexture; md3Texture.lpTexture->AddRef(); strcpy(md3Texture.szTextureName, szTexName); m_lpFirst->SetTexture(&md3Texture); }else{ lpCurrent=m_lpFirst; while(lpCurrent->GetNext() != NULL){ lpCurrent=lpCurrent->GetNext(); } lpNext=new CMD3Texture; if(lpNext==NULL){ return E_FAIL; } lpNext->SetNext(NULL); md3Texture.lpTexture=lpTexture; md3Texture.lpTexture->AddRef(); strcpy(md3Texture.szTextureName, szTexName); lpNext->SetTexture(&md3Texture); lpCurrent->SetNext(lpNext); } m_dwNumTextures++; return S_OK; } //Retrieves a texture by a reference number. HRESULT CMD3TextureDB::GetTexture( DWORD dwRef, LPDIRECT3DTEXTURE9 * lppTexture) { CMD3Texture * lpCurrent=NULL; MD3TEXTURE md3Texture; DWORD i=0; ZeroMemory(&md3Texture, sizeof(MD3TEXTURE)); if( (dwRef>m_dwNumTextures) || (dwRef<1) )return E_FAIL; //What we do to retriev the chosen texture //is go through the nodes until we get //to the speicifed number. Then we let //the pointer into the lppTexture param. lpCurrent=m_lpFirst; for(i=0; i<(dwRef-1); i++){ lpCurrent=lpCurrent->GetNext(); if(lpCurrent==NULL)return E_FAIL; } lpCurrent->GetTexture(&md3Texture); *lppTexture=md3Texture.lpTexture; md3Texture.lpTexture->AddRef(); return S_OK; } //Get a texture from it's name. HRESULT CMD3TextureDB::GetTexture( char szTexName[], LPDIRECT3DTEXTURE9 * lppTexture) { CMD3Texture * lpCurrent=NULL; MD3TEXTURE md3Texture; DWORD i=0; ZeroMemory(&md3Texture, sizeof(MD3TEXTURE)); //What we do is loop through each node //until we find on with a name matching //the szTexName param. lpCurrent=m_lpFirst; for(i=0; i<m_dwNumTextures; i++){ if(lpCurrent==NULL)return E_FAIL; lpCurrent->GetTexture(&md3Texture); if(strcmp(md3Texture.szTextureName, szTexName)==0){ *lppTexture=md3Texture.lpTexture; md3Texture.lpTexture->AddRef(); return S_OK; } lpCurrent=lpCurrent->GetNext(); } return E_FAIL; } //Sets the current render texture based on index. HRESULT CMD3TextureDB::SetRenderTexture( DWORD dwRef, DWORD dwStage, LPDIRECT3DDEVICE9 lpDevice) { CMD3Texture * lpCurrent=NULL; MD3TEXTURE md3Texture; DWORD i=0; ZeroMemory(&md3Texture, sizeof(MD3TEXTURE)); if( (dwRef>m_dwNumTextures) || (dwRef<1) )return E_FAIL; //Go through each node till we get to the one we want. lpCurrent=m_lpFirst; for(i=0; i<(dwRef-1); i++){ lpCurrent=lpCurrent->GetNext(); if(lpCurrent==NULL)return E_FAIL; } lpCurrent->GetTexture(&md3Texture); //Render the selected texture in the chosen stage. (lpDevice)->SetTexture(dwStage, md3Texture.lpTexture); return S_OK; } //Sets the current render texture based on name. HRESULT CMD3TextureDB::SetRenderTexture( LPSTR szTexName, DWORD dwStage, LPDIRECT3DDEVICE9 lpDevice) { CMD3Texture * lpCurrent=NULL; MD3TEXTURE md3Texture; DWORD i=0; ZeroMemory(&md3Texture, sizeof(MD3TEXTURE)); //Go through each texture till we find one with the matching name. lpCurrent=m_lpFirst; for(i=0; i<m_dwNumTextures; i++){ if(lpCurrent==NULL)return E_FAIL; lpCurrent->GetTexture(&md3Texture); if(strcmp(md3Texture.szTextureName, szTexName)==0){ //Set the render texture in the chosen stage. (lpDevice)->SetTexture(dwStage, md3Texture.lpTexture); return S_OK; } lpCurrent=lpCurrent->GetNext(); } //If no texture had the specified name we fail. return E_FAIL; } //Deletes the chosen texture out of the database by index. HRESULT CMD3TextureDB::DeleteTexture( DWORD dwRef) { CMD3Texture * lpPrev=NULL; CMD3Texture * lpCurrent=NULL; CMD3Texture * lpNext=NULL; DWORD i=0; lpCurrent=m_lpFirst; if((dwRef>m_dwNumTextures) || (dwRef<1))return E_FAIL; if(m_dwNumTextures<1)return E_FAIL; if(lpCurrent==NULL)return E_FAIL; if(dwRef==1){ //If we want to delete the first //node we simply delete it and make //the second node the first node. lpNext=lpCurrent->GetNext(); SAFE_DELETE(lpCurrent); m_lpFirst=lpNext; }else{ //Go though each texture till we get to the one //we want to delete and remove it. Setting it's //previous node's next node the it's next node. for(i=0; i<(dwRef-1); i++){ if(lpCurrent==NULL)return E_FAIL; lpPrev=lpCurrent; lpCurrent=lpCurrent->GetNext(); } lpNext=lpCurrent->GetNext(); SAFE_DELETE(lpCurrent); lpPrev->SetNext(lpNext); } //Decrement the number of textures. m_dwNumTextures--; return S_OK; } //Delete a texture from the database, based on teh textures name. HRESULT CMD3TextureDB::DeleteTexture( LPSTR szTexName) { CMD3Texture * lpPrev=NULL; CMD3Texture * lpCurrent=NULL; CMD3Texture * lpNext=NULL; MD3TEXTURE md3Texture; DWORD i=0; ZeroMemory(&md3Texture, sizeof(MD3TEXTURE)); lpCurrent=m_lpFirst; if(m_dwNumTextures<1)return E_FAIL; if(lpCurrent==NULL)return E_FAIL; m_lpFirst->GetTexture(&md3Texture); if(strcmp(md3Texture.szTextureName, szTexName)==0){ //If the name matches the first one we //do the same procedure as in the previous method. lpNext=lpCurrent->GetNext(); SAFE_DELETE(lpCurrent); m_lpFirst=lpNext; }else{ //Loop through till we find a texture with mathching name. for(i=0; i<m_dwNumTextures; i++){ if(lpCurrent==NULL)return E_FAIL; lpPrev=lpCurrent; lpCurrent=lpCurrent->GetNext(); if(lpCurrent==NULL)return E_FAIL; lpCurrent->GetTexture(&md3Texture); if(strcmp(md3Texture.szTextureName, szTexName)==0) break; } if(lpCurrent==NULL)return E_FAIL; lpCurrent->GetTexture(&md3Texture); if(strcmp(md3Texture.szTextureName, szTexName)!=0){ return E_FAIL; } //When we have texture we want to delete we //remove it and make it's previous node's next node //it's next node. lpNext=lpCurrent->GetNext(); SAFE_DELETE(lpCurrent); lpPrev->SetNext(lpNext); } m_dwNumTextures--; return S_FALSE; } //Clears the entire database. HRESULT CMD3TextureDB::ClearDB() { CMD3Texture * lpCurrent=NULL; CMD3Texture * lpNext=NULL; lpCurrent=m_lpFirst; //Loop through each node and delete it. while(lpCurrent != NULL){ lpNext=lpCurrent->GetNext(); SAFE_DELETE(lpCurrent); lpCurrent=lpNext; } //Clear the first node so we know it's empty. m_lpFirst=NULL; m_dwNumTextures=0; return S_OK; } <file_sep>/games/Legacy-Engine/Source/ws_sys/ws_sys.h #ifndef __WS_SYS_H__ #define __WS_SYS_H__ //I don't want to use common.h in this file, //but for now it is used for file IO. #include "common.h" #include <pshpack1.h> #define WS_MAX_STRING_LENGTH 512 #define WS_TRUE 1 #define WS_FALSE 0 #define WS_NULL 0 #define WS_MAP_VERSION 14 typedef char wsChar; typedef unsigned char wsByte; typedef unsigned short wsWord; typedef unsigned long wsDword; typedef signed short wsShort; typedef signed long wsLong; typedef float wsFloat; typedef char* wspString; typedef unsigned long wsName; typedef int wsBool; typedef unsigned char wsString[WS_MAX_STRING_LENGTH]; #define WS_SAFE_DELETE_ARRAY(p) {if(p){delete[]p;p=WS_NULL;}} typedef struct _wsColor3 { wsByte r, g, b; }wsColor3; typedef struct _wsVec2 { wsFloat x, y; }wsVec2; typedef struct _wsVec3 { wsFloat x, y, z; }wsVec3; typedef struct _wsVec4 { wsFloat x, y, z, w; }wsVec4; //Object Types: typedef struct _wsGroup{ wsByte Flags; wsLong Index; }wsGroup; typedef struct _wsVisGroup{ wsByte Flags; wsName Name; wsColor3 Color; }wsVisGroup; #define WS_MATERIAL_EXT_NAME 0x02 typedef struct _wsMaterial{ wsByte Flags; wsName GroupName; wsName ObjectName; wsName ExtensionName; //Only if Flags&2 }wsMaterial; typedef struct _wsMeshReference{ wsByte Flags; wsName GroupName; wsName ObjectName; wsByte LimbCount; }wsMeshReference; typedef struct _wsLightMap{ wsByte Flags; wsByte Resolution; //Actually 2^Resolution (always square). wsLong Format; wsColor3* Pixels; }wsLightMap; typedef struct _wsKey { wsName Name; wsName Value; }wsKey; #define WS_FACE_LIGHTMAP 0x10 typedef struct _wsIndex{ wsByte Vertex; wsVec2 TexCoords; wsVec2 LightMapTexCoords; //If 16 & Flags in wsFace structure }wsIndex; typedef struct _wsFace{ wsByte Flags; wsVec4 FacePlaneEquation; wsVec2 TexturePosition; wsVec2 TextureScale; wsVec2 TextureRotation; wsVec4 UTexMappingPlane; wsVec4 VTexMappingPlane; wsFloat LuxelSize; wsLong SmoothGroupIndex; wsLong MaterialIndex; wsLong LightMapIndex; //If Flags&0x10 wsByte IndexCount; }wsFace; #define WS_BRUSH_HIDDEN 0x04 typedef struct _wsBrush { wsByte Flags; wsLong NumKeys; wsKey* Keys; wsLong GroupIndex; wsLong VisGroupIndex; wsColor3 BrushColor; wsByte VertexCount; wsVec3* VertexPositions; wsByte FaceCount; wsFace* Faces; }wsBrush; #define WS_MESH_LIT 0x10 typedef struct _wsMeshShade{ wsLong MaterialIndex; //If(16&Flags) from wsMesh wsShort VertexCount; wsColor3* VertexColor; }wsMeshShade; #define WS_MESH_NO_SCALE 0x01 typedef struct _wsMesh{ wsByte Flags; wsLong NumKeys; wsKey* Keys; wsLong Group; wsLong VisGroup; wsColor3 MeshColor; wsLong MeshRefIndex; wsVec3 Position; wsVec3 Rotation; wsVec3 Scale; //If !(Flags&1) wsMeshShade* LimbShader; }wsMesh; typedef struct _wsEntity{ wsByte Flags; wsVec3 Position; wsLong NumKeys; wsKey* Keys; wsLong Group; wsLong VisGroup; }wsEntity; #include <poppack.h> class CWSFile { private: //Header Data: wsWord m_nMapVersion; //Should be 14 wsByte m_nMapFlags; wsLong m_nNameCount; wsLong m_nNameOffset; wsLong m_nObjectCount; wsLong m_nObjectOffset; wsString* m_pNameTable; wsBool m_bOpen; private: static wsDword ReadString(void* fin, fio_callbacks* pCB, wsString szOut); public: CWSFile(); ~CWSFile(); wsBool TempOpen(wspString szFilename); void Close(); }; #endif __WS_SYS_H__<file_sep>/games/Legacy-Engine/Source/engine/lv_font.h #ifndef __LV_FONT_H__ #define __LV_FONT_H__ #include <d3d9.h> #include "common.h" #include "lg_types.h" class CLFont { protected: IDirect3DDevice9* m_pDevice; lg_byte m_nCharWidth; lg_byte m_nCharHeight; lg_bool m_bIsDrawing; char m_szFont[LG_MAX_PATH+1]; public: CLFont(); ~CLFont(); virtual void Delete(){}; virtual lg_bool Validate(){return LG_TRUE;}; virtual void Invalidate(){}; virtual void Begin(){}; virtual void End(){}; virtual void DrawString(char* szString, lg_long x, lg_long y){}; virtual void GetDims(lg_byte* nWidth, lg_byte* nHeight, lg_void* pExtra){}; public: static CLFont* Create( IDirect3DDevice9* lpDevice, char* szFont, lg_byte nCharWidth, lg_byte nCharHeight, lg_bool bD3DXFont, lg_byte nCharWidthInFile, lg_byte nCharHeightInFile, lg_dword dwD3DColor); }; #endif /*__LV_FONT_H__*/<file_sep>/games/Legacy-Engine/Source/engine/lg_list.h #ifndef __LG_LIST_H__ #define __LG_LIST_H__ #include "lg_types.h" #include "lg_stack.h" template <class T> class CLList { public: //The node class class CNode { friend class CLList; public: T m_data; CNode* m_pPrev; CNode* m_pNext; }; private: lg_dword m_nMaxItems; CLStack<CNode*> m_stkUnusedNodes; CNode* m_pNodeList; public: CNode* m_pList; public: CLList(): m_nMaxItems(100), m_stkUnusedNodes(m_nMaxItems), m_pList(LG_NULL) { Init(); } CLList(lg_dword nMaxItems): m_nMaxItems(nMaxItems), m_stkUnusedNodes(m_nMaxItems), m_pList(LG_NULL) { Init(); } ~CLList() { Destroy(); } private: __inline void Init() { //m_pUnusedNodeStack=new CLStack<CNode>(m_nMaxItems); m_pList=LG_NULL; m_pNodeList=new CNode[m_nMaxItems]; for(lg_dword i=0; i<m_nMaxItems; i++) { m_stkUnusedNodes.Push(&m_pNodeList[i]); } } __inline void Destroy() { delete m_pNodeList; } public: void Insert(T data) { if(m_stkUnusedNodes.IsEmpty()) { //No memory, bad programming because //all lists should be of known size return; } //Get the new node and insert it at the //beginning of the list. CNode* pNodeNew = m_stkUnusedNodes.Pop(); pNodeNew->m_data=data; pNodeNew->m_pPrev=LG_NULL; pNodeNew->m_pNext=m_pList; if(m_pList) m_pList->m_pPrev=pNodeNew; m_pList=pNodeNew; } }; #endif __LG_LIST_H__<file_sep>/games/Legacy-Engine/Source/engine/wnd_sys/wnd_manager.h /* File: wnd_mgr.h - The window manager. Description: The window manager manages in game windows. It is currently incomplete. (c) 2009 <NAME> */ #pragma once #include "wnd_window.h" namespace wnd_sys{ class CManager{ private: CWindow m_TestWnd; CWindow m_TestWnd2; public: CManager(); ~CManager(); void Init(); void Shutdown(); void Render(); }; } //namespace wnd_sys<file_sep>/games/Sometimes-Y/SometimesY/SYGame.h #pragma once class CSYGame { public: enum PLACE_RESULT{PLACE_OK, PLACE_WIN, PLACE_BAD}; enum BLOCK_TYPE{ BLOCK_EMPTY=0x80000000, BLOCK_A=0, BLOCK_E, BLOCK_I, BLOCK_O, BLOCK_U, BLOCK_Y, BLOCK_UNUSABLE=0xFFFFFFFF}; enum BLOCK_STATUS{ STATUS_EMPTY, STATUS_PLACED, STATUS_FIXED}; DWORD m_nTypeAvail[6]; public: class Block{public:BLOCK_TYPE nType; BLOCK_STATUS nStatus; BOOL bValid;}; private: static const DWORD EMPTY_BLOCK=0; static const DWORD UNUSABLE_BLOCK=0xFFFFFFFF; BOOL m_bGameRunning; DWORD m_nGameSizeX, m_nGameSizeY; Block* m_GameMatrix; public: CSYGame(void); ~CSYGame(void); //StartGame - Loads the game file and starts a new game. //Returns TRUE if the game was sucessfully loaded, FALSE //if the game could BOOL StartGame(LPCTSTR szGameFile); void EndGame(); PLACE_RESULT PlaceLetter(BLOCK_TYPE type, DWORD nX, DWORD nY, LPTSTR szOutMsg); BOOL RemoveLetter(DWORD nX, DWORD nY); void GetSize(DWORD& x, DWORD& y); const Block* GetBlock(const DWORD x, const DWORD y); void GetAvailLetters(DWORD* pCounts); private: void SetBlock(DWORD x, DWORD y, BLOCK_TYPE nType, BLOCK_STATUS nStatus); void SetBlockValid(DWORD x, DWORD y, BOOL bValid=TRUE); void UpdateGameStatus(); BOOL CheckA(DWORD x, DWORD y); BOOL CheckE(DWORD x, DWORD y); BOOL CheckI(DWORD x, DWORD y); BOOL CheckO(DWORD x, DWORD y); BOOL CheckU(DWORD x, DWORD y); BOOL CheckY(DWORD x, DWORD y); void GetSides(DWORD x, DWORD y, BLOCK_TYPE* sides); }; <file_sep>/games/Explor2002/Source/Game/Readme.txt Explor Copyright (c) 2002, <NAME> by Beem Software Author: <NAME> for Beem Software Language: C++ Win32, DirectX API Version x.xxW Log: March 12, 2002 Created the new CGameMap class which is a modified version of the ExplorMap class used in ExplorED. I've removed some of the unusable functions, and added a new function: generateTFront(...) which generates the tiles-in-front array. There is no game yet. As soon as I have the will I will get the wall art, and then try to rig up a game similar to the current DOS beta, except with DirectDraw instead. March 14, 2002 The 3D Rendering functions have been built, though are not complete. They will take a tbase array, and load the appropriate tiles onto the secondary surface. I have not generated a game yet though. I also changed the Tile manager so it only has three tile objects. It adjusts their size appropriately when the tile manager draw function is called. March 15, 2002 The engine is complete. Though there is a problem with the ReleaseSurfaces() function in main.cpp. It seems that calling the Release for the TileSet Class doesn't work correctly, so I'm not having them be released. This will make it so memory is still being occupied even when the program ends, I hope to fix this. So for now it just doesn't release the memory. I'm not really satisfied with the engine, it didn't turn out how I hoped and a great deal of the rendering is not correct. I can redo the rendering functions to fix this, but I don't really want to do the work, after all this program will probably never really go anywhere. April 03, 2002 The engine now releases properly, which eliminates that goddamned bug. Old Log: (From the dos stages) 'Here it is the BETA release of EXPLOR it's not much but a good 'start. You probably won't want to play it for much more than a 'couple of minutes, probably less actually, but it's worth your 'time. 'The game is completely based off Might and Magic though there are other 'games like it). I had Might and Magic for nintendo but it just wouldn't 'save right so I decided to make my own game. It's rendered 3D just like 'the first two might and magic games. It's pretty cool and I'm proud of 'myself. I actually only spent three days on it. The first two I spent 'an average of 12 hours a day on it. (Why? Well I was bored.) Anyway here 'it is. 'Log 'I originally had plans for this program but now it is deemed as junk 'It has a story and credits but no game I doubt that it ever will have 'a game because Joe's Copter II is a lot better than any exploring game 'maybe when I get the internet I will be able to allow other people to 'use this piece of junk I don't want to throw it away because I spent 'so much time on it. 'That's old news I'm going to reincorporate EXPLOR and start the project 'it may end up junk anyways. 'Damn!!! It works perfectly. 'Well since the ASCII graphics interface didn't work right I changed 'To regular VGA graphics. I also incorporated the loadmap from venture.bas 'I'm sure the loser author won't care. Too much! Anyways he'll never know. 'The load map works extremely well. I figure if I want a different map 'loaded I can just use different subs for different levels. Anyway I have 'to change the movement arrow to VGA graphics rather than ASCII then I will 'have to redefine the movement so it stops when approaching a wall. 'I don't want to do that today though. It will actually take a while. 'Turnleft and Turnright will not to be changed but calcforward and calcbackward 'will. Placechar will need to be changed also. What the hell I did it today 'The engine is working fine all I need to do is write the code that will 'make it not be able to pass through walls. I'm actually proud of all I 'have accomplished today. 'I have changed the variable from 4.52 to con which equals the same thing. 'I have established borders for the character. 'I developed a method to stop the arrow from passing through walls now 'all thats left is to develop the 3D rendering. 'Well all done. The 3D rendering works fine, it's extremely buggy though. 'I'm not going to do anymore with this program, I've done enough. 'It takes so much memory qbasic 4.5 can't convert it to an .exe I'm 'kind of disapointed. No matter it will be fine. 'I made view1 look a lot better creating 0.02b. 'I've started working on the project again: 'Now supports new map format. That is the map format formed by ExplorED. 'Currently only supports 10's and 1's. I developed my own map loader will 'work better in the future. 'I've created the facing north rendering. It seems to work so far 'but I haven't really tested it. Will create east and south 'rendering later. Rendering only works if within 4 edge of map 'need to fix that. ' 'Current north rendering was deleted. I created a new method so it 'calculates an array by choosing the direction. This array is tfront% ' 'I have created calculations for North, South, East, and West ' 'Made the 3D rendering sub. It seems to work but actually probably has 'more than a dozen errors. Well maybe not a dozen. Any way need to 'make the movement subs. Will probably port them over from. V 0.04B 'May improve the render3D sub later so it only loads the images it has 'to. ' 'I brought over the moveinput sub and renamed it takeinput. The 3D rendering 'seems to work perfectly. It flashes a lot, I can fix this if I decide to 'redo the 3D rendering sub to only place the tiles that will show up in the 'end. ' 'Need to make it so one cannot pass through a wall. 'Made walls now not possible to pass through, unless you are inside one. 'Also fixed a bug where facing north fucked up on tfront%(10) and a bug 'where direction was displayed wrong. ' 'Explor is just about where it was before I redid the engine. An automap 'as well as the menu's are still missing. When I redo the credits I will 'probably drop most of the bullshit and do a more reasonable list of 'creators. Namely me with a special thanks to <NAME> and Craig 'Decker. ' 'Redid automap feature it works pretty well. A little better than before 'but mostly the same. Used some of the same code. ' 'It will be necessary to add door tiles if I really want to get anywhere 'decent. ' 'Updated some code deficiencies, to make future developments easier. 'What I need to do now is further the ExplorED Editor to do more things 'then come back to this code. 'Damn I love this code it just works so fucking well. ' 'Now supports Map version beta2: That is 0's instead of 1's for empty space ' 'Doors are now read by explor. Made some major fixes for moveing forward 'and backward. As well as automap display. ' 'Expected memory issues discovered when dimensioning the doors. Its just too 'damn big. So now for doors it simply places the preset version of the 'wall image. There is no fucking way we're going to leave that final. We'll 'figure something out. We don't know what yet maybe we should invent a 'fucking bitmap loader. BLOAD and BSAVE may also work !!! I'll look into 'what they are capable of doing. Current skyground is really sloppy this can 'easily be fixed when we fix the door sprites. ' 'I've done the BLOAD thing for the wall sprites. Now nothing is displayed 'for the doors. I need to write up some graphics and do the same thing 'for them as I did for the walls. To load a particular wall position you 'simply type loadwal(wallnumber) where wall number is the wall that is true 'check out render3D to see exactly how it is done. I'm pretty satisfied 'with it. ' 'I'm pretty fucking satisfied that I learned how to use BLOAD and BSAVE 'the program wallgen generates the wallimages. ' 'Now use CHDIR to set the current directory istead of using dir$ + "" 'this is a little more effective as only one line needs to be remarked 'out for the compile and no longer need to use dir$ 'I'm looking to port the code over to C++ so I can use some of the same 'features used in explorED. I plan on converting this program to a 'DirectX API. Double Buffering is something I want to do for the display. 'That would reduce flashing significantly. I don't know how to access video 'memory directly in a QB environment, so I plan on converting to C++ 'Created a new function called tbase% it takes x and y values as perameters 'and returns the value of tbase this replaced using t = ....... in the 'different functions. With this new function it should be easier to 'make any map size acceptable. 'Updated program so now the actuall first element of the tile arrays is 'storred in 0 instead of 1.<file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/ls_ogg.c /* ls_ogg.c - ogg file support for the Legacy Sound System Copyright (c) 2006, <NAME>. */ #include "common.h" #include "ls_ogg.h" size_t ogg_read(void* ptr, size_t size, size_t nmemb, void* datasource); int ogg_seek(void* datasource, ogg_int64_t offset, int whence); int ogg_close(void* datasource); long ogg_tell(void* datasource); L_bool Ogg_GetStreamInfo(OGGFILE* lpOgg); OGGFILE* Ogg_CreateFromDisk(char* szFilename) { OGGFILE* lpNew=L_null; ov_callbacks cb; LF_FILE2 File=L_null; lpNew=malloc(sizeof(OGGFILE)); if(!lpNew) return L_null; memset(lpNew, 0, sizeof(OGGFILE)); memset(&cb, 0, sizeof(cb)); cb.read_func=ogg_read; cb.seek_func=ogg_seek; cb.close_func=ogg_close; cb.tell_func=ogg_tell; File=File_Open(szFilename, 0, LF_ACCESS_READ, LFCREATE_OPEN_EXISTING); if(!File) { free(lpNew); return L_null; } /* We don't ever call the File_Close function here, because teh callbacks functions will call it on ogg_close callback. */ if(ov_open_callbacks( File, &lpNew->m_VorbisFile, L_null, 0, cb)<0) { free(lpNew); return L_null; } if(!Ogg_GetStreamInfo(lpNew)) { ov_clear(&lpNew->m_VorbisFile); free(lpNew); return L_null; } lpNew->m_bOpen=L_true; return lpNew; } /* OGGFILE* Ogg_CreateFromData(void* lpData, L_dword dwDataSize) { return L_null; } */ L_bool Ogg_Delete(OGGFILE* lpOgg) { if(!lpOgg) return L_false; ov_clear(&lpOgg->m_VorbisFile); free(lpOgg); return L_true; } L_dword Ogg_Read(OGGFILE* lpOgg, void* lpDest, L_dword dwSizeToRead) { char* pCurBuffer=(char*)lpDest; L_dword nBytesRead=0; int iSection=0; if(!lpOgg || !lpDest) return 0; while((nBytesRead<dwSizeToRead) && !lpOgg->m_bEOF) { L_long iRet=ov_read( &lpOgg->m_VorbisFile, pCurBuffer, dwSizeToRead-nBytesRead, 0, 2, 1, &iSection); if(iRet==0 || iSection !=0) lpOgg->m_bEOF=L_true; nBytesRead+=iRet; pCurBuffer+=iRet; } return nBytesRead; } L_bool Ogg_Reset(OGGFILE* lpOgg) { if(!lpOgg) return L_false; lpOgg->m_bEOF=L_false; ov_pcm_seek(&lpOgg->m_VorbisFile, 0); return L_true; } WAVEFORMATEX* Ogg_GetFormat(OGGFILE* lpOgg, WAVEFORMATEX* lpFormat) { if(!lpOgg) return L_null; if(lpFormat) { memcpy(lpFormat, &lpOgg->m_Format, sizeof(WAVEFORMATEX)); return lpFormat; } else return &lpOgg->m_Format; } L_dword Ogg_GetSize(OGGFILE* lpOgg) { if(!lpOgg) return 0; return lpOgg->m_nNumSamples*lpOgg->m_Format.nChannels*lpOgg->m_Format.wBitsPerSample/8; } L_bool Ogg_IsEOF(OGGFILE* lpOgg) { if(!lpOgg) return L_true; return lpOgg->m_bEOF; } L_bool Ogg_GetStreamInfo(OGGFILE* lpOgg) { if(!lpOgg) return L_false; lpOgg->m_pVorbisInfo=ov_info(&lpOgg->m_VorbisFile, -1); lpOgg->m_nNumSamples=(long)ov_pcm_total(&lpOgg->m_VorbisFile, -1); lpOgg->m_Format.wFormatTag=WAVE_FORMAT_PCM; lpOgg->m_Format.nChannels=lpOgg->m_pVorbisInfo->channels; lpOgg->m_Format.nSamplesPerSec=lpOgg->m_pVorbisInfo->rate; lpOgg->m_Format.wBitsPerSample=16; lpOgg->m_Format.nBlockAlign=lpOgg->m_Format.nChannels*lpOgg->m_Format.wBitsPerSample/8; lpOgg->m_Format.nAvgBytesPerSec=lpOgg->m_Format.nSamplesPerSec*lpOgg->m_Format.nBlockAlign; lpOgg->m_Format.cbSize=0; return L_true; } /**************************************** OGG Callback Functions for reading. ****************************************/ size_t ogg_read(void* ptr, size_t size, size_t nmemb, void* datasource) { return File_Read(datasource, size*nmemb, ptr); } int ogg_seek(void* datasource, ogg_int64_t offset, int whence) { return File_Seek(datasource, (L_long)offset, whence); } int ogg_close(void* datasource) { return File_Close(datasource); } long ogg_tell(void* datasource) { return File_Seek(datasource, 0, MOVETYPE_CUR); } <file_sep>/games/Legacy-Engine/Scrapped/old/ls_load.cpp #include <dsound.h> #include "common.h" #include "lg_err.h" #include "ls_load.h" #include "ls_sndfile.h" extern "C" lg_bool LS_LoadSound( IDirectSound8* lpDS, IDirectSoundBuffer8** lppBuffer, lg_dword dwBufferFlags, char* szFilename) { CLSndFile cSndFile; IDirectSoundBuffer* lpTempBuffer=LG_NULL; DSBUFFERDESC desc; void* lpLockedBuffer=LG_NULL; lg_dword dwBufferBytes=0; lg_dword dwBytesRead=0; void* lpSnd=LG_NULL; lg_result nResult=0; if(!lpDS) return LG_FALSE; if(!cSndFile.Open(szFilename)) return LG_FALSE; //lpSnd=pCB->Snd_CreateFromDisk(szFilename); //if(!lpSnd) // return LG_FALSE; memset(&desc, 0, sizeof(desc)); desc.dwSize=sizeof(DSBUFFERDESC); desc.dwFlags=dwBufferFlags; desc.dwBufferBytes=cSndFile.GetDataSize(); WAVEFORMATEX wf; wf.cbSize=0; wf.wFormatTag=0x0001; wf.nChannels=(WORD)cSndFile.GetNumChannels(); wf.nSamplesPerSec=cSndFile.GetSamplesPerSecond(); wf.wBitsPerSample=(WORD)cSndFile.GetBitsPerSample(); wf.nBlockAlign=wf.nChannels*wf.wBitsPerSample/8; wf.nAvgBytesPerSec=wf.nSamplesPerSec*wf.nBlockAlign; desc.lpwfxFormat=&wf; nResult=lpDS->CreateSoundBuffer(&desc, &lpTempBuffer, LG_NULL); if(LG_FAILED(nResult)) { cSndFile.Close(); Err_PrintDX("IDirectSound8::CreateSoundBuffer", nResult); return LG_FALSE; } lpTempBuffer->QueryInterface( IID_IDirectSoundBuffer8, (void**)lppBuffer); IDirectSoundBuffer_Release(lpTempBuffer); nResult=IDirectSoundBuffer8_Lock( (*lppBuffer), 0, 0, &lpLockedBuffer, &dwBufferBytes, LG_NULL, LG_NULL, DSBLOCK_ENTIREBUFFER); if(LG_FAILED(nResult)) { Err_PrintDX("IDirectSoundBuffer8::Lock", nResult); cSndFile.Close(); IDirectSoundBuffer8_Release((*lppBuffer)); return LG_FALSE; } dwBytesRead=cSndFile.Read((void*)lpLockedBuffer, dwBufferBytes); if(dwBytesRead<1) { cSndFile.Close(); IDirectSoundBuffer8_Release((*lppBuffer)); return LG_FALSE; } nResult=IDirectSoundBuffer8_Unlock((*lppBuffer), lpLockedBuffer, dwBufferBytes, LG_NULL, 0); cSndFile.Close(); if(LG_FAILED(nResult)) { Err_PrintDX("IDirectSoundBuffer8::Unlock", nResult); /* Not sure what to do if we can't unlock it. */ } return LG_TRUE; } <file_sep>/Misc/Decode/Readme.txt Decode v1.03 PC conversion by B.M. Software This folder includes: Decode.bas - Qbasic source code for Decode. Readme.txt - This file. Instructions: Make sure caps lock is on lower case letters will not be encoded properly. When prompted type in your message, press enter. Then press space to code it. To decode a message type in the encoded message an proceed as above. ============================================== === Version History === === for Decode === ============================================== v1.03 PC Removed printer support because it was pointless and a waste of time. v1.02 PC Added printer support. v1.01 PC Added color to the text. v1.00 PC The first PC version converted by B.M. Software. v1.00 The original program in the Macintosh Format. Author unknown.<file_sep>/games/Legacy-Engine/Scrapped/libs/lc_sys1/lc_cvar.c #include <stdio.h> #include "lg_malloc.h" #include "lc_sys.h" #include "lc_private.h" #include "common.h" #include <windows.h> unsigned long g_nNumCVars=0; /* Private function declarations. */ float CVar_TextToFloat(char* szValue); typedef struct tagCVarList{ CVar* varlist; /* Pointer to the list. */ void* console; /* Pointer to a console. */ HLDEFS defs; /* Definitions list. */ }CVarList, *LPCVarList; /* ============================================ Public Functions. ============================================ */ HCVARLIST CVar_CreateList(void* hConsole) { CVarList* lpNewList=NULL; /* All we really need to do to generate a new cvar list, is allocate the memory and set a few default values, and attach the console if there is one. We set the actual list to NULL since there are no variables yet. */ lpNewList=LG_Malloc(sizeof(CVarList)); if(lpNewList==NULL) { if(hConsole) Con_SendMessage(hConsole, "Could not allocate memory for cvarlist!"); return NULL; } lpNewList->varlist=NULL; /* Note that if the console is NULL, the cvarlist knows not to use it. */ lpNewList->console=hConsole; /* Attempt to create a definitions list, if the call doesn't work the feature will be unusable. */ lpNewList->defs=Defs_CreateDefs(); if(lpNewList->defs==NULL) if(hConsole) Con_SendMessage(hConsole, "Could not allocate memory for Definitions, feature unusable!"); return lpNewList; } int CVar_DeleteList(HCVARLIST hList) { /* We need to delete all the values, and then delete the list. */ CVar* var=NULL; CVar* oldvar=NULL; CVarList* lpList=(CVarList*)hList; if(lpList==NULL) return 0; /* Free all allocated memory. */ var=lpList->varlist; while(var) { L_safe_free(var->name); L_safe_free(var->string); g_nNumCVars--; oldvar=var; var=var->next; L_safe_free(oldvar); } Debug_printf("Number of CVars left: %i\n", g_nNumCVars); Defs_DeleteDefs(lpList->defs); lpList->console=NULL; L_safe_free(hList); return 1; } /* CVar_Register registers a cvar into the list. */ CVar* CVar_Register(HCVARLIST hList, const char* szName, const char* szValue, unsigned long dwFlags) { CVar* newvar=NULL; CVarList* lpList=(CVarList*)hList; char szOutOfMem[]="Cannot register \"%s\", out of memory!"; if(lpList==NULL) return NULL; /* Need to check if the cvar has a valid name, if not we can't create it. */ if(!L_CheckValueName(szName, NULL, NULL)) { if(lpList->console) Con_SendErrorMsg(lpList->console, "Cannot register \"%s\", invalid name!", szName); return NULL; } /* Check to see if a CVar with the same name is already registered. */ if(CVar_GetCVar(hList, szName)) { if(lpList->console) Con_SendErrorMsg(lpList->console, "Cannot register \"%s\", cvar already exists!", szName); return NULL; } /* Allocate memory vor CVarList. */ newvar=LG_Malloc(sizeof(CVar)); if(!newvar) { if(lpList->console) Con_SendErrorMsg(lpList->console, szOutOfMem, szName); return NULL; } /* Allocate space for the cvar's name. */ newvar->name=LG_Malloc(L_strlen(szName)+1); if(newvar->name==NULL) { L_safe_free(newvar); if(lpList->console) Con_SendErrorMsg(lpList->console, szOutOfMem, szName); return NULL; } L_strncpy(newvar->name, szName, L_strlen(szName)+1); /* Allocate space for the cvar's value. */ newvar->string=NULL; newvar->value=0.0f; newvar->flags=dwFlags; newvar->next=LG_NULL; //newvar->update=((dwFlags&CVAREG_UPDATE)==CVAREG_UPDATE); //newvar->save=((dwFlags&CVAREG_SAVE)==CVAREG_SAVE); //newvar->nosetchange=L_CHECK_FLAG(dwFlags, CVAREG_SETWONTCHANGE); /* Add to the linked list. */ /* TODO: We'll add the cvars in alphabetical order so search through the list til we find one that is higher in lower in the alphabed and at the cvar there.*/ /* For now the new cvar is added on the end, this is so they get saved in the same order they were registered. */ if(lpList->varlist==LG_NULL) { newvar->next=LG_NULL; lpList->varlist=newvar; } else { CVar* pItem; for(pItem=lpList->varlist; pItem; pItem=pItem->next) { CVar* pNext=pItem->next; if(!pNext) { pItem->next=newvar; break; } /* if((stricmp(newvar->name, pItem->name)<0)) { pItem->next=newvar; newvar->next=pNext; break; } */ } } //newvar->next=lpList->varlist; //lpList->varlist=newvar; g_nNumCVars++; /* Now set the new value using the set function. */ CVar_Set(lpList, szName, szValue); if(lpList->console) Con_SendErrorMsg(lpList->console, "Registered %s = \"%s\", %.0f", newvar->name, newvar->string, newvar->value); return newvar; } /* CVar_Set sets the selected cvar. */ int CVar_Set(HCVARLIST hList, const char* szName, const char* szValue) { CVarList* list=(CVarList*)hList; CVar* cvar=NULL; int bGotDef=0; if(!list) return 0; cvar=CVar_GetCVar(hList, szName); if(!cvar) { if(list->console) Con_SendErrorMsg(list->console, "Could not set \"%s\", no such cvar!", szName); return 0; } L_safe_free(cvar->string); cvar->string=LG_Malloc(L_strlen(szValue)+1); if(cvar->string==NULL) { if(list->console) Con_SendErrorMsg(list->console, "Could not reallocate memory for \"%s\"!", szName); return 0; } L_strncpy(cvar->string, szValue, L_strlen(szValue)+1); /* We also want to check to see if the value, is a definition, if it is we, give the value that parameter. If it is not a definition, then we try to convert the value to a number, if it isn't a number, the value will be 0.0f.*/ cvar->value=Defs_Get(list->defs, szValue, &bGotDef); if(!bGotDef) cvar->value=CVar_TextToFloat(cvar->string); return 1; } int CVar_SetValue(HCVARLIST hList, const char* szName, const float fValue) { char sz[32]; _snprintf(sz, 32, "%f", fValue); return CVar_Set(hList, szName, sz); } /* CVar_Get gets the string value of a cvar. */ char* CVar_Get(HCVARLIST hList, const char* szName, char* szOutput) { CVar* cvar=NULL; if(hList==NULL) return NULL; cvar=CVar_GetCVar(hList, szName); if(cvar==NULL) return NULL; if(szOutput) L_strncpy(szOutput, cvar->string, L_strlen(cvar->string)+1); return cvar->string; } float CVar_GetValue(HCVARLIST hList, const char*szName, int* bGotValue) { CVar* cvar=NULL; if(hList==NULL) { if(bGotValue) *bGotValue=0; return 0.0f; } cvar=CVar_GetCVar(hList, szName); if(cvar==NULL) { if(bGotValue) *bGotValue=0; return 0.0f; } if(bGotValue) *bGotValue=1; return cvar->value; } /* CVar_GetCVar returns a pointer to the cvar with the slected name. */ CVar* CVar_GetCVar(HCVARLIST hList, const char* szName) { CVar* var=NULL; CVarList* lpList=(CVarList*)hList; if(!lpList) return NULL; for(var=lpList->varlist; var; var=var->next) { if(L_strnicmp(szName, var->name, 0)) return var; } return NULL; } CVar* CVar_GetFirstCVar(HCVARLIST hList) { if(!hList) return NULL; return ((CVarList*)hList)->varlist; } int CVar_AddDef(HCVARLIST hList, const char* szDef, const float fValue) { CVarList* lpList=(CVarList*)hList; if(!lpList) return 0; return Defs_Add(lpList->defs, szDef, fValue); } float CVar_GetDef(HCVARLIST hList, const char* szDef, int* bGotDef) { if(!hList) { if(bGotDef)*bGotDef=0; return 0.0f; } return Defs_Get(((CVarList*)hList)->defs, szDef, bGotDef); } /* =============================================== Private Functions. =============================================== */ /* CVar_TextToFloat converts a text value to a float value. */ float CVar_TextToFloat(char* szValue) { return (float)L_atovalue(szValue); } <file_sep>/Misc/DBXExporter/DBXExporter/oedbx/examples/ex1.h #ifndef Ex1H #define Ex1H //*************************************************************************************** void ExtractAllMessages(const char * fileName, const char * logFile); void ShowAllDomains(const char * fileName, const char * logFile); void ShowAllLocaleFolders(const char * fileName, const char * logFile); //*************************************************************************************** #endif <file_sep>/games/Explor2002/README.md E.X.P.L.O.R. 2002 ================= This is the 2002 (and all previous versions) version of the engine meant to power Beem Media's "E.X.P.L.O.R.: A New World". The project is in active development using modern technology. The old versions of the game are only kept around for novelty purposes. <file_sep>/tools/fs_sys2/fs_list_stack.h /* fs_list_stack.h - The CLfListStack is a special type of list that works as both a stack and a linked list. It is designed to be used with anything, but all classes it contains must have the base type of LSItem. This is designed to work both as a stack and as a linked list. In that way it has a broad range of uses. It is was primarily designed to hold various lists of entities. */ #ifndef __FS_LIST_STACK_H__ #define __FS_LIST_STACK_H__ #include "fs_sys2.h" #define FS_CACHE_ALIGN __declspec(align(16)) struct FS_SYS2_EXPORTS CLfListStack { public: //All items to be stored in the list stack must inherit from //CLfListStack::LSItem. If they don't they can't be stored in //the list. FS_CACHE_ALIGN struct LSItem { LSItem* m_pNext; LSItem* m_pPrev; fs_dword m_nItemID; fs_dword m_nListStackID; }; private: //We keep track of the ID of this list, this ID is generated //to be unique from any other lists. const fs_dword m_nID; public: //It is necessary to keep track of a few items in the list. //The list is designed to be transversed either way. //The members are public, so they can be accessed directly, for //transversals. LSItem* m_pFirst; LSItem* m_pLast; fs_dword m_nCount; public: CLfListStack(); ~CLfListStack(); LSItem* Pop(); LSItem* Peek(); void Push(LSItem* pNode); void Remove(LSItem* pNode); fs_bool IsEmpty()const; void Clear(); void Init(LSItem* pList, fs_dword nCount, fs_dword nItemSize); private: //We keep track of the next id to be used when another list is created, //this is incremented each time we create a new list. static fs_dword s_nNextID; }; #endif __FS_LIST_STACK_H__<file_sep>/games/Legacy-Engine/Scrapped/old/lm_node.h #if 0 #ifndef __LM_NODE_H__ #define __LM_NODE_H__ #include "lm_mesh_lg.h" #include "lg_skin_mgr.h" class CLMeshNode { friend class CLMeshNode; public: CLMeshLG* m_pMesh; //The mesh for this node CLSkelLG* m_pDefSkel; //The default skeleton for this mesh. CLSkin* m_pSkin; //The skin for this node. private: CLSkelLG* m_pSkel; //The current skel for this node lg_dword m_nAnim; //The animation to use in the current skel float m_fTime; //The time for the animation (0.0f to 100.0f). lg_long m_nAnimSpeed; //How many milliseconds it takes to cycle through the animation lg_dword m_nTime; //The saved time for animation purposes lg_dword m_nLastUpdate;//The last time the animation was updated //The following info is used for transition animations CLSkelLG* m_pPrevSkel; //The previous skeleton lg_dword m_nPrevAnim; //The previous animation within the previous skeleton float m_fPrevTime; //The previous time for the previous animation lg_dword m_nTransTime; //How many milliseconds it should take to transition to the new animation private: CLMeshNode* m_pNext; //The next node in the list. CLMeshNode* m_pChildren; //The children of this node CLMeshNode* m_pParent; //The parent of the current node (not used) lg_dword m_nParentJoint; //The reference of the joint to which the child is attached. public: CLMeshNode(); ~CLMeshNode(); //Load a node. Note that the nodes are only used for frame and animation purposes, //they don't allocate or deallocate any memory. For this reason the load //method takes a preexisting mesh, the SetAnimation method takes a preexisting skeleton. //For this reason it is necessary that skeletons and meshes are not unloaded while //a mesh node still contains a reference to them. void Load(CLMeshLG* pMesh); void SetCompatibleWith(CLSkelLG* pSkel); void AddChild(CLMeshNode* pNode, lg_cstr szJoint); void Unload(); //It is only necessary to call Render on the topmost parent node, all child nodes //will be render according to the necessary joint transform. void Render(const ML_MAT* matTrans); //UpdateTime should be called once a frame, this sets all the time parameters //necessary for setting up the animation. Update time will update all child //nodes times as well so it is only necessary to call update time for the topmost //node in a set. void UpdateTime(lg_dword nTime); //SetAnimation changes the current animation to a new one, if the same animation //is specified the animation will not change. It is only necessary to call this //method when changing to a different animation, however calling it every frame //with the same paramters will not change anything, but it will waste processor //time. void SetAnimation(CLSkelLG* pSkel, lg_dword nAnim, lg_long nSpeed, lg_dword nTransTime); const CLMeshNode* GetParent(); }; //We can only use the mesh loading functions if FS2 is being used, //as fs2 is used for opening the xml file. CLMeshNode* LM_LoadMeshNodes(lg_path szXMLScriptFile, lg_dword* nNumMeshes); void LM_DeleteMeshNodes(CLMeshNode* pNodes); #endif __LM_NODE_H__ #endif<file_sep>/games/Legacy-Engine/Scrapped/old/lg_init.h #ifdef __L3DINIT_H__ #define __L3DINIT_H__ #include "lg_sys.h" #include <lc_sys.h> #include "common.h" #ifdef __cplusplus extern "C"{ #endif /* __cplusplus */ L3DGame* LG_GameInit(char* szGameDir, HWND hwnd); L_bool LG_GameShutdown(L3DGame* lpGame); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __L3DINIT_H__ */<file_sep>/games/Legacy-Engine/Source/3rdParty/ML_lib/ML_lib.h #ifndef __ML_LIB2_H__ #define __ML_LIB2_H__ #include "ML_types.h" #ifdef __cplusplus extern "C" { #endif __cplusplus #ifdef ML_LIB_MAIN #define ML_DECLARE_FUNC(out, fn) out (ML_FUNC * fn) #else !ML_LIB_MAIN #define ML_DECLARE_FUNC(out, fn) extern out (ML_FUNC * fn) extern const ml_mat ML_matIdentity; extern const ml_vec3 ML_v3Zero; #endif ML_LIB_MAIN typedef enum _ML_INSTR{ ML_INSTR_BEST=0, ML_INSTR_F, ML_INSTR_MMX, ML_INSTR_SSE, ML_INSTR_SSE2, ML_INSTR_SSE3, ML_INSTR_AMDMMX, ML_INSTR_3DNOW, ML_INSTR_3DNOW2 }ML_INSTR; /* PRE: N/A POST: Sets the instruction support, based on nInstr If the Instruction set was not supported or if ML_ISNTR_BEST was passed the instruction will will default to the best instruction set available. Returns false if the library could not be initalized. NOTE: Must be called before any ML_* functions are used. */ ml_bool ML_FUNC ML_Init(ML_INSTR nInstr); /* PRE: N/A POST: Returns true if the specified instruction set is supported. */ ml_bool ML_FUNC ML_InstrSupport(ML_INSTR nInstr); /* PRE: N/A POST: Returns the best available instruction set for the processor. */ ML_INSTR ML_FUNC ML_GetBestSupport(); /************************ *** ml_vec3 functions *** ************************/ ML_DECLARE_FUNC(ml_vec3*, ML_Vec3Add)(ml_vec3* pOut, const ml_vec3* pV1, const ml_vec3* pV2); ML_DECLARE_FUNC(ml_vec3*, ML_Vec3Subtract)(ml_vec3* pOut, const ml_vec3* pV1, const ml_vec3* pV2); ML_DECLARE_FUNC(ml_vec3*, ML_Vec3Cross)(ml_vec3* pOut, const ml_vec3* pV1, const ml_vec3* pV2); ML_DECLARE_FUNC(ml_float, ML_Vec3Dot)(const ml_vec3* pV1, const ml_vec3* pV2); ML_DECLARE_FUNC(ml_float, ML_Vec3Length)(const ml_vec3* pV); ML_DECLARE_FUNC(ml_float, ML_Vec3LengthSq)(const ml_vec3* pV); ML_DECLARE_FUNC(ml_vec3*, ML_Vec3Normalize)(ml_vec3* pOut, const ml_vec3* pV); ML_DECLARE_FUNC(ml_vec3*, ML_Vec3Scale)(ml_vec3* pOut, const ml_vec3* pV, ml_float s); ML_DECLARE_FUNC(ml_float, ML_Vec3Distance)(const ml_vec3* pV1, const ml_vec3* pV2); ML_DECLARE_FUNC(ml_float, ML_Vec3DistanceSq)(const ml_vec3* pV1, const ml_vec3* pV2); ML_DECLARE_FUNC(ml_vec4*, ML_Vec3Transform)(ml_vec4* pOut, const ml_vec3* pV, const ml_mat* pM); ML_DECLARE_FUNC(ml_vec3*, ML_Vec3TransformCoord)(ml_vec3* pOut, const ml_vec3* pV, const ml_mat* pM); ML_DECLARE_FUNC(ml_vec3*, ML_Vec3TransformNormal)(ml_vec3* pOut, const ml_vec3* pV, const ml_mat* pM); /*********************** *** ml_mat functions *** ***********************/ ml_mat* ML_FUNC ML_MatIdentity(ml_mat* pOut); ML_DECLARE_FUNC(ml_mat*, ML_MatMultiply)(ml_mat* pOut, const ml_mat* pM1, const ml_mat* pM2); ml_mat* ML_FUNC ML_MatRotationX(ml_mat* pOut, ml_float fAngle); ml_mat* ML_FUNC ML_MatRotationY(ml_mat* pOut, ml_float fAngle); ml_mat* ML_FUNC ML_MatRotationZ(ml_mat* pOut, ml_float fAngle); ml_mat* ML_FUNC ML_MatRotationAxis(ml_mat* pOut, const ml_vec3* pAxis, ml_float fAngle); ml_mat* ML_FUNC ML_MatRotationYawPitchRoll(ml_mat* pOut, ml_float Yaw, ml_float Pitch, ml_float Roll); ml_mat* ML_FUNC ML_MatScaling(ml_mat* pOut, ml_float sx, ml_float sy, ml_float sz); ml_mat* ML_FUNC ML_MatPerspectiveFovLH(ml_mat* pOut, ml_float fovy, ml_float Aspect, ml_float zn, ml_float zf); ml_mat* ML_FUNC ML_MatLookAtLH(ml_mat* pOut, const ml_vec3* pEye, const ml_vec3* pAt, const ml_vec3* pUp); ml_mat* ML_FUNC ML_MatRotationQuat(ml_mat* pOut, const ML_QUAT* pQ); ml_mat* ML_FUNC ML_MatSlerp(ml_mat* pOut, ml_mat* pM1, ml_mat* pM2, ml_float t); ml_float ML_FUNC ML_MatDeterminant(ml_mat* pM); ML_DECLARE_FUNC(ml_mat*, ML_MatInverse)(ml_mat* pOut, ml_float* pDet, const ml_mat* pM); ml_mat* ML_FUNC ML_MatTranslation(ml_mat* pOut, ml_float x, ml_float y, ml_float z); /************************ *** ml_quat functions *** ************************/ ml_quat* ML_FUNC ML_QuatRotationMat(ml_quat* pOut, const ml_mat* pM); ml_quat* ML_FUNC ML_QuatSlerp(ml_quat* pOut, const ml_quat* pQ1, const ml_quat* pQ2, ml_float t); /************************* *** ml_plane functions *** *************************/ ml_float ML_FUNC ML_PlaneDotCoord(const ML_PLANE* pPlane, const ml_vec3* pV); ml_plane* ML_FUNC ML_PlaneScale(ml_plane* pOut, const ml_plane* pPlane, ml_float s); /************************ *** ml_aabb functions *** ************************/ typedef enum _ML_AABB_CORNER{ ML_AABB_BLF=0x00, /* Botton Left Front */ ML_AABB_BRF=0x01, /* Bottom Right Front */ ML_AABB_TLF=0x02, /* Top Left Front */ ML_AABB_TRF=0x03, /* Top Right Front */ ML_AABB_BLB=0x04, /* Bottom Left Back */ ML_AABB_BRB=0x05, /* Bottom Right Back */ ML_AABB_TLB=0x06, /* Top Left Back */ ML_AABB_TRB=0x07 /* Top Right Back */ }ML_AABB_CORNER; ml_vec3* ML_FUNC ML_AABBCorner(ml_vec3* pV, const ml_aabb* pAABB, const ML_AABB_CORNER ref); ml_aabb* ML_FUNC ML_AABBTransform(ml_aabb* pOut, const ml_aabb* pAABB, const ml_mat* pM); ml_aabb* ML_FUNC ML_AABBFromVec3s(ml_aabb* pOut, const ml_vec3* pVList, const ml_dword nNumVecs); ml_bool ML_FUNC ML_AABBIntersect(const ml_aabb* pBox1, const ml_aabb* pBox2, ml_aabb* pIntersect); ml_float ML_FUNC ML_AABBIntersectMoving(const ml_aabb* pBoxMove, const ml_aabb* pBoxStat, const ml_vec3* pVel); ml_aabb* ML_FUNC ML_AABBCatenate(ml_aabb* pOut, const ml_aabb* pBox1, const ml_aabb* pBox2); ml_aabb* ML_FUNC ML_AABBAddPoint(ml_aabb* pOut, const ml_aabb* pBox, const ml_vec3* pVec); #define ML_INTERSECT_ONPOS 0x00000000 #define ML_INTERSECT_ONNEG 0x00000001 #define ML_INTERSECT_CUR 0x00000002 #define ML_INTERSECT_HITPOS 0x00000003 #define ML_INTERSECT_HITNEG 0x00000004 ml_bool ML_FUNC ML_AABBIntersectBlock(ml_aabb* pAABB, ML_PLANE* pPlanes, ml_dword nPlaneCount); ml_dword ML_FUNC ML_AABBIntersectPlane(const ml_aabb* pAABB, const ML_PLANE* pPlane); ml_float ML_FUNC ML_AABBIntersectPlaneVel(const ml_aabb* pAABB, const ML_PLANE* pPlane, const ml_vec3* pVel); ml_dword ML_FUNC ML_AABBIntersectPlaneVelType(const ml_aabb* pAABB, const ml_plane* pPlane, const ml_vec3* pVel, ml_float* pTime); ml_plane* ML_FUNC ML_AABBToPlanes(ml_plane* pOut, ml_aabb* pAABB); ml_vec4* ML_FUNC ML_Vec3TransformArray( ml_vec4* pOut, ml_uint nOutStride, const ml_vec3* pV, ml_uint nInStride, const ml_mat* pM, ml_uint nNum); ml_vec3* ML_FUNC ML_Vec3TransformCoordArray( ml_vec3* pOut, ml_uint nOutStride, const ml_vec3* pV, ml_uint nInStride, const ml_mat* pM, ml_uint nNum); ml_vec3* ML_FUNC ML_Vec3TransformNormalArray( ml_vec3* pOut, ml_uint nOutStride, const ml_vec3* pV, ml_uint nInStride, const ml_mat* pM, ml_uint nNum); /***************************** *** Miscelanious functions *** *****************************/ ml_dword ML_FUNC ML_NextPow2(const ml_dword n); // Find the next highest power of 2. ml_dword ML_FUNC ML_Pow2(const ml_byte n); // Find (2^n). ml_float ML_FUNC ML_sqrtf(const ml_float f); ml_float ML_FUNC ML_cosf(const ml_float f); ml_float ML_FUNC ML_sinf(const ml_float f); ml_float ML_FUNC ML_tanf(const ml_float f); ml_float ML_FUNC ML_acosf(const ml_float f); ml_float ML_FUNC ML_asinf(const ml_float f); ml_float ML_FUNC ML_sincosf(const ml_float f, ml_float *cos); ml_long ML_FUNC ML_absl(ml_long l); ml_float ML_FUNC ML_absf(ml_float f); #ifdef __cplusplus } #endif __cplusplus #endif __ML_LIB2_H__<file_sep>/tools/PodSyncPrep/src/podsyncp/PodcastRSS.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package podsyncp; import com.sun.cnpi.rss.elements.Channel; import com.sun.cnpi.rss.elements.Enclosure; import com.sun.cnpi.rss.elements.Item; import com.sun.cnpi.rss.elements.PubDate; import com.sun.cnpi.rss.elements.Rss; import com.sun.cnpi.rss.parser.RssParser; import com.sun.cnpi.rss.parser.RssParserFactory; import java.net.URL; import java.util.Collection; import java.util.Iterator; /** * * @author beemfx */ public class PodcastRSS{ public PodcastRSS(String strURL) { m_strFeedURL = strURL; m_nItems = 0; m_aItems = new RSSItem[MAX_ITEMS]; for (int i = 0; i < MAX_ITEMS; i++) { m_aItems[i] = new RSSItem(); } //The first thing we should do is load the settings file, so we know //what the date of the last downloaded feed is. ReadFeed(); } @Override public String toString() { StringBuilder str = new StringBuilder(); str.append(String.format("Feed %s (%d items):\n", m_strFeedURL, m_nItems)); for (int i = 0; i < m_nItems; i++) { str.append(String.format("%s: %s (%s)\n", m_aItems[i].strTitle, m_aItems[i].strFileURL, m_aItems[i].dtPub.toString())); } return str.toString(); } private final String m_strFeedURL; //The URL of the feed. private static final int MAX_ITEMS = 10; //Maximum number of items that will be downloaded. private int m_nItems; private final RSSItem[] m_aItems; //The RSSItem class is a subclass that defines the important information //of one of the RSS items, namely it contains the filename. private class RSSItem { public String strTitle; public String strFileURL; //URL of the file. public PubDate dtPub; //Date of publication. } /* * ReadFeed reads the feed of m_strFeedURL, when the function exists * m_nItems will contain the number of items that were read (this is all * items that were read, not necessarily the ones that have meaning). * And m_aItems will contain the important information about those items, * that is the title, filename, and date. * */ private void ReadFeed() { try { RssParser parser = RssParserFactory.createDefault(); Rss rss = parser.parse(new URL(m_strFeedURL)); Channel c = rss.getChannel(); Collection items = c.getItems(); m_nItems = 0; for (Iterator it = items.iterator(); it.hasNext() && m_nItems < MAX_ITEMS;) { Item item = (Item) it.next(); try { if (IsPodcast(item)) { m_aItems[m_nItems].strTitle = item.getTitle().toString(); m_aItems[m_nItems].strFileURL = item.getEnclosure().getAttribute("url"); m_aItems[m_nItems].dtPub = item.getPubDate(); m_nItems++; } } catch (Exception e) { System.out.println("An item with invalid data was found.\n"); } } } catch (Exception e) { System.out.println("Error reading feed:" + e.toString() + "\n"); } } private static boolean IsPodcast(Item item) { //This function returns true if the item is a podcast, and false otherwise boolean bPod = false; try { String url = item.getEnclosure().getAttribute("url"); //Currently only checking if it is an MP3, should probably check //for other podcast types. if (url.matches(".*mp3$")) { bPod = true; } } catch (Exception e) { System.out.println("No enclosure.\n"); } return bPod; } } <file_sep>/games/Legacy-Engine/Source/lf_sys2/lf_bdio_ex.c /********************************************************************** *** lf_bdio_ex.c - Includes extra functions for basic input output *** **********************************************************************/ #include <zlib.h> #include "lf_bdio.h" voidpf ZLIB_Alloc(voidpf opaque, uInt items, uInt size) { return LF_Malloc(items*size); } void ZLIB_Free(voidpf opaque, voidpf address) { LF_Free(address); } lf_dword BDIO_WriteCompressed(BDIO_FILE File, lf_dword nSize, void* pInBuffer) { lf_dword nWritten=0; z_stream stream; int err; lf_byte* pCmpBuffer=LF_Malloc(nSize); if(!pCmpBuffer) return 0; stream.next_in=(Bytef*)pInBuffer; stream.avail_in=(uInt)nSize; stream.next_out=pCmpBuffer; stream.avail_out=nSize; stream.zalloc=ZLIB_Alloc; stream.zfree=ZLIB_Free; stream.opaque=(voidpf)0; err=deflateInit(&stream, Z_DEFAULT_COMPRESSION); if(err!=Z_OK) { LF_Free(pCmpBuffer); return 0; } err=deflate(&stream, Z_FINISH); if(err!=Z_STREAM_END) { deflateEnd(&stream); LF_Free(pCmpBuffer); return 0; } nWritten=stream.total_out; deflateEnd(&stream); nWritten=BDIO_Write(File, nWritten, pCmpBuffer); LF_Free(pCmpBuffer); return nWritten; } lf_dword BDIO_ReadCompressed(BDIO_FILE File, lf_dword nSize, void* pInBuffer) { //The BDIO_ReadCompressed function is somewhat complicated. Unlike the //BDIO_WriteCompressed method. Also note that this function returns the //size of the data that was decompressed, and not the actual amount of //data read from the file. z_stream in_stream; int err; lf_dword nRead; lf_dword nPos; lf_byte* pCmpBuffer=LF_Malloc(nSize); if(!pCmpBuffer) return 0; nPos=BDIO_Tell(File); nRead=BDIO_Read(File, nSize, pCmpBuffer); in_stream.zalloc=ZLIB_Alloc; in_stream.zfree=ZLIB_Free; in_stream.opaque=(voidpf)0; in_stream.next_out=pInBuffer; in_stream.avail_out=nSize; in_stream.next_in=pCmpBuffer; in_stream.avail_in=nRead; err=inflateInit(&in_stream); if(Z_OK != err) { LF_Free(pCmpBuffer); BDIO_Seek(File, nPos, BDIO_SEEK_BEGIN); return 0; } err=inflate(&in_stream, Z_FINISH); nRead=in_stream.total_out; BDIO_Seek(File, nPos+in_stream.total_in, BDIO_SEEK_BEGIN); inflateEnd(&in_stream); LF_Free(pCmpBuffer); return nRead; } lf_dword LF_SYS2_EXPORTS BDIO_CopyData(BDIO_FILE DestFile, BDIO_FILE SourceFile, lf_dword nSize) { lf_dword i=0; lf_byte byte=0; lf_dword nWritten=0; lf_byte* pData=LF_Malloc(nSize); if(!pData) return 0; nWritten=BDIO_Read(SourceFile, nSize, pData); nWritten=BDIO_Write(DestFile, nWritten, pData); LF_Free(pData); return nWritten; } <file_sep>/games/Legacy-Engine/Source/lc_sys2/lc_sys2.h #ifndef __LC_SYS2_H__ #define __LC_SYS2_H__ /******************************** Disable some of VCs warnings *********************************/ #pragma warning(disable: 4267) #pragma warning(disable: 4996) #include "lg_types.h" #include "lc_def.h" #define LC_CVAR_MAX_LEN 127 #define LC_CVAR_HASH_SIZE 128 typedef struct _lg_cvar{ lg_char szName[LC_CVAR_MAX_LEN+1]; lg_char szValue[LC_CVAR_MAX_LEN+1]; lg_float fValue; //FP value atof lg_long nValue; //Int value atoi (signed and unsigned). lg_dword Flags; struct _lg_cvar* pHashNext; }lg_cvar; //cvar flags... #define CVAR_EMPTY 0x00000001 //This is a blank cvar, whose hash value hasn't come up. #define CVAR_ROM 0x00000002 //Cvar can't be changed. #define CVAR_SAVE 0x00000004 //Cvar should be saved upon exit. #define CVAR_UPDATE 0x00000008 //The game should change something immediated after this cvar is updated. #define LC_EXP __declspec(dllexport) #define LC_FUNC __cdecl typedef lg_dword LC_CMD; typedef lg_bool (LC_FUNC*LC_CMD_FUNC)(LC_CMD nCmd, lg_void* args, lg_void* pExtra); #ifdef __cplusplus extern "C"{ #endif __cplusplus LC_EXP lg_bool LC_FUNC LC_Init(); LC_EXP void LC_FUNC LC_Shutdown(); LC_EXP void LC_FUNC LC_Clear(); LC_EXP void LC_FUNC LC_SetCommandFunc(LC_CMD_FUNC pfn, lg_void* pExtra); LC_EXP void LC_FUNC LC_Print(lg_char* szText); LC_EXP void LC_FUNC LC_Printf(lg_char* szFormat, ...); LC_EXP void LC_FUNC LC_SendCommand(const lg_char* szCmd); LC_EXP void LC_FUNC LC_SendCommandf(lg_char* szFormat, ...); LC_EXP lg_bool LC_FUNC LC_RegisterCommand(lg_char* szCmd, lg_dword nID, lg_char* szHelpString); LC_EXP void LC_FUNC LC_ListCommands(); LC_EXP const lg_char* LC_FUNC LC_GetLine(lg_dword nRef, const lg_bool bStartWithNew); LC_EXP const lg_char* LC_FUNC LC_GetOldestLine(); LC_EXP const lg_char* LC_FUNC LC_GetNewestLine(); LC_EXP const lg_char* LC_FUNC LC_GetNextLine(); LC_EXP const lg_char* LC_FUNC LC_GetActiveLine(); LC_EXP void LC_FUNC LC_OnChar(lg_char c); LC_EXP lg_dword LC_FUNC LC_GetNumLines(); LC_EXP const lg_char* LC_FUNC LC_GetArg(lg_dword nParam, lg_void* args); LC_EXP lg_bool LC_FUNC LC_CheckArg(const lg_char* string, lg_void* args); //Cvar functions LC_EXP lg_cvar* LC_FUNC CV_Register(const lg_char* szName, const lg_char* szValue, lg_dword Flags); LC_EXP lg_bool LC_FUNC CV_Define_l(lg_char* szDef, lg_long nValue); LC_EXP lg_bool LC_FUNC CV_Define_f(const lg_char* szDef, lg_float fValue); LC_EXP lg_cvar* LC_FUNC CV_Get(const lg_char* szName); LC_EXP void LC_FUNC CV_Set(lg_cvar* cvar, const lg_char* szValue); LC_EXP void LC_FUNC CV_Set_l(lg_cvar* cvar, lg_long nValue); LC_EXP void LC_FUNC CV_Set_f(lg_cvar* cvar, lg_float fValue); LC_EXP lg_cvar* LC_FUNC CV_GetFirst(); LC_EXP lg_cvar* LC_FUNC CV_GetNext(); LC_EXP void LC_FUNC LC_ListCvars(const lg_char* szLimit); #ifdef __cplusplus } #endif __cplusplus #endif __LC_SYS2_H__<file_sep>/games/Explor2002/Source_Old/ExplorED DOS/dosexplored/EXPLORED.H /* Included Files */ #include <stdio.h> #include <conio.h> #include <stdlib.h> //#include "graph.h" #include <graphics.h> #include <alloc.h> /* Definitions */ #define UP 0 + 'H' #define DOWN 0 + 'P' #define LEFT 0 + 'K' #define RIGHT 0 + 'M' #define MAPWIDTH 15 #define FNAMELEN 13 /* Function Declarations */ void GetSprite(void far *buf1[4]); void PutSprite(void far *buf1[4], int x, int y); void BoardEdit(int x, int y, int stat, unsigned int propedit); void OpenMap(char openmap[13]); void NewMap(void); void dtext(char *string); void SaveMap(char openmap[13]); int GetKey(void); void GetCur(void far *buf[4]); void PutCur(void far *buf[4], int x, int y, int oldx, int oldy); void LoadDisp(void); void DispTileStats(void); void putDoor(int dswitch); void putWall(int wswitch); int quiting(int c); int takeInput(char theoutput[80]); unsigned int takeInput(void); void Initialize(); <file_sep>/games/Legacy-Engine/Source/engine/lw_server.cpp #include "lw_server.h" #include "lg_err.h" #include "lg_cvars.h" #include "lp_legacy.h" #include "lp_newton2.h" #include "lp_physx2.h" #include "lg_mmgr.h" #include "lg_func.h" #include "lw_ai.h" #include "lx_sys.h" CLWorldSrv::CLWorldSrv(): m_pEntList(LG_NULL), m_pPhys(LG_NULL), m_nFlags(0) { } CLWorldSrv::~CLWorldSrv() { //Technically we don't want to shut down the //server here, but just in case. Shutdown(); } lg_void CLWorldSrv::LoadEntTemplate(lg_cstr szTemplateScript) { Err_Printf("Loading entity template:"); Err_IncTab(); UnloadEntTemplate(); lg_dword nCount=0; lx_ent_template* pTemplate=LX_LoadEntTemplate(szTemplateScript, &nCount); if(pTemplate) { Err_Printf("%d entity types:", nCount); for(lg_dword i=0; i<nCount; i++) { Err_Printf("Type %d: \"%s\".", pTemplate[i].nID, pTemplate[i].szScript); } Err_Printf("Creating templates..."); m_nNumTemplateEnts=nCount; m_pTemplateEnt=new EntTemplate[m_nNumTemplateEnts]; LG_ASSERT(m_pTemplateEnt, "Out of memory."); for(lg_dword i=0; i<m_nNumTemplateEnts; i++) { SetupEntityFromScript(&m_pTemplateEnt[i].Ent, &m_pTemplateEnt[i].BdyInfo, pTemplate[i].szScript); } LX_DestroyEntTemplate(pTemplate); Err_Printf("Done."); } Err_DecTab(); } lg_void CLWorldSrv::UnloadEntTemplate() { LG_SafeDeleteArray(m_pTemplateEnt); m_nNumTemplateEnts=0; } lg_void CLWorldSrv::Broadcast() { //Everything in the m_AllClients should be broadcast to //all the connected clients: for(lg_dword i=0; i<m_nNumClnts; i++) { ClntData* pClnt = &m_Clients[m_nClntRefs[i]]; switch(pClnt->nType) { case CLNT_CONNECT_LOCAL: { //We don't need to do anything with the commands //that are specifically for the client, as they //will be processed by the client, we do however //need to copy in the commands that are for all //clients. for(CLWCmdItem* pCmd=(CLWCmdItem*)m_AllClients.m_CmdList.m_pFirst; pCmd; pCmd=(CLWCmdItem*)pCmd->m_pNext) { CLWCmdItem* pDestCmd=(CLWCmdItem*)m_UnusedCmds.Pop(); if(!pDestCmd) { Err_Printf("No commands available for local broadcast (%s.%d).", __FILE__, __LINE__); break; } pDestCmd->Command=pCmd->Command; pDestCmd->Size=pCmd->Size; memcpy(pDestCmd->Params, pCmd->Params, pCmd->Size); pClnt->m_CmdList.Push(pDestCmd); } break; } case CLNT_CONNECT_TCP: case CLNT_CONNECT_UDP: default: break; } } //Now clear the list for all commands. while(!m_AllClients.m_CmdList.IsEmpty()) { m_UnusedCmds.Push(m_AllClients.m_CmdList.Pop()); } } lg_void CLWorldSrv::Receive() { } lg_bool CLWorldSrv::AcceptLocalConnect(lg_dword* pPCEnt, lg_dword* pID, lg_cstr szName) { lg_bool bRes=LG_FALSE; Err_Printf("Obtained local connect request from: \"%s\" @ localhost", szName); Err_IncTab(); if(m_nNumClnts>=LSRV_MAX_CLIENTS) { Err_Printf("Cannot establish connect %d/%d clients connected.", m_nNumClnts, LSRV_MAX_CLIENTS); bRes=LG_FALSE; } else { lg_dword nSlot=0xFF; //Find the first avaialbe slot for the client: for(lg_dword i=0; nSlot==0xFF && i<LSRV_MAX_CLIENTS; i++) { lg_bool bFound=LF_FALSE; for(lg_dword j=0; j<m_nNumClnts; j++) { if(i==m_nClntRefs[j]) bFound=LG_TRUE; } if(!bFound) nSlot=i; } if(nSlot==0xFF) { Err_Printf("Cannot establish connection, no open data structure found."); bRes=LG_FALSE; } else { m_nClntRefs[m_nNumClnts++]=nSlot; Err_Printf("Connecting %s to structure %d.", szName, nSlot); m_Clients[nSlot].nClntID=nSlot; m_Clients[nSlot].nType=CLNT_CONNECT_LOCAL; LG_strncpy(m_Clients[nSlot].szName, szName, LG_MAX_STRING); ml_mat matTemp; ML_MatTranslation(&matTemp, 0.0f, 0.0f, 0.0f); m_Clients[nSlot].nClntEnt=AddEntity("/dbase/objects/jack_basic.xml", &matTemp); *pPCEnt=m_Clients[nSlot].nClntEnt; *pID=m_Clients[nSlot].nClntID; bRes=LG_TRUE; } } Err_DecTab(); return bRes; } lg_void CLWorldSrv::Init() { //If we initialize the server and it was already //running we shutdown first. if(IsRunning()) Shutdown(); Err_Printf("===Initializing Legacy World Server==="); Err_IncTab(); m_pTemplateEnt=LG_NULL; m_nNumTemplateEnts=0; m_szName=CV_Get(CVAR_srv_Name)->szValue; Err_Printf("SERVER \"%s\" @ localhost", m_szName); InitEnts(); Err_Printf("Initializing timer..."); m_Timer.Initialize(); Err_Printf("Initialzing phsycis engine..."); switch((PHYS_ENGINE)CV_Get(CVAR_srv_PhysEngine)->nValue) { default: case PHYS_ENGINE_LEGACY: Err_Printf("Using Legacy physics engine."); m_pPhys=(CLPhys*)new CLPhysLegacy(); break; case PHYS_ENGINE_NEWTON: Err_Printf("Using Newton Game Dynamics physics engine."); m_pPhys=(CLPhys*)new CLPhysNewton(); break; #if 0 case PHYS_ENGINE_PHYSX: Err_Printf("Using NVIDIA PHYSX physics engine."); m_pPhys=(CLPhys*)new CLPhysPhysX(); break; #endif } LG_ASSERT(m_pPhys, LG_TEXT("Physics engine was not created.")); m_pPhys->Init(m_nMaxEnts); //Initialize the ai: m_AIMgr.LoadAI(CV_Get(CVAR_lg_GameLib)->szValue); m_nEntKillCount=0; m_Timer.Update(); //m_bRunning=LG_TRUE; m_nFlags=LSRV_FLAG_RUNNING; m_nNumClnts=0; //Initialize the command sturctuers: m_pCmdList=new CLWCmdItem[LSRV_MAX_CMDS]; LG_ASSERT(m_pCmdList, "Out of memory."); m_UnusedCmds.Init(m_pCmdList, LSRV_MAX_CMDS, sizeof(CLWCmdItem)); //A Test: LoadEntTemplate("/dbase/scripts/basic_ent_template.xml"); Err_DecTab(); Err_Printf("======================================"); } lg_void CLWorldSrv::Shutdown() { //We only need to shutdown the server if it was running. if(IsRunning()) { Err_Printf("===Destroying Legacy World Server==="); DestroyEnts(); m_pPhys->Shutdown(); LG_SafeDelete(m_pPhys); m_nFlags=0; m_Map.Unload(); LG_SafeDeleteArray(m_pCmdList); UnloadEntTemplate(); Err_Printf("===================================="); } } lg_bool CLWorldSrv::SetupEntityFromScript(lg_srv_ent* pEnt, lp_body_info* pBdyInfo, lg_cstr szScript) { lx_object* pObj=LX_LoadObject(szScript); if(!pObj) return LG_FALSE; LG_strncpy(pEnt->m_szObjScript, szScript, LG_MAX_PATH); pEnt->m_fMass=pObj->fMass; ML_MatIdentity(&pEnt->m_matPos); pEnt->m_v3Thrust.x=0.0f; pEnt->m_v3Thrust.y=0.0f; pEnt->m_v3Thrust.z=0.0f; pEnt->m_v3Impulse.x=0.0f; pEnt->m_v3Impulse.y=0.0f; pEnt->m_v3Impulse.z=0.0f; pEnt->m_v3Torque.x=0.0f; pEnt->m_v3Torque.y=0.0f; pEnt->m_v3Torque.z=0.0f; pEnt->m_v3AngVel.x=0.0f; pEnt->m_v3AngVel.y=0.0f; pEnt->m_v3AngVel.z=0.0f; pEnt->m_v3Vel.x=0.0f; pEnt->m_v3Vel.y=0.0f; pEnt->m_v3Vel.z=0.0f; pEnt->m_v3ExtFrc.x=0.0f; pEnt->m_v3ExtFrc.x=0.0f; pEnt->m_v3ExtFrc.x=0.0f; pEnt->m_nFlags1=0; pEnt->m_nFlags2=0; pEnt->m_nMode1=0; pEnt->m_nMode2=0; pEnt->m_nNumRegions=0; pEnt->m_nRegions[0]=0; pEnt->m_nAnimFlags1=0; pEnt->m_nAnimFlags2=0; pEnt->m_nCmdsActive=0; pEnt->m_nCmdsPressed=0; pEnt->m_fAxis[0]=0.0f; pEnt->m_fAxis[1]=0.0f; pEnt->m_nFuncs=0; //Setup AI: pEnt->m_pAI=m_AIMgr.GetAI(pObj->szAiFunction); //Phsyics flags: switch(pObj->nShape) { default: case PHYS_SHAPE_BOX: pEnt->m_nPhysFlags=pEnt->EF_PHYS_BOX; break; case PHYS_SHAPE_CAPSULE: pEnt->m_nPhysFlags=pEnt->EF_PHYS_CAPSULE; break; case PHYS_SHAPE_SPHERE: pEnt->m_nPhysFlags=pEnt->EF_PHYS_SPHERE; break; case PHYS_SHAPE_CYLINDER: pEnt->m_nPhysFlags=pEnt->EF_PHYS_CYLINDER; break; } //Calculate the body size //The base bounding volume is set about the center of //the XZ plane and the y lenght starts at zero //(so by default an object at 0, 0, 0 would be standing //directly on and in the center of the XZ plane), the //offset of the shape is then added to this. pEnt->m_aabbBody.v3Min.x=-pObj->fRadius; pEnt->m_aabbBody.v3Min.y=0; pEnt->m_aabbBody.v3Min.z=-pObj->fRadius; pEnt->m_aabbBody.v3Max.x=pObj->fRadius; pEnt->m_aabbBody.v3Max.y=pObj->fHeight; pEnt->m_aabbBody.v3Max.z=pObj->fRadius; ML_Vec3Add(&pEnt->m_aabbBody.v3Min, &pEnt->m_aabbBody.v3Min, (ML_VEC3*)pObj->fShapeOffset); ML_Vec3Add(&pEnt->m_aabbBody.v3Max, &pEnt->m_aabbBody.v3Max, (ML_VEC3*)pObj->fShapeOffset); //Based off the flag gotten from the AI we'll assign //the intelligence flag. if(LG_CheckFlag(pEnt->m_pAI->PhysFlags(), AI_PHYS_INT)) { pEnt->m_nFlags1|=LEntitySrv::EF_1_INT; } else { pEnt->m_nFlags1|=LEntitySrv::EF_1_INERT; } pBdyInfo->m_fMass=pEnt->m_fMass; pBdyInfo->m_aabbBody=pEnt->m_aabbBody; pBdyInfo->m_matPos=pEnt->m_matPos; pBdyInfo->m_nAIPhysFlags=0; pBdyInfo->m_nShape=(PHYS_SHAPE)pObj->nShape; memcpy(pBdyInfo->m_fShapeOffset, pObj->fShapeOffset, sizeof(lg_float)*3); memcpy(pBdyInfo->m_fMassCenter, pObj->fMassCenter, sizeof(lg_float)*3); pBdyInfo->m_nAIPhysFlags=pEnt->m_pAI->PhysFlags(); LX_DestroyObject(pObj); return LG_TRUE; } lg_void CLWorldSrv::SetupEntFromTemplate(lg_srv_ent* pEnt, lp_body_info* pBdyInfo, const lg_dword nTemplate) { lg_srv_ent* pEntSrc = &m_pTemplateEnt[nTemplate].Ent; lp_body_info* pBdyInfoSrc=&m_pTemplateEnt[nTemplate].BdyInfo; LG_strncpy(pEnt->m_szObjScript, pEntSrc->m_szObjScript, LG_MAX_PATH); pEnt->m_fMass=pEntSrc->m_fMass; pEnt->m_matPos=pEntSrc->m_matPos; pEnt->m_v3Thrust=pEntSrc->m_v3Thrust; pEnt->m_v3Impulse=pEntSrc->m_v3Impulse; pEnt->m_v3Torque=pEntSrc->m_v3Torque; pEnt->m_v3AngVel=pEntSrc->m_v3AngVel; pEnt->m_v3Vel=pEntSrc->m_v3Vel; pEnt->m_v3ExtFrc=pEntSrc->m_v3ExtFrc; pEnt->m_nFlags1=pEntSrc->m_nFlags1; pEnt->m_nFlags2=pEntSrc->m_nFlags2; pEnt->m_nMode1=pEntSrc->m_nMode1; pEnt->m_nMode2=pEntSrc->m_nMode2; pEnt->m_nNumRegions=0; pEnt->m_nRegions[0]=0; pEnt->m_nAnimFlags1=pEntSrc->m_nAnimFlags1; pEnt->m_nAnimFlags2=pEntSrc->m_nAnimFlags1; pEnt->m_nCmdsActive=0; pEnt->m_nCmdsPressed=0; pEnt->m_fAxis[0]=0.0f; pEnt->m_fAxis[1]=0.0f; pEnt->m_nFuncs=pEntSrc->m_nFuncs; //Setup AI: pEnt->m_pAI=pEntSrc->m_pAI; pEnt->m_nPhysFlags=pEntSrc->m_nPhysFlags; pEnt->m_aabbBody=pEntSrc->m_aabbBody; pBdyInfo->m_fMass=pBdyInfoSrc->m_fMass; pBdyInfo->m_aabbBody=pBdyInfoSrc->m_aabbBody; pBdyInfo->m_matPos=pEnt->m_matPos; pBdyInfo->m_nAIPhysFlags=pBdyInfoSrc->m_nAIPhysFlags; pBdyInfo->m_nShape=pBdyInfoSrc->m_nShape; memcpy(pBdyInfo->m_fShapeOffset, pBdyInfoSrc->m_fShapeOffset, sizeof(lg_float)*3); memcpy(pBdyInfo->m_fMassCenter, pBdyInfoSrc->m_fMassCenter, sizeof(lg_float)*3); pBdyInfo->m_nAIPhysFlags=pEnt->m_pAI->PhysFlags(); } /* PRE: Server inititialzed. POST: Adds a new entity to the world server (if room for more entities is available. Information about the entity is based upon scripts. Scripts must be properly formed or a unpredictable functional entity may be created. In the future there will also be an AddClonedEntity, that will create an entity based off another entity, in that way scripts files will not need to be loaded. NOTE: This function isn't even close to complection as it doesn't really use all the script information yet, and the physics engine is not completed, which is required for full functionality. */ lg_dword CLWorldSrv::AddEntity(lf_path szObjScript, ML_MAT* matPos) { //No point in adding an ent if the server isn't running... if(!IsRunning()) return -1; LEntitySrv* pNew = (LEntitySrv*)m_EntsBlank.Pop(); if(!pNew) { return -1; } lp_body_info bdyinfo; if(SetupEntityFromScript(pNew, &bdyinfo, szObjScript)) { pNew->m_matPos=*matPos; bdyinfo.m_matPos=*matPos; pNew->m_pPhysBody=m_pPhys->AddBody(pNew, &bdyinfo); //LX_DestroyObject(pObj); //Based off the flag gotten from the AI we'll insert //the entity into either the intelligent list or the //inert list. if(LG_CheckFlag(pNew->m_pAI->PhysFlags(), AI_PHYS_INT)) { m_EntsInt.Push(pNew); } else { m_EntsInert.Push(pNew); } pNew->m_pAI->Init(pNew); return pNew->m_nUEID; } else { return -1; } } lg_dword CLWorldSrv::AddEntity(lg_dword nTemplate, ML_MAT* matPos) { if(!IsRunning() || nTemplate>=m_nNumTemplateEnts) return -1; lg_srv_ent* pNew=(lg_srv_ent*)m_EntsBlank.Pop(); if(!pNew) return -1; lp_body_info BdyInfo; SetupEntFromTemplate(pNew, &BdyInfo, nTemplate); pNew->m_matPos=*matPos; BdyInfo.m_matPos=*matPos; pNew->m_pPhysBody=m_pPhys->AddBody(pNew, &BdyInfo); //Based off the flag gotten from the AI we'll insert //the entity into either the intelligent list or the //inert list. if(LG_CheckFlag(pNew->m_pAI->PhysFlags(), AI_PHYS_INT)) { m_EntsInt.Push(pNew); } else { m_EntsInert.Push(pNew); } pNew->m_pAI->Init(pNew); return pNew->m_nUEID; } lg_void CLWorldSrv::RemoveEnt(const lg_dword nID) { LEntitySrv* pEnt=&m_pEntList[nID]; //Also need code so that client will know what entity has been //removed. if(LG_CheckFlag(pEnt->m_nFlags1, LEntitySrv::EF_1_INT)) { m_EntsInt.Remove(pEnt); } else { m_EntsInert.Remove(pEnt); } m_pPhys->RemoveBody(pEnt->m_pPhysBody); pEnt->m_nFlags1=LEntitySrv::EF_1_BLANK; m_EntsBlank.Push(pEnt); //Entity removal needs to be sent to all clients: CLWCmdItem* pCmd=(CLWCmdItem*)m_UnusedCmds.Pop(); if(!pCmd) { Err_Printf("Could not send command, command limit too small. (%s.%d)", __FILE__, __LINE__); } else { STCC_ENT_DESTROY_INFO* pInfo=(STCC_ENT_DESTROY_INFO*)pCmd->Params; pCmd->Command=STCC_ENT_DESTROY; pCmd->Size=sizeof(STCC_ENT_DESTROY_INFO); pInfo->nEntID=nID; //Push the command: m_AllClients.m_CmdList.Push(pCmd); } } lg_void CLWorldSrv::Pause() { LG_SetFlag(m_nFlags, LSRV_FLAG_PAUSED); } lg_void CLWorldSrv::Resume() { LG_UnsetFlag(m_nFlags, LSRV_FLAG_PAUSED); m_Timer.Update(); m_Timer.Update(); m_pPhys->Simulate(m_Timer.GetFElapsed()); } lg_void CLWorldSrv::TogglePause() { if(LG_CheckFlag(m_nFlags, LSRV_FLAG_PAUSED)) Resume(); else Pause(); } lg_void CLWorldSrv::ProcessEntFuncs(LEntitySrv* pEnt) { if(!pEnt->m_nFuncs) return; if(LG_CheckFlag(pEnt->m_nFuncs, AI_FUNC_DELETE)) { //When removing an entity, we add it to the kill list. m_nEntKillList[m_nEntKillCount++]=pEnt->m_nUEID; } } /* PRE: World server should be initialized. POST: The world is processed by the server, that means all AI (including client updates) is processed, physics are processed. */ lg_void CLWorldSrv::ProcessServer() { //The server doesn't get processed if it isn't running. if(!IsRunning() || LG_CheckFlag(m_nFlags, LSRV_FLAG_PAUSED)) return; //First thing to do is update the time. m_Timer.Update(); #if 0 //Process the AI. AI_DATA aidata; aidata.nTime=m_Timer.GetTime(); aidata.fTimeStepSec=m_Timer.GetFElapsed(); aidata.pPhysWorld=m_pPhys; #endif GAME_AI_GLOBALS AiGlobals={m_Timer.GetFElapsed()}; m_AIMgr.SetGlobals(&AiGlobals); //In the future we will only call the ai function for entities //that are within range of an area of interest, for now it //is called for all intelligent entities. //Also note that the aidata getting passed right now //is strictly preliminary and a more robust version will //exist as this project progresses. for(LEntitySrv* pEnt=(LEntitySrv*)m_EntsInt.m_pFirst; pEnt; pEnt=(LEntitySrv*)pEnt->m_pNext) { //Run the AI routine for all entities, not that an AI routine will //always exist, even if it is the default one (in which nothing occurs). //We only call the PrePhys method here, the PostPhys method is called from //the physics engine, and it is only called on entities that are being //processed by the physics engine, so PostPhys is not necessarily always //called. LG_UnsetFlag(pEnt->m_nAnimFlags1, LWAI_ANIM_CHANGE); LG_UnsetFlag(pEnt->m_nAnimFlags2, LWAI_ANIM_CHANGE); pEnt->m_nFuncs=0; pEnt->m_pAI->PrePhys(pEnt); ProcessEntFuncs(pEnt); #if 0 if(pEnt->m_nFuncs) { if(LG_CheckFlag(pEnt->m_nFuncs, AI_FUNC_DELETE)) { //The procedure for removing an entity isn't too complex, //but it isn't as simple as calling RemoveEnt on the entities //id, because we are currently looping through all intelligent //entities, so we have to save where we were in the list, //so we don't end up skipping any entities, or ending up //with a null reference. lg_dword nID=pEnt->m_nUEID; pEnt=(LEntitySrv*)pEnt->m_pPrev; RemoveEnt(nID); //If the reference we saved was null, that means that the //entity we removed was at the beginning of the list, and //we need to reset the current ent to the beginning of the //list. if(pEnt==LG_NULL) { pEnt=(LEntitySrv*)m_EntsInt.m_pFirst; } } } #endif } //Process the physics engine. //Note that the physics engine stores information //about the server bodies, so we never have to //explicitley update the physics bodies from the //server. For this reason an entities ai needs to update //it's m_v3Thrust, and m_v3Torque members to represent //the amount of force applied. This need to be set every //frame as the physics engine resets them to zero after //Simulate is called. Note that bodies that have "fallen //asleep" will not be affect by changes to these values, //bodies can be awakened when a moving bodie bumps into //them. m_pPhys->Simulate(33.0f);//m_Timer.GetFElapsed()); //Process the kill list, removing all entities in it. while(m_nEntKillCount) { RemoveEnt(m_nEntKillList[--m_nEntKillCount]); } Broadcast(); } /* PRE: Server Running, valid level script specified. POST: The level is set up, not for loading savegames, or transitioning between hubs. */ lg_void CLWorldSrv::LoadLevel(lg_str szLevelScriptFile) { //Can't load a level if the server isn't running. if(!IsRunning()) return; lx_level* pLevel=LX_LoadLevel(szLevelScriptFile); if(!pLevel) return; #if 1 Err_Printf("SERVER->LoadLevel:"); Err_Printf(" Map: \"%s\"", pLevel->szMapFile); Err_Printf(" SkyBox: \"%s\"", pLevel->szSkyBoxFile); Err_Printf(" SkyBox Skin: \"%s\"", pLevel->szSkyBoxSkin); Err_Printf(" Music: \"%s\"", pLevel->szMusicFile); Err_Printf(" Actors: %d", pLevel->nActorCount); for(lg_dword i=0; i< pLevel->nActorCount; i++) { Err_Printf(" Script: \"%s\"", pLevel->pActors[i].szObjFile); Err_Printf(" Position: (%f, %f, %f)", pLevel->pActors[i].fPosition[0], pLevel->pActors[i].fPosition[1], pLevel->pActors[i].fPosition[2]); } Err_Printf(" Objects: %d", pLevel->nObjCount); for(lg_dword i=0; i< pLevel->nObjCount; i++) { Err_Printf(" Script: \"%s\"", pLevel->pObjs[i].szObjFile); Err_Printf(" Position: (%f, %f, %f)", pLevel->pObjs[i].fPosition[0], pLevel->pObjs[i].fPosition[1], pLevel->pObjs[i].fPosition[2]); } #endif ClearEnts(); LoadMap(pLevel->szMapFile); ml_vec3 v3Grav={0.0f, -9.8f, 0.0f}; m_pPhys->SetGravity(&v3Grav); //Add entities... ML_MAT matPos; ML_MatIdentity(&matPos); for(lg_dword i=0; i<pLevel->nObjCount; i++) { memcpy(&matPos._41, pLevel->pObjs[i].fPosition, sizeof(lg_float)*3); AddEntity(pLevel->pObjs[i].szObjFile, &matPos); } for(lg_dword i=0; i<pLevel->nActorCount; i++) { memcpy(&matPos._41, pLevel->pActors[i].fPosition, sizeof(lg_float)*3); AddEntity(pLevel->pActors[i].szObjFile, &matPos); } LG_strncpy(m_szSkyboxFile, pLevel->szSkyBoxFile, LG_MAX_PATH); LG_strncpy(m_szSkyboxSkinFile, pLevel->szSkyBoxSkin, LG_MAX_PATH); LX_DestroyLevel(pLevel); //Since we loaded a new level we'll call Update on the time //just to reset the elapsed time to 0 (we've got to call it twice //for that, we'll also process the physics engine). m_Timer.Update(); m_Timer.Update(); m_pPhys->Simulate(0.0f); } /* PRE: N/A POST: The new map is loaded into the server, or no map if the map does not exist, so no matter what the previous map will no longer be loaded. */ lg_void CLWorldSrv::LoadMap(lg_str szMapFile) { //We don't load a map if the server isn't running. if(!IsRunning()) return; Err_Printf("Loading \"%s\"...", szMapFile); m_Map.Load(szMapFile); m_pPhys->SetupWorld(&m_Map); //Should post an update that the map has changed for the //clients. } /* PRE: Usually called when loading a level. POST: Clears all entities, and removes them from the physics engine. */ lg_void CLWorldSrv::ClearEnts() { //Empties out all the entities. LEntitySrv* pCurrent=LG_NULL; while(!m_EntsInt.IsEmpty()) { pCurrent=(LEntitySrv*)m_EntsInt.Pop(); m_pPhys->RemoveBody(pCurrent->m_pPhysBody); m_EntsBlank.Push(pCurrent); } while(!m_EntsInert.IsEmpty()) { pCurrent=(LEntitySrv*)m_EntsInert.Pop(); m_pPhys->RemoveBody(pCurrent->m_pPhysBody); m_EntsBlank.Push(pCurrent); } } /* PRE: N/A POST: Allocates memory for the maximum number of available enties in m_pEntList. Stores all entities in the m_pEntsBlank list. Returns false if there was not enough memory. Should only be called when the world server is created. */ lg_bool CLWorldSrv::InitEnts() { const lg_dword MAX_ENTS = ::CV_Get(CVAR_srv_MaxEntities)->nValue; m_nMaxEnts=MAX_ENTS; Err_Printf("Initializing entity list..."); //Initialzie all the LEntLists (note that this does not allocate //memory, the memory has already been allocated). DestroyEnts(); Err_Printf("Allocating memory for %u entities...", MAX_ENTS); //Allocate memory for the maximum number of available enties. m_pEntList = new LEntitySrv[MAX_ENTS]; if(!m_pEntList) return LG_FALSE; Err_Printf("%u bytes allocated (%uMB).", MAX_ENTS*sizeof(LEntitySrv), MAX_ENTS*sizeof(LEntitySrv)/1048576); //If we got the memory that we needed, then we put all the entities //in m_pEntsBlank list (which is where unused entities are stored). //We also assign the ID to each entity (which is it's spot in the //base list, this ID will be used by all clients because memory //addresses will certainly be different from client to client). Err_Printf("Assigning Unique Entity IDs (UEIDs)..."); for(lg_dword i=0; i<MAX_ENTS; i++) { //Once set m_nEntID should NEVER be changed. m_pEntList[i].m_nUEID = i; m_pEntList[i].m_nFlags1=LEntitySrv::EF_1_BLANK; m_EntsBlank.Push(&m_pEntList[i]); } m_EntsInt.Clear(); m_EntsInert.Clear(); Err_Printf("Entity list created."); return LG_TRUE; } /* PRE: Should only be called when completely finnished with world. POST: Deallocates memory that was used by entities, closes lists. Should only be called upon the destruction of the world server. */ lg_void CLWorldSrv::DestroyEnts() { //Close all the entities lists. m_EntsBlank.Clear(); m_EntsInt.Clear(); m_EntsInert.Clear(); //Deallocate the entity's memory. LG_SafeDeleteArray(m_pEntList); } lg_void CLWorldSrv::PrintEntInfo() { Err_Printf("===Legacy (%s) Entity Information===", m_szName); Err_Printf("Avaialbe entitis: %d", m_nMaxEnts); Err_Printf("Intelligent entities:"); for(LEntitySrv* pEnt=(LEntitySrv*)m_EntsInt.m_pFirst; pEnt; pEnt=(LEntitySrv*)pEnt->m_pNext) { Err_Printf("%d: \"%s\" (%f, %f, %f)", pEnt->m_nUEID, pEnt->m_szObjScript, pEnt->m_matPos._41, pEnt->m_matPos._42, pEnt->m_matPos._43); } Err_Printf("Inert entities:"); for(LEntitySrv* pEnt=(LEntitySrv*)m_EntsInert.m_pFirst; pEnt; pEnt=(LEntitySrv*)pEnt->m_pNext) { Err_Printf("%d: \"%s\" (%f, %f, %f)", pEnt->m_nUEID, pEnt->m_szObjScript, pEnt->m_matPos._41, pEnt->m_matPos._42, pEnt->m_matPos._43); } Err_Printf("========================================"); } <file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/lv_font2.c #include "lv_font2.h" #include <d3dx9.h> #include <lf_sys.h> #include "lg_err.h" #include "lv_tex.h" #define FONTRENDER_WIDTH 640.0f #define FONTRENDER_HEIGHT 480.0f #define LVFONTVERTEX_TYPE \ ( \ D3DFVF_XYZ| \ D3DFVF_TEX1 \ ) typedef struct _LVFONTVERTEX{ float x, y, z; float tu, tv; }LVFONTVERTEX, *PLVFONTVERTEX; typedef struct _LVFONT2{ IDirect3DDevice9* m_lpDevice; L_byte m_nCharWidth; L_byte m_nCharHeight; L_bool m_bD3DFont; L_bool m_bIsDrawing; char m_szFont[MAX_F_PATH]; /*D3DXFont Specific*/ ID3DXFont* m_lpD3DXFont; ID3DXSprite* m_lpD3DXSurface; L_dword m_dwD3DColor; /*Legacy Font Specific*/ IDirect3DTexture9* m_lpFontTexture; IDirect3DVertexBuffer9* m_lpFontVB; L_byte m_nCharWidthInFile; L_byte m_nCharHeightInFile; //LV2DIMAGE* m_lpChars[96]; LVFONTVERTEX m_lpVertices[96*4]; }LVFONT2, *PLVFONT2; HLVFONT2 Font_Create2( IDirect3DDevice9* lpDevice, char* szFont, L_byte nCharWidth, L_byte nCharHeight, L_bool bD3DXFont, L_byte nCharWidthInFile, L_byte nCharHeightInFile, L_dword dwD3DColor) { L_result nResult=0; LVFONT2* lpFont=L_null; /* Allocate memory for the font. */ lpFont=malloc(sizeof(LVFONT2)); if(!lpFont) { Err_Printf("Could not allocate memory for \"%s\" font.", szFont); return L_null; } /* Nullify everything in the font.*/ memset(lpFont, 0, sizeof(LVFONT2)); lpFont->m_lpDevice=lpDevice; lpDevice->lpVtbl->AddRef(lpDevice); lpFont->m_bD3DFont=bD3DXFont; lpFont->m_nCharWidth=nCharWidth; lpFont->m_nCharHeight=nCharHeight; lpFont->m_dwD3DColor=dwD3DColor; lpFont->m_nCharWidthInFile=nCharWidthInFile; lpFont->m_nCharHeightInFile=nCharHeightInFile; L_strncpy(lpFont->m_szFont, szFont, MAX_F_PATH-1); if(bD3DXFont) { D3DXFONT_DESC fdesc; nResult=D3DXCreateFont( lpDevice, nCharHeight, nCharWidth, FW_DONTCARE, 1, L_false, ANSI_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH, szFont, &lpFont->m_lpD3DXFont); if(L_failed(nResult)) { Err_Printf("Could not create \"%s\" font.", szFont); Err_PrintDX(" D3DXCreateFont", nResult); lpFont->m_lpDevice->lpVtbl->Release(lpFont->m_lpDevice); free(lpFont); return L_null; } nResult=D3DXCreateSprite(lpDevice, &lpFont->m_lpD3DXSurface); if(L_failed(nResult)) { Err_Printf("Failed to create font surface for writing, expect slower font drawing."); lpFont->m_lpD3DXSurface=L_null; } memset(&fdesc, 0, sizeof(fdesc)); lpFont->m_lpD3DXFont->lpVtbl->GetDescA(lpFont->m_lpD3DXFont, &fdesc); lpFont->m_nCharHeight=fdesc.Height; lpFont->m_nCharWidth=fdesc.Width; lpFont->m_bIsDrawing=L_false; /*And below the font will be returned.*/ } else { if(!Font_Validate2(lpFont)) { L_safe_release(lpFont->m_lpDevice); free(lpFont); return L_null; } } return lpFont; } L_bool Font_Delete2(HLVFONT2 hFont) { LVFONT2* lpFont=hFont; if(!lpFont)return L_false; if(lpFont->m_bD3DFont) { L_safe_release(lpFont->m_lpD3DXFont); L_safe_release(lpFont->m_lpD3DXSurface); } else { L_safe_release(lpFont->m_lpFontTexture); L_safe_release(lpFont->m_lpFontVB); } L_safe_release(lpFont->m_lpDevice); L_safe_free(lpFont); return L_true; } L_bool Font_GetDims(HLVFONT2 hFont, LVFONT_DIMS* pDims) { LVFONT2* lpFont=hFont; if(!lpFont)return L_false; pDims->bD3DXFont=lpFont->m_bD3DFont; pDims->dwD3DColor=lpFont->m_dwD3DColor; pDims->nCharHeight=lpFont->m_nCharHeight; pDims->nCharWidth=lpFont->m_nCharWidth; return L_true; } L_bool Font_SetResetStates(IDirect3DDevice9* lpDevice, L_bool bStart) { static L_dword dwPrevFVF=0; static L_dword dwOldCullMode=0; static L_dword dwOldAA=0; //static LPDIRECT3DVERTEXSHADER9 lpOldVS=NULL; static L_dword dwOldAlphaEnable=0, dwOldSrcBlend=0, dwOldDestBlend=0, dwOldAlphaA=0; static L_dword dwOldZEnable=0; static L_dword dwOldLighting=0; static L_dword dwOldMipFilter=0; static L_dword dwOldMinFilter=0; static L_dword dwOldMagFilter=0; static L_dword dwOldFill=0; if(bStart) { /* Save the old filter modes. */ IDirect3DDevice9_GetSamplerState(lpDevice, 0, D3DSAMP_MAGFILTER, &dwOldMagFilter); IDirect3DDevice9_GetSamplerState(lpDevice, 0, D3DSAMP_MINFILTER, &dwOldMinFilter); IDirect3DDevice9_GetSamplerState(lpDevice, 0, D3DSAMP_MIPFILTER, &dwOldMipFilter); IDirect3DDevice9_SetSamplerState(lpDevice, 0, D3DSAMP_MAGFILTER, D3DTEXF_POINT); IDirect3DDevice9_SetSamplerState(lpDevice, 0, D3DSAMP_MINFILTER, D3DTEXF_NONE); IDirect3DDevice9_SetSamplerState(lpDevice, 0, D3DSAMP_MIPFILTER, D3DTEXF_NONE); /* Save some rendering state values, they will be restored when this function is called with bStart set to FALSE. */ lpDevice->lpVtbl->GetRenderState(lpDevice, D3DRS_LIGHTING, &dwOldLighting); lpDevice->lpVtbl->SetRenderState(lpDevice, D3DRS_LIGHTING, FALSE); /* Get and set FVF. */ lpDevice->lpVtbl->GetFVF(lpDevice, &dwPrevFVF); lpDevice->lpVtbl->SetFVF(lpDevice, LVFONTVERTEX_TYPE); /* Get and set vertex shader. */ //lpDevice->lpVtbl->GetVertexShader(lpDevice, &lpOldVS); //lpDevice->lpVtbl->SetVertexShader(lpDevice, NULL); /* Get and set cull mode. */ lpDevice->lpVtbl->GetRenderState(lpDevice, D3DRS_CULLMODE, &dwOldCullMode); lpDevice->lpVtbl->SetRenderState(lpDevice, D3DRS_CULLMODE, D3DCULL_CCW); /* Set alpha blending. */ lpDevice->lpVtbl->GetRenderState(lpDevice, D3DRS_ALPHABLENDENABLE, &dwOldAlphaEnable); lpDevice->lpVtbl->SetRenderState(lpDevice, D3DRS_ALPHABLENDENABLE, TRUE); lpDevice->lpVtbl->GetRenderState(lpDevice, D3DRS_SRCBLEND, &dwOldSrcBlend); lpDevice->lpVtbl->SetRenderState(lpDevice, D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); lpDevice->lpVtbl->GetRenderState(lpDevice, D3DRS_DESTBLEND, &dwOldDestBlend); lpDevice->lpVtbl->SetRenderState(lpDevice, D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); lpDevice->lpVtbl->GetTextureStageState(lpDevice, 0, D3DTSS_ALPHAARG1, &dwOldAlphaA); lpDevice->lpVtbl->SetTextureStageState(lpDevice, 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); /* Get and set z-buffer status. */ lpDevice->lpVtbl->GetRenderState(lpDevice, D3DRS_ZENABLE, &dwOldZEnable); lpDevice->lpVtbl->SetRenderState(lpDevice, D3DRS_ZENABLE, FALSE); lpDevice->lpVtbl->GetRenderState(lpDevice, D3DRS_MULTISAMPLEANTIALIAS, &dwOldAA); lpDevice->lpVtbl->SetRenderState(lpDevice, D3DRS_MULTISAMPLEANTIALIAS, FALSE); lpDevice->lpVtbl->GetRenderState(lpDevice, D3DRS_FILLMODE, &dwOldFill); IDirect3DDevice9_SetRenderState(lpDevice, D3DRS_FILLMODE, D3DFILL_SOLID); } else { /* Restore all saved values. */ lpDevice->lpVtbl->SetFVF(lpDevice, dwPrevFVF); //lpDevice->lpVtbl->SetVertexShader(lpDevice, lpOldVS); lpDevice->lpVtbl->SetRenderState(lpDevice, D3DRS_CULLMODE, dwOldCullMode); /* Restore alpha blending state. */ lpDevice->lpVtbl->SetRenderState(lpDevice, D3DRS_ALPHABLENDENABLE, dwOldAlphaEnable); lpDevice->lpVtbl->SetRenderState(lpDevice, D3DRS_SRCBLEND, dwOldSrcBlend); lpDevice->lpVtbl->SetRenderState(lpDevice, D3DRS_DESTBLEND, dwOldDestBlend); lpDevice->lpVtbl->SetTextureStageState(lpDevice, 0, D3DTSS_ALPHAARG1, dwOldAlphaA); /* Restore Z-Buffering status. */ lpDevice->lpVtbl->SetRenderState(lpDevice, D3DRS_ZENABLE, dwOldZEnable); lpDevice->lpVtbl->SetRenderState(lpDevice, D3DRS_LIGHTING, dwOldLighting); lpDevice->lpVtbl->SetRenderState(lpDevice, D3DRS_MULTISAMPLEANTIALIAS, dwOldAA); IDirect3DDevice9_SetSamplerState(lpDevice, 0, D3DSAMP_MAGFILTER, dwOldMagFilter); IDirect3DDevice9_SetSamplerState(lpDevice, 0, D3DSAMP_MINFILTER, dwOldMinFilter); IDirect3DDevice9_SetSamplerState(lpDevice, 0, D3DSAMP_MIPFILTER, dwOldMipFilter); IDirect3DDevice9_SetRenderState(lpDevice, D3DRS_FILLMODE, dwOldFill); //lpDevice->lpVtbl->SetVertexShader(lpDevice, lpOldVS); //L_safe_release(lpOldVS); } return L_true; } L_bool Font_Begin2(HLVFONT2 hFont) { LVFONT2* lpFont=hFont; if(!lpFont)return L_false; if(lpFont->m_bIsDrawing) return L_true; if(lpFont->m_bD3DFont) { if(lpFont->m_lpD3DXSurface) lpFont->m_lpD3DXSurface->lpVtbl->Begin(lpFont->m_lpD3DXSurface, D3DXSPRITE_ALPHABLEND); } else { D3DMATRIX TempMatrix; /*Set some render states.*/ D3DXMatrixOrthoLH(&TempMatrix, FONTRENDER_WIDTH, FONTRENDER_HEIGHT, 0.0f, 1.0f); IDirect3DDevice9_SetTransform(lpFont->m_lpDevice, D3DTS_PROJECTION, &TempMatrix); IDirect3DDevice9_SetTransform(lpFont->m_lpDevice, D3DTS_VIEW, D3DXMatrixIdentity(&TempMatrix)); Font_SetResetStates(lpFont->m_lpDevice, L_true); /* Set the texture and vertex buffer. */ IDirect3DDevice9_SetTexture(lpFont->m_lpDevice, 0, (LPDIRECT3DBASETEXTURE9)lpFont->m_lpFontTexture); IDirect3DDevice9_SetStreamSource(lpFont->m_lpDevice, 0, lpFont->m_lpFontVB, 0, sizeof(LVFONTVERTEX)); } lpFont->m_bIsDrawing=L_true; return L_true; } L_bool Font_End2(HLVFONT2 hFont) { LVFONT2* lpFont=hFont; if(!lpFont)return L_false; if(!lpFont->m_bIsDrawing) return L_true; if(lpFont->m_bD3DFont) { if(lpFont->m_lpD3DXSurface) lpFont->m_lpD3DXSurface->lpVtbl->End(lpFont->m_lpD3DXSurface); } else { Font_SetResetStates(lpFont->m_lpDevice, L_false); } lpFont->m_bIsDrawing=L_false; return L_true; } L_bool Font_DrawChar(HLVFONT2 hFont, char c, L_long x, L_long y) { D3DMATRIX TempMatrix; LVFONT2* lpFont=hFont; if(!lpFont)return L_false; if(c<' ' || c>'~') c=' '; D3DXMatrixIdentity(&TempMatrix); D3DXMatrixTranslation(&TempMatrix, x-FONTRENDER_WIDTH/2.0f, FONTRENDER_HEIGHT/2.0f-y, 0.0f); IDirect3DDevice9_SetTransform(lpFont->m_lpDevice, D3DTS_WORLD, &TempMatrix); /* Set the texture. */ IDirect3DDevice9_DrawPrimitive(lpFont->m_lpDevice, D3DPT_TRIANGLEFAN, (c-' ')*4, 2); return L_true; } L_bool Font_DrawString2(HLVFONT2 hFont, char* szString, L_long x, L_long y) { LVFONT2* lpFont=hFont; if(!lpFont || !szString)return L_false; if(lpFont->m_bD3DFont) { L_result nResult=0; L_long nWidth = 1024; L_rect rcDest={x, y, x+nWidth, y+lpFont->m_nCharHeight}; if(!szString) return L_false; /* Note in parameter 2 we test to see if drawing has started, if it hasn't we pass null for the surface, so the text will be drawn anyway, but this will be slower.*/ lpFont->m_lpD3DXFont->lpVtbl->DrawText( lpFont->m_lpD3DXFont, lpFont->m_bIsDrawing?lpFont->m_lpD3DXSurface:L_null, szString, -1, (void*)&rcDest, DT_LEFT, lpFont->m_dwD3DColor); } else { L_dword dwLen=L_strlen(szString), i=0; for(i=0; i<dwLen; i++) { Font_DrawChar(lpFont, szString[i], x+(i*lpFont->m_nCharWidth), y); } } return L_true; } L_bool Font_Validate2(HLVFONT2 hFont) { LVFONT2* lpFont=hFont; if(!lpFont)return L_false; if(lpFont->m_bD3DFont) { L_result nResult=0; nResult=lpFont->m_lpD3DXFont->lpVtbl->OnResetDevice(lpFont->m_lpD3DXFont); if(L_failed(D3DXCreateSprite(lpFont->m_lpDevice, &lpFont->m_lpD3DXSurface))) { Err_Printf("Failed to create font surface for writing, expect slower font drawing."); lpFont->m_lpD3DXSurface=L_null; } return L_succeeded(nResult); } else { L_result nResult=0; D3DSURFACE_DESC desc; int i=0, j=0, c=0, a=0, nCharsPerLine=0; LVFONTVERTEX* v; /* We need a texture for the font.*/ if(!Tex_Load(lpFont->m_lpDevice, lpFont->m_szFont, D3DPOOL_DEFAULT, 0xFFFFFFFF, L_true, &lpFont->m_lpFontTexture)) { Err_Printf("Font_Create2 Error: Could not create texture from \"%s\".", lpFont->m_szFont); //L_safe_release(lpFont->m_lpDevice); //L_safe_free(lpFont); return L_false; } /* Create the vertex buffer. */ nResult=IDirect3DDevice9_CreateVertexBuffer( lpFont->m_lpDevice, sizeof(LVFONTVERTEX)*96*4, D3DUSAGE_WRITEONLY, LVFONTVERTEX_TYPE, D3DPOOL_DEFAULT, &lpFont->m_lpFontVB, L_null); if(L_failed(nResult)) { Err_Printf("Font_Create2 Error: Could not create vertex buffer."); Err_PrintDX(" IDirect3DDevice9::CreateVertexBuffer", nResult); L_safe_release(lpFont->m_lpFontTexture); return L_false; } lpFont->m_lpFontTexture->lpVtbl->GetLevelDesc(lpFont->m_lpFontTexture, 0, &desc); /* Now find each individual letter in the texture.*/ nCharsPerLine=desc.Width/lpFont->m_nCharWidthInFile; if((desc.Width%lpFont->m_nCharWidthInFile)>0) nCharsPerLine++;//+((desc.Width%lpFont->m_nCharWidthInFile)>0)?1:0; IDirect3DVertexBuffer9_Lock(lpFont->m_lpFontVB, 0, sizeof(LVFONTVERTEX)*96*4, &v, 0); i=0;j=0; for(c=0, a=0; c<96; c++, a+=4) { if(j>nCharsPerLine){j=0; i++;} v[a].x=0.0f; v[a].y=0.0f; v[a+1].x=(float)lpFont->m_nCharWidth; v[a+1].y=0.0f; v[a+2].x=(float)lpFont->m_nCharWidth; v[a+2].y=-(float)lpFont->m_nCharHeight; v[a+3].x=0.0f; v[a+3].y=-(float)lpFont->m_nCharHeight; v[a].z=v[a+1].z=v[a+2].z=v[a+3].z=0.0f; /* v[a].Diffuse= v[a+1].Diffuse= v[a+2].Diffuse= v[a+3].Diffuse=0xFFFFFFFF; */ } for(i=0, a=0; a<(96*4); i++) { for(j=0; j<nCharsPerLine && a<(96*4); j++, a+=4) { v[a].x=0.0f; v[a].y=0.0f; v[a+1].x=(float)lpFont->m_nCharWidth; v[a+1].y=0.0f; v[a+2].x=(float)lpFont->m_nCharWidth; v[a+2].y=-(float)lpFont->m_nCharHeight; v[a+3].x=0.0f; v[a+3].y=-(float)lpFont->m_nCharHeight; v[a].z=v[a+1].z=v[a+2].z=v[a+3].z=0.0f; /* v[a].Diffuse= v[a+1].Diffuse= v[a+2].Diffuse= v[a+3].Diffuse=0xFFFFFFFF; */ v[a].tu= v[a+3].tu=(float)j*(float)lpFont->m_nCharWidthInFile/(float)desc.Width; v[a+1].tu= v[a+2].tu=(float)(j+1)*(float)lpFont->m_nCharWidthInFile/(float)desc.Width; v[a+2].tv= v[a+3].tv=(float)(i+1)*(float)lpFont->m_nCharHeightInFile/(float)desc.Height; v[a].tv= v[a+1].tv=(float)i*(float)lpFont->m_nCharHeightInFile/(float)desc.Height; } } IDirect3DVertexBuffer9_Unlock(lpFont->m_lpFontVB); } return L_true; } L_bool Font_Invalidate2(HLVFONT2 hFont) { LVFONT2* lpFont=hFont; if(!lpFont)return L_false; if(lpFont->m_bD3DFont) { L_result nResult=0; nResult=lpFont->m_lpD3DXFont->lpVtbl->OnLostDevice(lpFont->m_lpD3DXFont); L_safe_release(lpFont->m_lpD3DXSurface); return L_succeeded(nResult); } else { int i=0; L_safe_release(lpFont->m_lpFontVB); L_safe_release(lpFont->m_lpFontTexture); } return L_true; }<file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/lv_img2d.c #include "common.h" #include <d3dx9.h> #include "lv_tex.h" #include "lv_img2d.h" #include <lf_sys.h> L_dword g_ViewWidth=0, g_ViewHeight=0; L_bool g_bDrawingStarted=L_false; /* The L2DI_StartStopDrawing function is used to start or stop drawing, the idea behind it is that it saves a few values, sets up the transformation matrices for use with 2d drawing, and when you stop drawing, it restores some of the saved values. */ L_bool L2DI_StartStopDrawing(IDirect3DDevice9* lpDevice, L_dword Width, L_dword Height, L_bool bStart) { static L_dword dwPrevFVF=0; static L_dword dwOldCullMode=0; static L_dword dwOldAA=0; //static LPDIRECT3DVERTEXSHADER9 lpOldVS=NULL; static L_dword dwOldAlphaEnable=0, dwOldSrcBlend=0, dwOldDestBlend=0, dwOldAlphaA=0; static L_dword dwOldZEnable=0; static L_dword dwOldLighting=0; static L_dword dwOldMipFilter=0; static L_dword dwOldMinFilter=0; static L_dword dwOldMagFilter=0; static L_dword dwOldFill=0; if(bStart) { /* Initialize all the projection matrices for 2d drawing. */ D3DMATRIX TempMatrix; g_ViewWidth=Width; g_ViewHeight=Height; D3DXMatrixOrthoLH(&TempMatrix, (float)Width, (float)Height, 0.0f, 1.0f); lpDevice->lpVtbl->SetTransform(lpDevice, D3DTS_PROJECTION, &TempMatrix); lpDevice->lpVtbl->SetTransform(lpDevice, D3DTS_VIEW, D3DXMatrixIdentity(&TempMatrix)); /* Save the old filter modes. */ IDirect3DDevice9_GetSamplerState(lpDevice, 0, D3DSAMP_MAGFILTER, &dwOldMagFilter); IDirect3DDevice9_GetSamplerState(lpDevice, 0, D3DSAMP_MINFILTER, &dwOldMinFilter); IDirect3DDevice9_GetSamplerState(lpDevice, 0, D3DSAMP_MIPFILTER, &dwOldMipFilter); IDirect3DDevice9_SetSamplerState(lpDevice, 0, D3DSAMP_MAGFILTER, D3DTEXF_POINT); IDirect3DDevice9_SetSamplerState(lpDevice, 0, D3DSAMP_MINFILTER, D3DTEXF_NONE); IDirect3DDevice9_SetSamplerState(lpDevice, 0, D3DSAMP_MIPFILTER, D3DTEXF_NONE); /* Save some rendering state values, they will be restored when this function is called with bStart set to FALSE. */ lpDevice->lpVtbl->GetRenderState(lpDevice, D3DRS_LIGHTING, &dwOldLighting); lpDevice->lpVtbl->SetRenderState(lpDevice, D3DRS_LIGHTING, FALSE); /* Get and set FVF. */ lpDevice->lpVtbl->GetFVF(lpDevice, &dwPrevFVF); lpDevice->lpVtbl->SetFVF(lpDevice, LV2DIMGVERTEX_TYPE); /* Get and set vertex shader. */ //lpDevice->lpVtbl->GetVertexShader(lpDevice, &lpOldVS); //lpDevice->lpVtbl->SetVertexShader(lpDevice, NULL); /* Get and set cull mode. */ lpDevice->lpVtbl->GetRenderState(lpDevice, D3DRS_CULLMODE, &dwOldCullMode); lpDevice->lpVtbl->SetRenderState(lpDevice, D3DRS_CULLMODE, D3DCULL_CCW); /* Set alpha blending. */ lpDevice->lpVtbl->GetRenderState(lpDevice, D3DRS_ALPHABLENDENABLE, &dwOldAlphaEnable); lpDevice->lpVtbl->SetRenderState(lpDevice, D3DRS_ALPHABLENDENABLE, TRUE); lpDevice->lpVtbl->GetRenderState(lpDevice, D3DRS_SRCBLEND, &dwOldSrcBlend); lpDevice->lpVtbl->SetRenderState(lpDevice, D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); lpDevice->lpVtbl->GetRenderState(lpDevice, D3DRS_DESTBLEND, &dwOldDestBlend); lpDevice->lpVtbl->SetRenderState(lpDevice, D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); lpDevice->lpVtbl->GetTextureStageState(lpDevice, 0, D3DTSS_ALPHAARG1, &dwOldAlphaA); lpDevice->lpVtbl->SetTextureStageState(lpDevice, 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); /* Get and set z-buffer status. */ lpDevice->lpVtbl->GetRenderState(lpDevice, D3DRS_ZENABLE, &dwOldZEnable); lpDevice->lpVtbl->SetRenderState(lpDevice, D3DRS_ZENABLE, FALSE); lpDevice->lpVtbl->GetRenderState(lpDevice, D3DRS_MULTISAMPLEANTIALIAS, &dwOldAA); lpDevice->lpVtbl->SetRenderState(lpDevice, D3DRS_MULTISAMPLEANTIALIAS, L_false); lpDevice->lpVtbl->GetRenderState(lpDevice, D3DRS_FILLMODE, &dwOldFill); IDirect3DDevice9_SetRenderState(lpDevice, D3DRS_FILLMODE, D3DFILL_SOLID); g_bDrawingStarted=L_true; } else { /* Restore all saved values. */ lpDevice->lpVtbl->SetFVF(lpDevice, dwPrevFVF); //lpDevice->lpVtbl->SetVertexShader(lpDevice, lpOldVS); lpDevice->lpVtbl->SetRenderState(lpDevice, D3DRS_CULLMODE, dwOldCullMode); /* Restore alpha blending state. */ lpDevice->lpVtbl->SetRenderState(lpDevice, D3DRS_ALPHABLENDENABLE, dwOldAlphaEnable); lpDevice->lpVtbl->SetRenderState(lpDevice, D3DRS_SRCBLEND, dwOldSrcBlend); lpDevice->lpVtbl->SetRenderState(lpDevice, D3DRS_DESTBLEND, dwOldDestBlend); lpDevice->lpVtbl->SetTextureStageState(lpDevice, 0, D3DTSS_ALPHAARG1, dwOldAlphaA); /* Restore Z-Buffering status. */ lpDevice->lpVtbl->SetRenderState(lpDevice, D3DRS_ZENABLE, dwOldZEnable); lpDevice->lpVtbl->SetRenderState(lpDevice, D3DRS_LIGHTING, dwOldLighting); lpDevice->lpVtbl->SetRenderState(lpDevice, D3DRS_MULTISAMPLEANTIALIAS, dwOldAA); IDirect3DDevice9_SetRenderState(lpDevice, D3DRS_FILLMODE, dwOldFill); IDirect3DDevice9_SetSamplerState(lpDevice, 0, D3DSAMP_MAGFILTER, dwOldMagFilter); IDirect3DDevice9_SetSamplerState(lpDevice, 0, D3DSAMP_MINFILTER, dwOldMinFilter); IDirect3DDevice9_SetSamplerState(lpDevice, 0, D3DSAMP_MIPFILTER, dwOldMipFilter); g_bDrawingStarted=L_false; } return L_true; } __inline void L2DI_SetVertices( LV2DIMAGE* lpImage, L_rect* rcSrc, float fTexWidth, float fTexHeight, float fWidth, float fHeight) { /* If no src rectangle was passed we use the whole thing. Otherwise we adjust the texture coordinates appropriately.*/ if(!rcSrc) { lpImage->Vertices[0].tu= lpImage->Vertices[3].tu=0.0f; lpImage->Vertices[1].tu= lpImage->Vertices[2].tu=1.0f; lpImage->Vertices[2].tv= lpImage->Vertices[3].tv=1.0f; lpImage->Vertices[0].tv= lpImage->Vertices[1].tv=0.0f; } else { float fxscale=fTexWidth; lpImage->Vertices[0].tu= lpImage->Vertices[3].tu=(float)rcSrc->left/fTexWidth; lpImage->Vertices[1].tu= lpImage->Vertices[2].tu=(float)(rcSrc->right+rcSrc->left)/fTexWidth; lpImage->Vertices[2].tv= lpImage->Vertices[3].tv=(float)(rcSrc->bottom+rcSrc->top)/fTexHeight; lpImage->Vertices[0].tv= lpImage->Vertices[1].tv=(float)(rcSrc->top)/fTexHeight; } /* Set all the z values to 0.0f. */ lpImage->Vertices[0].z= lpImage->Vertices[1].z= lpImage->Vertices[2].z= lpImage->Vertices[3].z=0.0f; /* Set all the diffuse to white. */ lpImage->Vertices[0].Diffuse= lpImage->Vertices[1].Diffuse= lpImage->Vertices[2].Diffuse= lpImage->Vertices[3].Diffuse=0xFFFFFFFFl; /* Set up the initial vertices. */ lpImage->Vertices[0].x=0.0f; lpImage->Vertices[0].y=0.0f; lpImage->Vertices[1].x=fWidth; lpImage->Vertices[1].y=0.0f; lpImage->Vertices[2].x=fWidth; lpImage->Vertices[2].y=-fHeight; lpImage->Vertices[3].x=0.0f; lpImage->Vertices[3].y=-fHeight; } /* LV2DIMAGE* L2DI_CreateFromImage( LV2DIMAGE* lpImageSrc, L_rect* rsrc, L_dword dwWidth, L_dword dwHeight, L_dword dwTransparent) { if(!lpImageSrc) return NULL; return L2DI_CreateFromTexture( lpImageSrc->lpDevice, rsrc, lpImageSrc->dwWidth, lpImageSrc->dwHeight, lpImageSrc->lpTexture, lpImageSrc); } */ LV2DIMAGE* L2DI_CreateFromFile( IDirect3DDevice9* lpDevice, char* szFilename, L_rect* rcSrc, L_dword dwWidth, L_dword dwHeight, L_dword dwTransparent) { HRESULT hr=0; LV2DIMAGE* lpImage=NULL; if(!lpDevice) return NULL; lpImage=malloc(sizeof(LV2DIMAGE)); if(lpImage==NULL) return NULL; memset(lpImage, 0, sizeof(LV2DIMAGE)); lpImage->lpTexture=NULL; lpImage->lpVB=NULL; lpImage->lpCreate=L_null; lpImage->dwWidth=dwWidth; lpImage->dwHeight=dwHeight; L_strncpy(lpImage->szFilename, szFilename, 259); lpImage->dwTransparent=dwTransparent; if(rcSrc) memcpy(&lpImage->rcSrc, rcSrc, sizeof(L_rect)); else memset(&lpImage->rcSrc, 0, sizeof(L_rect)); lpImage->lpDevice=lpDevice; lpImage->lpDevice->lpVtbl->AddRef(lpImage->lpDevice); lpImage->bIsColor=L_false; lpImage->bFromTexture=L_false; /* Create the texture and vertex buffer by validating the image.*/ if(!L2DI_Validate(lpImage, lpDevice, L_null)) { L_safe_release( (lpImage->lpDevice) ); L_safe_free(lpImage); return L_null; } return lpImage; } LV2DIMAGE* L2DI_CreateFromTexture( IDirect3DDevice9* lpDevice, L_rect* rcsrc, L_dword dwWidth, L_dword dwHeight, IDirect3DTexture9* lpTexture, L_pvoid* pExtra) { HRESULT hr=0; D3DSURFACE_DESC TexDesc; LV2DIMAGE* lpImage=NULL; if(!lpDevice) return NULL; lpImage=malloc(sizeof(LV2DIMAGE)); if(lpImage==NULL) return NULL; ZeroMemory(&TexDesc, sizeof(D3DSURFACE_DESC)); lpImage->lpTexture=NULL; lpImage->lpVB=NULL; lpImage->dwHeight=dwHeight; lpImage->dwWidth=dwWidth; if(rcsrc) lpImage->rcSrc=*rcsrc; // Set the texture. //lpTexture->lpVtbl->AddRef(lpTexture); lpImage->lpTexture=lpTexture; lpImage->lpDevice=lpDevice; lpImage->lpDevice->lpVtbl->AddRef(lpImage->lpDevice); lpImage->bIsColor=L_false; lpImage->bFromTexture=L_true; //lpImage->lpCreate=(LV2DIMAGE*)pExtra; // Create the vertex buffer by validating image. if(!L2DI_Validate(lpImage, lpDevice, lpTexture)) { L_safe_release( (lpImage->lpTexture) ); L_safe_release( (lpImage->lpDevice) ); L_safe_free(lpImage); return NULL; } return lpImage; } LV2DIMAGE* L2DI_CreateFromColor( IDirect3DDevice9* lpDevice, L_dword dwWidth, L_dword dwHeight, L_dword dwColor) { HRESULT hr=0; LV2DIMAGE* lpImage=NULL; if(!lpDevice) return NULL; lpImage=malloc(sizeof(LV2DIMAGE)); lpImage->lpTexture=NULL; lpImage->lpVB=NULL; lpImage->dwHeight=dwHeight; lpImage->dwWidth=dwWidth; lpImage->bIsColor=TRUE; L2DI_SetVertices(lpImage, L_null, 0.0f, 0.0f, (float)dwWidth, (float)dwHeight); lpImage->lpDevice=lpDevice; lpImage->lpDevice->lpVtbl->AddRef(lpImage->lpDevice); /* Set the color. */ lpImage->Vertices[0].Diffuse=dwColor; lpImage->Vertices[1].Diffuse=dwColor; lpImage->Vertices[2].Diffuse=dwColor; lpImage->Vertices[3].Diffuse=dwColor; /* Create the vertex buffer by validate image. */ if(!L2DI_Validate(lpImage, lpDevice, L_null)) { L_safe_release( (lpImage->lpTexture) ); L_safe_release( (lpImage->lpDevice) ); L_safe_free(lpImage); return L_null; } return lpImage; } BOOL L2DI_Invalidate(LV2DIMAGE* lpImage) { if(!lpImage) return FALSE; /* Release the vertex buffer. The texture is managed so we don't need to release it. */ L_safe_release( (lpImage->lpTexture) ); L_safe_release( (lpImage->lpVB) ); return TRUE; } L_bool L2DI_Validate(LV2DIMAGE* lpImage, IDirect3DDevice9* lpDevice, void* pExtra) { HRESULT hr=0; LPVOID lpVertices=L_null; LF_FILE2 fin=L_null; D3DSURFACE_DESC TexDesc; L_rect* rcSrc=L_null; if(!lpImage) return FALSE; if( (((LV2DIMAGE*)lpImage)->lpVB) ) return FALSE; if(lpImage->bFromTexture && pExtra) { lpImage->lpTexture=pExtra; IDirect3DTexture9_AddRef(lpImage->lpTexture); } /* Reload the texture. */ if(!lpImage->bIsColor) { if(!lpImage->bFromTexture) { if(!Tex_Load( lpDevice, lpImage->szFilename, D3DPOOL_DEFAULT, lpImage->dwTransparent, L_true, &lpImage->lpTexture)) return L_false; } memset(&TexDesc, 0, sizeof(TexDesc)); lpImage->lpTexture->lpVtbl->GetLevelDesc(lpImage->lpTexture, 0, &TexDesc); if(lpImage->dwHeight==-1) lpImage->dwHeight=TexDesc.Height; if(lpImage->dwWidth==-1) lpImage->dwWidth=TexDesc.Width; if(lpImage->rcSrc.bottom==0 && lpImage->rcSrc.right==0) rcSrc=L_null; else rcSrc=&lpImage->rcSrc; L2DI_SetVertices( lpImage, rcSrc, (float)TexDesc.Width, (float)TexDesc.Height, (float)lpImage->dwWidth, (float)lpImage->dwHeight); } /* Create the vertex buffer. */ hr=lpImage->lpDevice->lpVtbl->CreateVertexBuffer( lpImage->lpDevice, sizeof(LV2DIMGVERTEX)*4, 0, LV2DIMGVERTEX_TYPE, D3DPOOL_DEFAULT, &lpImage->lpVB, NULL); if(L_failed(hr)) { L_safe_release(lpImage->lpTexture); return L_false; } /* Copy over the transformed vertices. */ hr=lpImage->lpVB->lpVtbl->Lock(lpImage->lpVB, 0, sizeof(LV2DIMGVERTEX)*4, &lpVertices, 0); if(L_failed(hr)) { L_safe_release(lpImage->lpTexture); return L_false; } memcpy(lpVertices, &lpImage->Vertices, sizeof(LV2DIMGVERTEX)*4); hr=lpImage->lpVB->lpVtbl->Unlock(lpImage->lpVB); return L_true; } BOOL L2DI_Delete(LV2DIMAGE* lpImage) { if(!lpImage) return FALSE; /* Release the texture and VB. */ L_safe_release( (lpImage->lpTexture) ); L_safe_release( (lpImage->lpVB) ); L_safe_release( (lpImage->lpDevice) ); L_safe_free(lpImage); return TRUE; } BOOL L2DI_Render( LV2DIMAGE* lpImage, IDirect3DDevice9* lpDevice, float x, float y) { HRESULT hr=0; D3DMATRIX TempMatrix; if(!lpImage) return FALSE; if(!lpImage->lpVB) return FALSE; /* The start stop drawing function needs to be called prior to 2D rendering. */ if(!g_bDrawingStarted) return L_false; D3DXMatrixIdentity(&TempMatrix); D3DXMatrixTranslation(&TempMatrix, x-(float)(g_ViewWidth/2), (float)(g_ViewHeight/2)-y, 0.0f); lpDevice->lpVtbl->SetTransform(lpDevice, D3DTS_WORLD, &TempMatrix); /* Set the texture. */ lpDevice->lpVtbl->SetTexture(lpDevice, 0, (LPDIRECT3DBASETEXTURE9)lpImage->lpTexture); /* Render the image. */ lpDevice->lpVtbl->SetStreamSource(lpDevice, 0, lpImage->lpVB, 0, sizeof(LV2DIMGVERTEX)); lpDevice->lpVtbl->DrawPrimitive(lpDevice, D3DPT_TRIANGLEFAN, 0, 2); return L_true; } /* BOOL L2DI_RenderEx( LV2DIMAGE* lpImage, L_rect* rcDest, L_rect* rcSrc) { LV2DIMAGE FinalImage; float fSrcWidth=0.0f; float fSrcHeight=0.0f; if(!lpImage) return FALSE; memset(&FinalImage, 0, sizeof(LV2DIMAGE)); fSrcWidth=(float)(rcSrc->right-rcSrc->left); fSrcHeight=(float)(rcSrc->bottom-rcSrc->top); FinalImage=*lpImage; FinalImage.dwWidth=rcDest->right-rcDest->left; FinalImage.dwHeight=rcDest->bottom-rcDest->top; FinalImage.Vertices[0].x=(float)FinalImage.dwWidth; FinalImage.Vertices[0].y=(float)FinalImage.dwHeight; FinalImage.Vertices[1].y=(float)FinalImage.dwHeight; FinalImage.Vertices[3].x=(float)FinalImage.dwWidth; // Set the texture coordinates. FinalImage.Vertices[0].tu=(fSrcWidth+rcSrc->left)/lpImage->dwWidth; FinalImage.Vertices[0].tv=(fSrcHeight+rcSrc->top)/lpImage->dwHeight; FinalImage.Vertices[1].tu=(float)rcSrc->left/(float)lpImage->dwWidth; FinalImage.Vertices[1].tv=(float)(fSrcHeight+rcSrc->top)/(float)lpImage->dwHeight; FinalImage.Vertices[2].tu=(float)rcSrc->left/(float)lpImage->dwWidth; FinalImage.Vertices[2].tv=(float)rcSrc->top/(float)lpImage->dwHeight; FinalImage.Vertices[3].tu=(float)(fSrcWidth+rcSrc->left)/lpImage->dwWidth; FinalImage.Vertices[3].tv=(float)rcSrc->top/(float)lpImage->dwHeight; return L2DI_Render(&FinalImage, rcDest->left, rcDest->top); } */ /* BOOL L2DI_RenderRelativeEx( LV2DIMAGE* lpImage, float fXDest, float fYDest, float fWidthDest, float fHeightDest, LONG nXSrc, LONG nYSrc, LONG nWidthSrc, LONG nHeightSrc) { LV2DIMAGE FinalImage; LONG dwScreenWidth=0, dwScreenHeight=0; D3DVIEWPORT9 ViewPort; if(!lpImage) return FALSE; ZeroMemory(&FinalImage, sizeof(LV2DIMAGE)); ZeroMemory(&ViewPort, sizeof(D3DVIEWPORT9)); ((LV2DIMAGE*)lpImage)->lpDevice->lpVtbl->GetViewport(((LV2DIMAGE*)lpImage)->lpDevice, &ViewPort); dwScreenWidth=ViewPort.Width; dwScreenHeight=ViewPort.Height; FinalImage=*(LV2DIMAGE*)lpImage; // Scale down the dest values. fWidthDest/=100.0f; fHeightDest/=100.0f; fXDest/=100.0f; fYDest/=100.0f; FinalImage.dwWidth=(LONG)(fWidthDest*(float)dwScreenWidth); FinalImage.dwHeight=(LONG)(fHeightDest*(float)dwScreenHeight); FinalImage.Vertices[0].x=(float)FinalImage.dwWidth; FinalImage.Vertices[0].y=(float)FinalImage.dwHeight; FinalImage.Vertices[1].y=(float)FinalImage.dwHeight; FinalImage.Vertices[3].x=(float)FinalImage.dwWidth; // Discover the proper texture coords. FinalImage.Vertices[0].tu=(float)(nWidthSrc+nXSrc)/(float)lpImage->dwWidth; FinalImage.Vertices[0].tv=(float)(nHeightSrc+nYSrc)/(float)lpImage->dwHeight; FinalImage.Vertices[1].tu=(float)nXSrc/(float)lpImage->dwWidth; FinalImage.Vertices[1].tv=(float)(nHeightSrc+nYSrc)/(float)lpImage->dwHeight; FinalImage.Vertices[2].tu=(float)nXSrc/(float)lpImage->dwWidth; FinalImage.Vertices[2].tv=(float)nYSrc/(float)lpImage->dwHeight; FinalImage.Vertices[3].tu=(float)(nWidthSrc+nXSrc)/(float)lpImage->dwWidth; FinalImage.Vertices[3].tv=(float)nYSrc/(float)lpImage->dwHeight; return L2DI_Render(&FinalImage, (L_long)(fXDest*dwScreenWidth), (L_long)(fYDest*dwScreenHeight)); } */<file_sep>/Misc/DBXExporter/DBXExporter/oedbx/library/oedbx/dbxIndexedInfo.h //*************************************************************************************** #ifndef dbxIndexedInfoH #define dbxIndexedInfoH //*************************************************************************************** #include <oedbx/dbxCommon.h> //*************************************************************************************** const int1 MaxIndex = 0x20; // I only found indexes from 0x00 to 0x1c. But to be sure // that everything is ok, indexes up to 0x1f are allowed. // !!! // !!! This is not right. In the message dbx file for a Hotmail Http eMail // !!! account the index 0x23 is used. This source code is not changed yet // !!! and throws a exception if the index is >= MaxIndex. // !!! // The data types I found stored in the indexed info objects enum IndexedInfoDataType { dtNone=0, dtInt4=1, dtDateTime=2, dtString=4, dtData=8 }; //*************************************************************************************** class AS_EXPORT DbxIndexedInfo { public : DbxIndexedInfo(InStream ins, int4 address); ~DbxIndexedInfo(); int4 GetAddress() const { return Address; } int4 GetBodyLength() const { return BodyLength; } int1 GetEntries() const { return Entries; } int1 GetCounter() const { return Counter; } int4 GetIndexes() const { return Indexes; } bool IsIndexed(int1 index) const { return Indexes&(1<<index); } virtual const char * GetIndexText(int1 index) const { return 0; } virtual IndexedInfoDataType GetIndexDataType(int1 index) const { return dtNone; } int1 * GetValue(int1 index, int4 * length) const; const char * GetString(int1 index) const; int4 GetValue(int1 index) const; void ShowResults(OutStream outs) const; private : void init(); void readIndexedInfo(InStream ins); void SetIndex(int1 index, int1 * begin, int4 length=0); void SetEnd(int1 index, int1 * end); // message info data int4 Address, BodyLength; int2 ObjectLength; int1 Entries, Counter, * Buffer; int4 Indexes; // Bit field for the used indexes (MaxIndexe bits) int1 * Begin[MaxIndex]; int4 Length[MaxIndex]; }; //*********************************************** #endif dbxIndexedInfoH <file_sep>/games/Legacy-Engine/Source/engine/lx_skin.cpp #include "lx_sys.h" #include "lg_xml.h" #include "lg_err.h" #include "lg_err_ex.h" #include "lm_skin.h" #include "lg_malloc.h" #include "lg_mtr_mgr.h" #include <string.h> struct LX_SKIN_DATA { CLSkin* pSkin; lg_dword nCurrentGroup; }; void LX_SkinEnd(void* userData, const XML_Char* name); lg_bool LX_LoadSkin(const lg_path szFilename, void* pSkin) { LF_FILE3 fileScript=LF_Open(szFilename, LF_ACCESS_READ|LF_ACCESS_MEMORY, LF_OPEN_EXISTING); if(!fileScript) { Err_Printf("LX_LoadSkin ERROR: Could not open \"%s\".", szFilename); return LG_FALSE; } XML_Parser parser = XML_ParserCreate_LG(LG_NULL); if(!parser) { Err_Printf("LX_LoadSkin ERROR: Could not create XML parser. (%s)", szFilename); LF_Close(fileScript); return LG_FALSE; } LX_SKIN_DATA data; data.pSkin=(CLSkin*)pSkin; data.nCurrentGroup=0; XML_ParserReset(parser, LG_NULL); XML_SetUserData(parser, &data); XML_SetElementHandler(parser, CLSkin::LX_SkinStart, LX_SkinEnd); //Do the parsing lg_bool bSuccess=XML_Parse(parser, (const char*)LF_GetMemPointer(fileScript), LF_GetSize(fileScript), LG_TRUE); if(!bSuccess) { Err_Printf("LX_LoadSkin ERROR: Parse error at line %d: \"%s\"", XML_GetCurrentLineNumber(parser), XML_ErrorString(XML_GetErrorCode(parser))); } XML_ParserFree(parser); LF_Close(fileScript); //The output will be in pSkin return bSuccess; } void CLSkin::LX_SkinStart(void* userData, const XML_Char* name, const XML_Char** atts) { CLSkin* pSkin=((LX_SKIN_DATA*)userData)->pSkin; lg_dword* pCurGrp=&((LX_SKIN_DATA*)userData)->nCurrentGroup; if(stricmp(name, "skin")==0) { //The skin flags should only be used once. if(LG_CheckFlag(pSkin->m_nFlags, LM_FLAG_LOADED)) { Err_Printf("LX_LoadSkin ERROR: The skin tag should only be used once."); return; } LX_START_ATTR LX_ATTR_DWORD(pSkin->m_nMtrCount, material_count) LX_ATTR_DWORD(pSkin->m_nGrpCount, group_count) LX_END_ATTR //Should now allocate memory... //Err_Printf("Loading skin with %d materials and %d groups.", pSkin->m_nMtrCount, pSkin->m_nGrpCount); //Calculate the size of memory we need and allocate. lg_dword nMtrSize, nGrpSize, nRefSize; nMtrSize=pSkin->m_nMtrCount*sizeof(*pSkin->m_pMaterials); nGrpSize=pSkin->m_nGrpCount*sizeof(*pSkin->m_pGrps); nRefSize=pSkin->m_nGrpCount*sizeof(*pSkin->m_pCmpRefs); lg_dword nMemSize=nMtrSize+nGrpSize+nRefSize; pSkin->m_pMem=(lg_byte*)LG_Malloc(nMemSize); if(!pSkin->m_pMem) throw LG_ERROR(LG_ERR_OUTOFMEMORY, LG_NULL); pSkin->m_pMaterials=(lg_material*)&pSkin->m_pMem[0]; pSkin->m_pGrps=(CLSkin::MtrGrp*)&pSkin->m_pMem[nMtrSize]; pSkin->m_pCmpRefs=(lg_dword*)&pSkin->m_pMem[nMtrSize+nGrpSize]; //Set all the data to 0s for(lg_dword i=0; i<pSkin->m_nGrpCount; i++) { pSkin->m_pGrps[i].nMtr=0; pSkin->m_pGrps[i].szName[0]=0; pSkin->m_pCmpRefs[i]=0; } for(lg_dword i=0; i<pSkin->m_nMtrCount; i++) { pSkin->m_pMaterials[i]=0; } //We'll flags it as loaded now. pSkin->m_nFlags=LM_FLAG_LOADED; } else if(stricmp(name, "material")==0) { lg_dword nNum=0; lg_path szFilename; szFilename[0]=0; LX_START_ATTR LX_ATTR_DWORD(nNum, mtr_num) LX_ATTR_STRING(szFilename, file, LG_MAX_PATH) LX_END_ATTR //If the material number was specifed as zero or //greater than the mtr_count attribute we can't do //anything with it. if(!nNum || !pSkin->m_nMtrCount || nNum>pSkin->m_nMtrCount) { Err_Printf("LX_LoadSkin WARNING: A material was referenced as %d and mtr_count was set to %d.", nNum, pSkin->m_nMtrCount); } else { //We obtain the material, note that we'll get the default //material if we can't load it. pSkin->m_pMaterials[nNum-1]=CLMtrMgr::MTR_Load(szFilename, 0); } } else if(stricmp(name, "group")==0) { lg_dword nRef=0; LMName szName; LX_START_ATTR LX_ATTR_DWORD(nRef, mtr_ref) LX_ATTR_STRING(szName, name, LM_MAX_NAME-1) LX_END_ATTR if(*pCurGrp<pSkin->m_nGrpCount) { pSkin->m_pGrps[*pCurGrp].nMtr=nRef; LG_strncpy(pSkin->m_pGrps[*pCurGrp].szName, szName, LM_MAX_NAME-1); ++(*pCurGrp); } else { Err_Printf("LX_LoadSkin WARNING: More group tags used than specifed by group_count attribute."); } } else { Err_Printf("LX_LoadSkin WARNING: %s is not a recognized tag.", name); } } void LX_SkinEnd(void* userData, const XML_Char* name) { } <file_sep>/games/Legacy-Engine/Scrapped/old/lp_newton.cpp #include "lp_newton.h" #include "lg_err_ex.h" #include "lg_malloc.h" #include "lg_err.h" NewtonWorld* CElementNewton::s_pNewtonWorld=LG_NULL; NewtonBody* CElementNewton::s_pWorldBody=LG_NULL; lg_int CElementNewton::MTR_DEFAULT=0; lg_int CElementNewton::MTR_LEVEL=0; lg_int CElementNewton::MTR_CHARACTER=0; lg_int CElementNewton::MTR_OBJECT=0; void CElementNewton::Initialize() { s_pNewtonWorld=NewtonCreate(0, 0);//(NewtonAllocMemory)LG_Malloc, (NewtonFreeMemory)LG_Free); if(!s_pNewtonWorld) throw CLError(LG_ERR_DEFAULT, __FILE__, __LINE__, "Newton Initialization: Could not create physics model."); MTR_DEFAULT=NewtonMaterialGetDefaultGroupID(s_pNewtonWorld); NewtonMaterialSetDefaultSoftness(s_pNewtonWorld, MTR_DEFAULT, MTR_DEFAULT, 1.0f); NewtonMaterialSetDefaultElasticity(s_pNewtonWorld, MTR_DEFAULT, MTR_DEFAULT, 0.0f); NewtonMaterialSetDefaultCollidable(s_pNewtonWorld, MTR_DEFAULT, MTR_DEFAULT, 1); NewtonMaterialSetDefaultFriction(s_pNewtonWorld, MTR_DEFAULT, MTR_DEFAULT, 1.0f, 1.0f); //NewtonMaterialSetCollisionCallback (s_pNewtonWorld, MTR_DEFAULT, MTR_DEFAULT, &wood_wood, GenericContactBegin, GenericContactProcess, GenericContactEnd); MTR_LEVEL=NewtonMaterialCreateGroupID(s_pNewtonWorld); MTR_CHARACTER=NewtonMaterialCreateGroupID(s_pNewtonWorld); MTR_OBJECT=NewtonMaterialCreateGroupID(s_pNewtonWorld); NewtonMaterialSetDefaultSoftness(s_pNewtonWorld, MTR_CHARACTER, MTR_LEVEL, 1.0f); NewtonMaterialSetDefaultElasticity(s_pNewtonWorld, MTR_CHARACTER, MTR_LEVEL, 0.0f); NewtonMaterialSetDefaultCollidable(s_pNewtonWorld, MTR_CHARACTER, MTR_LEVEL, 1); NewtonMaterialSetDefaultFriction(s_pNewtonWorld, MTR_CHARACTER, MTR_LEVEL, 0.0f, 0.0f); NewtonMaterialSetDefaultSoftness(s_pNewtonWorld, MTR_OBJECT, MTR_LEVEL, 1.0f); NewtonMaterialSetDefaultElasticity(s_pNewtonWorld, MTR_OBJECT, MTR_LEVEL, 0.0f); NewtonMaterialSetDefaultCollidable(s_pNewtonWorld, MTR_OBJECT, MTR_LEVEL, 1); NewtonMaterialSetDefaultFriction(s_pNewtonWorld, MTR_OBJECT, MTR_LEVEL, 1.0f, 0.5f); NewtonMaterialSetDefaultSoftness(s_pNewtonWorld, MTR_OBJECT, MTR_CHARACTER, 0.5f); NewtonMaterialSetDefaultElasticity(s_pNewtonWorld, MTR_OBJECT, MTR_CHARACTER, 0.0f); NewtonMaterialSetDefaultCollidable(s_pNewtonWorld, MTR_OBJECT, MTR_CHARACTER, 1); NewtonMaterialSetDefaultFriction(s_pNewtonWorld, MTR_OBJECT, MTR_CHARACTER, 1.0f, 0.5f); NewtonMaterialSetDefaultSoftness(s_pNewtonWorld, MTR_CHARACTER, MTR_CHARACTER, 0.5f); NewtonMaterialSetDefaultElasticity(s_pNewtonWorld, MTR_CHARACTER, MTR_CHARACTER, 0.0f); NewtonMaterialSetDefaultCollidable(s_pNewtonWorld, MTR_CHARACTER, MTR_CHARACTER, 1); NewtonMaterialSetDefaultFriction(s_pNewtonWorld, MTR_CHARACTER, MTR_CHARACTER, 1.0f, 0.5f); NewtonMaterialSetDefaultSoftness(s_pNewtonWorld, MTR_OBJECT, MTR_OBJECT, 0.5f); NewtonMaterialSetDefaultElasticity(s_pNewtonWorld, MTR_OBJECT, MTR_OBJECT, 0.0f); NewtonMaterialSetDefaultCollidable(s_pNewtonWorld, MTR_OBJECT, MTR_OBJECT, 1); NewtonMaterialSetDefaultFriction(s_pNewtonWorld, MTR_OBJECT, MTR_OBJECT, 1.0f, 0.5f); } void CElementNewton::Shutdown() { SetupWorld(LG_NULL); NewtonMaterialDestroyAllGroupID(s_pNewtonWorld); NewtonDestroy(s_pNewtonWorld); } void CElementNewton::SetupWorld(CLWorldMap* pMap) { if(s_pWorldBody) { NewtonDestroyBody(s_pNewtonWorld, s_pWorldBody); s_pWorldBody=LG_NULL; } if(!pMap) return; NewtonCollision* pCol=NewtonCreateTreeCollision( s_pNewtonWorld, LG_NULL); if(!pCol) { Err_Printf(" CLWorldMap::Load ERROR: Could not create Newton collisison."); return; } NewtonTreeCollisionBeginBuild(pCol); for(lg_dword i=0; i<pMap->m_nVertexCount/3; i++) { NewtonTreeCollisionAddFace( pCol, 3, (dFloat*)&pMap->m_pVertexes[i*3], sizeof(LW_VERTEX), MTR_LEVEL); } NewtonTreeCollisionEndBuild(pCol, LG_TRUE); s_pWorldBody=NewtonCreateBody(s_pNewtonWorld, pCol); NewtonReleaseCollision(s_pNewtonWorld, pCol); NewtonBodySetMaterialGroupID(s_pWorldBody, MTR_LEVEL); NewtonSetWorldSize( s_pNewtonWorld, (dFloat*)&pMap->m_aabbMapBounds.v3Min, (dFloat*)&pMap->m_aabbMapBounds.v3Max); return; } void CElementNewton::Simulate(lg_float fSeconds) { static lg_float fCumuSecs=0.0f; fCumuSecs+=fSeconds; if(fCumuSecs<=0.003f) return; NewtonUpdate(s_pNewtonWorld, fCumuSecs); fCumuSecs=0; }<file_sep>/samples/D3DDemo/code/MD3Base/ToDo.txt The following needs to be completed in the MD3 library Functions that need to be completed: FindMD3Header() I need to do the following: Also need the ability for an MD3 to look up and down, and rotate the torso left and right. Need to be able to load only the default skin, and load the rest of the skins on demand. MD3's should be mirrored from right to left. Need to make it so animation stops for non-looping animations. Unless forceloop was specified. Ability to pause MD3 Objects.<file_sep>/games/Legacy-Engine/Scrapped/libs/lc_sys1/lc_cmd.c #include <stdio.h> #include "lg_malloc.h" #include "lc_sys.h" #include "lc_private.h" #include "common.h" #include <windows.h> #define CVAR_CHECK_EXIT {if(lpConsole->cvarlist==NULL){Con_SendMessage(hConsole, "No cvarlist loaded!");break;}} /* Con_InternalCommands attempts to process internal commands. */ /* As of right now this is the only function that uses the very max, setting, but I do want to eliminate it from this. */ int Con_InternalCommands(unsigned long nCommand, const char* szParams, HLCONSOLE hConsole) { LPLCONSOLE lpConsole=hConsole; /* unsigned long nCommand=0; */ char* szString1=NULL; char* szString2=NULL; char* szString3=NULL; int nResult=0; if(lpConsole==NULL) return 0; /* nCommand=Con_CmdNameToValue(hConsole, szCommand); */ if(nCommand==0) return 0; /* Go ahead, and allocate three strings for the use of these functions. */ szString1=LG_Malloc(lpConsole->nMaxStrLen+1); szString2=LG_Malloc(lpConsole->nMaxStrLen+1); szString3=LG_Malloc(lpConsole->nMaxStrLen+1); if(!szString1 || !szString2 || !szString3) { L_safe_free(szString1); L_safe_free(szString2); L_safe_free(szString3); Con_SendMessage(hConsole, "Could not allocate memory for temp strings."); return 1; } /* We'll set the nResult to 1, but then if nothing gets processed, the default switch with change it to a zero, which means we didn't process a message. */ nResult=1; switch(nCommand) { case CONF_ECHO: { char* szEcho=szString1; CCParse_GetParam(szEcho, szParams, 1); Con_SendMessage(hConsole, szEcho); break; } case CONF_CLEAR: { Con_Clear(hConsole); break; } case CONF_CMDLIST: { LDefs* defs=lpConsole->commands; LDef* def=NULL; char* szLimit=szString1; lg_dword dwLen=0; if(!defs) { Con_SendMessage(hConsole, "Could not obtain list of commands."); break; } CCParse_GetParam(szLimit, szParams, 1); /* If there is a parameter, it is to limit the listed commands to the ones starting with the specified string. */ dwLen=L_strlen(szLimit); Con_SendMessage(hConsole, "Registered commands:"); for(def=defs->list; def; def=def->next) { if(dwLen) if(!L_strnicmp(szLimit, def->name, dwLen)) continue; Con_SendErrorMsg(hConsole, " %s", def->name); } break; } case CONF_REGCVAR: { char* szCVarName=szString1; char* szCVarValue=szString2; char* szUpdate=szString3; unsigned long dwCreateFlags=0x00000000l; CVAR_CHECK_EXIT CCParse_GetParam(szCVarName, szParams, 1); CCParse_GetParam(szCVarValue, szParams, 2); /* Make sure that we at least have two parameters for the value and name. */ if( (L_strlen(szCVarName)<1) || (L_strlen(szCVarValue)<1) ) { Con_SendMessage(hConsole, "Usage: REGCVAR name$ value$ [UPDATE] [NOSAVE]"); break; } //CCParse_GetParam(szUpdate, szParams, 3); dwCreateFlags=CVAREG_SAVE; /* If the update value is set to true then, we update. */ if(CCParse_CheckParam(szParams, "UPDATE", 3)) dwCreateFlags=dwCreateFlags|CVAREG_UPDATE; //CCParse_GetParam(szUpdate, szParams, 4); if(CCParse_CheckParam(szParams, "NOSAVE", 3)) dwCreateFlags=dwCreateFlags^CVAREG_SAVE; CVar_Register(lpConsole->cvarlist, szCVarName, szCVarValue, dwCreateFlags); break; } case CONF_SET: { /* Changes a cvars value. */ char* cvarname=szString1; char* newvalue=szString2; CVar* cvar=NULL; CVAR_CHECK_EXIT CCParse_GetParam(cvarname, szParams, 1); CCParse_GetParam(newvalue, szParams, 2); if((L_strlen(cvarname)<1) || (L_strlen(newvalue)<1)) { Con_SendMessage(hConsole, "Usage: SET name$ newvalue$"); break; } cvar=CVar_GetCVar(lpConsole->cvarlist, cvarname); if(!cvar) { Con_SendErrorMsg( hConsole, "Could not set \"%s\", no such cvar!", cvarname); break; } if(L_CHECK_FLAG(cvar->flags, CVAREG_SETWONTCHANGE)) { Con_SendErrorMsg(hConsole, "Cannot change \"%s\" permission denied by app.", cvarname); break; } if(CVar_Set(lpConsole->cvarlist, cvarname, newvalue)) { if(cvar) { Con_SendErrorMsg( hConsole, " %s = \"%s\", %.0f", cvarname, newvalue, cvar->value); if(L_CHECK_FLAG(cvar->flags, CVAREG_UPDATE)) { sprintf(szString1, "cvarupdate \"%s\"", cvar->name); Con_SendCommand(hConsole, szString1); } } else Con_SendErrorMsg( hConsole, "Could not check to see if \"%s\" was successfully set.", cvarname); } break; } case CONF_GET: { /* Retrieves a cvar. */ char* szCVarName=szString1; char* lpValue=NULL; CVar* value=NULL; CVAR_CHECK_EXIT CCParse_GetParam(szCVarName, szParams, 1); if(L_strlen(szCVarName)<1) { Con_SendMessage(hConsole, "Usage: GET name$ [FP]"); break; } value=CVar_GetCVar(lpConsole->cvarlist, szCVarName); if(value) { if(CCParse_CheckParam(szParams, "FP", 2)) Con_SendErrorMsg(hConsole, " %s = \"%s\", %f", value->name, value->string, value->value); else Con_SendErrorMsg(hConsole, " %s = \"%s\", %.0f", value->name, value->string, value->value); } else Con_SendErrorMsg(hConsole, "Cannot get \"%s\", no such cvar!", szCVarName); break; } case CONF_DEFINE: { char* szDef=szString1; char* szValue=szString2; CVAR_CHECK_EXIT CCParse_GetParam(szDef, szParams, 1); CCParse_GetParam(szValue, szParams, 2); if( (L_strlen(szDef)<1) || (L_strlen(szValue)<1)) { Con_SendMessage(hConsole, "Usage: DEFINE name$ value%"); break; } if(CVar_AddDef(lpConsole->cvarlist, szDef, L_atof(szValue))) Con_SendErrorMsg(lpConsole, "Defined \"%s\" as %f", szDef, L_atof(szValue)); else Con_SendErrorMsg(hConsole, "Couldn't define \"%s\", possible bad name, or already defined.", szDef); break; } case CONF_CVARLIST: { CVar* cvarlist=NULL; char* szLimit=szString1; lg_dword dwLen=0; CVAR_CHECK_EXIT Con_SendMessage(hConsole, "Registered cvars:"); cvarlist=CVar_GetFirstCVar(lpConsole->cvarlist); CCParse_GetParam(szLimit, szParams, 1); /* We can limit the number of cvars displayed, by putting a parameter with the first leters we want. */ dwLen=L_strlen(szLimit); for(cvarlist=CVar_GetFirstCVar(lpConsole->cvarlist); cvarlist; cvarlist=cvarlist->next) { if(dwLen) if(!L_strnicmp(szLimit, cvarlist->name, dwLen)) continue; Con_SendErrorMsg(hConsole, " %s = \"%s\", %.0f", cvarlist->name, cvarlist->string, cvarlist->value); } break; } default: L_safe_free(szString1); L_safe_free(szString2); L_safe_free(szString3); nResult=0; } L_safe_free(szString1); L_safe_free(szString2); L_safe_free(szString3); return nResult; } <file_sep>/games/Explor2002/Source/Game/tiles.h #ifndef __TILES_H__ #define __TILES_H__ #include <ddraw.h> #include "bmp.h" class CTileObject{ protected: LPDIRECTDRAWSURFACE m_lpTileImage; int m_nWidth, m_nHeight; void CreateSurface(); RECT m_rectSource; public: CTileObject(int width, int height); ~CTileObject(); BOOL load(CBitmapReader *buffer, int x, int y, int w, int h); void Release(); BOOL Restore(); void draw(LPDIRECTDRAWSURFACE dest, int x, int y, int w, int h); }; #endif<file_sep>/games/Legacy-Engine/Scrapped/old/lv_d3dfont.c #include "common.h" #include <d3d9.h> #include <d3dx9.h> #include "lg_err.h" #include "libs\lf_sys.h" #include "lv_d3dfont.h" LVFONT* Font_Create( IDirect3DDevice9* lpDevice, char* szFontName, L_dword dwWidth, L_dword dwHeight, L_dword dwWeight) { LVFONT* lpNewFont=L_null; L_result nResult=0; D3DXFONT_DESC fdesc; lpNewFont=malloc(sizeof(LVFONT)); if(!lpNewFont) { Err_Printf("Could not allocate memory to create font."); return L_null; } memset(lpNewFont, 0, sizeof(LVFONT)); nResult=D3DXCreateFont( lpDevice, dwWidth, dwHeight, dwWeight, 1, //D3DX_DEFAULT, L_false, ANSI_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH, szFontName, &lpNewFont->m_lpFont); if(L_failed(nResult)) { Err_Printf("Could not create \"%s\" font.", szFontName); Err_PrintDX(" D3DXCreateFont", nResult); return L_null; } nResult=D3DXCreateSprite(lpDevice, &lpNewFont->m_lpSurface); if(L_failed(nResult)) { Err_Printf("Failed to create surface for font writing, writing will be slower."); lpNewFont->m_lpSurface=L_null; } memset(&fdesc, 0, sizeof(fdesc)); lpNewFont->m_lpFont->lpVtbl->GetDescA(lpNewFont->m_lpFont, &fdesc); lpNewFont->m_dwFontHeight=fdesc.Height; lpNewFont->m_dwFontWidth=fdesc.Width; lpNewFont->m_bDrawing=L_false; return lpNewFont; } L_bool Font_Delete(LVFONT* lpFont) { if(!lpFont) return L_false; L_safe_release(lpFont->m_lpSurface); L_safe_release(lpFont->m_lpFont); L_safe_free(lpFont); return L_true; } L_bool Font_Begin(LVFONT* lpFont) { if(!lpFont) return L_false; if(lpFont->m_lpSurface) lpFont->m_lpSurface->lpVtbl->Begin(lpFont->m_lpSurface, D3DXSPRITE_ALPHABLEND); lpFont->m_bDrawing=L_true; return L_true; } L_bool Font_End(LVFONT* lpFont) { if(!lpFont) return L_false; if(lpFont->m_lpSurface) lpFont->m_lpSurface->lpVtbl->End(lpFont->m_lpSurface); lpFont->m_bDrawing=L_false; return L_true; } L_bool Font_DrawString( LVFONT* lpFont, char* szString, L_long x, L_long y) { L_result nResult=0; L_long nWidth = 1024; L_rect rcDest={x, y, x+nWidth, y+(L_long)lpFont->m_dwFontHeight}; if(!szString) return L_false; /* Note in parameter 2 we test to see if drawing has started, if it hasn't we pass null for the surface, so the text will be drawn anyway, but this will be slower.*/ lpFont->m_lpFont->lpVtbl->DrawText( lpFont->m_lpFont, lpFont->m_bDrawing?lpFont->m_lpSurface:L_null, szString, -1, (RECT*)&rcDest, DT_LEFT, 0xFFFFFF00); return L_true; } L_bool Font_Validate(LVFONT* lpFont, IDirect3DDevice9* lpDevice) { L_result nResult=0; nResult=lpFont->m_lpFont->lpVtbl->OnResetDevice(lpFont->m_lpFont); nResult=D3DXCreateSprite(lpDevice, &lpFont->m_lpSurface); if(L_failed(nResult)) { Err_Printf("Failed to create surface for font writing, writing will be slower."); lpFont->m_lpSurface=L_null; } return L_succeeded(nResult); } L_bool Font_Invalidate(LVFONT* lpFont) { L_result nResult=0; nResult=lpFont->m_lpFont->lpVtbl->OnLostDevice(lpFont->m_lpFont); L_safe_release(lpFont->m_lpSurface); return L_succeeded(nResult); }<file_sep>/games/Legacy-Engine/Source/lm_sys/lm_mesh_anim.h #ifndef __LM_MESH_ANIM_H__ #define __LM_MESH_ANIM_H__ #include "lm_mesh.h" #include "lm_skel.h" //#include "lm_sys.h" class CLMeshAnim: public CLMesh2 { //Internally used data: protected: //Some structures to hold the stuff that is used every //frame but is only temporary. ML_MAT* m_pAnimMats; ML_MAT* m_pAttachMats; //The joint reference coordination array. lg_dword* m_pBoneRef; public: CLMeshAnim(); ~CLMeshAnim(); /* PRE: pSkel should be loaded. POST: The mesh will be compatible with the skeleton, and should properly be animated with the skeleton (assuming the skeleton was designed for the mesh, note taht when more than one skeleton is used with a mesh, then those skeletons should be compatible with each other or the animation will be haywire. */ lg_void SetCompatibleWith(CLSkel2* pSkel); /* PRE: N/A POST: Sets up the default frame for the mesh (base pose). DoTransform must be called to carry out the transform. */ lg_void SetupDefFrame(); /* PRE: pSkel should be loaded properly and compatbile with the mesh. POST: Sets up the transformation frames. DoTransform should still be called. */ lg_void SetupFrame(lg_dword dwFrame1, lg_dword dwFrame2, lg_float t, CLSkel2* pSkel); /* PRE: See above. Chooses a particular animation form the skel and then loops through it approapriately. POST: See above, must call DoTransform afterwards. */ lg_void CLMeshAnim::SetupFrame(lg_dword nAnim, lg_float fTime, CLSkel2* pSkel); /* PRE: Called after a Setup method, this method then can transition to another skeleton's animation. POST: Should be setup, but DoTransform must be called to carry out the transform. */ lg_void TransitionTo(lg_dword nAnim, lg_float fTime, CLSkel2* pSkel); /* PRE: Should have called one of the Setup* methods POST: Transforms all the vertices according to the animation data that was Setup*. NOTE: This transforms whatever data was acquired by the LockTransfVB() method (weither it is a IDirect3DVertexBuffer data or whatever. */ lg_void DoTransform(); /* The following methods return the transform for a particular joint, and the attach transform. The attach transform is the transformation matrix that an object being attached to that particular joint needs to be transformed by, so to attach a head to a body, you'd get the transform for the neck and use that transform to position the head. */ lg_dword GetJointRef(lg_cstr szJoint); const ML_MAT* GetJointTransform(lg_dword nRef); const ML_MAT* GetJointAttachTransform(lg_dword nRef); protected: /* PRE: Should be called somewhere within the overriden Load method, once the mesh header has been read. POST: Allocates memory and sets up structurs associated with the animation. Returns false if it could not initialize the data. */ lg_bool InitAnimData(); /* PRE: Should be called during the Unload overriden method. POST: Deletes all data created with InitAnimData. */ lg_void DeleteAnimData(); //Overrides: protected: /* PRE: Called during the SetupMesh methods. POST: Must return a destination vertex buffer with consisting of a list of vertexes that will contain the transformed data. Should return LG_NULL if it failed for some reason. */ virtual MeshVertex* LockTransfVB()=0; /* PRE: Called during the SetupMesh methods. POST: Should lock or do whatever is necessary to finalize the transformed vertexes. */ virtual void UnlockTransfVB()=0; public: //This class doesn't override the Load or Save methods: //virtual lg_bool Load(LMPath szFile)=0; //virtual lg_bool Save(LMPath szFile)=0; }; #endif __LM_MESH_ANIM_H__<file_sep>/games/Legacy-Engine/Source/lc_sys2/lc_cvar.h #ifndef __LC_CVAR_H__ #define __LC_CVAR_H__ #include "lc_def.h" #include "lg_types.h" #include "lc_sys2.h" class CCvarList { friend void LC_FUNC CV_Set(lg_cvar* cvar, const lg_char* szValue); friend void LC_FUNC LC_ListCvars(const lg_char* szLimit); private: lg_cvar* m_pHashList; CDefs m_Defs; lg_dword m_nLastGotten; lg_cvar* m_pLastGotten; lg_dword GenHash(const lg_char* szName); lg_dword DefToUnsigned(const lg_char* szDef); lg_long DefToLong(const lg_char* szDef); lg_float DefToFloat(const lg_char* szDef); public: CCvarList(); ~CCvarList(); lg_cvar* Register(const lg_char* szName, const lg_char* szValue, lg_dword Flags); lg_cvar* Get(const lg_char* szName); lg_cvar* GetFirst(); lg_cvar* GetNext(); lg_bool Define(lg_char* szDef, lg_float fValue); lg_bool Define(lg_char* szDef, lg_long nValue); lg_bool Define(lg_char* szDef, lg_dword nValue); static void Set(lg_cvar* cvar, const lg_char* szValue, CDefs* pDefs); static void Set(lg_cvar* cvar, lg_float fValue); static void Set(lg_cvar* cvar, lg_dword nValue); static void Set(lg_cvar* cvar, lg_long nValue); }; #endif __LC_CVAR_H__<file_sep>/games/Legacy-Engine/Scrapped/old/lw_entity.cpp #include "lw_entity.h" #ifdef OLD_METHOD /* PRE: pList must already be allocated, the EntList_ functions do not allocate or deallocate memory, they just change pointers. POST: The list will be ready to use. */ _LEntList::_LEntList() { Clear(); } _LEntList::~_LEntList() { } /* PRE: N/A POST: If there was a ent available it is returned and removed from the list. */ LEntityBase* _LEntList::Pop() { if(!m_pFirst) return LG_NULL; LEntityBase* pRes=m_pFirst; //Removing the first node is a special case. m_pFirst=m_pFirst->m_pNext; //If the first node was also the last node then we also //need to set the last node to null. if(m_pFirst==LG_NULL) { m_pLast=LG_NULL; } else { //The first node's previous must be set to null. m_pFirst->m_pPrev=LG_NULL; } m_nCount--; return pRes; } /* PRE: N/A POST: Returns the first available item in the list, or null if there is no first item. */ LEntityBase* _LEntList::Peek() { return m_pFirst; } /* PRE: pEnt should not be in pList, and it should be removed from any other list that it might be in. POST: pEnt will be added to the beginning of the list. */ void _LEntList::Push(LEntityBase* pEnt) { pEnt->m_pPrev=LG_NULL; pEnt->m_pNext=m_pFirst; if(m_pFirst) { m_pFirst->m_pPrev=pEnt; } m_pFirst=pEnt; m_nCount++; } /* PRE: N/A POST: Returns true if the list is empty. */ lg_bool _LEntList::IsEmpty() { return m_pFirst?LG_FALSE:LG_TRUE; } /* PRE: N/A POST: Clears the list. */ void _LEntList::Clear() { m_pFirst=LG_NULL; m_pLast=LG_NULL; m_nCount=0; } /* PRE: pEnt should be in this list. POST: pEnt is removed. */ void _LEntList::Remove(LEntityBase* pEnt) { if(pEnt==m_pFirst) { //Removing the first node is a special case. m_pFirst=m_pFirst->m_pNext; //If the first node was also the last node then we also //need to set the last node to null. if(m_pFirst==LG_NULL) { m_pLast=LG_NULL; } else { //The first node's previous must be set to null. m_pFirst->m_pPrev=LG_NULL; } } else if(pEnt==m_pLast) { //The last node is also a special case, but we know it isn't the only //node in the list because that would have been checked above. m_pLast=m_pLast->m_pPrev; m_pLast->m_pNext=LG_NULL; } else { //One problem here is that it isn't gauranteed that pEnt //was actually in pList, but it is a quick way to remove //a node. if(pEnt->m_pPrev && pEnt->m_pNext) { pEnt->m_pPrev->m_pNext=pEnt->m_pNext; pEnt->m_pNext->m_pPrev=pEnt->m_pPrev; } } m_nCount--; } #endif OLD_METHOD <file_sep>/games/Legacy-Engine/Source/engine/lg_cmd.cpp /************************************************************** File: lg_cmd.c Copyright (c) 2006, <NAME> Purpose: Contains the command function for the console. It also contains the function that registers the console commands, and various functions that are called by console commands. **************************************************************/ #include "lg_func.h" #include <stdio.h> #include "lg_malloc.h" #include "lg_cmd.h" #include "lg_sys.h" #include "lf_sys2.h" #include "lg_err.h" #include "../lc_sys2/lc_sys2.h" #include "lg_cvars.h" #define MAX_T_LEN (1024) void LGC_DisplayDeviceCaps(CLGame* pGame); void LGC_Dir(const lg_char* szLimit); void LGC_Extract(const lg_char* szFile, const lg_char* szOutFile); void LGC_Test(const lg_char* szParam); void LGC_ConDump(lf_path szFilename); void LGC_LoadCFG(const lg_char* szFilename); void LGC_SaveCFG(const lg_char* szFilename, lg_bool bAppend, lg_bool bAll); void LGC_Set(const lg_char* szCvar, const lg_char* szValue); void LGC_Get(const lg_char* szCvar); //void LGC_CvarUpdate(CLGame* pGame, const lg_char* szCvar); void LGC_CvarList(const lg_char* szLimit); /************************************************************** static CLGame::LGC_RegConCmds() Called from LG_Init(), it registers all of the console commands so that when a user types one it it will actually get processed. As sort of a standard the value of all console commands start with CONF_ then are appended with the function name. **************************************************************/ void CLGame::LGC_RegConCmds() { #define REG_CMD(name) LC_RegisterCommand(#name, CONF_##name, 0) REG_CMD(QUIT); REG_CMD(VRESTART); REG_CMD(DIR); REG_CMD(EXTRACT); REG_CMD(D3DCAPS); REG_CMD(VIDMEM); //REG_CMD(HARDVRESTART); REG_CMD(TEXFORMATS); REG_CMD(LOADMODEL); REG_CMD(VERSION); REG_CMD(CONDUMP); REG_CMD(LOADCFG); REG_CMD(SAVECFG); REG_CMD(LOADMAP); REG_CMD(SETMESSAGE); REG_CMD(CVARUPDATE); REG_CMD(SET); REG_CMD(GET); REG_CMD(CLEAR); REG_CMD(ECHO); REG_CMD(CVARLIST); REG_CMD(CMDLIST); REG_CMD(MUSIC_START); REG_CMD(MUSIC_PAUSE); REG_CMD(MUSIC_STOP); REG_CMD(MUSIC_RESUME); REG_CMD(SHOW_INFO); REG_CMD(INIT_SRV); REG_CMD(SHUTDOWN_SRV); REG_CMD(CONNECT); REG_CMD(DISCONNECT); REG_CMD(PAUSE); REG_CMD(TEST); } /************************************************************* static CLGame::LGC_ConCommand() This is the command function for the console, by design the pExtra parameter is a pointe to the game structure. All of the console commands are managed in this function, except for the built in commands. *************************************************************/ lg_bool CLGame::LCG_ConCommand(LC_CMD nCmd, lg_void* args, lg_void* pExtra) { CLGame* pGame=(CLGame*)pExtra; switch(nCmd) { case CONF_PAUSE: { pGame->m_WorldSrv.TogglePause(); } break; case CONF_INIT_SRV: { pGame->m_WorldSrv.Init(); //Should reconnect the client? } break; case CONF_SHUTDOWN_SRV: { pGame->m_WorldSrv.Shutdown(); } break; case CONF_CONNECT: { pGame->m_WorldCln.ConnectLocal(&pGame->m_WorldSrv); } break; case CONF_DISCONNECT: { pGame->m_WorldCln.Disconnect(); } break; case CONF_SHOW_INFO: { const char szUsage[]="Usage: SHOW_INFO [MESH|SKEL|TEXTURE|ENT|FX|MTR]"; const lg_char* szType=LC_GetArg(1, args); if(!szType) Err_Printf(szUsage); else if(stricmp(szType, "MESH")==0) pGame->m_pMMgr->PrintMeshes(); else if(stricmp(szType, "SKEL")==0) pGame->m_pMMgr->PrintSkels(); else if(stricmp(szType, "TEXTURE")==0) pGame->m_pTexMgr->PrintDebugInfo(); else if(stricmp(szType, "ENT")==0) pGame->m_WorldSrv.PrintEntInfo(); else if(stricmp(szType, "FX")==0) pGame->m_pFxMgr->PrintDebugInfo(); else if(stricmp(szType, "MTR")==0) pGame->m_pMtrMgr->PrintDebugInfo(); else Err_Printf(szUsage); break; } case CONF_CVARLIST: LGC_CvarList(LC_GetArg(1, args)); break; case CONF_TEST: LGC_Test(LC_GetArg(1, args)); break; case CONF_SET: LGC_Set(LC_GetArg(1, args), LC_GetArg(2, args)); break; case CONF_GET: LGC_Get(LC_GetArg(1, args)); break; case CONF_QUIT: CV_Set_l(pGame->cv_l_ShouldQuit, 1); break; case CONF_CVARUPDATE: LGC_CvarUpdate(pGame, LC_GetArg(1, args)); break; case CONF_SAVECFG: LGC_SaveCFG(LC_GetArg(1, args), LC_CheckArg("APPEND", args), LC_CheckArg("ALL", args)); break; case CONF_LOADCFG: LGC_LoadCFG(LC_GetArg(1, args)); break; case CONF_SETMESSAGE: { const lg_char* szTemp=LC_GetArg(1, args); if(szTemp) pGame->m_VCon.SetMessage(2, (lg_char*)szTemp); break; } case CONF_VERSION: Err_PrintVersion(); break; case CONF_LOADMAP: { const lg_char* szMapFilename=LC_GetArg(1, args); if(szMapFilename) { lf_path szTemp; if(szMapFilename[0]!='/') { _snprintf(szTemp, LF_MAX_PATH, "/dbase/maps/%s", szMapFilename); } else { _snprintf(szTemp, LF_MAX_PATH, "%s", szMapFilename); } #ifdef OLD_WORLD pGame->m_pWorld->LoadMap(szTemp); #endif pGame->m_WorldSrv.LoadMap(szTemp); pGame->m_WorldCln.ConnectLocal(&pGame->m_WorldSrv); } else Err_Printf("Usage: LOADMAP \"filename$\""); break; } case CONF_CLEAR: LC_Clear(); break; case CONF_CMDLIST: LC_ListCommands(); break; case CONF_CONDUMP: LGC_ConDump((lg_char*)LC_GetArg(1, args)); break; case CONF_TEXFORMATS: //pGame->m_Video.SupportedTexFormats(); Err_Printf("Not implemented."); break; case CONF_VIDMEM: { lg_dword nMem=IDirect3DDevice9_GetAvailableTextureMem(s_pDevice); Err_Printf("Estimated available video memory: %uMB", nMem/1024/1024); break; } case CONF_D3DCAPS: LGC_DisplayDeviceCaps(pGame); break; case CONF_EXTRACT: LGC_Extract(LC_GetArg(1, args), LC_GetArg(2, args)); break; case CONF_DIR: LGC_Dir(LC_GetArg(1, args)); break; case CONF_VRESTART: pGame->LV_Restart(); break; /* case CONF_HARDVRESTART: // Should save game, and shut it down. LV_Shutdown(lpGame); LV_Init(lpGame); // Should load saved game. break; */ case CONF_ECHO: LC_Print((lg_char*)LC_GetArg(1, args)); break; //Music control functions... case CONF_MUSIC_START: { lg_str szPath=(lg_str)LC_GetArg(1, args); lf_path szAdjPathname; if(!szPath) { Err_Printf("Usage: MUSIC_START \"$filename$\""); break; } if(szPath[0]!='/') { _snprintf(szAdjPathname, LF_MAX_PATH, "/dbase/music/%s", szPath); szPath=szAdjPathname; } pGame->m_SndMgr.Music_Start(szPath); break; } case CONF_MUSIC_PAUSE: pGame->m_SndMgr.Music_Pause(); break; case CONF_MUSIC_STOP: pGame->m_SndMgr.Music_Stop(); break; case CONF_MUSIC_RESUME: pGame->m_SndMgr.Music_Resume(); break; default: return LG_FALSE; } return LG_TRUE; } void CLGame::LGC_CvarUpdate(CLGame* pGame, const lg_char* szCvar) { /* Check to see if a sampler or render state cvar has been changed if so, call LV_SetStates.*/ if( L_strnicmp(szCvar, CVAR_v_TextureFilter, 0) || L_strnicmp(szCvar, CVAR_v_MaxAnisotropy, 0) || L_strnicmp(szCvar, CVAR_v_DebugWireframe, 0) ) { /* Break if the device is not initialized, this happens because the set command gets called when we are loading config.cfg, and the device hasn't been*/ Err_Printf("Calling LV_SetStates..."); if(!pGame->m_Video.SetStates()) Err_Printf("An error occured while setting the sampler and render states."); } else if(stricmp(szCvar, CVAR_s_MusicVolume)==0) { pGame->m_SndMgr.Music_UpdateVolume(); } } void LGC_CvarList(const lg_char* szLimit) { LC_ListCvars(szLimit); } void LGC_Get(const lg_char* szCvar) { if(!szCvar) { Err_Printf("USAGE: get \"$cvarname$\""); return; } lg_cvar* cvar=CV_Get(szCvar); if(cvar) Err_Printf(" %s (\"%s\", %.2f, %d)", cvar->szName, cvar->szValue, cvar->fValue, cvar->nValue); else Err_Printf("Could not get %s, no such cvar.", szCvar); } void LGC_Set(const lg_char* szCvar, const lg_char* szValue) { if(!szCvar || !szValue) { Err_Printf("USAGE: set \"$cvarname$\" \"$value$\""); return; } lg_cvar* cvar=CV_Get(szCvar); if(cvar) { CV_Set(cvar, szValue); Err_Printf(" %s (\"%s\", %.2f, %d)", cvar->szName, cvar->szValue, cvar->fValue, cvar->nValue); if(L_CHECK_FLAG(cvar->Flags, CVAR_UPDATE)) LC_SendCommandf("CVARUPDATE %s", cvar->szName); } else Err_Printf("Could not set %s, no such cvar.", szCvar); } //LGC Test is only for debugging purposes and it //is a place in which test code can be placed. void LGC_Test(const lg_char* szParam) { if(szParam) { char szTemp[LF_MAX_PATH]; LF_GetDirFromPath(szTemp, szParam); Err_Printf("The path is: \"%s\"", szTemp); } else { char szTemp[LF_MAX_PATH]; LF_GetDirFromPath(szTemp, ""); Err_Printf("The path is: \"%s\"", szTemp); } return; } //LGC_ConDump dumps the console to the specified file. void LGC_ConDump(lf_path szFilename) { if(!szFilename) { Err_Printf("Usage: CONDUMP filename$"); return; } LF_FILE3 fOut=LF_Open(szFilename, LF_ACCESS_WRITE, LF_CREATE_ALWAYS); if(!fOut) { Err_Printf("CONDUMP Error: Could not open file for writing."); return; } Err_Printf("Dumping console to \"%s\"...", szFilename); const lg_char* szLine=LC_GetOldestLine(); while(szLine) { LF_Write(fOut, (lf_void*)szLine, strlen(szLine)); LF_Write(fOut, "\r\n", 2); szLine=LC_GetNextLine(); } LF_Close(fOut); Err_Printf("Finnished dumping console."); } void LGC_LoadCFG(const lg_char* szFilename) { if(!szFilename) { Err_Printf("Usage: LOADCFG filename$"); return; } LF_FILE3 fIn=LF_Open(szFilename, LF_ACCESS_READ, LF_OPEN_EXISTING); if(!fIn) { Err_Printf("LOADCFG Error: Could not open file for reading."); return; } Err_Printf("Processing \"%s\"...", szFilename); while(!LF_IsEOF(fIn)) { lg_char szLine[512]; for(lg_dword i=0; i<512; i++) { if(!LF_Read(fIn, &szLine[i], 1) || szLine[i]=='\n') { szLine[i]=0; break; } } //Ignore lines that aren't anything. lg_dword nLen=L_strlen(szLine); if(nLen<1) continue; //Err_Printf("LINE: %s", szLine); if(szLine[0]=='\r' || szLine[0]=='\n') continue; /* Check to see for comments, and remove them. */ for(lg_dword i=0; i<=nLen; i++) { if((szLine[i]=='/')&&(szLine[i+1]=='/')) { szLine[i]=0; break; } if(szLine[i]=='\r' || szLine[i]=='\n') { szLine[i]=0; break; } } if(szLine[0]==0) continue; LC_SendCommand(szLine); } LF_Close(fIn); } void LGC_SaveCFG(const lg_char* szFilename, lg_bool bAppend, lg_bool bAll) { if(!szFilename) { Err_Printf("Usage: SAVECFG filename$ [APPEND] [ALL]"); return; } LF_FILE3 fOut=LF_Open(szFilename, LF_ACCESS_WRITE, bAppend?LF_OPEN_ALWAYS:LF_CREATE_ALWAYS); if(!fOut) { Err_Printf("SAVECFG Error: Could not open file for writing."); return; } //If appending, seek to the end of the file (and add a new line, just in case //we need one. if(bAppend) { LF_Seek(fOut, LF_SEEK_END, 0); LF_Write(fOut, "\r\n", 2); } Err_Printf("Saving cvars to \"%s\"...", szFilename); lg_cvar* cvar=CV_GetFirst(); while(cvar) { if(bAll || (L_CHECK_FLAG(cvar->Flags, CVAR_SAVE)) ) { //Write the line... LF_Write(fOut, "set \"", 5); LF_Write(fOut, cvar->szName, L_strlen(cvar->szName)); LF_Write(fOut, "\" \"", 3); LF_Write(fOut, cvar->szValue, L_strlen(cvar->szValue)); LF_Write(fOut, "\"\r\n", 3); } cvar=CV_GetNext(); } //In the future key binding data will need to be saved as well. Err_Printf("Finnished saving cvars."); LF_Close(fOut); } /********************************************************* LGC_Extract() Routine for the EXTRACT console command, note that extract is designed to extract files from lpks, if a output file is specified the file will be renamed if not it will maintain it's original path and name. Also note that if extract is called on a file that is not in an LPK it will still "extract" the in that it will read the file, and write the new file. **********************************************************/ void LGC_Extract(const lg_char* szFile, const lg_char* szOutFile) { LF_FILE3 fin=LG_NULL; LF_FILE3 fout=LG_NULL; lg_byte nByte=0; lg_dword i=0; if(!szFile) { Err_Printf("Usage: EXTRACT filename$ [outputfile$]"); return; } if(!szOutFile) { szOutFile=szFile; } Err_Printf("Extracting \"%s\" to \"%s\"...", szFile, szOutFile); /* We have to open with the LF_ACCESS_MEMORY flag, in case our output file is a file with the exact same name, this happens if we call extract on a file, that is not in an archive. */ fin=LF_Open(szFile, LF_ACCESS_READ|LF_ACCESS_MEMORY, LF_OPEN_EXISTING); if(!fin) { Err_Printf("Could not open \"%s\".", szFile); return; } fout=LF_Open(szOutFile, LF_ACCESS_WRITE, LF_CREATE_NEW); if(!fout) { LF_Close(fin); Err_Printf("Could not open \"%s\" for writing.", szOutFile); return; } LF_Write(fout, (lf_void*)LF_GetMemPointer(fin), LF_GetSize(fin)); LF_Close(fout); LF_Close(fin); Err_Printf("Finnished extracting \"%s\"", szFile); return; } void LGC_Dir(const lg_char* szLimit) { //The dir command needs only print the mount info on the file system //information will be printed depending on the error level for //the file system. FS_PrintMountInfo(); return; } /***************************************************************** LGC_DisplayDeviceCaps() Called by the console command D3DCAPS, this dumps all of the D3DCAPS9 information to the console. *****************************************************************/ void LGC_DisplayDeviceCaps(CLGame* pGame) { D3DCAPS9 d3dcaps; D3DADAPTER_IDENTIFIER9 adi; memset(&d3dcaps, 0, sizeof(D3DCAPS9)); lg_result nResult=IDirect3DDevice9_GetDeviceCaps(pGame->s_pDevice, &d3dcaps); if(LG_FAILED(nResult)) { Err_PrintDX("IDirect3DDevice9::GetDeviceCaps", nResult); return; } memset(&adi, 0, sizeof(adi)); pGame->s_pD3D->GetAdapterIdentifier( pGame->s_nAdapterID, 0, &adi); char szDeviceType[4]; nResult=0; #define CAPFLAG(a, b) Err_Printf(" "#b"=%s", (L_CHECK_FLAG(d3dcaps.a, b)?"YES":"NO")) switch(d3dcaps.DeviceType) { case D3DDEVTYPE_HAL: LG_strncpy(szDeviceType, "HAL", 3); break; case D3DDEVTYPE_REF: LG_strncpy(szDeviceType, "REF", 3); break; case D3DDEVTYPE_SW: LG_strncpy(szDeviceType, "SW", 3); break; } Err_Printf("\"%s\" (%s) Capabilities:", adi.Description, szDeviceType); Err_Printf(" Adapter Ordinal: %i", d3dcaps.AdapterOrdinal); //Err_Printf(" Caps: %s", L_CHECK_FLAG(d3dcaps.Caps, D3DCAPS_READ_SCANLINE)?"D3DCAPS_READ_SCANLINE":""); Err_Printf("Driver Caps:"); CAPFLAG(Caps, D3DCAPS_READ_SCANLINE); Err_Printf("Driver Caps 2:"); CAPFLAG(Caps2, D3DCAPS2_CANAUTOGENMIPMAP), CAPFLAG(Caps2, D3DCAPS2_CANCALIBRATEGAMMA), CAPFLAG(Caps2, D3DCAPS2_CANMANAGERESOURCE), CAPFLAG(Caps2, D3DCAPS2_DYNAMICTEXTURES), CAPFLAG(Caps2, D3DCAPS2_FULLSCREENGAMMA), Err_Printf("Driver Caps 3:"); CAPFLAG(Caps2, D3DCAPS2_RESERVED); CAPFLAG(Caps3, D3DCAPS3_ALPHA_FULLSCREEN_FLIP_OR_DISCARD); CAPFLAG(Caps3, D3DCAPS3_COPY_TO_VIDMEM); CAPFLAG(Caps3, D3DCAPS3_COPY_TO_SYSTEMMEM); CAPFLAG(Caps3, D3DCAPS3_LINEAR_TO_SRGB_PRESENTATION); CAPFLAG(Caps3, D3DCAPS3_RESERVED); Err_Printf("Available Presentation Intervals:"); CAPFLAG(PresentationIntervals, D3DPRESENT_INTERVAL_IMMEDIATE); CAPFLAG(PresentationIntervals, D3DPRESENT_INTERVAL_ONE); CAPFLAG(PresentationIntervals, D3DPRESENT_INTERVAL_TWO); CAPFLAG(PresentationIntervals, D3DPRESENT_INTERVAL_THREE); CAPFLAG(PresentationIntervals, D3DPRESENT_INTERVAL_FOUR); Err_Printf("Cursor Caps:"); CAPFLAG(CursorCaps, D3DCURSORCAPS_COLOR); CAPFLAG(CursorCaps, D3DCURSORCAPS_LOWRES); Err_Printf("Device Caps:"); CAPFLAG(DevCaps, D3DDEVCAPS_CANBLTSYSTONONLOCAL); CAPFLAG(DevCaps, D3DDEVCAPS_CANRENDERAFTERFLIP); CAPFLAG(DevCaps, D3DDEVCAPS_DRAWPRIMITIVES2); CAPFLAG(DevCaps, D3DDEVCAPS_DRAWPRIMITIVES2EX); CAPFLAG(DevCaps, D3DDEVCAPS_DRAWPRIMTLVERTEX); CAPFLAG(DevCaps, D3DDEVCAPS_EXECUTESYSTEMMEMORY); CAPFLAG(DevCaps, D3DDEVCAPS_EXECUTEVIDEOMEMORY); CAPFLAG(DevCaps, D3DDEVCAPS_HWRASTERIZATION); CAPFLAG(DevCaps, D3DDEVCAPS_HWTRANSFORMANDLIGHT); CAPFLAG(DevCaps, D3DDEVCAPS_NPATCHES); CAPFLAG(DevCaps, D3DDEVCAPS_PUREDEVICE); CAPFLAG(DevCaps, D3DDEVCAPS_QUINTICRTPATCHES); CAPFLAG(DevCaps, D3DDEVCAPS_RTPATCHES); CAPFLAG(DevCaps, D3DDEVCAPS_RTPATCHHANDLEZERO); CAPFLAG(DevCaps, D3DDEVCAPS_SEPARATETEXTUREMEMORIES); CAPFLAG(DevCaps, D3DDEVCAPS_TEXTURENONLOCALVIDMEM); CAPFLAG(DevCaps, D3DDEVCAPS_TEXTURESYSTEMMEMORY); CAPFLAG(DevCaps, D3DDEVCAPS_TEXTUREVIDEOMEMORY); CAPFLAG(DevCaps, D3DDEVCAPS_TLVERTEXSYSTEMMEMORY); CAPFLAG(DevCaps, D3DDEVCAPS_TLVERTEXVIDEOMEMORY); Err_Printf("Miscellaneous Driver Primitive Caps:"); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_MASKZ); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_CULLNONE); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_CULLCW); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_CULLCCW); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_COLORWRITEENABLE); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_CLIPPLANESCALEDPOINTS); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_CLIPTLVERTS); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_TSSARGTEMP); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_BLENDOP); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_NULLREFERENCE); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_INDEPENDENTWRITEMASKS); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_PERSTAGECONSTANT); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_FOGANDSPECULARALPHA); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_SEPARATEALPHABLEND); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_MRTINDEPENDENTBITDEPTHS); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_MRTPOSTPIXELSHADERBLENDING); CAPFLAG(PrimitiveMiscCaps, D3DPMISCCAPS_FOGVERTEXCLAMPED); Err_Printf("Raster Drawing Caps:"); CAPFLAG(RasterCaps, D3DPRASTERCAPS_ANISOTROPY); CAPFLAG(RasterCaps, D3DPRASTERCAPS_COLORPERSPECTIVE); CAPFLAG(RasterCaps, D3DPRASTERCAPS_DITHER); CAPFLAG(RasterCaps, D3DPRASTERCAPS_DEPTHBIAS); CAPFLAG(RasterCaps, D3DPRASTERCAPS_FOGRANGE); CAPFLAG(RasterCaps, D3DPRASTERCAPS_FOGTABLE); CAPFLAG(RasterCaps, D3DPRASTERCAPS_FOGVERTEX); CAPFLAG(RasterCaps, D3DPRASTERCAPS_MIPMAPLODBIAS); CAPFLAG(RasterCaps, D3DPRASTERCAPS_MULTISAMPLE_TOGGLE); CAPFLAG(RasterCaps, D3DPRASTERCAPS_SCISSORTEST); CAPFLAG(RasterCaps, D3DPRASTERCAPS_SLOPESCALEDEPTHBIAS); CAPFLAG(RasterCaps, D3DPRASTERCAPS_WBUFFER); CAPFLAG(RasterCaps, D3DPRASTERCAPS_WFOG); CAPFLAG(RasterCaps, D3DPRASTERCAPS_ZBUFFERLESSHSR); CAPFLAG(RasterCaps, D3DPRASTERCAPS_ZFOG); CAPFLAG(RasterCaps, D3DPRASTERCAPS_ZTEST); Err_Printf("Z-Buffer Comparison Caps:"); CAPFLAG(ZCmpCaps, D3DPCMPCAPS_ALWAYS); CAPFLAG(ZCmpCaps, D3DPCMPCAPS_EQUAL); CAPFLAG(ZCmpCaps, D3DPCMPCAPS_GREATER); CAPFLAG(ZCmpCaps, D3DPCMPCAPS_GREATEREQUAL); CAPFLAG(ZCmpCaps, D3DPCMPCAPS_LESS); CAPFLAG(ZCmpCaps, D3DPCMPCAPS_LESSEQUAL); CAPFLAG(ZCmpCaps, D3DPCMPCAPS_NEVER); CAPFLAG(ZCmpCaps, D3DPCMPCAPS_NOTEQUAL); Err_Printf("Source Blend Caps:"); CAPFLAG(SrcBlendCaps, D3DPBLENDCAPS_BLENDFACTOR); CAPFLAG(SrcBlendCaps, D3DPBLENDCAPS_BOTHINVSRCALPHA); CAPFLAG(SrcBlendCaps, D3DPBLENDCAPS_BOTHSRCALPHA); CAPFLAG(SrcBlendCaps, D3DPBLENDCAPS_DESTALPHA); CAPFLAG(SrcBlendCaps, D3DPBLENDCAPS_DESTCOLOR); CAPFLAG(SrcBlendCaps, D3DPBLENDCAPS_INVDESTALPHA); CAPFLAG(SrcBlendCaps, D3DPBLENDCAPS_INVDESTCOLOR); CAPFLAG(SrcBlendCaps, D3DPBLENDCAPS_INVSRCALPHA); CAPFLAG(SrcBlendCaps, D3DPBLENDCAPS_INVSRCCOLOR); CAPFLAG(SrcBlendCaps, D3DPBLENDCAPS_ONE); CAPFLAG(SrcBlendCaps, D3DPBLENDCAPS_SRCALPHA); CAPFLAG(SrcBlendCaps, D3DPBLENDCAPS_SRCALPHASAT); CAPFLAG(SrcBlendCaps, D3DPBLENDCAPS_SRCCOLOR); CAPFLAG(SrcBlendCaps, D3DPBLENDCAPS_ZERO); Err_Printf("Dest Blend Caps:"); CAPFLAG(DestBlendCaps, D3DPBLENDCAPS_BLENDFACTOR); CAPFLAG(DestBlendCaps, D3DPBLENDCAPS_BOTHINVSRCALPHA); CAPFLAG(DestBlendCaps, D3DPBLENDCAPS_BOTHSRCALPHA); CAPFLAG(DestBlendCaps, D3DPBLENDCAPS_DESTALPHA); CAPFLAG(DestBlendCaps, D3DPBLENDCAPS_DESTCOLOR); CAPFLAG(DestBlendCaps, D3DPBLENDCAPS_INVDESTALPHA); CAPFLAG(DestBlendCaps, D3DPBLENDCAPS_INVDESTCOLOR); CAPFLAG(DestBlendCaps, D3DPBLENDCAPS_INVSRCALPHA); CAPFLAG(DestBlendCaps, D3DPBLENDCAPS_INVSRCCOLOR); CAPFLAG(DestBlendCaps, D3DPBLENDCAPS_ONE); CAPFLAG(DestBlendCaps, D3DPBLENDCAPS_SRCALPHA); CAPFLAG(DestBlendCaps, D3DPBLENDCAPS_SRCALPHASAT); CAPFLAG(DestBlendCaps, D3DPBLENDCAPS_SRCCOLOR); CAPFLAG(DestBlendCaps, D3DPBLENDCAPS_ZERO); Err_Printf("Alpha Test Comparison Caps:"); CAPFLAG(AlphaCmpCaps, D3DPCMPCAPS_ALWAYS); CAPFLAG(AlphaCmpCaps, D3DPCMPCAPS_EQUAL); CAPFLAG(AlphaCmpCaps, D3DPCMPCAPS_GREATER); CAPFLAG(AlphaCmpCaps, D3DPCMPCAPS_GREATEREQUAL); CAPFLAG(AlphaCmpCaps, D3DPCMPCAPS_LESS); CAPFLAG(AlphaCmpCaps, D3DPCMPCAPS_LESSEQUAL); CAPFLAG(AlphaCmpCaps, D3DPCMPCAPS_NEVER); CAPFLAG(AlphaCmpCaps, D3DPCMPCAPS_NOTEQUAL); Err_Printf("Shading Operations Caps:"); CAPFLAG(ShadeCaps, D3DPSHADECAPS_ALPHAGOURAUDBLEND); CAPFLAG(ShadeCaps, D3DPSHADECAPS_COLORGOURAUDRGB); CAPFLAG(ShadeCaps, D3DPSHADECAPS_FOGGOURAUD); CAPFLAG(ShadeCaps, D3DPSHADECAPS_SPECULARGOURAUDRGB); Err_Printf("Texture Mapping Caps:"); CAPFLAG(TextureCaps, D3DPTEXTURECAPS_ALPHA); CAPFLAG(TextureCaps, D3DPTEXTURECAPS_ALPHAPALETTE); CAPFLAG(TextureCaps, D3DPTEXTURECAPS_CUBEMAP); CAPFLAG(TextureCaps, D3DPTEXTURECAPS_CUBEMAP_POW2); CAPFLAG(TextureCaps, D3DPTEXTURECAPS_MIPCUBEMAP); CAPFLAG(TextureCaps, D3DPTEXTURECAPS_MIPMAP); CAPFLAG(TextureCaps, D3DPTEXTURECAPS_MIPVOLUMEMAP); CAPFLAG(TextureCaps, D3DPTEXTURECAPS_NONPOW2CONDITIONAL); CAPFLAG(TextureCaps, D3DPTEXTURECAPS_NOPROJECTEDBUMPENV); CAPFLAG(TextureCaps, D3DPTEXTURECAPS_PERSPECTIVE); CAPFLAG(TextureCaps, D3DPTEXTURECAPS_POW2); CAPFLAG(TextureCaps, D3DPTEXTURECAPS_PROJECTED); CAPFLAG(TextureCaps, D3DPTEXTURECAPS_SQUAREONLY); CAPFLAG(TextureCaps, D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE); CAPFLAG(TextureCaps, D3DPTEXTURECAPS_VOLUMEMAP); CAPFLAG(TextureCaps, D3DPTEXTURECAPS_VOLUMEMAP_POW2); Err_Printf("Texture Filter Caps:"); CAPFLAG(TextureFilterCaps, D3DPTFILTERCAPS_MINFPOINT); CAPFLAG(TextureFilterCaps, D3DPTFILTERCAPS_MINFLINEAR); CAPFLAG(TextureFilterCaps, D3DPTFILTERCAPS_MINFANISOTROPIC); CAPFLAG(TextureFilterCaps, D3DPTFILTERCAPS_MINFPYRAMIDALQUAD); CAPFLAG(TextureFilterCaps, D3DPTFILTERCAPS_MINFGAUSSIANQUAD); CAPFLAG(TextureFilterCaps, D3DPTFILTERCAPS_MIPFPOINT); CAPFLAG(TextureFilterCaps, D3DPTFILTERCAPS_MIPFLINEAR); CAPFLAG(TextureFilterCaps, D3DPTFILTERCAPS_MAGFPOINT); CAPFLAG(TextureFilterCaps, D3DPTFILTERCAPS_MAGFLINEAR); CAPFLAG(TextureFilterCaps, D3DPTFILTERCAPS_MAGFANISOTROPIC); CAPFLAG(TextureFilterCaps, D3DPTFILTERCAPS_MAGFPYRAMIDALQUAD); CAPFLAG(TextureFilterCaps, D3DPTFILTERCAPS_MAGFGAUSSIANQUAD); Err_Printf("Cube Texture Filter Caps:"); CAPFLAG(CubeTextureFilterCaps, D3DPTFILTERCAPS_MINFPOINT); CAPFLAG(CubeTextureFilterCaps, D3DPTFILTERCAPS_MINFLINEAR); CAPFLAG(CubeTextureFilterCaps, D3DPTFILTERCAPS_MINFANISOTROPIC); CAPFLAG(CubeTextureFilterCaps, D3DPTFILTERCAPS_MINFPYRAMIDALQUAD); CAPFLAG(CubeTextureFilterCaps, D3DPTFILTERCAPS_MINFGAUSSIANQUAD); CAPFLAG(CubeTextureFilterCaps, D3DPTFILTERCAPS_MIPFPOINT); CAPFLAG(CubeTextureFilterCaps, D3DPTFILTERCAPS_MIPFLINEAR); CAPFLAG(CubeTextureFilterCaps, D3DPTFILTERCAPS_MAGFPOINT); CAPFLAG(CubeTextureFilterCaps, D3DPTFILTERCAPS_MAGFLINEAR); CAPFLAG(CubeTextureFilterCaps, D3DPTFILTERCAPS_MAGFANISOTROPIC); CAPFLAG(CubeTextureFilterCaps, D3DPTFILTERCAPS_MAGFPYRAMIDALQUAD); CAPFLAG(CubeTextureFilterCaps, D3DPTFILTERCAPS_MAGFGAUSSIANQUAD); Err_Printf("Volume Texture Filter Caps:"); CAPFLAG(VolumeTextureFilterCaps, D3DPTFILTERCAPS_MINFPOINT); CAPFLAG(VolumeTextureFilterCaps, D3DPTFILTERCAPS_MINFLINEAR); CAPFLAG(VolumeTextureFilterCaps, D3DPTFILTERCAPS_MINFANISOTROPIC); CAPFLAG(VolumeTextureFilterCaps, D3DPTFILTERCAPS_MINFPYRAMIDALQUAD); CAPFLAG(VolumeTextureFilterCaps, D3DPTFILTERCAPS_MINFGAUSSIANQUAD); CAPFLAG(VolumeTextureFilterCaps, D3DPTFILTERCAPS_MIPFPOINT); CAPFLAG(VolumeTextureFilterCaps, D3DPTFILTERCAPS_MIPFLINEAR); CAPFLAG(VolumeTextureFilterCaps, D3DPTFILTERCAPS_MAGFPOINT); CAPFLAG(VolumeTextureFilterCaps, D3DPTFILTERCAPS_MAGFLINEAR); CAPFLAG(VolumeTextureFilterCaps, D3DPTFILTERCAPS_MAGFANISOTROPIC); CAPFLAG(VolumeTextureFilterCaps, D3DPTFILTERCAPS_MAGFPYRAMIDALQUAD); CAPFLAG(VolumeTextureFilterCaps, D3DPTFILTERCAPS_MAGFGAUSSIANQUAD); Err_Printf("Texture Address Caps:"); CAPFLAG(TextureAddressCaps, D3DPTADDRESSCAPS_BORDER); CAPFLAG(TextureAddressCaps, D3DPTADDRESSCAPS_CLAMP); CAPFLAG(TextureAddressCaps, D3DPTADDRESSCAPS_INDEPENDENTUV); CAPFLAG(TextureAddressCaps, D3DPTADDRESSCAPS_MIRROR); CAPFLAG(TextureAddressCaps, D3DPTADDRESSCAPS_MIRRORONCE); CAPFLAG(TextureAddressCaps, D3DPTADDRESSCAPS_WRAP); Err_Printf("Volume Texture Address Caps:"); CAPFLAG(VolumeTextureAddressCaps, D3DPTADDRESSCAPS_BORDER); CAPFLAG(VolumeTextureAddressCaps, D3DPTADDRESSCAPS_CLAMP); CAPFLAG(VolumeTextureAddressCaps, D3DPTADDRESSCAPS_INDEPENDENTUV); CAPFLAG(VolumeTextureAddressCaps, D3DPTADDRESSCAPS_MIRROR); CAPFLAG(VolumeTextureAddressCaps, D3DPTADDRESSCAPS_MIRRORONCE); CAPFLAG(VolumeTextureAddressCaps, D3DPTADDRESSCAPS_WRAP); Err_Printf("Line Caps:"); CAPFLAG(LineCaps, D3DLINECAPS_ALPHACMP); CAPFLAG(LineCaps, D3DLINECAPS_ANTIALIAS); CAPFLAG(LineCaps, D3DLINECAPS_BLEND); CAPFLAG(LineCaps, D3DLINECAPS_FOG); CAPFLAG(LineCaps, D3DLINECAPS_TEXTURE); CAPFLAG(LineCaps, D3DLINECAPS_ZTEST); Err_Printf("Device Limits:"); Err_Printf(" Max Texture Width: %i", d3dcaps.MaxTextureWidth); Err_Printf(" Max Texture Height: %i", d3dcaps.MaxTextureHeight); Err_Printf(" Max Volume Extent: %i", d3dcaps.MaxVolumeExtent); Err_Printf(" Max Texture Repeat: %i", d3dcaps.MaxTextureRepeat); Err_Printf(" Max Texture Aspect Ratio: %i", d3dcaps.MaxTextureAspectRatio); Err_Printf(" Max Anisotropy: %i", d3dcaps.MaxAnisotropy); Err_Printf(" Max W-Based Depth Value: %f", d3dcaps.MaxVertexW); Err_Printf(" Guard Band Left: %f", d3dcaps.GuardBandLeft); Err_Printf(" Guard Band Top: %f", d3dcaps.GuardBandTop); Err_Printf(" Gaurd Band Right: %f", d3dcaps.GuardBandRight); Err_Printf(" Guard Band Bottom: %f", d3dcaps.GuardBandBottom); Err_Printf(" Extents Adjust: %f", d3dcaps.ExtentsAdjust); Err_Printf("Stencil Caps:"); CAPFLAG(StencilCaps, D3DSTENCILCAPS_KEEP); CAPFLAG(StencilCaps, D3DSTENCILCAPS_ZERO); CAPFLAG(StencilCaps, D3DSTENCILCAPS_REPLACE); CAPFLAG(StencilCaps, D3DSTENCILCAPS_INCRSAT); CAPFLAG(StencilCaps, D3DSTENCILCAPS_DECRSAT); CAPFLAG(StencilCaps, D3DSTENCILCAPS_INVERT); CAPFLAG(StencilCaps, D3DSTENCILCAPS_INCR); CAPFLAG(StencilCaps, D3DSTENCILCAPS_DECR); CAPFLAG(StencilCaps, D3DSTENCILCAPS_TWOSIDED); Err_Printf("FVF Caps:"); CAPFLAG(FVFCaps, D3DFVFCAPS_DONOTSTRIPELEMENTS); CAPFLAG(FVFCaps, D3DFVFCAPS_PSIZE); CAPFLAG(FVFCaps, D3DFVFCAPS_TEXCOORDCOUNTMASK); Err_Printf("Texture Operation Caps:"); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_ADD); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_ADDSIGNED); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_ADDSIGNED2X); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_ADDSMOOTH); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_BLENDCURRENTALPHA); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_BLENDDIFFUSEALPHA); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_BLENDFACTORALPHA); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_BLENDTEXTUREALPHA); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_BLENDTEXTUREALPHAPM); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_BUMPENVMAP); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_BUMPENVMAPLUMINANCE); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_DISABLE); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_DOTPRODUCT3); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_LERP); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_MODULATE); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_MODULATE2X); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_MODULATE4X); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_MODULATEALPHA_ADDCOLOR); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_MODULATECOLOR_ADDALPHA); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_MODULATEINVALPHA_ADDCOLOR); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_MODULATEINVCOLOR_ADDALPHA); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_MULTIPLYADD); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_PREMODULATE); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_SELECTARG1); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_SELECTARG2); CAPFLAG(TextureOpCaps, D3DTEXOPCAPS_SUBTRACT); Err_Printf("Multi-Texture Limits:"); Err_Printf(" Max Texture Blend Stages: %i", d3dcaps.MaxTextureBlendStages); Err_Printf(" Max Simultaneous Textures: %i", d3dcaps.MaxSimultaneousTextures); Err_Printf("Vertex Processing Caps:"); CAPFLAG(VertexProcessingCaps, D3DVTXPCAPS_DIRECTIONALLIGHTS); CAPFLAG(VertexProcessingCaps, D3DVTXPCAPS_LOCALVIEWER); CAPFLAG(VertexProcessingCaps, D3DVTXPCAPS_MATERIALSOURCE7); CAPFLAG(VertexProcessingCaps, D3DVTXPCAPS_NO_TEXGEN_NONLOCALVIEWER); CAPFLAG(VertexProcessingCaps, D3DVTXPCAPS_POSITIONALLIGHTS); CAPFLAG(VertexProcessingCaps, D3DVTXPCAPS_TEXGEN); CAPFLAG(VertexProcessingCaps, D3DVTXPCAPS_TEXGEN_SPHEREMAP); CAPFLAG(VertexProcessingCaps, D3DVTXPCAPS_TWEENING); Err_Printf("Device Limits:"); Err_Printf(" Max Active Lights: %i", d3dcaps.MaxActiveLights); Err_Printf(" Max User Clip Planes: %i", d3dcaps.MaxUserClipPlanes); Err_Printf(" Max Vertex Blend Matrices: %i", d3dcaps.MaxVertexBlendMatrices); Err_Printf(" Max Vertex Blend Matrix Index: %i", d3dcaps.MaxVertexBlendMatrixIndex); Err_Printf(" Max Point Size: %f", d3dcaps.MaxPointSize); Err_Printf(" Max Primitive Count: %i", d3dcaps.MaxPrimitiveCount); Err_Printf(" Max Vertex Index: %i", d3dcaps.MaxVertexIndex); Err_Printf(" Max Streams: %i", d3dcaps.MaxStreams); Err_Printf(" Max Stream Stride: %i", d3dcaps.MaxStreamStride); Err_Printf(" Vertex Shader Version: 0x%04X 0x%04X", HIWORD(d3dcaps.VertexShaderVersion), LOWORD(d3dcaps.VertexShaderVersion)); Err_Printf(" Max Vertex Shader Const: %i", d3dcaps.MaxVertexShaderConst); Err_Printf(" Pixel Shader Version: 0x%04X 0x%04X", HIWORD(d3dcaps.PixelShaderVersion), LOWORD(d3dcaps.PixelShaderVersion)); Err_Printf(" Pixel Shader 1x Max Value: %f", d3dcaps.PixelShader1xMaxValue); Err_Printf("Device Caps 2:"); CAPFLAG(DevCaps2, D3DDEVCAPS2_ADAPTIVETESSRTPATCH); CAPFLAG(DevCaps2, D3DDEVCAPS2_ADAPTIVETESSNPATCH); CAPFLAG(DevCaps2, D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES); CAPFLAG(DevCaps2, D3DDEVCAPS2_DMAPNPATCH); CAPFLAG(DevCaps2, D3DDEVCAPS2_PRESAMPLEDDMAPNPATCH); CAPFLAG(DevCaps2, D3DDEVCAPS2_STREAMOFFSET); CAPFLAG(DevCaps2, D3DDEVCAPS2_VERTEXELEMENTSCANSHARESTREAMOFFSET); Err_Printf("Device Limits:"); Err_Printf(" Max Npatch Tessellation Level: %f", d3dcaps.MaxNpatchTessellationLevel); //Err_Printf(" Min Antialiased Line Width: %i", d3dcaps.MinAntialiasedLineWidth); //Err_Printf(" Max Antialiased Line Width: %i", d3dcaps.MaxAntialiasedLineWidth); Err_Printf(" Master Adapter Ordinal: %i", d3dcaps.MasterAdapterOrdinal); Err_Printf(" Adapter Ordinal In Group: %i", d3dcaps.AdapterOrdinalInGroup); Err_Printf(" Number Of Adapters In Group: %i", d3dcaps.NumberOfAdaptersInGroup); Err_Printf("Vertex Data Bytes:"); CAPFLAG(DeclTypes, D3DDTCAPS_UBYTE4); CAPFLAG(DeclTypes, D3DDTCAPS_UBYTE4N); CAPFLAG(DeclTypes, D3DDTCAPS_SHORT2N); CAPFLAG(DeclTypes, D3DDTCAPS_SHORT4N); CAPFLAG(DeclTypes, D3DDTCAPS_USHORT2N); CAPFLAG(DeclTypes, D3DDTCAPS_USHORT4N); CAPFLAG(DeclTypes, D3DDTCAPS_UDEC3); CAPFLAG(DeclTypes, D3DDTCAPS_DEC3N); CAPFLAG(DeclTypes, D3DDTCAPS_FLOAT16_2); CAPFLAG(DeclTypes, D3DDTCAPS_FLOAT16_4); Err_Printf("Device Limits:"); Err_Printf(" Num Simultaneous Render Targets: %i", d3dcaps.NumSimultaneousRTs); Err_Printf("StretchRect Filter Caps:"); CAPFLAG(StretchRectFilterCaps, D3DPTFILTERCAPS_MINFPOINT); CAPFLAG(StretchRectFilterCaps, D3DPTFILTERCAPS_MAGFPOINT); CAPFLAG(StretchRectFilterCaps, D3DPTFILTERCAPS_MINFLINEAR); CAPFLAG(StretchRectFilterCaps, D3DPTFILTERCAPS_MAGFLINEAR); Err_Printf("Vertex Shader 2.0 Extended Caps:"); CAPFLAG(VS20Caps.Caps, D3DVS20CAPS_PREDICATION); Err_Printf(" Dynamic Flow Control Depth: %i", d3dcaps.VS20Caps.DynamicFlowControlDepth); Err_Printf(" Num Temps: %i", d3dcaps.VS20Caps.NumTemps); Err_Printf(" Static Flow Control Depth: %i", d3dcaps.VS20Caps.StaticFlowControlDepth); Err_Printf("Pixel Shader 2.0 Extended Caps:"); CAPFLAG(PS20Caps.Caps, D3DPS20CAPS_ARBITRARYSWIZZLE); CAPFLAG(PS20Caps.Caps, D3DPS20CAPS_GRADIENTINSTRUCTIONS); CAPFLAG(PS20Caps.Caps, D3DPS20CAPS_PREDICATION); CAPFLAG(PS20Caps.Caps, D3DPS20CAPS_NODEPENDENTREADLIMIT); CAPFLAG(PS20Caps.Caps, D3DPS20CAPS_NOTEXINSTRUCTIONLIMIT); Err_Printf(" Dynamic Flow Control Depth: %i", d3dcaps.PS20Caps.DynamicFlowControlDepth); Err_Printf(" Num Temps: %i", d3dcaps.PS20Caps.NumTemps); Err_Printf(" Static Flow Control Depth: %i", d3dcaps.PS20Caps.StaticFlowControlDepth); Err_Printf(" Num Instruction Slots: %i", d3dcaps.PS20Caps.NumInstructionSlots); Err_Printf("Vertex Texture Filter Caps:"); CAPFLAG(VertexTextureFilterCaps, D3DPTFILTERCAPS_MINFPOINT); CAPFLAG(VertexTextureFilterCaps, D3DPTFILTERCAPS_MINFLINEAR); CAPFLAG(VertexTextureFilterCaps, D3DPTFILTERCAPS_MINFANISOTROPIC); CAPFLAG(VertexTextureFilterCaps, D3DPTFILTERCAPS_MINFPYRAMIDALQUAD); CAPFLAG(VertexTextureFilterCaps, D3DPTFILTERCAPS_MINFGAUSSIANQUAD); CAPFLAG(VertexTextureFilterCaps, D3DPTFILTERCAPS_MIPFPOINT); CAPFLAG(VertexTextureFilterCaps, D3DPTFILTERCAPS_MIPFLINEAR); CAPFLAG(VertexTextureFilterCaps, D3DPTFILTERCAPS_MAGFPOINT); CAPFLAG(VertexTextureFilterCaps, D3DPTFILTERCAPS_MAGFLINEAR); CAPFLAG(VertexTextureFilterCaps, D3DPTFILTERCAPS_MAGFANISOTROPIC); CAPFLAG(VertexTextureFilterCaps, D3DPTFILTERCAPS_MAGFPYRAMIDALQUAD); CAPFLAG(VertexTextureFilterCaps, D3DPTFILTERCAPS_MAGFGAUSSIANQUAD); Err_Printf("Device Limits:"); Err_Printf(" Max Vertex Shader Instructions Executed: %i", d3dcaps.MaxVShaderInstructionsExecuted); Err_Printf(" Max Pixel Shader Instructions Executed: %i", d3dcaps.MaxPShaderInstructionsExecuted); Err_Printf(" Max Vertex Shader 3.0 Instruction Slots: %i", d3dcaps.MaxVertexShader30InstructionSlots); Err_Printf(" Max Pixel Shader 3.0 Instruction Slots: %i", d3dcaps.MaxPixelShader30InstructionSlots); }<file_sep>/games/Legacy-Engine/Scrapped/old/lp_physx.cpp #pragma comment(lib, "NxCharacter.lib") #pragma comment(lib, "NxExtensions.lib") #pragma comment(lib, "NxCooking.lib") #pragma comment(lib, "PhysXLoader.lib") #include "lg_err.h" #include "lg_err_ex.h" #include "lp_physx.h" class UserStream; NxPhysicsSDK* CElementPhysX::s_pNxPhysics=LG_NULL; NxScene* CElementPhysX::s_pNxScene=LG_NULL; CLPhysXOutputStream CElementPhysX::s_Output; NxActor* CElementPhysX::s_pWorldActor=LG_NULL; void CElementPhysX::Initialize() { s_pNxPhysics=NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, 0, &s_Output); if(!s_pNxPhysics) throw ERROR_CODE(LG_ERR_DEFAULT, "Could not initialize PhysX engine."); s_pNxPhysics->setParameter(NX_SKIN_WIDTH, 0.01f); s_pNxPhysics->setParameter(NX_VISUALIZATION_SCALE, 1); s_pNxPhysics->setParameter(NX_VISUALIZE_COLLISION_SHAPES, 1); s_pNxPhysics->setParameter(NX_VISUALIZE_ACTOR_AXES, 1); NxSceneDesc SceneDesc; //memset(&SceneDesc, 0, sizeof(NxSceneDesc)); SceneDesc.gravity.set(0.0f, -9.8f, 0.0f); //SceneDesc.broadPhase = NX_BROADPHASE_COHERENT; //SceneDesc.collisionDetection = LG_TRUE; s_pNxScene=s_pNxPhysics->createScene(SceneDesc); if(!s_pNxScene) throw ERROR_CODE(LG_ERR_DEFAULT, "Could not initialize PhysX scene."); // Create the default material NxMaterial* defaultMaterial = s_pNxScene->getMaterialFromIndex(0); defaultMaterial->setRestitution(0.0f); defaultMaterial->setStaticFriction(0.5f); defaultMaterial->setDynamicFriction(0.5f); } void CElementPhysX::Shutdown() { if(s_pNxScene) s_pNxPhysics->releaseScene(*s_pNxScene); if(s_pNxPhysics) { s_pNxPhysics->release(); s_pNxPhysics=LG_NULL; } } void CElementPhysX::SetupWorld(CLWorldMap* pMap) { if(s_pWorldActor) s_pNxScene->releaseActor(*s_pWorldActor); s_pWorldActor=LG_NULL; #if 0 //Test code... NxPlaneShapeDesc planeDesc; NxActorDesc actorDesc; actorDesc.shapes.pushBack(&planeDesc); s_pWorldActor=s_pNxScene->createActor(actorDesc); #elif 0 gLevelMesh.convertLevel(); // Build physical model NxTriangleMeshDesc levelDesc; levelDesc.numVertices = g_Level.m_numOfVerts; levelDesc.numTriangles = gLevelMesh.nbTriangles; levelDesc.pointStrideBytes = sizeof(tBSPVertex); levelDesc.triangleStrideBytes = 3*sizeof(NxU32); levelDesc.points = (const NxPoint*)&(g_Level.m_pVerts[0].vPosition); levelDesc.triangles = gLevelMesh.triangles; levelDesc.flags = 0; NxTriangleMeshShapeDesc levelShapeDesc; NxInitCooking(); if (0) { // Cooking from file bool status = NxCookTriangleMesh(levelDesc, UserStream("c:\\tmp.bin", false)); levelShapeDesc.meshData = gPhysicsSDK->createTriangleMesh(UserStream("c:\\tmp.bin", true)); } else { // Cooking from memory MemoryWriteBuffer buf; bool status = NxCookTriangleMesh(levelDesc, buf); levelShapeDesc.meshData = gPhysicsSDK->createTriangleMesh(MemoryReadBuffer(buf.data)); } NxActorDesc actorDesc; actorDesc.shapes.pushBack(&levelShapeDesc); NxActor* actor = gScene->createActor(actorDesc); actor->userData = (void*)1; return actor; #elif 1 lg_dword* pIndexes=new lg_dword[pMap->m_nVertexCount]; for(lg_dword i=0; i<pMap->m_nVertexCount; i++) { pIndexes[i]=i; } NxTriangleMeshDesc desc; desc.numTriangles=pMap->m_nVertexCount/3; desc.numVertices=pMap->m_nVertexCount; desc.pointStrideBytes=sizeof(LW_VERTEX); desc.triangleStrideBytes=sizeof(lg_dword)*3; desc.points=pMap->m_pVertexes; desc.triangles=pIndexes; NxActorDesc actorDesc; NxTriangleMeshShapeDesc triShape; NxInitCooking(); CLNxStream buf("/dbase/cook.bin", LG_FALSE); lg_bool status = NxCookTriangleMesh(desc, buf); buf.Close(); buf.Open("/dbase/cook.bin", LG_TRUE); triShape.meshData=s_pNxPhysics->createTriangleMesh(buf); actorDesc.shapes.pushBack(&triShape); s_pWorldActor=s_pNxScene->createActor(actorDesc); delete[]pIndexes; #endif } void CElementPhysX::Simulate(lg_float fSeconds) { s_pNxScene->simulate((NxReal)fSeconds); s_pNxScene->flushStream(); s_pNxScene->fetchResults(NX_RIGID_BODY_FINISHED, LG_TRUE); } void CLPhysXOutputStream::reportError(NxErrorCode code, const char* message, const char* file, int line) { Err_Printf("PhysX ERROR: %d: %s (%s.%d)", code, message, file, line); } NxAssertResponse CLPhysXOutputStream::reportAssertViolation(const char* message, const char* file, int line) { Err_Printf("PhysX ASSERT VIOLATION: %s (%s.%d)", message, file, line); return NX_AR_BREAKPOINT; } void CLPhysXOutputStream::print(const char* message) { Err_Printf("PhysX: %s", message); } <file_sep>/tools/img_lib/img_lib2/img_lib/img_bmp.c #include <malloc.h> #include <memory.h> #include "img_private.h" /* Structures used by bitmap files.*/ typedef struct _bmp_header_s { img_word nType; img_dword nSize; img_word nReserved1; img_word nReserved2; img_dword nOffsetBits; }bmp_header_s, *pbmp_header_s; typedef struct _bmp_info_header_s { img_dword biHeaderSize; img_long biWidth; img_long biHeight; img_word biPlanes; img_word biBitCount; img_dword biCompression; img_dword biSizeImage; img_long biXPelsPerMeter; img_long biYPelsPerMeter; img_dword biClrUsed; img_dword biClrImportant; }bmp_info_header_s, *pbmp_info_header_s; typedef struct _bmp_color_s{ img_byte b; img_byte g; img_byte r; img_byte a; }bmp_color_s, *pbmp_color_s; /* Function prototyes for bitmap files.*/ img_bool BMP_ReadHeaders( void* stream, IMG_CALLBACKS* lpCB, bmp_header_s* pHeader, bmp_info_header_s* pIH); img_bool BMP_Read24BitData(img_void* stream, IMG_CALLBACKS* pCB, IMAGE_S* lpImage); img_bool BMP_Read8BitData(img_void* stream, IMG_CALLBACKS* pCB, IMAGE_S* lpImage); img_bool BMP_Read4BitData(img_void* stream, IMG_CALLBACKS* pCB, IMAGE_S* lpImage); img_bool BMP_Read1BitData(img_void* stream, IMG_CALLBACKS* pCB, IMAGE_S* lpImage); img_bool BMP_DecodeRLE8(img_void* stream, IMG_CALLBACKS* pCB, IMAGE_S* lpImage); img_bool BMP_DecodeRLE4(img_void* stream, IMG_CALLBACKS* pCB, IMAGE_S* lpImage); /* The loading function.*/ HIMG IMG_LoadBMPCallbacks(img_void* stream, IMG_CALLBACKS* lpCB) { IMAGE_S* lpImage=IMG_NULL; bmp_header_s Header; bmp_info_header_s InfoHeader; memset(&Header, 0, sizeof(bmp_header_s)); memset(&InfoHeader, 0, sizeof(bmp_info_header_s)); //Seek to the beginning of the file. lpCB->seek(stream, 0, IMG_SEEK_SET); if(!BMP_ReadHeaders(stream, lpCB, &Header, &InfoHeader)) return IMG_FALSE; lpImage=malloc(sizeof(IMAGE_S)); if(!lpImage) return IMG_NULL; memset(lpImage, 0, sizeof(IMAGE_S)); lpImage->nWidth=(img_word)InfoHeader.biWidth; lpImage->nHeight=(img_word)InfoHeader.biHeight; lpImage->nBitDepth=(img_byte)InfoHeader.biBitCount; lpImage->nOrient=IMGORIENT_BOTTOMLEFT; switch(InfoHeader.biBitCount) { case 24: lpImage->nBitDepth=24; lpImage->nPaletteBitDepth=0; lpImage->nPaletteEntries=0; lpImage->nPaletteFmt=IMGFMT_NONE; lpImage->nDataFmt=IMGFMT_R8G8B8; break; case 8: lpImage->nBitDepth=8; lpImage->nPaletteBitDepth=32; lpImage->nPaletteFmt=IMGFMT_A8R8G8B8; lpImage->nPaletteEntries=256; lpImage->nDataFmt=IMGFMT_PALETTE; break; //Note that we will be converting all formats less than, //1 byte wide to 1 byte wide (8 bit). case 4: lpImage->nBitDepth=8; lpImage->nPaletteBitDepth=32; lpImage->nPaletteFmt=IMGFMT_A8R8G8B8; lpImage->nPaletteEntries=16; lpImage->nDataFmt=IMGFMT_PALETTE; break; case 2: lpImage->nBitDepth=8; lpImage->nPaletteBitDepth=32; lpImage->nPaletteFmt=IMGFMT_A8R8G8B8; lpImage->nPaletteEntries=4; lpImage->nDataFmt=IMGFMT_PALETTE; break; case 1: lpImage->nBitDepth=8; lpImage->nPaletteBitDepth=32; lpImage->nPaletteFmt=IMGFMT_A8R8G8B8; lpImage->nPaletteEntries=2; lpImage->nDataFmt=IMGFMT_PALETTE; break; default: lpImage->nBitDepth=0; lpImage->nPaletteBitDepth=0; lpImage->nPaletteFmt=IMGFMT_UNKNOWN; lpImage->nPaletteEntries=0; lpImage->nDataFmt=IMGFMT_UNKNOWN; break; } if(lpImage->nPaletteFmt==IMGFMT_UNKNOWN && lpImage->nDataFmt==IMGFMT_UNKNOWN) { free(lpImage); return IMG_NULL; } lpImage->nDataSize=lpImage->nWidth*lpImage->nHeight*lpImage->nBitDepth/8; lpImage->nPaletteSize=lpImage->nPaletteEntries*lpImage->nPaletteBitDepth/8; //Allocate memory for the palette and read the palette if there is one. if(lpImage->nDataFmt==IMGFMT_PALETTE) { bmp_color_s* pPalette=IMG_NULL; img_dword i=0; lpImage->pPalette=malloc(lpImage->nPaletteSize); if(!lpImage->pPalette) { free(lpImage); return IMG_NULL; } lpCB->read(lpImage->pPalette, 1, lpImage->nPaletteSize, stream); //We need to change the alpha channel on our palette images, cause //by default bitmaps ar at 0 which is completely transparent. pPalette=(bmp_color_s*)lpImage->pPalette; for(i=0; i<lpImage->nPaletteEntries; i++) { pPalette[i].a=0xFF; } } //Now allocate memory for the image and read it, not that we need to convert //for file formats. (We'll allocate an extra scanline, just becuse of some //bitmap formats that don't line up with 1 byte wide (namely 1 bit and 4 bit //bitmaps.) lpImage->pImage=malloc(lpImage->nDataSize+lpImage->nWidth*lpImage->nBitDepth/8); if(!lpImage->pImage) { IMG_SAFE_FREE(lpImage->pPalette); free(lpImage); return IMG_FALSE; } //Go to bitmap information. lpCB->seek(stream, Header.nOffsetBits, IMG_SEEK_SET); //Reading the data gets a little complicated. switch(InfoHeader.biBitCount) { case 24: BMP_Read24BitData(stream, lpCB, lpImage); break; case 8: if(InfoHeader.biCompression==1) BMP_DecodeRLE8(stream, lpCB, lpImage); else BMP_Read8BitData(stream, lpCB, lpImage); break; case 4: if(InfoHeader.biCompression==2) BMP_DecodeRLE4(stream, lpCB, lpImage); else BMP_Read4BitData(stream, lpCB, lpImage); break; case 2: break; case 1: BMP_Read1BitData(stream, lpCB, lpImage); break; } return (HIMG)lpImage; } /* BMP_ReadHeaders reads the headers, returns IMG_FALSE if the data read is not a valid bitmap file.*/ img_bool BMP_ReadHeaders( img_void* stream, IMG_CALLBACKS* lpCB, bmp_header_s* pHeader, bmp_info_header_s* pIH) { lpCB->seek(stream, 0, IMG_SEEK_SET); lpCB->read(&pHeader->nType, 2, 1, stream); lpCB->read(&pHeader->nSize, 4, 1, stream); lpCB->read(&pHeader->nReserved1, 2, 1, stream); lpCB->read(&pHeader->nReserved2, 2, 1, stream); lpCB->read(&pHeader->nOffsetBits, 4, 1, stream); /* Make sure this is a valid bitmap. */ if(pHeader->nType != *(unsigned short*)"BM") return IMG_FALSE; lpCB->read(&pIH->biHeaderSize, 4, 1, stream); lpCB->read(&pIH->biWidth, 4, 1, stream); lpCB->read(&pIH->biHeight, 4, 1, stream); lpCB->read(&pIH->biPlanes, 2, 1, stream); lpCB->read(&pIH->biBitCount, 2, 1, stream); lpCB->read(&pIH->biCompression, 4, 1, stream); lpCB->read(&pIH->biSizeImage, 4, 1, stream); lpCB->read(&pIH->biXPelsPerMeter, 4, 1, stream); lpCB->read(&pIH->biYPelsPerMeter, 4, 1, stream); lpCB->read(&pIH->biClrUsed, 4, 1, stream); lpCB->read(&pIH->biClrImportant, 4, 1, stream); /* { char szTemp[2048]; sprintf(szTemp, "Header Size: %d\nWidth: %d\nHieght: %d\nPlanes: %d\nBit Count: %d\nCompression: %d\nSize Image: %d\nXPelsPerMeter: %d\nYPelsPerMeter: %d\nClrUsed: %d\nClrImportant: %d", pIH->biHeaderSize, pIH->biWidth, pIH->biHeight, pIH->biPlanes, pIH->biBitCount, pIH->biCompression, pIH->biSizeImage, pIH->biXPelsPerMeter, pIH->biYPelsPerMeter, pIH->biClrUsed, pIH->biClrImportant); MessageBoxA(0, szTemp, 0, 0); } */ if((pIH->biHeaderSize != 40) || (pIH->biPlanes!=1)) { return IMG_FALSE; } return IMG_TRUE; } /* The following functions read the image data in various bitdepths, they assume that the file pointer for stream is at the beginning of the data. Note that images with a bitdepth less than 8 are converted to 8 bit.*/ img_bool BMP_Read24BitData(img_void* stream, IMG_CALLBACKS* pCB, IMAGE_S* lpImage) { img_dword i=0, j=0, nOffset=0; img_dword nLineWidth=0; void* pTempLine=IMG_NULL; //Find the width of each scanline. nLineWidth=lpImage->nWidth*3; while(nLineWidth%4) nLineWidth++; pTempLine=malloc(nLineWidth); if(!pTempLine) return IMG_FALSE; for(i=0; i<lpImage->nHeight; i++) { //Read each scanline. pCB->read(pTempLine, 1, nLineWidth, stream); //And copy it into the image data. nOffset=i*lpImage->nWidth*3; memcpy( (void*)((int)lpImage->pImage+nOffset), (int*)pTempLine, lpImage->nWidth*3); } IMG_SAFE_FREE(pTempLine); return IMG_TRUE; } img_bool BMP_Read8BitData(img_void* stream, IMG_CALLBACKS* pCB, IMAGE_S* lpImage) { img_dword i=0, j=0, nOffset=0; img_dword nLineWidth=0; void* pTempLine=IMG_NULL; //Find the width of each scanline. nLineWidth=lpImage->nWidth; //We need to dword align the image width. while(nLineWidth%4) nLineWidth++; pTempLine=malloc(nLineWidth); if(!pTempLine) return IMG_FALSE; for(i=0; i<lpImage->nHeight; i++) { //Read each scanline. pCB->read(pTempLine, 1, nLineWidth, stream); //And copy it into the image data. nOffset=i*lpImage->nWidth; memcpy( (void*)((int)lpImage->pImage+nOffset), (int*)pTempLine, lpImage->nWidth); } IMG_SAFE_FREE(pTempLine); return IMG_TRUE; } //The following code is not solid and could easily cause a crash if //corrupted data is input. img_bool BMP_DecodeRLE8(img_void* stream, IMG_CALLBACKS* pCB, IMAGE_S* lpImage) { img_byte* pDest=lpImage->pImage; img_byte nCount=0, nCode=0; img_dword i=0; img_word nLine=0; while(IMG_TRUE) { pCB->read(&nCount, 1, 1, stream); pCB->read(&nCode, 1, 1, stream); if(nCount==0) //Escape code. { if(nCode==0) //End of line. { nLine++; pDest=(img_byte*)lpImage->pImage+nLine*lpImage->nWidth; //Technically if there is anything left in the line it should //be assigned the background color. } else if(nCode==1) //End of bitmap code. { //Break out of loop. break; } else if(nCode==2) { //Not really sure if this code is correct, haven't encountered a bitmap //that uses it. img_byte x, y; pCB->read(&x, 1, 1, stream); pCB->read(&y, 1, 1, stream); nLine+=y; pDest+=x+y*lpImage->nWidth; } else //Absolute mode. { pCB->read(pDest, 1, nCode, stream); pDest+=nCode; //Seek to make sure we're word aligned. pCB->seek(stream, nCode%2, IMG_SEEK_CUR); } } else //Encode mode. { for(i=0; i<nCount; i++) { *pDest=nCode; pDest++; } } } return IMG_TRUE; } img_bool BMP_Read4BitData(img_void* stream, IMG_CALLBACKS* pCB, IMAGE_S* lpImage) { img_dword i=0, j=0, nOffset=0; img_dword nLineWidth=0; void* pTempLine=IMG_NULL; img_byte n2Pix=0; img_byte nPix[2]={0, 0}; //Find the width of each scanline. nLineWidth=lpImage->nWidth; if(nLineWidth%2) { nLineWidth/=2; nLineWidth++; } else nLineWidth/=2; while(nLineWidth%4) nLineWidth++; pTempLine=malloc(nLineWidth); if(!pTempLine) return IMG_FALSE; for(i=0; i<lpImage->nHeight; i++) { //Read each scanline. pCB->read(pTempLine, 1, nLineWidth, stream); //we have to change the pixel format to 8 bits. nOffset=i*lpImage->nWidth; for(j=0; j<lpImage->nWidth; j+=2) { img_dword nBytesToCopy=0; memcpy(&n2Pix, (void*)((int)pTempLine+j/2), 1); nPix[0]=(n2Pix&0xF0)>>4; nPix[1]=(n2Pix&0x0F)>>0; //For images with less than 8 bits we need to make sure //we're not writing past the edge of the scanline. nBytesToCopy=2; if((j+2)>lpImage->nWidth) { nBytesToCopy=2-(lpImage->nWidth-j); } memcpy( (void*)((int)lpImage->pImage+nOffset+j), &nPix[0], nBytesToCopy); } } IMG_SAFE_FREE(pTempLine); return IMG_TRUE; } img_bool BMP_DecodeRLE4(img_void* stream, IMG_CALLBACKS* pCB, IMAGE_S* lpImage) { img_byte* pDest=lpImage->pImage; img_byte nCount=0, nCode=0; img_dword i=0; img_word nLine=0; while(IMG_TRUE) { pCB->read(&nCount, 1, 1, stream); pCB->read(&nCode, 1, 1, stream); if(nCount==0) //Escape code. { if(nCode==0) //End of line. { nLine++; pDest=(img_byte*)lpImage->pImage+nLine*lpImage->nWidth; //Technically if there is anything left in the line it should //be assigned the background color. } else if(nCode==1) //End of bitmap code. { //Break out of loop. break; } else if(nCode==2) { //Not really sure if this code is correct, haven't encountered a bitmap //that uses it. img_byte x, y; pCB->read(&x, 1, 1, stream); pCB->read(&y, 1, 1, stream); nLine+=y; pDest+=x+y*lpImage->nWidth; } else //Absolute mode. { //This isn't right, it doesn't convert to 8 bit. pCB->read(pDest, 1, nCode, stream); pDest+=nCode; //Seek to make sure we're word aligned. pCB->seek(stream, nCode%2, IMG_SEEK_CUR); } } else //Encode mode. { for(i=0; i<nCount; i++) { if((i%2)) *pDest=nCode&0x0F; else *pDest=(nCode&0xF0)>>4; pDest++; } } } return IMG_TRUE; } img_bool BMP_Read1BitData(img_void* stream, IMG_CALLBACKS* pCB, IMAGE_S* lpImage) { img_dword i=0, j=0, nOffset=0; img_dword nLineWidth=0; void* pTempLine=IMG_NULL; img_byte n8Pix=0; img_byte nPix[8]={0, 0, 0, 0, 0, 0, 0, 0}; //Find the width of each scanline. //nLineWidth=lpImage->nWidth/8; nLineWidth=lpImage->nWidth; if(nLineWidth%8) { nLineWidth/=8; nLineWidth++; } else nLineWidth/=8; while(nLineWidth%4) nLineWidth++; pTempLine=malloc(nLineWidth); if(!pTempLine) return IMG_FALSE; for(i=0; i<lpImage->nHeight; i++) { //Read each scanline. pCB->read(pTempLine, 1, nLineWidth, stream); //we have to change the pixel format to 8 bits. nOffset=i*lpImage->nWidth; for(j=0; j<lpImage->nWidth; j+=8) { img_dword nBytesToCopy=0; memcpy(&n8Pix, (void*)((int)pTempLine+j/8), 1); nPix[0]=(n8Pix&0x80)>>7; nPix[1]=(n8Pix&0x40)>>6; nPix[2]=(n8Pix&0x20)>>5; nPix[3]=(n8Pix&0x10)>>4; nPix[4]=(n8Pix&0x08)>>3; nPix[5]=(n8Pix&0x04)>>2; nPix[6]=(n8Pix&0x02)>>1; nPix[7]=(n8Pix&0x01)>>0; //For less than 8 bit images we need to make sure that //we're not writing past the end of the scanline. nBytesToCopy=8; if((j+8)>lpImage->nWidth) { nBytesToCopy=8-(lpImage->nWidth-j); } memcpy( (void*)((int)lpImage->pImage+nOffset+j), &nPix[0], nBytesToCopy); } } IMG_SAFE_FREE(pTempLine); return IMG_TRUE; } <file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/lm_d3d.h #include <d3dx9.h> #include <d3d9.h> #include "lm_sys.h" //Some temporary bone rendering structures //and definitions. typedef struct _JOINTVERTEX{ float x, y, z; float psize; L_dword color; }JOINTVERTEX; #define JOINTVERTEX_FVF (D3DFVF_XYZ|D3DFVF_PSIZE|D3DFVF_DIFFUSE) typedef struct _BONEVERTEX{ float x, y, z; L_dword color; }BONEVERTEX; #define BONEVERTEX_FVF (D3DFVF_XYZ|D3DFVF_DIFFUSE) //void CreateBoneMatrices2(D3DXMATRIX* pMList, LMESH_BONE* pBoneList, L_dword nNumBones); class CLegacyMeshD3D: public CLegacyMesh { public: CLegacyMeshD3D(); L_bool Create(char* szFilename, IDirect3DDevice9* lpDevice); L_bool CreateD3DComponents(IDirect3DDevice9* lpDevice); L_bool Validate(); L_bool Invalidate(); L_bool Render(); L_bool RenderSkeleton(); L_bool SetupSkeleton(L_dword nFrame1, L_dword nFrame2, float fTime); L_bool PrepareFrame(L_dword dwFist, L_dword dwSecond, float fTime); virtual L_bool Unload(); private: IDirect3DDevice9* m_lpDevice; IDirect3DVertexBuffer9* m_lpVB; IDirect3DTexture9** m_lppTexs; L_bool m_bD3DValid; //Some structures to hold the stuff that is used every //frame but is only temporary. D3DXMATRIX* m_pAnimMats; //Some temp skeleton rendering stuff. JOINTVERTEX* m_pSkel; };<file_sep>/tools/CornerBin/CornerBin/MainFrm.cpp // MainFrm.cpp : implementation of the CMainFrame class // #include "stdafx.h" #include "CornerBin.h" #include "MainFrm.h" extern LPCTSTR g_strAPP_GUID; #ifdef _DEBUG #define new DEBUG_NEW #endif // CMainFrame IMPLEMENT_DYNAMIC(CMainFrame, CFrameWnd) BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) ON_WM_CREATE() ON_WM_SETFOCUS() ON_WM_TIMER() END_MESSAGE_MAP() // CMainFrame construction/destruction CMainFrame::CMainFrame(CCBSettings* pSettings) : m_pSettings(NULL) { m_pSettings = pSettings; } CMainFrame::~CMainFrame() { } int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CFrameWnd::OnCreate(lpCreateStruct) == -1) return -1; // create a view to occupy the client area of the frame if (!m_wndView.Create(NULL, NULL, AFX_WS_DEFAULT_VIEW, CRect(0, 0, 0, 0), this, AFX_IDW_PANE_FIRST, NULL)) { TRACE0("Failed to create view window\n"); return -1; } return 0; } BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) { if( !CFrameWnd::PreCreateWindow(cs) ) return FALSE; WNDCLASS cls; memset(&cls, 0, sizeof(cls)); cls.lpfnWndProc = AfxWndProc; cls.hInstance = cs.hInstance; cls.lpszClassName = g_strAPP_GUID; AfxRegisterClass(&cls); cs.style = 0; cs.dwExStyle =0; cs.lpszClass = g_strAPP_GUID;//AfxRegisterWndClass(0); cs.lpszName = _T("CornerBin"); return TRUE; } // CMainFrame diagnostics #ifdef _DEBUG void CMainFrame::AssertValid() const { CFrameWnd::AssertValid(); } void CMainFrame::Dump(CDumpContext& dc) const { CFrameWnd::Dump(dc); } #endif //_DEBUG // CMainFrame message handlers void CMainFrame::OnSetFocus(CWnd* /*pOldWnd*/) { // forward focus to the view window m_wndView.SetFocus(); } BOOL CMainFrame::OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo) { // let the view have first crack at the command if (m_wndView.OnCmdMsg(nID, nCode, pExtra, pHandlerInfo)) return TRUE; // otherwise, do default handling return CFrameWnd::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo); } BOOL CMainFrame::OnWndMsg(UINT message, WPARAM wParam, LPARAM lParam, LRESULT* pResult) { //Now process our custom messages if(WM_SYSTRAYNOTIFY == message) { switch(lParam) { case WM_RBUTTONDOWN: { DWORD nMenu = m_pSettings->GetSimpleMenu()?1:0; //Setting this to the foreground window insures that the menu will dissapear when clicked outside. this->SetForegroundWindow(); POINT pnt; GetCursorPos(&pnt); this->GetMenu()->GetSubMenu(nMenu)->TrackPopupMenu( TPM_BOTTOMALIGN|TPM_RIGHTALIGN, pnt.x, pnt.y, this); //The null message insures that the popup doesn't dissapear right away. this->PostMessage(WM_NULL); } break; case WM_RBUTTONDBLCLK: //Should open up the settings box. ((CCornerBinApp*)::AfxGetApp())->OpenSettingsDlg(); break; case WM_LBUTTONDBLCLK: ((CCornerBinApp*)::AfxGetApp())->OnDblClkTrayIcon(); break; } return TRUE; } else if (WM_EXTSETTINGSUP == message) { ((CCornerBinApp*)::AfxGetApp())->OpenSettingsDlg(); return TRUE; } return CFrameWnd::OnWndMsg(message, wParam, lParam, pResult); } void CMainFrame::OnTimer(UINT_PTR nIDEvent) { if(UPDATE_TIMER_ID == nIDEvent) { ((CCornerBinApp*)::AfxGetApp())->OnTimerUpdate(); } CFrameWnd::OnTimer(nIDEvent); } void CMainFrame::SetTimerUpdate(DWORD nFreq) { if(0 == nFreq) this->KillTimer(UPDATE_TIMER_ID); else this->SetTimer(UPDATE_TIMER_ID, nFreq, 0); } <file_sep>/games/Legacy-Engine/Scrapped/tools/warchiver/lf_file.c #include "lf_sys.h" <file_sep>/samples/D3DDemo/code/MD3Base/MD3Skin.cpp #define D3D_MD3 #include <stdio.h> #include "Defines.h" #include "Functions.h" #include "MD3.h" #define SKINSUC_READSUCCESS 0x00000001l #define SKINSUC_EOF 0x00000002l #define SKINSUC_FINISHED 0x00000003l #define SKINERR_NOTALINE 0x80000001l #define SKINERR_INVALIDFILE 0x80000002l CMD3TextureDB CMD3SkinFile::m_md3TexDB; HRESULT CMD3SkinFile::ClearTexDB() { return m_md3TexDB.ClearDB(); } HRESULT CMD3SkinFile::SetSkinRef( char szName[], DWORD dwRef) { DWORD i=0; if((dwRef < 0) || (dwRef >= m_dwNumSkins))return E_FAIL; for(i=0; i<m_dwNumSkins; i++){ if(strcmp(szName, m_lpSkins[i].szMeshName)==0){ m_lpSkinRef[dwRef]=i; break; } } m_bRefsSet=TRUE; return S_FALSE; } HRESULT CMD3SkinFile::GetTexturePointer( DWORD dwRef, LPDIRECT3DTEXTURE9 * lppTexture) { if((dwRef < 0) || (dwRef >= m_dwNumSkins)){ *lppTexture=NULL; return E_FAIL; } if(m_bRefsSet) { *lppTexture=m_lppTextures[m_lpSkinRef[dwRef]]; } else { *lppTexture=m_lppTextures[dwRef]; } if( (*lppTexture) ) (*lppTexture)->AddRef(); return S_OK; } HRESULT CMD3SkinFile::SetSkin( LPDIRECT3DDEVICE9 lpDevice, DWORD dwRef) { if((dwRef < 0) || (dwRef >= m_dwNumSkins))return E_FAIL; if(m_bRefsSet) lpDevice->SetTexture(0, m_lppTextures[m_lpSkinRef[dwRef]]); else{ lpDevice->SetTexture(0, NULL); return S_FALSE; } if(m_lppTextures[m_lpSkinRef[dwRef]]==NULL) return S_SKINNULL; else return S_OK; } CMD3SkinFile::CMD3SkinFile() { m_bLoaded=FALSE; m_lpSkins=NULL; m_lpSkinRef=NULL; m_bUseStaticDB=TRUE; m_bRefsSet=FALSE; m_dwNumSkins=0; m_lppTextures=NULL; } CMD3SkinFile::~CMD3SkinFile() { UnloadSkin(); } HRESULT CMD3SkinFile::ReadSkins( HANDLE hFile, DWORD dwNumSkinsToRead, DWORD * dwNumSkinsRead, DWORD dwFlags) { HRESULT hr=0; DWORD dwBytes=0; DWORD i=0; char szLine[MAX_PATH]; if(hFile==INVALID_HANDLE_VALUE) return E_FAIL; for(i=0; i<dwNumSkinsToRead; i++) { hr=ReadLine(hFile, szLine); if(FAILED(hr))return hr; if(hr!=SKINSUC_FINISHED) { ParseLine(&(m_lpSkins[i]), szLine); if((dwFlags&MD3SKINCREATE_REMOVEDIR)==MD3SKINCREATE_REMOVEDIR) RemoveDirectoryFromStringA(m_lpSkins[i].szSkinPath, m_lpSkins[i].szSkinPath); } } return S_OK; } HRESULT CMD3SkinFile::LoadSkinA( LPDIRECT3DDEVICE9 lpDevice, char szFilename[MAX_PATH], DWORD dwFlags, LPVOID lpTexDB) { HANDLE hFile=NULL; DWORD dwNumSkins=0; UnloadSkin(); hFile=CreateFileA( szFilename, GENERIC_READ, FILE_SHARE_READ, (LPSECURITY_ATTRIBUTES)NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, (HANDLE)NULL); if(hFile==INVALID_HANDLE_VALUE) return E_FAIL; dwNumSkins=GetNumLinesInFile(hFile); CreateSkinFile(dwNumSkins); ReadSkins(hFile, dwNumSkins, NULL, MD3SKINCREATE_REMOVEDIR); char szTexPath[MAX_PATH]; GetDirectoryFromStringA(szTexPath, szFilename); ObtainTextures(lpDevice, szTexPath, dwFlags, lpTexDB); return S_OK; } HRESULT CMD3SkinFile::LoadSkinW( LPDIRECT3DDEVICE9 lpDevice, WCHAR szFilename[MAX_PATH], DWORD dwFlags, LPVOID lpTexDB) { HANDLE hFile=NULL; DWORD dwNumSkins=0; UnloadSkin(); hFile=CreateFileW( szFilename, GENERIC_READ, FILE_SHARE_READ, (LPSECURITY_ATTRIBUTES)NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, (HANDLE)NULL); if(hFile==INVALID_HANDLE_VALUE) return E_FAIL; dwNumSkins=GetNumLinesInFile(hFile); CreateSkinFile(dwNumSkins); ReadSkins(hFile, dwNumSkins, NULL, MD3SKINCREATE_REMOVEDIR); WCHAR szTemp[MAX_PATH]; char szTexPath[MAX_PATH]; GetDirectoryFromStringW(szTemp, szFilename); WideCharToMultiByte(CP_ACP, 0, szTemp, -1, szTexPath, MAX_PATH, NULL, NULL); ObtainTextures(lpDevice, szTexPath, dwFlags, lpTexDB); return S_OK; } HRESULT CMD3SkinFile::ObtainTextures( LPDIRECT3DDEVICE9 lpDevice, char szTexPath[], DWORD dwFlags, LPVOID lpTexDB) { //The name and path to the texture. char szFilename[MAX_PATH]; DWORD i=0; DWORD dwLen=0; for(i=0; i<m_dwNumSkins; i++){ strcpy(szFilename, szTexPath); //Insure that there is a backslash at the end of the texture path. dwLen=strlen(szFilename); if(szFilename[dwLen-1] != '\\'){ szFilename[dwLen]='\\'; szFilename[dwLen+1]=0; MessageBox(0, szFilename, 0, 0); } //Attach the filename to the texture path. strcat(szFilename, m_lpSkins[i].szSkinPath); //If using static texture buffer create and/or obtain texture from //the static buffer if( (dwFlags&MD3SKINCREATE_STATICTEXDB)==MD3SKINCREATE_STATICTEXDB){ if(SUCCEEDED(m_md3TexDB.AddTexture(lpDevice, szFilename))){ if(SUCCEEDED(m_md3TexDB.GetTexture(m_lpSkins[i].szSkinPath, &m_lppTextures[i]))){ }else{ m_lppTextures[i]=NULL; } }else{ m_lppTextures[i]=NULL; } //If using dynamic buffer add texture to the parameter as database. }else if( (dwFlags&MD3SKINCREATE_DYNAMICTEXDB)==MD3SKINCREATE_DYNAMICTEXDB){ if(SUCCEEDED(((CMD3TextureDB*)lpTexDB)->AddTexture(lpDevice, szFilename))){ if(SUCCEEDED(((CMD3TextureDB*)lpTexDB)->GetTexture(m_lpSkins[i].szSkinPath, &m_lppTextures[i]))){ }else{ m_lppTextures[i]=NULL; } }else{ m_lppTextures[i]=NULL; } //If invalid parameter apply null to the texture. }else{ m_lppTextures[i]=NULL; } } if( (dwFlags&MD3SKINCREATE_STATICTEXDB)==MD3SKINCREATE_STATICTEXDB){ m_bUseStaticDB=TRUE; } else{ m_bUseStaticDB=FALSE; } return S_OK; } HRESULT CMD3SkinFile::UnloadSkin() { if(SUCCEEDED(DeleteSkinFile())){ m_dwNumSkins=0; return S_OK; } else return E_FAIL; } HRESULT CMD3SkinFile::CreateSkinFile(DWORD dwNumSkins) { DWORD i=0; m_dwNumSkins=dwNumSkins; m_lpSkins=(MD3SKIN*)malloc(sizeof(MD3SKIN)*dwNumSkins); m_lpSkinRef=(DWORD*)malloc(sizeof(DWORD)*dwNumSkins); for(i=0; i<dwNumSkins; i++){ m_lpSkinRef[i]=0; } m_lppTextures=(LPDIRECT3DTEXTURE9*)malloc(sizeof(LPDIRECT3DTEXTURE9)*dwNumSkins); for(i=0; i<dwNumSkins; i++){ m_lppTextures[i]=NULL; } return S_OK; } HRESULT CMD3SkinFile::DeleteSkinFile() { DWORD i=0; SAFE_FREE(m_lpSkins); SAFE_FREE(m_lpSkinRef); for(i=0; i<m_dwNumSkins; i++){ SAFE_RELEASE(m_lppTextures[i]); } SAFE_FREE(m_lppTextures); return S_OK; } BOOL CMD3SkinFile::ParseLine(MD3SKIN * skinout, LPSTR szLineIn) { DWORD dwLineLen=0; BOOL bSecondPart=FALSE; DWORD i=0; DWORD nStringPos=0; dwLineLen=strlen(szLineIn); for(i=0; i<dwLineLen; i++, nStringPos++){ if( szLineIn[i] == ',' ){ skinout->szMeshName[nStringPos]=0; i++; nStringPos=0; bSecondPart=TRUE; } if(!bSecondPart) skinout->szMeshName[nStringPos]=szLineIn[i]; else skinout->szSkinPath[nStringPos]=szLineIn[i]; } skinout->szSkinPath[nStringPos]=0; return TRUE; } <file_sep>/games/Legacy-Engine/Source/engine/lg_err.h #ifndef __L_ERROR_H__ #define __L_ERROR_H__ #include "lg_types.h" #ifdef __cplusplus extern "C"{ #endif __cplusplus #define MAX_ERR_MSG_LEN (1024) void Err_Printf(const char* format, ...); void Err_IncTab(); void Err_DecTab(); void Err_MsgPrintf(const char* format, ...); void Err_PrintfDebug(const char* format, ...); void Err_PrintDX(const char* function, lg_result result); void Err_ErrBox(const char* format, ...); void Err_PrintMatrix(void* pM); void Err_PrintVersion(); void __cdecl Err_FSCallback(lg_cwstr szString); #ifdef __cplusplus } #endif __cplusplus #endif /*__L_ERROR_H__*/<file_sep>/games/Legacy-Engine/Source/common/common.c /*************************************************************** File: common.c Copyright (c) 2006, <NAME> Purpose: All of the types and functions that are universal are contained in common.c and common.h. These two files are used not just for Legacy Engine, but for lc_sys.dll and la_sys.dll, as well as others. ***************************************************************/ #include "common.h" //#include <direct.h> #include <stdlib.h> #ifdef _DEBUG #include <windows.h> #include <stdio.h> #include <stdarg.h> //void __stdcall OutputDebugStringA(const char* lpOutputString); #ifdef _UNICODE //void __stdcall OutputDebugStringW(const char* lpOutputString); #endif _UNICODE #endif /*_DEBUG*/ lg_char* L_GetNameFromPath(lg_char* szName, const char* szFilename) { lg_dword dwLen=L_strlenA(szFilename); lg_dword i=0, j=0; for(i=dwLen; i>0; i--) { if(szFilename[i]=='\\' || szFilename[i]=='/') { i++; break; } } for(j=0 ;i<dwLen+1; i++, j++) { szName[j]=szFilename[i]; } return szName; } lg_char* L_GetShortNameFromPath(lg_char* szName, const char* szFilename) { lg_dword dwLen=L_strlenA(szFilename); lg_dword i=0, j=0; for(i=dwLen; i>0; i--) { if(szFilename[i]=='\\' || szFilename[i]=='/') { i++; break; } } for(j=0 ;i<dwLen+1; i++, j++) { szName[j]=szFilename[i]; if(szName[j]=='.') { szName[j]=0; break; } } return szName; } char* L_GetPathFromPath(char* szDir, const char* szFilename) { lg_dword dwLen=L_strlenA(szFilename); lg_long i=0; for(i=(lg_long)dwLen-1; i>=0; i--) { if(szFilename[i]=='\\' || szFilename[i]=='/') break; } L_strncpy(szDir, szFilename, i+2); return szDir; } char* L_strncat(char* szDest, const char* szSrc, unsigned long nMax) { lg_dword dwLen=L_strlenA(szDest); L_strncpy(&szDest[dwLen], szSrc, nMax-dwLen); return szDest; } /******************************************************************* L_CopyString() Copies a string, up till a 0 is reached or the max is reached whichever comes first. Appends a null terminating character at the end of the string. Returns the number of characters copied. *******************************************************************/ unsigned long L_strncpy(char* szOut, const char* szIn, unsigned long nMax) { unsigned long i=0; if((szOut==LG_NULL) || (szIn==LG_NULL)) return 0; for(i=0; szIn[i]!=0, i<nMax; i++) { szOut[i]=szIn[i]; } if(i<nMax) szOut[i]=0; else szOut[nMax-1]=0; return i; } /********************************************** lg_strnlen() Returns the length of the specified string. **********************************************/ lg_dword L_strlenA(const lg_char* string) { lg_dword count=0; while (string[count]) count++; return count; } lg_dword L_strlenW(const lg_wchar* string) { lg_dword count=0; while (string[count]) count++; return count; } /************************************************************ L_strnicmp() Compare two strings without regard to case of a certain number of characters long. Returns 0 if not the same, otherwize returns nonzero. This function is not used in exactly the same way that the _strnicmp stdlib function is used. ************************************************************/ int L_strnicmp(const char* szOne, const char* szTwo, unsigned long nNum) { unsigned long i=0; unsigned long nLen1=0, nLen2=0; char c1=0, c2=0; if((szOne==LG_NULL) || (szTwo==LG_NULL)) return 0; nLen1=L_strlenA(szOne); nLen2=L_strlenA(szTwo); if(nNum>0) { if(nLen1>nNum) nLen1=nNum; if(nLen2>nNum) nLen2=nNum; } if(nLen1!=nLen2) return 0; for(i=0; i<nLen1; i++) { if(szOne[i]!=szTwo[i]) { c1=szOne[i]; c2=szTwo[i]; if( (c1>='a') && (c1<='z') ) c1 -= ('a'-'A'); if( (c2>='a') && (c2<='z') ) c2 -= ('a'-'A'); if(c1==c2) continue; return 0; } } return 1; } /***************************************************** L_axtol() Converts a hexidecimal string to a unsigned long. *****************************************************/ unsigned long L_axtol(char* string) { int i=0; char c=0; unsigned long nHexValue=0; /*int sign=1;*/ /*sign=(string[0]=='-')?-1:1;*/ /* Make sure it is actually a hex string. */ if(!L_strnicmp("0X", string, 2)/* && !L_StringICompare("-0X", string, 3)*/) return 0x00000000l; /* The idea behind this is keep adding to value, until we reach an invalid character, or the end of the string. */ for(i=2/*(sign>0)?2:3*/, nHexValue=0x00000000; string[i]!=0; i++) { c=string[i]; if(c>='0' && c<='9') nHexValue=(nHexValue<<4)|(c-'0'); else if(c>='a' && c<='f') nHexValue=(nHexValue<<4)|(c-'a'+10); else if(c>='A' && c<='F') nHexValue=(nHexValue<<4)|(c-'A'+10); else break; } return /*sign**/nHexValue; } /******************************************* L_atof() Converts a string to a floating point. *******************************************/ float L_atof(char* string) { /* Check for a hexidecimal value. */ int sign=1; int i=0; float fValue=0.0f; signed long total=0, decimal=0; double value=0.0f; char c=0; /* Check for sign. */ sign=(string[0]=='-')?-1:1; for(i=(sign>0)?0:1, total=0, value=0.0f, decimal=-1; ;i++) { c=string[i]; if(c=='.') { decimal=total; continue; } if(c<'0' || c>'9') break; value=value*10+(c-'0'); total++; } if (decimal==-1) return (float)(value*sign); while(total>decimal) { value /= 10; total--; } return(float)(value*sign); } /************************************************************* L_atovalue() Converts a string to a floating point, but checks to see if the value is a hexidecimal. *************************************************************/ float L_atovalue(char* string) { /* Check to see if it is a hex. */ if((string[0]=='0') && (string[1]=='x' || string[1]=='X')) return (float)L_axtol(string); /* Figure its a float*/ return (float)L_atof(string); } /**************************************** L_atol() Converts a string to a long. *****************************************/ signed long L_atol(char* string) { signed long lValue=0; char c=0; int i=0; int sign=1; sign=(string[0]=='-')?-1:1; for(i=(sign>0)?0:1, lValue=0; ;i++) { c=string[i]; if(c<'0' || c>'9') break; lValue=lValue*10+c-'0'; } return sign*lValue; } /************************************* lg_strtok Replacement for stdc strtok *************************************/ char* L_strtokA(char* strToken, char* strDelimit, char cIgIns) { static char* szString=LG_NULL; static char* szDelimit=LG_NULL; static lg_dword nPosition=0; static char cIgnore=0; lg_bool bIgnoring=LG_FALSE; lg_bool bFoundFirst=LG_FALSE; lg_bool bIgnoreIsDel=LG_FALSE; lg_dword i=0, j=0; lg_dword nStrLen=0, nDelLen=0; cIgnore=(cIgIns==' ' || cIgIns==0)?cIgnore:cIgIns; if(strToken) { szString=strToken; nPosition=0; } if(strDelimit) { szDelimit=strDelimit; } if(!szString || !szDelimit) return LG_NULL; szString=&szString[nPosition]; nDelLen=L_strlenA(szDelimit); nStrLen=L_strlenA(szString); for(i=0; i<nDelLen; i++) { if(cIgnore==szDelimit[i]) bIgnoreIsDel=LG_TRUE; } for(i=0; i<nStrLen ;i++) { if(szString[i]==cIgnore) { bIgnoring=!bIgnoring; if(!bFoundFirst) { if(bIgnoreIsDel) i++; szString=&szString[i]; i=0; nStrLen=L_strlenA(szString); bFoundFirst=LG_TRUE; } } if(bIgnoring) continue; if(bFoundFirst) { for(j=0; j<nDelLen; j++) { if(bFoundFirst) { if(szString[i]==szDelimit[j]) { szString[i]=0; nPosition=i+1; return szString; } } } } else { for(j=0; j<nDelLen; j++) { if(szString[i]==szDelimit[j]) { bFoundFirst=LG_TRUE; } } if(bFoundFirst) bFoundFirst=LG_FALSE; else { szString=&szString[i]; i=0; nStrLen=L_strlenA(szString); bFoundFirst=LG_TRUE; } } } //If we got to the end of the string... nPosition=nStrLen; return szString; } lg_wchar* L_strtokW(lg_wchar* strToken, lg_wchar* strDelimit, lg_wchar cIgIns) { static lg_wchar* szString=LG_NULL; static lg_wchar* szDelimit=LG_NULL; static lg_dword nPosition=0; static lg_wchar cIgnore=0; lg_bool bIgnoring=LG_FALSE; lg_bool bFoundFirst=LG_FALSE; lg_bool bIgnoreIsDel=LG_FALSE; lg_dword i=0, j=0; lg_dword nStrLen=0, nDelLen=0; cIgnore=(cIgIns==' ' || cIgIns==0)?cIgnore:cIgIns; if(strToken) { szString=strToken; nPosition=0; } if(strDelimit) { szDelimit=strDelimit; } if(!szString || !szDelimit) return LG_NULL; szString=&szString[nPosition]; nDelLen=L_strlenW(szDelimit); nStrLen=L_strlenW(szString); for(i=0; i<nDelLen; i++) { if(cIgnore==szDelimit[i]) bIgnoreIsDel=LG_TRUE; } for(i=0; i<nStrLen ;i++) { if(szString[i]==cIgnore) { bIgnoring=!bIgnoring; if(!bFoundFirst) { if(bIgnoreIsDel) i++; szString=&szString[i]; i=0; nStrLen=L_strlenW(szString); bFoundFirst=LG_TRUE; } } if(bIgnoring) continue; if(bFoundFirst) { for(j=0; j<nDelLen; j++) { if(bFoundFirst) { if(szString[i]==szDelimit[j]) { szString[i]=0; nPosition=i+1; return szString; } } } } else { for(j=0; j<nDelLen; j++) { if(szString[i]==szDelimit[j]) { bFoundFirst=LG_TRUE; } } if(bFoundFirst) bFoundFirst=LG_FALSE; else { szString=&szString[i]; i=0; nStrLen=L_strlenW(szString); bFoundFirst=LG_TRUE; } } } //If we got to the end of the string... nPosition=nStrLen; return szString; } /********************************************* Debug_printf() In debug mode with print a string to the debugger window. *********************************************/ void Debug_printfA(char* format, ...) { #ifdef _DEBUG char szOutput[1024]; va_list arglist=LG_NULL; /* Allocate memory for output, we free when we exit the function. */ if(!format) return; /* We use _vsnprintf so we can print arguments, and also so we can limit the number of characters, put to the output buffer by the max string length allowed in the console. */ va_start(arglist, format); _vsnprintf(szOutput, 1023, format, arglist); va_end(arglist); OutputDebugStringA(szOutput); #endif /* _DEBUG */ } void Debug_printfW(lg_wchar_t* format, ...) { #ifdef _DEBUG wchar_t szOutput[1024]; va_list arglist=LG_NULL; /* Allocate memory for output, we free when we exit the function. */ if(!format) return; /* We use _vsnprintf so we can print arguments, and also so we can limit the number of characters, put to the output buffer by the max string length allowed in the console. */ va_start(arglist, format); _vsnwprintf(szOutput, 1023, format, arglist); va_end(arglist); OutputDebugStringW(szOutput); #endif /* _DEBUG */ } <file_sep>/tools/CornerBin/CornerBin/IconDlg/Resource.h //{{NO_DEPENDENCIES}} // Microsoft Developer Studio generated include file. // Used by IconDlgTest.rc // #define IDS_ICO_FILTER 1 #define IDS_ICO_CAPTION 2 #define IDBROWSE 3 #define IDS_NO_ICONS 3 #define IDS_PLEASE_SELECT_ICON 4 #define IDS_NOT_A_FILE 5 #define IDD_ICONDLGTEST 102 #define IDR_POPUP_ICON 103 #define IDR_MAINFRAME 128 #define IDD_CHOOSE_ICON 129 #define IDC_FILENAME 1000 #define IDC_SHOW 1002 #define IDC_ICONLIST 1004 #define IDC_SELECTED_ICON 1005 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 132 #define _APS_NEXT_COMMAND_VALUE 32772 #define _APS_NEXT_CONTROL_VALUE 1006 #define _APS_NEXT_SYMED_VALUE 104 #endif #endif <file_sep>/games/Legacy-Engine/Source/LMEdit/AnimDialog.h #pragma once #include "afxcmn.h" #include "afxwin.h" // CAnimDialog dialog class CAnimDialog : public CDialog { DECLARE_DYNAMIC(CAnimDialog) public: CAnimDialog(CWnd* pParent = NULL); // standard constructor virtual ~CAnimDialog(); // Dialog Data enum { IDD = ID_ANIM_DIALOG }; enum { ANIM_NAME=0, ANIM_FIRST_FRAME=1, ANIM_NUM_FRAMES=2, ANIM_LOOPING_FRAMES=3, ANIM_RATE=4, ANIM_FLAGS=5}; typedef TCHAR NUMBER_STRING[32]; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support DECLARE_MESSAGE_MAP() public: virtual BOOL OnInitDialog(); CLSkel2* m_pSkel; public: void SetSkel(CLSkel2* pSkel); public: BOOL AddAnimation(const CLSkel2::SkelAnim* pAnim); public: afx_msg void OnBnClickedAddAnim(); public: afx_msg void OnBnClickedDeleteAnim(); BOOL ModifySkeleton(void); public: CListCtrl m_ListCtrl; public: CComboBox m_cLoopBox; }; <file_sep>/games/Legacy-Engine/Source/lc_sys2/lc_con.h #ifndef __LC_CON_H__ #define __LC_CON_H__ #include "lc_sys2.h" #include "lc_def.h" #define LC_MAX_LINE_LEN 127 #define LC_MAX_CMD_ARGS 8 class CConsole { friend void LC_Printf(lg_char* szFormat, ...); friend void LC_SendCommandf(lg_char* szFormat, ...); friend lg_dword LC_FUNC LC_GetNumLines(); private: enum GET_LINE_MODE{GET_NONE=0, GET_OLDER, GET_NEWER}; struct LC_LINE{ lg_char szLine[LC_MAX_LINE_LEN+1]; LC_LINE* pOlder; LC_LINE* pNewer; }; struct LC_ARGS{ lg_dword nArgCount; lg_char szArg[LC_MAX_CMD_ARGS+1][LC_MAX_LINE_LEN+1]; }; private: lg_char m_szActiveLine[LC_MAX_LINE_LEN+1]; lg_dword m_nActiveCursorPos; LC_LINE* m_pNewestLine; LC_LINE* m_pOldestLine; lg_dword m_nLineCount; LC_CMD_FUNC m_pfnCmd; lg_void* m_pCmdExtra; GET_LINE_MODE m_nGetLineMode; LC_LINE* m_pGetLine; CDefs m_Commands; void AddEntry(lg_char* szText); static void SimpleParse1(lg_char* szLine); public: CConsole(); ~CConsole(); void SetCommandFunc(LC_CMD_FUNC pfn, lg_void* pExtra); void Clear(); void Print(lg_char* szText); void Printf(lg_char* szFormat, ...); void SendCommand(lg_char* szCmd); void SendCommandf(lg_char* szFormat, ...); void OnChar(lg_char c); const lg_char* GetLine(lg_dword nRef, const lg_bool bStartWithNew); const lg_char* GetNewestLine(); const lg_char* GetOldestLine(); const lg_char* GetNextLine(); const lg_char* GetActiveLine(); lg_bool RegisterCommand(const lg_char* szCommand, lg_dword nID, const lg_char* szHelpString); void ListCommands(); private: static lg_char s_szTemp[LC_MAX_LINE_LEN+1]; static lg_char s_szTemp2[LC_MAX_LINE_LEN+1]; //static lg_char s_szArgs[sizeof(lg_tchar)*(LC_MAX_CMD_ARGS+1)+LC_MAX_LINE_LEN+1]; static LC_ARGS s_Args; public: static const lg_char* GetArg(lg_dword nParam, lg_void* pParams); static lg_bool CheckArg(const lg_char* string, lg_void* args); }; #endif __LC_CON_H__<file_sep>/games/Legacy-Engine/Scrapped/libs/tga_lib/tga_lib.h /* lv_tga.h - TGA file support for Legacy 3D. */ #ifndef __LV_TGA_H__ #define __LV_TGA_H__ #ifdef __cplusplus extern "C"{ #endif /*__cplusplus*/ typedef void* HTGAIMAGE; typedef struct _TGA_CALLBACKS{ int (__cdecl *close)(void* stream); int (__cdecl *seek)(void* stream, long offset, int origin); long (__cdecl *tell)(void* stream); unsigned int (__cdecl *read)(void* buffer, unsigned int size, unsigned int count, void* stream); }TGA_CALLBACKS, *PTGA_CALLBACKS; typedef enum _TGAORIENT{ TGAORIENT_BOTTOMLEFT=0, TGAORIENT_BOTTOMRIGHT=1, TGAORIENT_TOPLEFT=2, TGAORIENT_TOPRIGHT=3 }TGAORIENT; typedef enum _TGAFMT{ TGAFMT_UNKNOWN=0, TGAFMT_NONE=0, TGAFMT_PALETTE=1, TGAFMT_X1R5G5B5=2, TGAFMT_R5G6B5=3, TGAFMT_R8G8B8=4, TGAFMT_A8R8G8B8=5 }TGAFMT; typedef enum _TGAFILTER{ TGAFILTER_NONE=0, TGAFILTER_POINT=0, TGAFILTER_LINEAR=1 }TGAFILTER; typedef struct _TGA_DESC{ unsigned short Width; unsigned short Height; unsigned char BitsPerPixel; unsigned short NumCMEntries; unsigned char ColorMapBitDepth; }TGA_DESC, *PTGA_DESC; HTGAIMAGE TGA_OpenCallbacks(void* stream, TGA_CALLBACKS* lpFuncs); HTGAIMAGE TGA_Open(char* szFilename); int TGA_Delete(HTGAIMAGE hImage); int TGA_GetDesc( HTGAIMAGE hImage, TGA_DESC* lpDescript); int TGA_CopyBits( HTGAIMAGE hImage, void* lpOut, TGAORIENT nOrient, TGAFMT Format, unsigned short nWidth, unsigned short nHeight, unsigned short nPitch, unsigned char nExtra); int TGA_CopyBitsStretch( HTGAIMAGE hImage, TGAFILTER Filter, void* lpOut, TGAORIENT nOrient, TGAFMT Format, unsigned short nWidth, unsigned short nHeight, unsigned short nPitch, unsigned char nExtra); int TGA_GetPalette( HTGAIMAGE hImage, void* lpDataOut); void* TGA_CreateDIBitmap(char* szFilename, void* hdc); #ifdef __cplusplus } #endif /*__cplusplus*/ #endif /*__LV_TGA_H__*/<file_sep>/games/Legacy-Engine/Scrapped/UnitTests/lf_sys2_test/main.cpp //#define UNICODE //#define _UNICODE #include <conio.h> #include <direct.h> #include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <tchar.h> #include <time.h> #include "lf_sys2.h" FILE* fout=NULL; void __cdecl Debug_PrintfW(lf_cwstr szFormat) { lf_char szString[512]; wcstombs(szString, szFormat, 511); printf("FS: %s\n", szString); if(fout) fprintf(fout, "%s\r\n", szString); } void CreateAlwaysTest() { char szString[1024]; time_t tm; LF_FILE3 File=LF_NULL; time(&tm); sprintf(szString, "This file is always created. %s.\r\n", ctime(&tm)); File=LF_Open(_T("/Create Always.txt"), LF_ACCESS_READ|LF_ACCESS_WRITE, LF_CREATE_ALWAYS); if(!File) return; LF_Write(File, szString, strlen(szString)); LF_Close(File); } void CreateNewTest() { char szString[1024]; LF_FILE3 File=LF_NULL; time_t tm; time(&tm); sprintf(szString, "This file is new created. %s.\r\n", ctime(&tm)); File=LF_Open(_T("/Create New.txt"), LF_ACCESS_READ|LF_ACCESS_WRITE, LF_CREATE_NEW); if(!File) return; LF_Write(File, szString, strlen(szString)); LF_Close(File); } void OpenExistingTest() { LF_FILE3 Existing, Out; Existing=LF_Open(_T("/Existing File.txt"), LF_ACCESS_READ, LF_OPEN_EXISTING); if(!Existing) return; Out=LF_Open(_T("/Create Always Out.txt"), LF_ACCESS_WRITE, LF_CREATE_ALWAYS); if(!Out) { LF_Close(Existing); return; } while(!LF_IsEOF(Existing)) { lf_byte data[12]; lf_dword nRead=LF_Read(Existing, data, 12); LF_Write(Out, data, nRead); } LF_Close(Existing); LF_Close(Out); } void OpenArchiveFilesTest() { LF_FILE3 Cmp, UnCmp; UnCmp=LF_Open(_T("/Existing File Archived Uncompressed.txt"), LF_ACCESS_READ, LF_OPEN_EXISTING); if(!UnCmp) return; Cmp=LF_Open(_T("/Existing File Archived Compressed.txt"), LF_ACCESS_READ, LF_OPEN_EXISTING); if(!Cmp) { LF_Close(UnCmp); return; } printf("Uncompressed Contents:\n\n"); while(!LF_IsEOF(UnCmp)) { char szData[41]; //pFile->Read(szSample, 20); szData[LF_Read(UnCmp, szData, 40)]=0; printf("%s", szData); } printf("Compressed Contents:\n\n"); while(!LF_IsEOF(Cmp)) { char szData[41]; //pFile->Read(szSample, 20); szData[LF_Read(Cmp, szData, 40)]=0; printf("%s", szData); } printf("\n\n"); LF_Close(UnCmp); LF_Close(Cmp); } int _tmain(int argc, TCHAR *argv[], TCHAR *envp[]) { fout=fopen("out.txt", "w"); //LF_SetErrLevel(ERR_LEVEL_NOTICE); LF_SetErrPrintFn(Debug_PrintfW); FS_Initialze(); FS_MountBase(_T(".\\")); FS_MountLPK(_T("/Test.lpk"), 0); FS_Mount(_T("base"), _T("/base1"), MOUNT_MOUNT_SUBDIRS); FS_MountLPK(_T("/base1/pak00.lpk"), MOUNT_FILE_OVERWRITELPKONLY); FS_MountLPK(_T("/base1/pak01.lpk"), MOUNT_FILE_OVERWRITELPKONLY); FS_PrintMountInfo(); //CreateAlwaysTest(); //CreateNewTest(); //OpenExistingTest(); //OpenArchiveFilesTest(); FS_Shutdown(); fclose(fout); _getch(); return 0; } <file_sep>/tools/fs_sys2/fs_mem.cpp /* Memory allocation. */ #include "fs_sys2.h" #include "fs_internal.h" static FS_ALLOC_FUNC g_pMalloc=0; static FS_FREE_FUNC g_pFree=0; extern "C" void FS_SetMemFuncs(FS_ALLOC_FUNC pAlloc, FS_FREE_FUNC pFree) { g_pMalloc=pAlloc; g_pFree=pFree; } extern "C" void* FS_Malloc(fs_size_t size, LF_ALLOC_REASON reason, const fs_char8*const type, const fs_char8*const file, const fs_uint line) { if(g_pMalloc) { return g_pMalloc(size, reason, type, file, line); } else { __debugbreak(); return FS_NULL; } } extern "C" void FS_Free(void* p, LF_ALLOC_REASON reason) { if(g_pFree) { return g_pFree(p, reason); } else { __debugbreak(); } } void* IFsMemObj::operator new(fs_size_t Size) { return FS_Malloc(Size, LF_ALLOC_REASON_SYSTEM, "FS", __FILE__, __LINE__); } void IFsMemObj::operator delete(void* pData) { FS_Free(pData, LF_ALLOC_REASON_SYSTEM); } <file_sep>/Misc/DBXExporter/DBXExporter/oedbx/library/oedbx/dbxFolderList.h //*************************************************************************************** #ifndef dbxFolderListH #define dbxFolderListH #include <oedbx/dbxCommon.h> //*************************************************************************************** const int1 DbxFolderListSize = 0x68, DbxFolderListEntries = DbxFolderListSize >> 2; const int1 flFolderInfo = 0x15, flNextFolderListNode = 0x17, flPreviousFolderListNode = 0x18; class AS_EXPORT DbxFolderList { public : DbxFolderList(InStream ins, int4 address); int4 GetValue(int1 index) const { if(index>=DbxFolderListEntries) throw DbxException("Index to big !"); return Buffer[index]; } void ShowResults(OutStream outs) const; private : void readFolderList(InStream ins); //data int4 Address; int4 Buffer[DbxFolderListEntries]; }; //*********************************************** #endif dbxFolderListH <file_sep>/games/Explor2002/Source_Old/ExplorED DOS/dosexplored/OPENFILE.CPP #include "openmap.h" #include "explored.h" int LoadMap(char templist[13]) /* LoadMap generates a scrolling list of filenames which you can select and load. Changes char array described by templist to the filename returns 0 if successfully preformed -1 if failed. */ { char thelist[MAXFLIST][FNAMELEN]; int i; int highcount; int lownum=0; int selection = 0; int button; Initialize(); highcount = GenList(thelist); printList(thelist, 0, highcount); setcolor(RED); outtextxy(1, 35, "--->"); do{ setcolor(WHITE); button = getch(); switch(button){ case UP: if(selection > lownum){ if(selection != 0){ selection--; setcolor(RED); outtextxy(1, 35+16*(selection-lownum), "--->"); setcolor(BLACK); outtextxy(1, 35+16*((selection+1)-lownum), "--->"); setcolor(WHITE); } }else{ if(selection > 0){ lownum--; printList(thelist,lownum, highcount); selection--; } } break; case DOWN: if(selection < (lownum+MAXTODISP-1)){ if(selection != (highcount-1)){ selection++; setcolor(RED); outtextxy(1, 35+16*(selection-lownum), "--->"); setcolor(BLACK); outtextxy(1, 35+16*((selection-1)-lownum), "--->"); setcolor(WHITE); } }else{ if(selection < highcount-1){ lownum++; printList(thelist,lownum, highcount); selection++; } } break; case 27: return -1; break; case 13: clrscr(); strcpy(templist, thelist[selection]); closegraph(); return 0; break; default: ; } }while(1); return 0; } int printList(char listtoprint[MAXFLIST][FNAMELEN], int startposition, int maximum) /* Prints a list of length MAXTODISP on the screen. The list it prints must come from a multiple dimensional string array each string no more than 13 characters in length. Prints starting from teh startposition in the array. */ { int looping; gotoxy(1, 1); printf("Directory Listing of *.map"); for(looping = 0; looping < MAXTODISP; looping++){ if(looping == maximum){ return 1; } gotoxy(5, looping+3); printf("File #%d: %s ", startposition+1, listtoprint[startposition]); startposition++; } return 0; } int GenList(char templist[MAXFLIST][FNAMELEN]) /* Generates a list of files and copies them to the array labeld by templist it then returns the number of files. */ { struct find_t files; int numfiles; int i; char filelist[MAXFLIST][13]; _dos_findfirst("*.map",_A_NORMAL,&files); numfiles = 0; do{ strcpy(filelist[numfiles], files.name); numfiles++; } while (_dos_findnext(&files) == 0); for (i=0; i<numfiles; i++){ strcpy(templist[i], filelist[i]); } return numfiles; }<file_sep>/games/Legacy-Engine/Source/engine/lg_sys.h #ifndef __LG_SYS2_H__ #define __LG_SYS2_H__ #include "lv_con.h" #include "ls_sys.h" //#include "lw_sys.h" #include "lv_sys.h" #include "lt_sys.h" #include "li_sys.h" #include "lw_server.h" #include "lw_client.h" #include "lg_mgr.h" #include "lc_sys2.h" #include "wnd_sys/wnd_manager.h" #define LGAME_NAME "Legacy Game Engine" #define LGAME_VERSION "1.00" const char g_GameString[]=LGAME_NAME " BUILD " LGAME_VERSION " (" __DATE__ " " __TIME__ ")"; class CLGame: private CElementD3D, private CElementTimer, private CLMgrs { friend void LGC_DisplayDeviceCaps(CLGame* pGame); private: //Legacy Game Error Codes... #define LG_FAIL 0x80000001 #define LG_SHUTDOWN 0x80000010 #define LG_V_OR_S_DISABLED 0x80000020 #define LG_OK 0x00000001 #define LVERR_NODEVICE 0x80000010 #define LVERR_DEVICELOST 0x80000000 #define LVERR_CANTRECOVER 0x80000001 #define LVERR_DEVICERESET 0x80000002 public: enum LGSTATE{ LGSTATE_UNKNOWN=0, LGSTATE_NOTSTARTED=1, LGSTATE_RUNNING=2, LGSTATE_SHUTDOWN=3, LGSTATE_FORCE_DWORD=0xFFFFFFFF }; enum LGTYPE{ LGTYPE_CLIENT=0, LGTYPE_SERVER_CLIENT=1, LGTYPE_SERVER=2 }; private: LGSTATE m_nGameState; LGTYPE m_nGameType; HWND m_hwnd; public: //The video manager CLVideo m_Video; private: //The graphic console. CLVCon m_VCon; //The sound manager CLSndMgr m_SndMgr; //Input manger CLInput m_Input; //The window manager wnd_sys::CManager m_WndMgr; private: //Some CVarst that we keep track of every frame. lg_cvar* cv_l_ShouldQuit; lg_cvar* cv_l_AverageFPS; //Game management variables. public: //Base Game Initialization: lg_bool LG_GameInit(lg_str szGameDir, HWND hwnd); void LG_GameShutdown(); lg_bool LG_GameLoop(); void LG_SendCommand(lg_cstr szCommand); private: void LG_RegisterCVars(); //Command processing methods: static void LGC_RegConCmds(); static lg_bool LCG_ConCommand(LC_CMD nCmd, lg_void* args, lg_void* pExtra); static void CLGame::LGC_CvarUpdate(CLGame* pGame, const lg_char* szCvar); //Direct3D Display Initialization: //void LV_InitTexLoad(); //Video reset stuff: lg_result LV_ValidateDevice(); void LV_ValidateGraphics(); void LV_InvalidateGraphics(); lg_result LV_Restart(); //Functions for setting render states void SetWorldRS(); void SetWindowRS(); void SetConsoleRS(); private: //The game server (to replace CLWorld). CLWorldSrv m_WorldSrv; CLWorldClnt m_WorldCln; public: //Constructor CLGame(); //Destructor ~CLGame(); public: //Game processing methods. void LG_ProcessGame(); lg_result LG_RenderGraphics(); void LG_OnChar(char c); //OnChar for console input. }; #endif __LG_SYS2_H__<file_sep>/tools/QInstall/Source/directoryex.c /* Directory.c - CopyDirectory Commands. Copyright (c) 2003, <NAME> */ #include <stdio.h> #include "directoryex.h" HRESULT CopyDirectory(LPCTSTR szSource, LPCTSTR szDest, DWORD dwFileAttributes) { TCHAR strCommand[MAX_PATH*2 + 100]; STARTUPINFO SI; PROCESS_INFORMATION PI; BOOL bSuccess; sprintf(strCommand, TEXT("xcopy /Y /E /I /H \"%s\" \"%s\""), szSource, szDest); memset(&SI, 0, sizeof(SI)); memset(&PI, 0, sizeof(PI)); SI.dwFlags = STARTF_USESHOWWINDOW; SI.wShowWindow = SW_HIDE; bSuccess = CreateProcess(NULL, strCommand, NULL, NULL, FALSE, 0, NULL, NULL, &SI, &PI); WaitForSingleObject(PI.hProcess, INFINITE); return S_OK; } <file_sep>/games/Explor2002/Source_Old/ExplorED DOS/borland/Wxplored.cpp /* wxplored.cpp - ExplorED for Windows Author: <NAME> for Beem Software Language: C++ Win32 API Version x.xxW */ /* Note to self: Be sure to prompt whether or not to save when quitting. Impliment save feature. Impliment property editing: either shift click or right click. Impliment load feature. */ /* Log: October 30, 2001 Began Development of ExplorED for Windows, only created a window. October 31, 2001 WinExplorED is really coming along. The interface works fairly correctly. I'm having trouble dealing with file input output so I haven't implimented most features yet. File input is now working. I had to specifie certain variables as being short rather than defaulting to int. Now if the program is started default.map is loaded. Or you can used a filname as a command line perameter if you do that that map will be loaded. I have not implimented either the ability to save or the ability to load when not loading from the start. Developing the win port wasn't nearly as hard as I thought it would be. November 7, 2001 Implemented save and save as feature, both work fine. */ /* NOTE: The following Log applies to the dos version of ExplorED January 12, 2001 I've created a GUI and I'm pretty satisfied. I'm having troubles dealing with sprites and moving them from one function to another. Using the arrow keys is really crappy. If you press a capitol of the corresponding letter it reads it as the up arrow. My next goal will be to write a program similar to my QBasic Moveen program once I have completed that I may continue to develop this one. January 13, 2001 I perfected the location of the placement of the cursor. Now it needs an input consistent with a x, y format. The cursor now moves fine except that it leaves behind a lot of funny pixel formations. What needs to be done now is design sprites for different tiles and then impliment them by placing them on the map when certain buttons are pressed. January 14, 2001 Now if you press 'T' it places a tile sprite on the screen it doesn't it will need to activate the fact that there is a tile at that location for the save feature. I'm facing many issues with the buffered memory. I've perfected the binary writing but now the cursor disapears for an unexplained reason. My goodness I think it's working! I believe open works correctly it just doesn't re-display the tileset. It now opens the tileset fine, but the cursor doesn't work quite right. The file commands are really screwy. Save seems to work fine. The rest of them create visual errors. July 21, 2001 Removed the necessity for the temb.buf file which cleared up a lot of the memory issues. But still a lot of memory issues remain. If you only edit the first map loaded and then us SaveAs you can make multiple maps. NewMap and LoadMap cause a lot of errors. Probably need to redo the graphicsloading to fix that. OpenMap will load the screen correctly but after that the cursor gets very screwed up. <no longer keeping track of dates> BoardEdit has been slighly altered for greater effect. Updated to map type 2. 0's instead of 1's. Changed tiles to 'D' 's and 'W' 's for Door and Wall correspondingly. Improved the algorithm for mapping out the board when initial map load happens. This improved some of the memory issues. Fixed a damn good portion of the memory issues. I'm not even sure if any are left. Have expiramented quite a bit. Updated to map type 3 it took a damn bit of a long time but I am so fucking satisfied now. There are a lot of bugs it will take time to fix them. Most bugs are fixed. I know memory issues exist when saving. Need to make it so alternate tile properties may be altered besides 1 and 2. To do that need to make it so you can change the size of fileHeader.mapNumProperty. Wrote a new function that takes input. It is used to take input for property and for new map names, as well as save as. Works pretty damn good. Greatly increased the LoadMap function now scrolls down when more than 23 maps are present. It supports a maximum number of maps described by a definition in openmap.h. Preforming a Save causes memory issues. One thing to implement. If escape is pressed while in the LoadMap menu the program should return to the previous map, as it was right before the LoadMap was called. Right now it will return to the previous map, but in the state it was in when it was last saved. I'd also like to implement a screenshot feature. Now supports mouse, the mouse doesn't actually do anything yet though. October 18, 2001 I have implemented the EXPLORMAP class which contains all the variables of an explor type map, as well as the functions to load an explormap into memory, save an explor map on the disk, and edit and explor map. Mapboard.cpp and mapboard.h contain this class and work independently of any other programs. Just include #include "mapboard.h" in the file that uses the EXPLORMAP class and include the mapboard.cpp as part of the project. With this new class it should be much easier to port the code to windows. The code in now C++ rather than C language. I also separated the source into 3 parts. One for the defintion of the CASTLEMAP class: mapboard.cpp. Another for the openfile process: openfile.cpp. And finally the main program; explored.cpp. I also implemented overlaoding functions for the input for easier usage. */ /* About Explor Map Type 3: Explor Maps are read in the following manner: The first bytes are the fileheader described by the typedef MAPHEADER. Directly after the map data is the tile data. Each tile is an unsigned int which represents the type of tile (see below). Directly after the tile type is the property data. They are unsigned ints as well. There may be as many properties as you wish per tile. Tile types: 0: Nothing - Means nothing is there 10: Wall - Regular wall represented by 'W' on the display 20: Door - A Door represented by 'D' on the display Possible Future Tile tipes: xx: Invisible Wall - Wall you cannot see but cannot pass through xx: Visible Emptiness - You see a wall but can pass through Property values: The property values can be incremented by 1 and 2 on the keyboard. They have not been assigned to any specific functions yet. But may either in explor source code or ExplorSCRIPT. */ #define EXIT exit(0); //#define EXIT #define MAXFILENAMELEN 256 //#define MAXX 15 //#define MAXY 15 #define MAXX explormap.getMapWidth() #define MAXY explormap.getMapHeight() #include <windows.h> #include <stdio.h> #include "wxplored.h" #include "mapboard.h" #include "resource.h" /* BOOL RegisterBoardWindowClass(void); LRESULT MainEditWindowProc(HWND hEditWnd, unsigned msg, WORD wParam, LONG lParam); */ char edAppName[]="WExplorED"; //char edEditWinName[]="WExplorEDit"; EXPLORMAP explormap; int PASCAL WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow) { MSG msg; HWND hMainWnd; HACCEL hAccel; int errcode; TCHAR temperrmessage[100]; //HWND hEditWnd; if(!hPrevInstance) RegisterWindowClass(); /* if(!hPrevInstance) RegisterBoardWindowClass(); */ //The following code will take the command line perameters //MessageBox(NULL, lpszCmdLine, "Notice", MB_OK); if(!(strlen(lpszCmdLine)<1)){ //errcode=explormap.openMap(lpszCmdLine); strcpy(explormap.boardname, lpszCmdLine); errcode=explormap.openMap(explormap.boardname); if(errcode!=0){ sprintf(temperrmessage, "Error #%i: Could not open map", errcode); MessageBox(NULL, temperrmessage, "Error Opening Map", MB_OK); } }else{ strcpy(explormap.boardname, "default.map"); errcode=explormap.openMap(explormap.boardname); } hMainWnd=CreateWindow(edAppName, "ExplorED For Windows", WS_OVERLAPPED|WS_SYSMENU|WS_MINIMIZEBOX| WS_CLIPCHILDREN|WS_CLIPSIBLINGS| WS_VSCROLL|WS_HSCROLL| //WS_THICKFRAME|WS_CAPTION|WS_MAXIMIZEBOX, //For resizeable WS_DLGFRAME, //For Not resizeable CW_USEDEFAULT, CW_USEDEFAULT, 640, 480, NULL, NULL, hInstance, NULL); ShowWindow(hMainWnd, nCmdShow); UpdateWindow(hMainWnd); /* hEditWnd=CreateWindow(edEditWinName, "Edit Board:", WS_CHILDWINDOW|WS_SYSMENU|WS_CAPTION|//WS_THICKFRAME|WS_BORDER| WS_DLGFRAME|WS_MINIMIZEBOX|WS_MAXIMIZEBOX|WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, 640, 480, hMainWnd, NULL, hInstance, NULL); ShowWindow(hEditWnd, SW_SHOWNORMAL); UpdateWindow(hEditWnd); */ hAccel=LoadAccelerators(hInstance, MAKEINTRESOURCE(IDR_ACCELERATOR1)); while(GetMessage(&msg, hMainWnd, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccel, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return msg.wParam; } /* LRESULT MainEditWindowProc(HWND hEditWnd, unsigned msg, WORD wParam, LONG lParam) { HDC hDc; switch (msg) { case WM_LBUTTONDOWN: MessageBox(hEditWnd, "Pressed Left Mouse Button", "Notice", MB_OK|MB_ICONINFORMATION); break; case WM_PAINT: MainWindowPaint(hEditWnd, hDc); } return 0; } */ LRESULT MainWindowProc(HWND hMainWnd, unsigned msg, WORD wParam, LONG lParam) { HDC hDc; POINTS mpoint; RECT vWindow; TCHAR buffermessage[500]; int cursor_x, cursor_y; GetClientRect(hMainWnd, &vWindow); switch (msg) { case WM_CREATE: break; case WM_LBUTTONDOWN: mpoint=MAKEPOINTS(lParam); cursor_x = (mpoint.x/(vWindow.right/MAXX))+1; cursor_y = (mpoint.y/(vWindow.bottom/MAXY))+1; sprintf(buffermessage, "Mouse x:%i Mouse y:%i Cursor x:%i Cursor y:%i", mpoint.x, mpoint.y, cursor_x, cursor_y); //MessageBox(hMainWnd, buffermessage, "Notice", MB_OK); explormap.boardEdit(cursor_x,cursor_y); RedrawWindow(hMainWnd,NULL,NULL,RDW_INVALIDATE); return 0; case WM_PAINT: MainWindowPaint(hMainWnd, hDc); return 0; case WM_COMMAND: MainCommandProc(hMainWnd, LOWORD(wParam), HIWORD(wParam), (HWND)lParam); return 0; case WM_DESTROY: PostQuitMessage(0); EXIT; return 0; } return DefWindowProc(hMainWnd, msg, wParam, lParam); } BOOL MainCommandProc(HWND hMainWnd, WORD wCommand, WORD wNotify, HWND hControl) { char tempfilename[256]; //Make sure not to keep this arround. char temp[500]; switch (wCommand) { /* The File Menu */ case CM_FILEEXIT: DestroyWindow(hMainWnd); return 0; case CM_FILENEW: return 0; case CM_FILESAVE_AS: if (GetSaveFileName(hMainWnd, tempfilename)==TRUE){ sprintf(temp, "Filename was:%s", tempfilename); //MessageBox(hMainWnd, temp, "Notice", MB_OK); strcpy(explormap.boardname, tempfilename); }else return 0; case CM_FILESAVE: if((explormap.saveMap(explormap.boardname)==0)) MessageBox(hMainWnd, "File Save Successfully", "Notice", MB_OK|MB_ICONINFORMATION); return 0; case CM_FILEPRINT: return 0; case CM_FILEOPEN: if(GetOpenFileName(hMainWnd, tempfilename)==TRUE){ sprintf(temp, "Filename was:%s", tempfilename); MessageBox(hMainWnd, temp, "Notice", MB_OK); //explormap.openMap("default.map"); //RedrawWindow(hMainWnd, NULL,NULL, RDW_INVALIDATE); }else return 0; return 0; } return FALSE; } int GetSaveFileName(HWND hWnd, char *filename) { OPENFILENAME ofn; ZeroMemory(&ofn, sizeof(OPENFILENAME)); ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = hWnd; ofn.lpstrFilter = "Map Files (*.map)\0*.map\0All Files (*.*)\0*.*\0"; ofn.lpstrFile = filename; ofn.nMaxFile = MAXFILENAMELEN; ofn.lpstrTitle = "Save Map As..."; ofn.Flags = OFN_OVERWRITEPROMPT|OFN_HIDEREADONLY|OFN_NONETWORKBUTTON; return GetSaveFileName(&ofn); } int GetOpenFileName(HWND hWnd, char *filename) { OPENFILENAME ofn; ZeroMemory(&ofn, sizeof(OPENFILENAME)); ofn.lStructSize = sizeof( OPENFILENAME ); ofn.hwndOwner = hWnd; // An invalid hWnd causes non-modality ofn.lpstrFilter = "Map Files (*.map)\0*.map\0All Files (*.*)\0*.*\0"; ofn.lpstrFile = filename; // Stores the result in this variable ofn.nMaxFile = MAXFILENAMELEN; ofn.lpstrTitle = "Open Map"; // Title for dialog ofn.Flags = OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_PATHMUSTEXIST; return GetOpenFileName(&ofn); } void MainWindowPaint(HWND hWnd, HDC hDc) { #define GRIDCOLOR RGB(0,0,0) #define WALLCOLOR RGB(140,87,15) #define DOORCOLOR RGB(84,219,60) #define BGCOLOR RGB(255,255,255) //I want to remove those defines #define blockheight (vWindow.bottom)/MAXY #define blockwidth (vWindow.right)/MAXX int i; int j; //int testiles[225]; //ZeroMemory(testiles, sizeof(testiles)); TCHAR buffer[100]; PAINTSTRUCT ps; RECT vWindow; HPEN hpen; HGDIOBJ hpenOld; HGDIOBJ hbrushOld; HBRUSH wallbrush, doorbrush, blankbrush; wallbrush=CreateSolidBrush(WALLCOLOR); doorbrush=CreateSolidBrush(DOORCOLOR); blankbrush=CreateSolidBrush(BGCOLOR); GetClientRect(hWnd, &vWindow); hDc=BeginPaint(hWnd, &ps); hpen=CreatePen(PS_SOLID,2, GRIDCOLOR); hpenOld=SelectObject(hDc, hpen); //Painting The Grid for(i=0; i<=MAXX; i++){ MoveToEx(hDc, i*blockwidth, 0, NULL); LineTo(hDc, i*blockwidth, vWindow.bottom); } for(i=0; i<=MAXY;i++){ MoveToEx(hDc, 0,i*blockheight, NULL); LineTo(hDc, vWindow.right, i*blockheight); } //Paint the board for(j=1;j<=MAXY;j++){ for(i=1;i<=MAXX;i++){ switch (explormap.getTileStat(i, j)) { case 10: hbrushOld=SelectObject(hDc, wallbrush); FloodFill(hDc, (i-1)*blockwidth+2, (j-1)*blockheight+2, GRIDCOLOR); break; case 20: hbrushOld=SelectObject(hDc, doorbrush); FloodFill(hDc, (i-1)*blockwidth+2, (j-1)*blockheight+2, GRIDCOLOR); break; default: hbrushOld=SelectObject(hDc, blankbrush); FloodFill(hDc, (i-1)*blockwidth+2, (j-1)*blockheight+2, GRIDCOLOR); break; } //#define DEBUG2 #ifdef DEBUG2 sprintf(buffer, "%i ", explormap.getTileStat(i, j)); TextOut(hDc, (i-1)*blockwidth+2, (j-1)*blockheight+2,buffer, strlen(buffer)); #endif } } EndPaint(hWnd, &ps); SelectObject(hDc, hpenOld); DeleteObject(hpen); SelectObject(hDc, hbrushOld); DeleteObject(wallbrush); DeleteObject(doorbrush); DeleteObject(blankbrush); } BOOL RegisterWindowClass(void) { WNDCLASS wndClass; ZeroMemory(&wndClass, sizeof(WNDCLASS)); wndClass.style=CS_HREDRAW|CS_VREDRAW; wndClass.lpfnWndProc=(WNDPROC)MainWindowProc; wndClass.cbClsExtra=0; wndClass.cbWndExtra=0; wndClass.hInstance=GetModuleHandle(NULL); wndClass.hIcon=LoadIcon(wndClass.hInstance, MAKEINTRESOURCE(ICON_1)); wndClass.hCursor=LoadCursor(NULL, IDC_CROSS); wndClass.hbrBackground=(HBRUSH)GetStockObject(WHITE_BRUSH); wndClass.lpszMenuName=MAKEINTRESOURCE(MENU_MAIN); wndClass.lpszClassName=edAppName; if(!RegisterClass(&wndClass)) return FALSE; return TRUE; } /* BOOL RegisterBoardWindowClass(void) { WNDCLASS wndClassB; ZeroMemory(&wndClassB, sizeof(WNDCLASS)); wndClassB.style=CS_HREDRAW|CS_VREDRAW; wndClassB.lpfnWndProc=(WNDPROC)MainEditWindowProc; wndClassB.cbClsExtra=0; wndClassB.cbWndExtra=0; wndClassB.hInstance=GetModuleHandle(NULL); wndClassB.hIcon=LoadIcon(wndClassB.hInstance, MAKEINTRESOURCE(ICON_1)); wndClassB.hCursor=LoadCursor(NULL, IDC_ARROW); wndClassB.hbrBackground=GetStockObject(WHITE_BRUSH); wndClassB.lpszMenuName=NULL; wndClassB.lpszClassName=edEditWinName; if(!RegisterClass(&wndClassB)) return FALSE; return TRUE; } */ <file_sep>/tools/fs_sys2/fs_file.h #include "fs_sys2.h" #include "fs_bdio.h" class FS_SYS2_EXPORTS CLFile { public: fs_dword Read(void* pOutBuffer, fs_dword nSize); fs_dword Write(const void* pInBuffer, fs_dword nSize); fs_dword Tell(); fs_dword Seek(LF_SEEK_TYPE nMode, fs_long nOffset); fs_dword GetSize(); const void* GetMemPointer(); fs_bool IsEOF(); private: fs_dword m_nAccess; fs_dword m_nSize; fs_dword m_nFilePointer; fs_pathW m_szPathW; fs_byte* m_pData; BDIO_FILE m_BaseFile; fs_dword m_nBaseFileBegin; //Where the CLFile starts in the base file (0 if the file is being accessed directly from the disk). fs_bool m_bEOF; //Public methods. private: friend class CLFileSystem; void* operator new(fs_size_t Size); void operator delete(void*); CLFile(); ~CLFile(); };<file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/lm_math.h #ifndef __LM_MATH_H__ #define __LM_MATH_H__ #include "common.h" #ifdef __cplusplus extern "C"{ #endif /*__cplusplus*/ L_dword __cdecl L_nextpow2_ASM(L_dword n); L_dword __cdecl L_nextpow2_C(L_dword n); //#define __USEASM__ #ifdef __USEASM__ #define L_nextpow2 L_nextpow2_ASM #else #define L_nextpow2 L_nextpow2_C #endif void* L_matslerp(void* pOut, void* pM1, void* pM2, float t); #ifdef __cplusplus } #endif /*__cplusplus*/ #endif /*__LM_MATH_H__*/<file_sep>/games/Legacy-Engine/Source/lm_sys/lm_mesh_edit.cpp #include "stdafx.h" #include "lm_mesh_edit.h" #include "lg_func.h" IDirect3DDevice9* CLMeshEdit::s_pDevice=LG_NULL; CLMesh2::MeshVertex* CLMeshEdit::LockTransfVB() { return m_pTransfVB; } lg_void CLMeshEdit::UnlockTransfVB() { } lg_void CLMeshEdit::SetRenderTexture(lg_bool bRenderTexture) { if(bRenderTexture) LG_SetFlag(m_nFlags, LM_FLAG_RENDER_TEX); else LG_UnsetFlag(m_nFlags, LM_FLAG_RENDER_TEX); } const ml_aabb* CLMeshEdit::GetBoundingBox() { return &m_AABB; } lg_bool CLMeshEdit::Load(LMPath szFile) { Unload(); CFile fin; if(!fin.Open(szFile, fin.modeRead)) return LG_FALSE; lg_bool bResult=Serialize((lg_void*)&fin, ReadFn, RW_READ); fin.Close(); m_nFlags=bResult?LM_FLAG_LOADED:0; if(bResult) { lg_path szTexDir; lg_path szTexPath; GetDirFromPath(szTexDir, szFile); m_ppTex=new IDirect3DTexture9*[m_nNumMtrs]; for(lg_dword i=0; i<m_nNumMtrs; i++) { _snprintf(szTexPath, LG_MAX_PATH, "%s%s", szTexDir, m_pMtrs[i].szFile); szTexPath[LG_MAX_PATH]=0; HRESULT nRes=D3DXCreateTextureFromFileEx( s_pDevice, szTexPath, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, 0, LG_NULL, LG_NULL, &m_ppTex[i]); if(FAILED(nRes)) { m_ppTex[i]=LG_NULL; } } m_pTransfVB=new MeshVertex[m_nNumVerts]; for(lg_dword i=0; i<m_nNumVerts; i++) { m_pTransfVB[i]=m_pVerts[i]; } InitAnimData(); } return bResult; } lg_bool CLMeshEdit::Save(LMPath szFile) { if(!IsLoaded()) return LG_FALSE; CFile fin; if(!fin.Open(szFile, fin.modeWrite|fin.modeCreate)) return LG_FALSE; lg_bool bResult=Serialize((lg_void*)&fin, WriteFn, RW_WRITE); fin.Close(); return bResult; } lg_void CLMeshEdit::Unload() { CLMesh2::Unload(); if(m_ppTex) { for(lg_dword i=0; i<this->m_nNumMtrs; i++) { LG_SafeRelease(m_ppTex[i]); } LG_SafeDeleteArray(m_ppTex); } LG_SafeDeleteArray(m_pTransfVB); DeleteAnimData(); } lg_str CLMeshEdit::GetDirFromPath(lg_str szDir, lg_cstr szFullPath) { lg_dword dwLen=strlen(szFullPath); lg_long i=0; for(i=(lg_long)dwLen-1; i>=0; i--) { if(szFullPath[i]=='\\' || szFullPath[i]=='/') break; } strncpy(szDir, szFullPath, i+1); szDir[i+1]=0; return szDir; } lg_void CLMeshEdit::Render() { if(!LG_CheckFlag(m_nFlags, LM_FLAG_LOADED)) return; /* s_pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); s_pDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); s_pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); s_pDevice->SetRenderState(D3DRS_NORMALIZENORMALS, TRUE); s_pDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); s_pDevice->SetRenderState(D3DRS_ZENABLE, TRUE); s_pDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE); s_pDevice->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP); s_pDevice->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP); */ s_pDevice->SetFVF(D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX1); //Set the material for the mesh, in the future this might //be controlled by model properties, for now it is //just a default material. static const D3DMATERIAL9 d3d9mtr={ {1.0f, 1.0f, 1.0f, 1.0f},//Diffuse {1.0f, 1.0f, 1.0f, 1.0f},//Ambient {1.0f, 1.0f, 1.0f, 1.0f},//Specular {0.0f, 0.0f, 0.0f, 1.0f},//Emissive 0.0f}; //Power s_pDevice->SetMaterial(&d3d9mtr); for(lg_dword i=0; i<m_nNumSubMesh; i++) { s_pDevice->SetTexture(0, LG_CheckFlag(m_nFlags, LM_FLAG_RENDER_TEX)?m_ppTex[m_pSubMesh[i].nMtrIndex]:LG_NULL); HRESULT Res = s_pDevice->DrawIndexedPrimitiveUP( D3DPT_TRIANGLELIST, 0, m_nNumVerts, m_pSubMesh[i].nNumTri, &m_pIndexes[m_pSubMesh[i].nFirstIndex], D3DFMT_INDEX16, m_pTransfVB, sizeof(MeshVertex)); if( FAILED( Res ) ) { __debugbreak(); } } } lg_uint __cdecl CLMeshEdit::ReadFn(lg_void* file, lg_void* buffer, lg_uint size) { CFile* pFile=(CFile*)file; return pFile->Read(buffer, size);//LF_Read(file, buffer, size); } lg_uint __cdecl CLMeshEdit::WriteFn(lg_void* file, lg_void* buffer, lg_uint size) { CFile* pFile=(CFile*)file; pFile->Write(buffer, size);//LF_Read(file, buffer, size); return size; }<file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/common/img_lib.h /* img_lib.h - The Image Loader library. Copyright (c) 2006 <NAME>*/ #ifndef __IMG_LIB_H__ #define __IMG_LIB_H__ /* Insure that if a c++ app is calling the img_lib functions that it knows they were written in C. This is for VC++ and is not ANSI C.*/ #ifdef __cplusplus extern "C"{ #endif /*__cplusplus*/ /* Some types that we will use.*/ typedef unsigned char img_byte; typedef signed char img_sbyte; typedef unsigned short img_word; typedef signed short img_short; typedef unsigned long img_dword; typedef signed long img_long; typedef int img_bool; typedef unsigned int img_uint; typedef signed int img_int; typedef void img_void; /* A few definitions. */ #define IMG_TRUE (1) #define IMG_FALSE (0) /* A definition for the function type (all functions will be __cdecl, but if for some reason that needed to be changed only the following line needs to be changed. This is not ANSI C, but to make this file ANSI C compatible IMG_FUNC need only to be changed to a blank defintion.*/ #define IMG_FUNC __cdecl #ifdef __cplusplus #define IMG_NULL (0) #else /*__cplusplus*/ #define IMG_NULL ((void*)0) #endif /*__cplusplus*/ /* IMG_SAFE_FREE safely frees memory allocated using malloc (or calloc, etc). IMG_CLAMP insures that the value of v1 is within min and max.*/ #define IMG_SAFE_FREE(p) if(p){free(p);p=IMG_NULL;} #define IMG_CLAMP(v1, min, max) ( (v1)>(max)?(max):(v1)<(min)?(min):(v1) ) /* HIMG is the handle for our image. Obtained by a call to IMG_Open or IMG_OpenCallbacks*/ typedef void* HIMG; /* The structure for the callback functions used when opening the image.*/ typedef struct _IMG_CALLBACKS{ img_int (__cdecl *close)(void* stream); img_int (__cdecl *seek)(void* stream, long offset, int origin); img_long (__cdecl *tell)(void* stream); img_uint (__cdecl *read)(void* buffer, img_uint size, img_uint count, void* stream); }IMG_CALLBACKS, *PIMG_CALLBACKS; /* The seeking parametres for the seek function.*/ #define IMG_SEEK_CUR 1 #define IMG_SEEK_END 2 #define IMG_SEEK_SET 0 /* The IMGORIENT enumeration describes where the upper-left pixel is located in the file.*/ typedef enum _IMGORIENT{ IMGORIENT_BOTTOMLEFT=0, IMGORIENT_BOTTOMRIGHT=1, IMGORIENT_TOPLEFT=2, IMGORIENT_TOPRIGHT=3, IMGORIENT_FORCE_DWORD=0xFFFFFFFF }IMGORIENT; /* The IMGFMT enumeration describes the images pixel format.*/ typedef enum _IMGFMT{ IMGFMT_UNKNOWN=0, IMGFMT_NONE=0, IMGFMT_PALETTE=1, IMGFMT_X1R5G5B5=2, IMGFMT_R5G6B5=3, IMGFMT_R8G8B8=4, IMGFMT_A8R8G8B8=5, IMGFMT_R8G8B8A8=6, IMGFMT_FORCE_DWORD=0xFFFFFFFF }IMGFMT; /* The IMGFILTER enumeration is used to determine how an images pixels are filter when calls IMG_CopyBits involve shrinking and stretching.*/ typedef enum _IMGFILTER{ IMGFILTER_NONE=0, IMGFILTER_POINT=0, IMGFILTER_LINEAR=1, IMGFILTER_FORCE_DWORD=0xFFFFFFFF }IMGFILTER; /* The IMG_RECT structure is used to describe the rectangluar area that is being copied from on the source image.*/ typedef struct _IMG_RECT{ img_long left; img_long top; img_long right; img_long bottom; }IMG_RECT, *PIMG_RECT; /* The IMG_DES_RECT structure describes the destination images format (size, pixel format, and area to be copied to) for the IMG_CopyBits function.*/ typedef struct _IMG_DEST_RECT{ img_dword nWidth; img_dword nHeight; img_dword nPitch; IMGFMT nFormat; IMGORIENT nOrient; IMG_RECT rcCopy; void* pImage; }IMG_DEST_RECT, *PIMG_DEST_RECT; /* IMG_DESC is used when retreiving information about the image stored in an HIMG.*/ typedef struct _IMG_DESC{ img_word Width; img_word Height; img_byte BitsPerPixel; IMGFMT Format; img_word NumPaletteEntries; img_byte PaletteBitDepth; IMGFMT PaletteFormat; }IMG_DESC, *PIMG_DESC; /********************************* The img_lib public functions. *********************************/ HIMG IMG_FUNC IMG_OpenCallbacks(void* stream, IMG_CALLBACKS* lpFuncs); HIMG IMG_FUNC IMG_Open(char* szFilename); img_bool IMG_FUNC IMG_Delete(HIMG hImage); img_bool IMG_FUNC IMG_GetDesc( HIMG hImage, IMG_DESC* lpDescript); img_bool IMG_FUNC IMG_CopyBits( HIMG hImage, IMG_DEST_RECT* pDest, IMGFILTER Filter, IMG_RECT* rcSrc, img_byte nExtra); img_bool IMG_FUNC IMG_GetPalette( HIMG hImage, void* lpDataOut); /* Terminate the extern "C" (see above).*/ #ifdef __cplusplus } #endif /*__cplusplus*/ #endif /*__IMG_LIB_H__*/<file_sep>/tools/ListingGen/MovieLister/MovieLister.h #ifndef __GAMELISTER_H__ #define __GAMELISTER_H__ #include "Lister.h" class CGameLister; CLister * ObtainLister(); class CGameLister: public CLister { private: char * m_szItemName; char * m_szItemType; char * m_szItemDesc; char * m_szItemCondition; char * m_szShippingCost; char * m_szShippingInfo; char * m_szPaymentOptions; char * m_szShippingTerms; char * m_szFeedbackTerms; char * m_szWarrantyTerms; public: CGameLister() { m_szItemName=NULL; m_szItemType=NULL; m_szItemDesc=NULL; m_szItemCondition=NULL; m_szShippingCost=NULL; m_szShippingInfo=NULL; m_szPaymentOptions=NULL; m_szShippingTerms=NULL; m_szFeedbackTerms=NULL; m_szWarrantyTerms=NULL; } virtual ~CGameLister() { SAFE_DELETE_ARRAY(m_szItemName); SAFE_DELETE_ARRAY(m_szItemType); SAFE_DELETE_ARRAY(m_szItemDesc); SAFE_DELETE_ARRAY(m_szItemCondition); SAFE_DELETE_ARRAY(m_szShippingCost); SAFE_DELETE_ARRAY(m_szShippingInfo); SAFE_DELETE_ARRAY(m_szPaymentOptions); SAFE_DELETE_ARRAY(m_szShippingTerms); SAFE_DELETE_ARRAY(m_szFeedbackTerms); SAFE_DELETE_ARRAY(m_szWarrantyTerms); } virtual BOOL CreateListing(char szFilename[MAX_PATH]); virtual BOOL RunDialog(HWND hwndParent); virtual BOOL SaveListing(char szFilename[MAX_PATH]); virtual BOOL LoadListing(char szFilename[MAX_PATH]); BOOL SetItemName(LPSTR szItemName, LPSTR szItemType); BOOL SetItemDesc(LPSTR szItemDesc); BOOL SetItemCondition(LPSTR szItemCondition); BOOL SetShippingInfo(LPSTR szShippingCost, LPSTR szShippingInfo); BOOL SetPaymentOptions(LPSTR szPaymentOptions); BOOL SetShippingTerms(LPSTR szShippingTerms); BOOL SetFeedbackTerms(LPSTR szFeedbackTerms); BOOL SetWarrantyTerms(LPSTR szWarrantyTerms); //Friend Functions. friend BOOL CALLBACK TitleDesc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); friend BOOL CALLBACK ShipPay(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); friend BOOL CALLBACK Terms(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); }; #endif //__GAMELISTER_H__<file_sep>/samples/Project5/src/project5/Zoo.java /* <NAME> CS 2420-002 Zoo - class for managing zoo and operating on it. */ package project5; import java.io.*; import java.util.*; import bcol.*; public class Zoo { private BGraph<ZVector> m_grphZoo; /* PRE: strFilename must point to a validly formatted zoo graph filename. POST: The zoo is setup and ready for processing. */ public Zoo(String strFilename){ try{ //BufferedReader fin = new BufferedReader(new File(szFilename)); Scanner fin = new Scanner(new File(strFilename), "UTF-8"); //The first thing we read is the number of vectors in the zoo, //we can then proceed to create the graph based //on the upcoming information. int nCount = fin.nextInt(); //System.out.println("The count: " + nCount); //Read the data and create the graph appropriately. m_grphZoo=new BGraph<ZVector>(nCount); for(int i=0; i<nCount; i++){ m_grphZoo.setData(i, new ZVector(fin.next())); for(int j=0; j<nCount; j++){ int n = fin.nextInt(); if(n!=0) m_grphZoo.addEdge(i, j, n); } } //Test stuff... //System.out.println(m_grphZoo); /* //Prints out all the neighbors... for(int i=0; i<m_grphZoo.size(); i++){ ZVector v = m_grphZoo.getData(i); int[] neig = m_grphZoo.neighbors(i); String strNeig = v + ": "; for(int n: neig){ strNeig+=m_grphZoo.getData(n) + " "; } System.out.println(strNeig); } */ }catch (FileNotFoundException e){ System.out.println("Could not find " + strFilename); }catch (BColException e){ System.out.println("A data formating error ocurred " + e); } } /* PRE: N/A POST: Prompts user for two zoo locations and finds the shortest path. */ public void shortestPath(){ String strPath=""; try{ String strStart, strEnd; int nStart=-1, nEnd=-1; System.out.println("Where do you want to start from?"); strStart=KBInput.readLine(); System.out.println("Where do you want to end from?"); strEnd=KBInput.readLine(); //Now that we have the desired infor find the references for those. for(int i=0; (i<m_grphZoo.size()); i++){ ZVector v = m_grphZoo.getData(i); if(v.m_strAnimal.compareToIgnoreCase(strStart)==0){ nStart=i; } if(v.m_strAnimal.compareToIgnoreCase(strEnd)==0){ nEnd=i; } } if(nEnd==-1 || nStart==-1){ System.out.println("Invalid animals specified, no path defined."); }else{ int[] path = m_grphZoo.shortestPath(nStart); boolean bDone=false; int nDistance=0; while(!bDone){ int nDist=m_grphZoo.distance(path[nEnd], nEnd); strPath = String.format( "%s ==> %s %d\n", m_grphZoo.getData(path[nEnd]).m_strAnimal, m_grphZoo.getData(nEnd).m_strAnimal, nDist) + strPath; nDistance+=nDist; if(path[nEnd]==nStart) { bDone=true; }else { nEnd=path[nEnd]; } } System.out.println("Results: "); System.out.println(strPath + "\nTotal Distance: " + nDistance); } } catch(BColException e){ System.out.println("Internal Logic Error:" + e + "\n" + strPath); } } /* PRE: N/A POST: Returns a string rep of all the animals in the zoo, the graph is traversed in order to show the animals. */ public String toString(){ return m_grphZoo.toString(); } private class ZVector{ private String m_strAnimal; //PRE: strAnimal is the name of the animal. //POST: ZVector is created and the name of the animal is et. public ZVector(String strAnimal){ m_strAnimal = strAnimal; } /* PRE: N/A POST: Returns a string rep of the zoo vector (the animal's name). */ public String toString(){ return m_strAnimal; } } } <file_sep>/tools/CornerBin/CornerBin/DlgSettings.h #pragma once // CDlgSettings dialog class CDlgSettings : public CDialogEx { DECLARE_DYNAMIC(CDlgSettings) public: CDlgSettings(CWnd* pParent, CCBSettings* pSettings); // standard constructor virtual ~CDlgSettings(); // Dialog Data enum { IDD = IDD_DLG_SETTINGS }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support DECLARE_MESSAGE_MAP() private: CCBSettings* m_pSettings; public: afx_msg void OnBnClickedBtnbrowsee(); void BrowseForIcon(int nCtrlID); afx_msg void OnBnClickedBtnbrowsef(); afx_msg void OnBnClickedBtnsysempty(); afx_msg void OnBnClickedBtnsysfull(); private: void SetStartWithWindows(BOOL bStartWith); private: static BOOL IsStartWithWindowsSet(void); public: afx_msg void OnBnClickedBtndefs(); }; <file_sep>/games/Legacy-Engine/Scrapped/old/le_camera.cpp #include "le_camera.h" #include <d3dx9.h> #include "common.h" #include <al/al.h> CLCamera::CLCamera(): CLEntity(), m_pAttachedEnt(LG_NULL), m_nMode(0), m_fDistance(1.0f) { m_v3Up.x=m_v3Up.z=0.0f; m_v3Up.y=1.0f; m_v3LookAt.x=m_v3LookAt.y=m_v3LookAt.z=0.0f; m_v3AttachedOffset.x=m_v3AttachedOffset.y=m_v3AttachedOffset.z=0.0f; } CLCamera::~CLCamera() { } void CLCamera::AttachToObject(CLEntity* pEntity, lg_dword mode, ML_VEC3* pv3Offset, float fDist) { m_pAttachedEnt=pEntity; m_nMode=mode; m_v3AttachedOffset=*pv3Offset; m_fDistance=fDist; } void CLCamera::SetYawPitchRoll(float yaw, float pitch, float roll) { m_fYaw=yaw; m_fPitch=pitch; m_fRoll=roll; } void CLCamera::Update() { static const ML_VEC3 v3At={0.0f, 0.0f, 1.0f}, v3Up={0.0f, 1.0f, 0.0f}; if(m_pAttachedEnt) { m_v3Pos=m_pAttachedEnt->m_v3Pos; m_fYaw=m_pAttachedEnt->m_fYaw; m_fPitch=-m_pAttachedEnt->m_fPitch; m_fRoll=m_pAttachedEnt->m_fRoll; switch(m_nMode) { case CLCAMERA_ATTACH_FOLLOW: CLEntity::Update(); ML_Vec3Add(&m_v3LookAt, &m_v3Pos, &m_v3AttachedOffset); m_v3Pos.x=0.0f; m_v3Pos.y=0.0f; m_v3Pos.z=m_fDistance; ML_MatRotationYawPitchRoll(&m_matView, m_fYaw, m_fPitch, m_fRoll); ML_Vec3TransformCoord(&m_v3Pos, &m_v3Pos, &m_matView); ML_Vec3Subtract(&m_v3Pos, &m_v3LookAt, &m_v3Pos); break; case CLCAMERA_ATTACH_EYE: ML_Vec3Add(&m_v3Pos, &m_v3AttachedOffset, &m_v3Pos); CLEntity::Update(); ML_Vec3TransformCoord(&m_v3LookAt, &v3At, &m_matOrient); ML_Vec3TransformNormal(&m_v3Up, &v3Up, &m_matOrient); break; } return; } } void CLCamera::Render() { if(!s_pDevice) return; ML_MatLookAtLH( &m_matView, &m_v3Pos, &m_v3LookAt, &m_v3Up); s_pDevice->SetTransform(D3DTS_VIEW, (D3DMATRIX*)&m_matView); alListener3f(AL_POSITION, m_v3Pos.x, m_v3Pos.y, -m_v3Pos.z); //alListener3f(AL_VELOCITY, 0, 0, 0); #if 1 ML_VEC3 v3[2]={ m_v3LookAt.x-m_v3Pos.x, m_v3LookAt.y-m_v3Pos.y, -(m_v3LookAt.z-m_v3Pos.z), m_v3Up.x, m_v3Up.y, -m_v3Up.z}; #else ML_VEC3 v3[2]={ ML_sinf(m_fYaw), 0.0f, -ML_cosf(m_fYaw), 0, 1.0f, 0.0f}; #endif alListenerfv(AL_ORIENTATION, (ALfloat*)v3); } void CLCamera::RenderForSkybox() { if(!s_pDevice) return; ML_VEC3 v3Pos={0.0f, 0.0f, 0.0f}; ML_VEC3 v3LookAt; ML_Vec3Subtract(&v3LookAt, &m_v3LookAt, &m_v3Pos); ML_MatLookAtLH( &m_matView, &v3Pos, &v3LookAt, &m_v3Up); s_pDevice->SetTransform(D3DTS_VIEW, (D3DMATRIX*)&m_matView); } void CLCamera::SetPosition(ML_VEC3* pVec) { m_v3Pos=*pVec; } void CLCamera::SetLookAt(ML_VEC3* pVec) { m_v3LookAt=*pVec; } void CLCamera::SetTransform(ML_MAT* pM) { m_matView=*pM; } <file_sep>/games/Legacy-Engine/Source/lm_sys/lm_mesh_tree.cpp #include "lm_mesh_tree.h" #include "lx_sys.h" #include "lg_mmgr.h" #include "lg_skin_mgr.h" CLMeshTree::MeshNode::MeshNode() /* : m_pMesh(LG_NULL) , m_pSkin(LG_NULL) , m_pDefSkel(LG_NULL) , m_pSkel(LG_NULL) , m_nAnim(0) , m_fAnimProgress(0.0f) , m_nAnimSpeed(0) , m_pPrevSkel(LG_NULL) , m_nPrevAnim(0) , m_fPrevAnimProgress(0.0f) , m_fTransitionTime(0.0f) , m_nParentJoint(0) */ { Clear(); } CLMeshTree::MeshNode::~MeshNode() { //Don't need to do anything as no //memory was allocated. } lg_void CLMeshTree::MeshNode::Load(CLMeshLG* pMesh, CLSkin* pSkin, CLSkelLG* pSkel) { Clear(); m_pMesh=pMesh; m_pSkin=pSkin; m_pDefSkel=pSkel; m_pSkel=m_pDefSkel; } lg_void CLMeshTree::MeshNode::Clear() { m_pMesh=LG_NULL; m_pSkin=LG_NULL; m_pDefSkel=LG_NULL; m_pSkel=LG_NULL; m_pNextSkel=LG_NULL; m_nAnim=0; m_fAnimProgress=0.0f; m_fAnimSpeed=1.0f; m_fElapsed=0.0f; m_pPrevSkel=LG_NULL; m_nPrevAnim=0; m_fPrevAnimProgress=0.0f; m_fPostTransSpeed=1.0f; m_nNumChildren=0; m_nParentJoint=0xFFFFFFFF; for(lg_dword i=0; i<MT_MAX_MESH_NODES; i++) { m_pChildren[i]=LG_NULL; } } lg_void CLMeshTree::MeshNode::Render(ml_mat* pMatWorldTrans) { m_pMesh->s_pDevice->SetTransform(D3DTS_WORLD, (D3DMATRIX*)pMatWorldTrans); if(m_pMesh) { m_pMesh->DoTransform(); m_pMesh->Render(m_pSkin); } //Now Render all the children... If the children have any children //they will get rendered as well. for(lg_dword i=0; i<m_nNumChildren; i++) { ML_MAT matTrans; matTrans=*pMatWorldTrans; //Note that if the parent joint reference is invalid (0xFFFFFFFF) //then we'll end up multiplying by the identiy matrix //so we are alright. ML_MatMultiply( &matTrans, m_pMesh->GetJointAttachTransform(m_pChildren[i]->m_nParentJoint), pMatWorldTrans); m_pChildren[i]->Render(&matTrans); } } lg_void CLMeshTree::MeshNode::AddChild(MeshNode* pChild, lg_str szJoint) { if(m_nNumChildren>=CLMeshTree::MT_MAX_MESH_NODES) return; m_pChildren[m_nNumChildren]=pChild; m_nNumChildren++; pChild->m_nParentJoint=m_pMesh->GetJointRef(szJoint); } CLMeshTree::CLMeshTree() : CLMBase() { //Unload will clear all the data: Unload(); } CLMeshTree::~CLMeshTree() { } lg_void CLMeshTree::GetAttachTransform(ml_mat* pOut, lg_dword nChild) { //Not really quite right as this gets the mesh attached to the //base node. if(m_MeshNodes[0].m_nNumChildren!=0) { nChild=LG_Clamp(nChild, 0, m_MeshNodes[0].m_nNumChildren-1); *pOut=*(m_MeshNodes[0].m_pMesh->GetJointAttachTransform(m_MeshNodes[0].m_pChildren[nChild]->m_nParentJoint)); ML_MatMultiply(pOut, pOut, &m_matBaseTrans); } else { ML_MatIdentity(pOut); } } lg_bool CLMeshTree::Load(lg_path szFile) { Unload(); lx_mesh_tree_data mtd; lg_bool bRes=LX_LoadMeshTree(szFile, &mtd); if(bRes) { //Now we must construct the mesh tree: m_nNumNodes=mtd.nNodeCount; m_nNumSkels=mtd.nSkelCount; static ml_mat matTemp; //Set up the base transform (should include scale): if(mtd.bYaw180) ML_MatRotationY(&matTemp, ML_PI); else ML_MatIdentity(&matTemp); ML_MatMultiply(&m_matBaseTrans, &matTemp, &m_matBaseTrans); if(mtd.fScale!=1.0f) ML_MatScaling(&matTemp, mtd.fScale, mtd.fScale, mtd.fScale); else ML_MatIdentity(&matTemp); ML_MatMultiply(&m_matBaseTrans, &matTemp, &m_matBaseTrans); //First we'll load all the resources: //Setup the nodes: for(lg_dword i=0; i<m_nNumNodes; i++) { CLMeshLG* pMesh=CLMMgr::MM_LoadMesh(mtd.Nodes[i].szMeshFile, 0); CLSkelLG* pDefSkel=CLMMgr::MM_LoadSkel(mtd.Nodes[i].szDefSkelFile, 0); CLSkin* pSkin=CLSkinMgr::SM_Load(mtd.Nodes[i].szSkinFile, 0); pMesh->SetCompatibleWith(pDefSkel); pSkin->MakeCompatibleWithMesh(pMesh); m_MeshNodes[i].Load(pMesh, pSkin, pDefSkel); } //Load the skels: for(lg_dword i=0; i<m_nNumSkels; i++) { m_pSkels[i]=CLMMgr::MM_LoadSkel(mtd.szSkels[i], 0); } //Now we should set up the heirarchy. //We start at 1 because 0 is the base node, //so even if a parent was specified it doesn't //matter. for(lg_dword i=1; i<m_nNumNodes; i++) { m_MeshNodes[mtd.Nodes[i].nParentNode].AddChild( &m_MeshNodes[i], mtd.Nodes[i].szParentJoint); } } return bRes; } lg_void CLMeshTree::Unload() { for(lg_dword i=0; i<MT_MAX_MESH_NODES; i++) { m_MeshNodes[i].Clear(); } for(lg_dword i=0; i<MT_MAX_SKELS; i++) { m_pSkels[i]=0; } m_nNumNodes=0; m_nNumSkels=0; m_nFlags=0; ML_MatIdentity(&m_matBaseTrans); } lg_void CLMeshTree::Render(ml_mat *pMatWorldTrans) { static ml_mat matTrans; //We only need to render the base node, all other //notes should get render subsequentiall. ML_MatMultiply(&matTrans, &m_matBaseTrans, pMatWorldTrans); m_MeshNodes[0].Render(&matTrans); } lg_void CLMeshTree::Update(lg_float fDeltaTimeSec) { for(lg_dword i=0; i<m_nNumNodes; i++) { static MeshNode* pCur; pCur=&m_MeshNodes[i]; if(!pCur->m_pSkel) continue; //This is just here as a test. pCur->m_fElapsed+=fDeltaTimeSec; if(pCur->m_fElapsed>pCur->m_fAnimSpeed) { //Since it is possible that a transition completed //we'll set the speed to teh post trans speed, which //should contain the desired speed. pCur->m_pPrevSkel=LG_NULL; //In the case that we have the next animation in que, //we'll need to transition to that. if(pCur->m_pNextSkel) { pCur->m_pPrevSkel=pCur->m_pSkel; pCur->m_nPrevAnim=pCur->m_nAnim; pCur->m_fPrevAnimProgress=1.0f; pCur->m_pSkel=pCur->m_pNextSkel; pCur->m_nAnim=pCur->m_nNextAnim; pCur->m_pNextSkel=LG_NULL; } else { pCur->m_fAnimSpeed=pCur->m_fPostTransSpeed; } pCur->m_fElapsed=0.0f; } //There are two options, either we are transitioning, //or we are doing a regular animation. If pCur->m_pPrevSkel //is not null then we are transitioning. if(pCur->m_pPrevSkel) { pCur->m_pMesh->SetupFrame(pCur->m_nPrevAnim, pCur->m_fPrevAnimProgress, pCur->m_pPrevSkel); pCur->m_fAnimProgress=(pCur->m_fElapsed/pCur->m_fAnimSpeed)*100.0f; pCur->m_pMesh->TransitionTo(pCur->m_nAnim, pCur->m_fAnimProgress*0.01f, pCur->m_pSkel); } else { pCur->m_fAnimProgress=(pCur->m_fElapsed/pCur->m_fAnimSpeed)*100.0f; pCur->m_pMesh->SetupFrame(pCur->m_nAnim, pCur->m_fAnimProgress, pCur->m_pSkel); } /* if(i==0) Err_MsgPrintf("Time: %.2f Progress: %.2f", pCur->m_fElapsed, pCur->m_fAnimProgress); */ } } lg_void CLMeshTree::SetAnimation( lg_dword nNode, lg_dword nSkel, lg_dword nAnim, lg_float fSpeed, lg_float fTransitionTime) { //We'll clamp some values, just so we don't go out of bounds. nNode=LG_Clamp(nNode, 0, m_nNumNodes-1); nSkel=LG_Clamp(nSkel, 0, m_nNumSkels-1); static MeshNode* pCur; pCur=&m_MeshNodes[nNode]; if((pCur->m_pSkel==m_pSkels[nSkel]) && (pCur->m_nAnim==nAnim)) { //If we set the animation to the current animation, //then we need to insure that we aren't queing a new animation //and further, that we don't reset the animation, but we will //changed the speed (which won't take effect until the current //animation completes). pCur->m_pNextSkel=LG_NULL; pCur->m_fPostTransSpeed=fSpeed; } else if(pCur->m_pPrevSkel) { //If we are currently transitioning, then we'll que up //the new animation (that is we wait for the current //transition to complete, then we transition to the //new animation (note that if the new animation is the //same animation we are transitioning to then the //case above will occur. pCur->m_pNextSkel=m_pSkels[nSkel]; pCur->m_nNextAnim=nAnim; pCur->m_fPostTransSpeed=fSpeed; #if 0 //We won't use the fTransitionTime value because //it could cause some jumping, when we change the //m_fAnimSpeed. pCur->m_fAnimSpeed=fTransitionTime; #endif } else { //If this is just a regular transition then we //need only set the new values, and save the old values //for the transition: //Set the current values, to the old values: pCur->m_fPrevAnimProgress=pCur->m_fAnimProgress; pCur->m_pPrevSkel=pCur->m_pSkel; pCur->m_nPrevAnim=pCur->m_nAnim; //Set the new values pCur->m_fAnimProgress=0.0f; //We save the transition time as teh speed, because it will //be the speed during the transition. pCur->m_fAnimSpeed=fTransitionTime; pCur->m_fElapsed=0.0f; //We'll save the future speed, the anim speed will change //to this after the transition is complete. pCur->m_fPostTransSpeed=fSpeed; pCur->m_nAnim=nAnim; pCur->m_pSkel=m_pSkels[nSkel]; } } lg_bool CLMeshTree::Serialize(lg_void*, ReadWriteFn, RW_MODE) { return LG_FALSE; } #include "lw_ai_sdk.h" lg_void CLMeshTree::SetAnimation(lg_dword nFlags) { if(!LG_CheckFlag(nFlags, LWAI_ANIM_CHANGE)) return; SetAnimation( LWAI_GetAnimNode(nFlags), LWAI_GetAnimSkel(nFlags), LWAI_GetAnimAnim(nFlags), LWAI_GetAnimSpeed(nFlags), LWAI_GetAnimTrans(nFlags)); } <file_sep>/games/Legacy-Engine/Source/lm_sys/lm_skel_lg.h #ifndef __LM_SKEL_LG_H__ #define __LM_SKEL_LG_H__ #include "lm_skel.h" class CLSkelLG: public CLSkel2 { public: virtual lg_bool Load(LMPath szFile); virtual lg_bool Save(LMPath szFile); }; #endif __LM_SKEL_LG_H__<file_sep>/games/Legacy-Engine/Source/engine/lt_sys.h //lt_sys.h - The Legacy Timer //Copyright (c) 2007 <NAME> #ifndef __LT_SYS_H__ #define __LT_SYS_H__ #include "lg_types.h" lg_dword LT_GetTimeMS(); //Return the time since the game was started in milliseconds. class CLTimer { private: lg_dword m_dwInitialTime; lg_dword m_dwTime; lg_dword m_dwLastTime; lg_dword m_dwElapsed; lg_float m_fTime; lg_float m_fLastTime; lg_float m_fElapsed; public: CLTimer(); void Initialize(); //Should only be called once. void Update(); //Update should be called once per frame. lg_dword GetTime(); //return time in milliseconds lg_dword GetElapsed(); //return time elapsed in milliseconds. lg_float GetFTime(); //Return floating time in seconds lg_float GetFElapsed(); //return floating time elapsed in seconds }; class CElementTimer { protected: static CLTimer s_Timer; }; #endif __LT_SYS_H__<file_sep>/games/Legacy-Engine/Source/engine/lx_mesh_tree.cpp #include "lx_sys.h" void LX_MTreeStart(void* userData, const XML_Char* name, const XML_Char** atts); void LX_MTreeEnd(void* userData, const XML_Char* name); lg_bool LX_LoadMeshTree(const lg_path szXMLFile, lx_mesh_tree_data* pOut) { pOut->bYaw180=LG_FALSE; pOut->fScale=1.0f; return LX_Process(szXMLFile, LX_MTreeStart, LX_MTreeEnd, LG_NULL, pOut); } void LX_MTreeStart(void* userData, const XML_Char* name, const XML_Char** atts) { lx_mesh_tree_data* pData=(lx_mesh_tree_data*)userData; LX_START_TAG LX_TAG(mesh_tree) { LX_START_ATTR LX_ATTR_DWORD(pData->nNodeCount, node_count) LX_ATTR_DWORD(pData->nSkelCount, skel_count) LX_ATTR_STRING(pData->szName, name, LG_MAX_STRING) LX_ATTR_DWORD(pData->bYaw180, yaw_180) LX_ATTR_FLOAT(pData->fScale, scale) LX_END_ATTR pData->nSkelCount=LG_Clamp(pData->nSkelCount, 0, CLMeshTree::MT_MAX_SKELS); pData->nNodeCount=LG_Clamp(pData->nNodeCount, 0, CLMeshTree::MT_MAX_MESH_NODES); } LX_TAG(node) { lg_dword nID=0; lg_dword nParent=0; lg_string szName; lg_string szParentJoint; lg_path szMeshFile; lg_path szSkinFile; lg_path szDefSkelFile; szName[0]=0; szParentJoint[0]=0; szMeshFile[0]=0; szSkinFile[0]=0; szDefSkelFile[0]=0; LX_START_ATTR LX_ATTR_DWORD(nID, id) LX_ATTR_STRING(szName, name, LG_MAX_STRING) LX_ATTR_STRING(szMeshFile, mesh_file, LG_MAX_PATH) LX_ATTR_DWORD(nParent, parent_node) LX_ATTR_STRING(szParentJoint, parent_joint, LG_MAX_STRING) LX_ATTR_STRING(szSkinFile, skin_file, LG_MAX_PATH) LX_ATTR_STRING(szDefSkelFile, default_skel, LG_MAX_PATH) LX_END_ATTR //Copy the data in: if(nID<pData->nNodeCount) { pData->Nodes[nID].nParentNode=nParent; LG_strncpy(pData->Nodes[nID].szName, szName, LG_MAX_STRING); LG_strncpy(pData->Nodes[nID].szParentJoint, szParentJoint, LG_MAX_STRING); LG_strncpy(pData->Nodes[nID].szMeshFile, szMeshFile, LG_MAX_PATH); LG_strncpy(pData->Nodes[nID].szSkinFile, szSkinFile, LG_MAX_PATH); LG_strncpy(pData->Nodes[nID].szDefSkelFile, szDefSkelFile, LG_MAX_PATH); //Should probably print a warning if the base node nID==0 has a parent //node or parent joint specified. } } LX_TAG(skel) { lg_dword nID=0; lg_path szFile; szFile[0]=0; LX_START_ATTR LX_ATTR_STRING(szFile, file, LG_MAX_PATH) LX_ATTR_DWORD(nID, id) LX_END_ATTR //Go ahead and insert the skel file. if(nID<pData->nSkelCount) { LG_strncpy(pData->szSkels[nID], szFile, LG_MAX_PATH); } else { Err_Printf( "LX_LoadMeshTree WARNING: Skeleton id (%d) for \"%s\" out of range.", nID, pData->szName); } } LX_END_TAG } void LX_MTreeEnd(void* userData, const XML_Char* name) { }<file_sep>/tools/AutoEmailer/U_emailer.php <?php mail("<EMAIL>", "Question", "Could you please check to see...", "From: <EMAIL>); ?><file_sep>/games/Legacy-Engine/Source/engine/lg_cvars.h /* lg_cvars.h - The cvars used in the legacy game. This file is where all the cvars used in the game should be declared, though they are registered in the CLGame::LG_RegisterCvars method (lg_sys_init.h). All cvars and defintions should be declared here. the DECLARE_DEF/CVAR macros will create statements similar to the following: const char DEF/CVAR_NAME = "NAME" From that point on the cvar can be refered to by CVAR_NAME so it isn't necessary to enter the string every time and hence it is unlikely to make a mistake by putting the wrong string in the code and not knowing why it isn't working right. */ #ifndef __LG_CVARS_H__ #define __LG_CVARS_H__ #include "../lc_sys2/lc_sys2.h" //Definition declarations. #ifdef DECLARING_CVARS #define DECLARE_DEF(name) extern const char DEF_##name[] = #name #define DECLARE_CVAR(name) extern const char CVAR_##name[] = #name #else DECLARING_CVARS #define DECLARE_DEF(name) extern const char DEF_##name[] #define DECLARE_CVAR(name) extern const char CVAR_##name[] #endif DECLARING_CVARS //Boolean definitions DECLARE_DEF(TRUE); DECLARE_DEF(FALSE); //Adapter ID definitions DECLARE_DEF(ADAPTER_DEFAULT); //Defice type definitions DECLARE_DEF(HAL); DECLARE_DEF(REF); DECLARE_DEF(SW); //Vertex processing definitions DECLARE_DEF(SWVP); DECLARE_DEF(HWVP); DECLARE_DEF(MIXEDVP); //Texture format declarations //Back Buffer formats DECLARE_DEF(FMT_UNKNOWN); DECLARE_DEF(FMT_A8R8G8B8); DECLARE_DEF(FMT_X8R8G8B8); DECLARE_DEF(FMT_R5G6B5); DECLARE_DEF(FMT_X1R5G5B5); DECLARE_DEF(FMT_A1R5G5B5); DECLARE_DEF(FMT_A2R10G10B10); //Depth stencil formats DECLARE_DEF(FMT_D16_LOCKABLE); DECLARE_DEF(FMT_D32); DECLARE_DEF(FMT_D15S1); DECLARE_DEF(FMT_D24S8); DECLARE_DEF(FMT_D24X8); DECLARE_DEF(FMT_D24X4S4); DECLARE_DEF(FMT_D16); DECLARE_DEF(FMT_D32F_LOCKABLE); DECLARE_DEF(FMT_D24FS8); //Multi sample types /* DECLARE_DEF(D3DMULTISAMPLE_NONE); DECLARE_DEF(D3DMULTISAMPLE_NONMASKABLE); DECLARE_DEF(D3DMULTISAMPLE_2_SAMPLES); DECLARE_DEF(D3DMULTISAMPLE_3_SAMPLES); DECLARE_DEF(D3DMULTISAMPLE_4_SAMPLES); DECLARE_DEF(D3DMULTISAMPLE_5_SAMPLES); DECLARE_DEF(D3DMULTISAMPLE_6_SAMPLES); DECLARE_DEF(D3DMULTISAMPLE_7_SAMPLES); DECLARE_DEF(D3DMULTISAMPLE_8_SAMPLES); DECLARE_DEF(D3DMULTISAMPLE_9_SAMPLES); DECLARE_DEF(D3DMULTISAMPLE_10_SAMPLES); DECLARE_DEF(D3DMULTISAMPLE_11_SAMPLES); DECLARE_DEF(D3DMULTISAMPLE_12_SAMPLES); DECLARE_DEF(D3DMULTISAMPLE_13_SAMPLES); DECLARE_DEF(D3DMULTISAMPLE_14_SAMPLES); DECLARE_DEF(D3DMULTISAMPLE_15_SAMPLES); DECLARE_DEF(D3DMULTISAMPLE_16_SAMPLES); */ //Swap effect DECLARE_DEF(SWAP_DISCARD); DECLARE_DEF(SWAP_FLIP); DECLARE_DEF(SWAP_COPY); //Presentation intervals /* DECLARE_DEF(D3DPRESENT_INTERVAL_DEFAULT); DECLARE_DEF(D3DPRESENT_INTERVAL_ONE); DECLARE_DEF(D3DPRESENT_INTERVAL_TWO); DECLARE_DEF(D3DPRESENT_INTERVAL_THREE); DECLARE_DEF(D3DPRESENT_INTERVAL_FOUR); DECLARE_DEF(D3DPRESENT_INTERVAL_IMMEDIATE); */ //Filter types DECLARE_DEF(POINT); DECLARE_DEF(LINEAR); DECLARE_DEF(BILINEAR); DECLARE_DEF(TRILINEAR); DECLARE_DEF(ANISOTROPIC); //Physics Engine Types: DECLARE_DEF(PHYS_LEGACY); DECLARE_DEF(PHYS_NEWTON); DECLARE_DEF(PHYS_PHYSX); //CVar declarations //D3D Initialization DECLARE_CVAR(v_AdapterID); DECLARE_CVAR(v_DeviceType); DECLARE_CVAR(v_VertexProc); DECLARE_CVAR(v_FPU_Preserve); DECLARE_CVAR(v_MultiThread); DECLARE_CVAR(v_PureDevice); DECLARE_CVAR(v_DisableDriverManagement); DECLARE_CVAR(v_AdapterGroupDevice); DECLARE_CVAR(v_Managed); //D3DPRESENT_PARAMETERS DECLARE_CVAR(v_Width); DECLARE_CVAR(v_Height); DECLARE_CVAR(v_BitDepth); DECLARE_CVAR(v_ScreenBuffers); DECLARE_CVAR(v_FSAAQuality); DECLARE_CVAR(v_SwapEffect); DECLARE_CVAR(v_Windowed); DECLARE_CVAR(v_EnableAutoDepthStencil); DECLARE_CVAR(v_AutoDepthStencilFormat); //D3DPP_Flags DECLARE_CVAR(v_LockableBackBuffer); DECLARE_CVAR(v_DiscardDepthStencil); DECLARE_CVAR(v_DeviceClip); DECLARE_CVAR(v_VideoHint); //More D3DPP DECLARE_CVAR(v_RefreshRate); DECLARE_CVAR(v_EnableVSync); //Texture filter cvars //FILTER_MODE "v_TextureFilter" //FILTER_MAXANISOTROPY "v_MaxAnisotropy" DECLARE_CVAR(v_TextureFilter); DECLARE_CVAR(v_MaxAnisotropy); //Texture loading cvars DECLARE_CVAR(tm_UseMipMaps); //DECLARE_CVAR(tm_HWMipMaps); //DECLARE_CVAR(tm_MipGenFilter); DECLARE_CVAR(tm_TextureSizeLimit); DECLARE_CVAR(tm_Force16BitTextures); //DECLARE_CVAR(tm_32BitTextureAlpha); //DECLARE_CVAR(tm_16BitTextureAlpha); DECLARE_CVAR(tm_DefaultTexture); //Debug cvars DECLARE_CVAR(v_DebugWireframe); //Sound cvars DECLARE_CVAR(s_Channels); DECLARE_CVAR(s_Frequency); DECLARE_CVAR(s_BitsPerSample); DECLARE_CVAR(s_MusicVolume); //Console cvars DECLARE_CVAR(lc_UseLegacyFont); DECLARE_CVAR(lc_BG); DECLARE_CVAR(lc_Font); DECLARE_CVAR(lc_FontColor); DECLARE_CVAR(lc_LegacyFont); DECLARE_CVAR(lc_LegacyFontSizeInFile); DECLARE_CVAR(lc_FontSize); //game cvars DECLARE_CVAR(lg_ShouldQuit); DECLARE_CVAR(lg_AverageFPS); //Debug Dump? DECLARE_CVAR(lg_DumpDebugData); //Input cvars DECLARE_CVAR(li_ExclusiveKB); DECLARE_CVAR(li_ExclusiveMouse); DECLARE_CVAR(li_DisableWinKey); DECLARE_CVAR(li_MouseSmoothing); //Server cvars DECLARE_CVAR(srv_MaxEntities); DECLARE_CVAR(srv_Name); DECLARE_CVAR(srv_PhysEngine); //Additional game cvars DECLARE_CVAR(lg_MaxMeshes); DECLARE_CVAR(lg_MaxSkels); DECLARE_CVAR(lg_MaxTex); DECLARE_CVAR(lg_MaxFx); DECLARE_CVAR(lg_MaxMtr); DECLARE_CVAR(lg_MaxSkin); DECLARE_CVAR(lg_GameLib); //Effect manager cvars DECLARE_CVAR(fxm_DefaultFx); #endif __LG_CVARS_H__<file_sep>/games/Legacy-Engine/Source/engine/ls_ogg.c /* ls_ogg.c - ogg file support for the Legacy Sound System Copyright (c) 2006, <NAME>. */ #include <vorbis\codec.h> #include <vorbis\vorbisfile.h> #include "lf_sys2.h" #include "common.h" #include "ls_ogg.h" #include "lg_malloc.h" typedef struct _OGGFILE{ WAVEFORMATEX m_Format; lg_bool m_bOpen; OggVorbis_File m_VorbisFile; vorbis_info* m_pVorbisInfo; void* m_pBufferPtr; void* m_pBuffer; lg_dword m_nBufferSize; lg_dword m_nNumSamples; lg_bool m_bEOF; }OGGFILE, *POGGFILE; size_t ogg_read(void* ptr, size_t size, size_t nmemb, void* datasource); int ogg_seek(void* datasource, ogg_int64_t offset, int whence); int ogg_close(void* datasource); long ogg_tell(void* datasource); lg_bool Ogg_GetStreamInfo(OGGFILE* lpOggs); lg_void* Ogg_CreateFromDisk(lg_str szFilename) { OGGFILE* lpNew=LG_NULL; ov_callbacks cb; LF_FILE3 File=LG_NULL; int nErr; lpNew=LG_Malloc(sizeof(OGGFILE)); if(!lpNew) return LG_NULL; memset(lpNew, 0, sizeof(OGGFILE)); memset(&cb, 0, sizeof(cb)); cb.read_func=ogg_read; cb.seek_func=ogg_seek; cb.close_func=ogg_close; cb.tell_func=ogg_tell; File=LF_Open(szFilename, LF_ACCESS_READ, LF_OPEN_EXISTING); if(!File) { LG_Free(lpNew); return LG_NULL; } /* We don't ever call the File_Close function here, because the callbacks functions will call it on ogg_close callback. */ nErr=ov_open_callbacks( File, &lpNew->m_VorbisFile, LG_NULL, 0, cb); if(nErr<0) { LG_Free(lpNew); return LG_NULL; } if(!Ogg_GetStreamInfo(lpNew)) { ov_clear(&lpNew->m_VorbisFile); LG_Free(lpNew); return LG_NULL; } lpNew->m_bOpen=LG_TRUE; return lpNew; } /* OGGFILE* Ogg_CreateFromData(void* lpData, lg_dword dwDataSize) { return LG_NULL; } */ lg_bool Ogg_Delete(lg_void* lpOgg) { OGGFILE* lpOggs=(OGGFILE*)lpOgg; if(!lpOggs) return LG_FALSE; ov_clear(&lpOggs->m_VorbisFile); LG_Free(lpOggs); return LG_TRUE; } lg_dword Ogg_Read(lg_void* lpOgg, void* lpDest, lg_dword dwSizeToRead) { OGGFILE* lpOggs=(OGGFILE*)lpOgg; char* pCurBuffer=(char*)lpDest; lg_dword nBytesRead=0; int iSection=0; if(!lpOggs || !lpDest) return 0; while((nBytesRead<dwSizeToRead) && !lpOggs->m_bEOF) { lg_long iRet=ov_read( &lpOggs->m_VorbisFile, pCurBuffer, dwSizeToRead-nBytesRead, 0, 2, 1, &iSection); if(iRet==0 || iSection !=0) lpOggs->m_bEOF=LG_TRUE; nBytesRead+=iRet; pCurBuffer+=iRet; } return nBytesRead; } lg_bool Ogg_Reset(lg_void* lpOgg) { OGGFILE* lpOggs=(OGGFILE*)lpOgg; if(!lpOggs) return LG_FALSE; lpOggs->m_bEOF=LG_FALSE; ov_pcm_seek(&lpOggs->m_VorbisFile, 0); return LG_TRUE; } WAVEFORMATEX* Ogg_GetFormat(lg_void* lpOgg, WAVEFORMATEX* lpFormat) { OGGFILE* lpOggs=(OGGFILE*)lpOgg; if(!lpOggs) return LG_NULL; if(lpFormat) { memcpy(lpFormat, &lpOggs->m_Format, sizeof(WAVEFORMATEX)); return lpFormat; } else return &lpOggs->m_Format; } lg_dword Ogg_GetSize(lg_void* lpOgg) { OGGFILE* lpOggs=(OGGFILE*)lpOgg; if(!lpOggs) return 0; return lpOggs->m_nNumSamples*lpOggs->m_Format.nChannels*lpOggs->m_Format.wBitsPerSample/8; } lg_bool Ogg_IsEOF(lg_void* lpOgg) { OGGFILE* lpOggs=(OGGFILE*)lpOgg; if(!lpOggs) return LG_TRUE; return lpOggs->m_bEOF; } lg_bool Ogg_GetStreamInfo(OGGFILE* lpOggs) { if(!lpOggs) return LG_FALSE; lpOggs->m_pVorbisInfo=ov_info(&lpOggs->m_VorbisFile, -1); lpOggs->m_nNumSamples=(long)ov_pcm_total(&lpOggs->m_VorbisFile, -1); lpOggs->m_Format.wFormatTag=WAVE_FORMAT_PCM; lpOggs->m_Format.nChannels=lpOggs->m_pVorbisInfo->channels; lpOggs->m_Format.nSamplesPerSec=lpOggs->m_pVorbisInfo->rate; lpOggs->m_Format.wBitsPerSample=16; lpOggs->m_Format.nBlockAlign=lpOggs->m_Format.nChannels*lpOggs->m_Format.wBitsPerSample/8; lpOggs->m_Format.nAvgBytesPerSec=lpOggs->m_Format.nSamplesPerSec*lpOggs->m_Format.nBlockAlign; lpOggs->m_Format.cbSize=0; return LG_TRUE; } /**************************************** OGG Callback Functions for reading. ****************************************/ size_t ogg_read(void* ptr, size_t size, size_t nmemb, void* datasource) { return LF_Read(datasource, ptr, size*nmemb); } int ogg_seek(void* datasource, ogg_int64_t offset, int whence) { int nMode; if(whence==SEEK_SET) nMode=LF_SEEK_BEGIN; else if(whence==SEEK_CUR) nMode=LF_SEEK_CURRENT; else if(whence==SEEK_END) nMode=LF_SEEK_END; else return 1; LF_Seek(datasource, nMode, (lg_long)offset); return 0; } int ogg_close(void* datasource) { return !LF_Close(datasource); } long ogg_tell(void* datasource) { return LF_Tell(datasource); } <file_sep>/games/Explor2002/Source_Old/ExplorED DOS/dosexplored/BINREAD.C #include <stdio.h> void BinRead(FILE *fin); main(int argc, char *argv[]) { FILE *fptr; char *filename; if (argv != NULL) filename=argv[1]; else filename="new.map"; fptr = fopen(filename, "rb"); if(filename == NULL) printf("Failed to open %s", filename); else BinRead(fptr); fclose(fptr); return 0; } void BinRead(FILE *fin) { int i; int x; i = 1; printf("Reading Binary\n"); while(!feof(fin)){ printf("%i: ", i); i++; fread(&x, sizeof(int), (size_t)1, fin); printf("%i\n", x); if(i==300) getch(); } }<file_sep>/games/Legacy-Engine/Source/engine/lg_mmgr.cpp #include "lg_mmgr.h" #include "lg_err.h" #include "lg_err_ex.h" #include "lg_func.h" CLMMgr* CLMMgr::s_pMMgr=LG_NULL; CLMeshLG* CLMMgr::MM_LoadMesh(lg_path szFilename, lg_dword nFlags) { return s_pMMgr->LoadMesh(szFilename, nFlags); } CLSkelLG* CLMMgr::MM_LoadSkel(lg_path szFilename, lg_dword nFlags) { return s_pMMgr->LoadSkel(szFilename, nFlags); } /*Constructor PRE: Direct3D must also be initialized, and we must decide the maximum number of skeletons and meshes, a mesh manager should not have been previously initialized. POST: The mesh manager is initialized, and the global manager is set. */ CLMMgr::CLMMgr(IDirect3DDevice9 *pDevice, lg_dword nMaxMesh, lg_dword nMaxSkel) : m_MeshMgr(pDevice, nMaxMesh) , m_SkelMgr(nMaxSkel) { //If the Mesh Manager already exists, then we have failed, because //it should only be initialized once. if(s_pMMgr) { throw LG_ERROR(LG_ERR_DEFAULT, LG_TEXT("The Mesh Manager can only be initialized once.")); } //Set the global manager s_pMMgr=this; Err_Printf( "MMgr: Initialized with %u meshes & %u skels available.", nMaxMesh, nMaxSkel); } /* Destructor PRE: The mesh manager should be deleted before Direct3D is uninitialized. POST: Deletes everything associated with the manager, no meshes should be used after it is deleted, or memory error will occur. */ CLMMgr::~CLMMgr() { //Clear the global manager. s_pMMgr=LG_NULL; //Delete all meshes UnloadMeshes(MM_FORCE_UNLOAD); UnloadSkels(MM_FORCE_UNLOAD); m_MeshMgr.UnloadItems(); m_SkelMgr.UnloadItems(); } /* PRE: Initialized POST: Returns the mesh if it exists, else returns NULL, also sets flags for the mesh. */ CLMeshLG* CLMMgr::LoadMesh(lg_path szFilename, lg_dword nFlags) { hm_item mesh=m_MeshMgr.Load(szFilename, nFlags); CLMeshLG* pOut=m_MeshMgr.GetInterface(mesh); //Just in case we loaded the mesh previously without //the MM_NOD3D flag, and we want the mesh to be renderable //now we'll do a check. if(pOut && !LG_CheckFlag(nFlags, MM_NOD3D)) { pOut->MakeD3DReady(pOut->D3DR_FLAG_LOAD_DEF_TEX); } return pOut; } /* PRE: Initialized POST: Returns the mesh if it exists, else returns NULL, also sets flags for the mesh. */ CLSkelLG* CLMMgr::LoadSkel(lg_path szFilename, lg_dword nFlags) { hm_item skel=m_SkelMgr.Load(szFilename, nFlags); CLSkelLG* pOut=m_SkelMgr.GetInterface(skel); return pOut; } void CLMMgr::UnloadMeshes(lg_dword nFlags) { m_MeshMgr.UnloadItems(); #if 0 for(lg_dword i=0; i<m_nMaxMeshes; i++) { if(LG_CheckFlag(nFlags, this->MM_FORCE_UNLOAD) || !LG_CheckFlag(m_pMeshMem[i].nFlags, this->MM_RETAIN)) { m_pMeshMem[m_pMeshMem[i].nHashCode].nHashCount--; m_pMeshMem[i].nHashCode=MM_EMPTY_NODE; m_pMeshMem[i].Mesh.Unload(); m_pMeshMem[i].nFlags=0; m_pMeshMem[i].szName[0]=0; } } #endif } void CLMMgr::UnloadSkels(lg_dword nFlags) { m_SkelMgr.UnloadItems(); #if 0 for(lg_dword i=0; i<m_nMaxSkels; i++) { if(LG_CheckFlag(nFlags, this->MM_FORCE_UNLOAD) || !LG_CheckFlag(m_pSkelList[i].nFlags, this->MM_RETAIN)) { m_pSkelList[m_pSkelList[i].nHashCode].nHashCount--; m_pSkelList[i].nHashCode=MM_EMPTY_NODE; m_pSkelList[i].Skel.Unload(); m_pSkelList[i].nFlags=0; m_pSkelList[i].szName[0]=0; } } #endif } void CLMMgr::ValidateMeshes() { m_MeshMgr.Validate(); #if 0 for(lg_dword i=0; i<m_nMaxMeshes; i++) { if(m_pMeshMem[i].nHashCode!=MM_EMPTY_NODE) m_pMeshMem[i].Mesh.Validate(); } #endif } void CLMMgr::InvalidateMeshes() { m_MeshMgr.Invalidate(); #if 0 for(lg_dword i=0; i<m_nMaxMeshes; i++) { if(m_pMeshMem[i].nHashCode!=MM_EMPTY_NODE) m_pMeshMem[i].Mesh.Invalidate(); } #endif } void CLMMgr::PrintMeshes() { /* for(lg_dword i=0; i<m_nMaxMeshes; i++) { if(m_pMeshMem[i].nHashCode!=MM_EMPTY_NODE) Err_Printf("%i \"%s\" %i@%i (%s) (%i)", i, m_pMeshMem[i].szName, m_pMeshMem[i].nHashCode, i, m_pMeshMem[i].Mesh.IsD3DReady()?"D3D Ready":"No Render", m_pMeshMem[i].nHashCount); else Err_Printf("%i Empty (%i)", i, m_pMeshMem[i].nHashCount); } */ m_MeshMgr.PrintDebugInfo(); } void CLMMgr::PrintSkels() { m_SkelMgr.PrintDebugInfo(); #if 0 for(lg_dword i=0; i<m_nMaxSkels; i++) { if(m_pSkelList[i].nHashCode!=MM_EMPTY_NODE) Err_Printf("%i \"%s\" %i@%i (%i)", i, m_pSkelList[i].szName, m_pSkelList[i].nHashCode, i, m_pSkelList[i].nHashCount); else Err_Printf("%i Empty (%i)", i, m_pSkelList[i].nHashCount); } #endif } /*********************** *** The Mesh Manager *** ***********************/ CLMeshMgr::CLMeshMgr(IDirect3DDevice9* pDevice, lg_dword nMaxMeshes) : CLHashMgr(nMaxMeshes, "MeshMgr") , m_pMeshMem(LG_NULL) , m_stkMeshes() { //We save a reference to the device, //if the device doesn't exist, then we can't //create D3D meshes. CLMeshLG::LM_Init(pDevice); //Create and initialize the mesh stack. //A list of meshes is stored in a stack, that //way when we need a new mesh we can retrive one from //the stack without creating a new instance. m_pMeshMem=new MeshItem[m_nMaxItems]; if(!m_pMeshMem) throw LG_ERROR(LG_ERR_OUTOFMEMORY, LG_NULL); for(lg_dword i=0; i<m_nMaxItems; i++) { m_stkMeshes.Push(&m_pMeshMem[i]); } //The default item is simply nothing for the mesh manager. //m_pDefItem=LG_NULL; Err_Printf(LG_TEXT("MeshMgr: Initialized with %d meshes available."), m_nMaxItems); } CLMeshMgr::~CLMeshMgr() { UnloadItems(); //m_pDefItem=LG_NULL; m_stkMeshes.Clear(); LG_SafeDeleteArray(m_pMeshMem); CLMeshLG::LM_Shutdown(); } MeshItem* CLMeshMgr::DoLoad(lg_path szFilename, lg_dword nFlags) { MeshItem* pOut = (MeshItem*)m_stkMeshes.Pop(); if(!pOut) return LG_NULL; if(pOut->Mesh.Load(szFilename)) { if(!LG_CheckFlag(CLMMgr::MM_NOD3D, nFlags)) { pOut->Mesh.MakeD3DReady(pOut->Mesh.D3DR_FLAG_LOAD_DEF_TEX); } } else { m_stkMeshes.Push(pOut); pOut=LG_NULL; } return pOut; } void CLMeshMgr::DoDestroy(MeshItem* pItem) { pItem->Mesh.Unload(); m_stkMeshes.Push(pItem); } CLMeshLG* CLMeshMgr::GetInterface(hm_item mesh) { if(mesh==0 || mesh==CLHashMgr::HM_DEFAULT_ITEM) { return LG_NULL; } else { return &m_pItemList[mesh-1].pItem->Mesh; } } void CLMeshMgr::Validate() { //We start at 1 because the default mesh, is //not loaded. for(lg_dword i=1; i<m_nMaxItems; i++) { if(m_pItemList[i].nHashCode!=CLHashMgr::HM_EMPTY_NODE) { m_pItemList[i].pItem->Mesh.Validate(); } } } void CLMeshMgr::Invalidate() { //We start at 1 because the default mesh, is //not loaded. for(lg_dword i=1; i<m_nMaxItems; i++) { if(m_pItemList[i].nHashCode!=CLHashMgr::HM_EMPTY_NODE) { m_pItemList[i].pItem->Mesh.Invalidate(); } } } /******************************* *** Skeleton Manager Methods *** *******************************/ CLSkelMgr::CLSkelMgr(lg_dword nMaxSkels) : CLHashMgr(nMaxSkels, "SkelMgr") , m_pSkelMem(LG_NULL) , m_stkSkels() { //Create and initialize the skel stack. //A list of skels is stored in a stack, that //way when we need a new skel we can retrive one from //the stack without creating a new instance. m_pSkelMem=new SkelItem[m_nMaxItems]; if(!m_pSkelMem) throw LG_ERROR(LG_ERR_OUTOFMEMORY, LG_NULL); for(lg_dword i=0; i<m_nMaxItems; i++) { m_stkSkels.Push(&m_pSkelMem[i]); } //The default item is simply nothing for the skel manager. //m_pDefItem=LG_NULL; Err_Printf(LG_TEXT("SkelMgr: Initialized with %d skels available."), m_nMaxItems); } CLSkelMgr::~CLSkelMgr() { CLHashMgr::UnloadItems(); //m_pDefItem=LG_NULL; m_stkSkels.Clear(); LG_SafeDeleteArray(m_pSkelMem); } SkelItem* CLSkelMgr::DoLoad(lg_path szFilename, lg_dword nFlags) { SkelItem* pOut = (SkelItem*)m_stkSkels.Pop(); if(!pOut) return LG_NULL; if(!pOut->Skel.Load(szFilename)) { m_stkSkels.Push(pOut); pOut=LG_NULL; } return pOut; } void CLSkelMgr::DoDestroy(SkelItem* pItem) { if(!pItem) return; pItem->Skel.Unload(); m_stkSkels.Push(pItem); } CLSkelLG* CLSkelMgr::GetInterface(hm_item skel) { if(skel==0 || skel==CLHashMgr::HM_DEFAULT_ITEM) { return LG_NULL; } else { return &m_pItemList[skel-1].pItem->Skel; } } <file_sep>/games/Explor2002/Source/Game/tilemgr.cpp //Tile Manager #include "tilemgr.h" #include "tiles.h" #include "bmp.h" CTileSet::CTileSet(){ } CTileSet::~CTileSet(){ } BOOL CTileSet::draw(LPDIRECTDRAWSURFACE dest, int index, int x, int y){ //m_cTiles[index]->draw(dest, x, y); switch (index){ //Facing case 0: m_cTiles[0]->draw(dest, x, y, 320, 320); break; case 1: m_cTiles[0]->draw(dest, x, y, 160, 160); break; case 2: m_cTiles[0]->draw(dest, x, y, 80, 80); break; //At an angle to right case 3: m_cTiles[1]->draw(dest, x, y, 160, 640); break; case 4: m_cTiles[1]->draw(dest, x, y, 80, 320); break; case 5: m_cTiles[1]->draw(dest, x, y, 40, 160); break; case 6: m_cTiles[1]->draw(dest, x, y, 20, 80); break; //At an angle to right case 7: m_cTiles[2]->draw(dest, x, y, 160, 640); break; case 8: m_cTiles[2]->draw(dest, x, y, 80, 320); break; case 9: m_cTiles[2]->draw(dest, x, y, 40, 160); break; case 10: m_cTiles[2]->draw(dest, x, y, 20, 80); break; //at an angle 1 row to the left case 11: m_cTiles[1]->draw(dest, x, y, 160, 320); break; case 12: m_cTiles[1]->draw(dest, x, y, 120, 160); break; case 13: m_cTiles[1]->draw(dest, x, y, 60, 80); break; //at an angle 1 row to the right case 14: m_cTiles[2]->draw(dest, x, y, 160, 320); break; case 15: m_cTiles[2]->draw(dest, x, y, 120, 160); break; case 16: m_cTiles[2]->draw(dest, x, y, 60, 80); break; //at an angle 2 rows to the left case 17: m_cTiles[1]->draw(dest, x, y, 200,160); break; case 18: m_cTiles[1]->draw(dest, x, y, 100, 80); break; //at an angle 2 rows to the right case 19: m_cTiles[2]->draw(dest, x, y, 200, 160); break; case 20: m_cTiles[2]->draw(dest, x, y, 100, 80); break; //at an angle 3 rows to the left case 21: m_cTiles[1]->draw(dest, x, y, 140, 80); break; //at an angle 3 rows to the right case 22: m_cTiles[2]->draw(dest, x, y, 140, 80); break; } return TRUE; } BOOL CTileSet::Restore(){ BOOL result=TRUE; for(int i=0;i<NUM_TILES;i++){ if(SUCCEEDED(m_cTiles[i]->Restore()))result=result&&TRUE; } return result; } BOOL CTileSet::Release(){ for(int i=0; i<NUM_TILES;i++){ m_cTiles[i]->Release(); } return TRUE; } BOOL CTileSet::GetImages(CBitmapReader *bitmap){ m_cTiles[0]->load(bitmap, 0, 0, 160, 160); m_cTiles[1]->load(bitmap, 160, 0, 40, 160); m_cTiles[2]->load(bitmap, 200, 0, 40, 160); return TRUE; } /* BOOL CTileSet::LoadImageFile(CBitmapReader *buffer){ return buffer.load(filename); } */ void CTileSet::InitTileObjects(){ m_cTiles[0]=new CTileObject(160, 160); m_cTiles[1]=new CTileObject(40, 160); m_cTiles[2]=new CTileObject(40, 160); } <file_sep>/games/Legacy-Engine/Source/engine/lx_mtr.cpp #include "lg_xml.h" #include "lx_sys.h" #include "lg_func.h" #include "lg_err.h" #include <string.h> void LX_MtrStart(void* userData, const XML_Char* name, const XML_Char** atts); void LX_MtrEnd(void* userData, const XML_Char* name); lg_bool LX_LoadMtr(const lg_path szFilename, lx_mtr* pMtr) { LF_FILE3 fileScript=LF_Open(szFilename, LF_ACCESS_READ|LF_ACCESS_MEMORY, LF_OPEN_EXISTING); if(!fileScript) { Err_Printf("LX_LoadMtr ERROR: Could not open \"%s\".", szFilename); return LG_FALSE; } XML_Parser parser = XML_ParserCreate_LG(LG_NULL); if(!parser) { Err_Printf("LX_LoadMtr ERROR: Could not create XML parser. (%s)", szFilename); LF_Close(fileScript); return LG_FALSE; } pMtr->szFx[0]=0; pMtr->szTexture[0]=0; XML_ParserReset(parser, LG_NULL); XML_SetUserData(parser, pMtr); XML_SetElementHandler(parser, LX_MtrStart, LX_MtrEnd); //Do the parsing lg_bool bSuccess=XML_Parse(parser, (const char*)LF_GetMemPointer(fileScript), LF_GetSize(fileScript), LG_TRUE); if(!bSuccess) { Err_Printf("LX_LoadMtr ERROR: Parse error at line %d: \"%s\"", XML_GetCurrentLineNumber(parser), XML_ErrorString(XML_GetErrorCode(parser))); } LF_Close(fileScript); XML_ParserFree(parser); //The output will be in pMtr return bSuccess; } void LX_MtrStart(void* userData, const XML_Char* name, const XML_Char** atts) { lx_mtr* pMtr=(lx_mtr*)userData; if(stricmp(name, "material")==0) { for(lg_dword i=0; atts[i]; i+=2) { if(stricmp(atts[i], "texture")==0) { LG_strncpy(pMtr->szTexture, atts[i+1], LG_MAX_PATH); } else if(stricmp(atts[i], "fx")==0) { LG_strncpy(pMtr->szFx, atts[i+1], LG_MAX_PATH); } } } else { Err_Printf("LX_LoadMtr WARNING: %s is not a recognized tag.", name); } } void LX_MtrEnd(void* userData, const XML_Char* name) { } <file_sep>/games/Legacy-Engine/Source/lm_sys/lm_skel_edit.h #ifndef __LM_SKEL_EDIT_H__ #define __LM_SKEL_EDIT_H__ //The skeleton class for LMEdit.exe #include "lm_skel.h" #include <d3d9.h> class CLSkelEdit:public CLSkel2 { friend class CLSkelEdit; private: struct JointVertex{ lg_float x, y, z; lg_float psize; lg_dword color; }; static const lg_dword JOINT_VERTEX_FORMAT=D3DFVF_XYZ|D3DFVF_PSIZE|D3DFVF_DIFFUSE; struct BoneVertex{ lg_float x, y, z; lg_dword color; }; static const lg_dword BONE_VERTEX_FORMAT=D3DFVF_XYZ|D3DFVF_DIFFUSE; static const lg_dword LM_FLAG_D3D_VALID=0x00010000; public: CLSkelEdit(); ~CLSkelEdit(); lg_bool SetAnims(lg_dword nCount, SkelAnim* pAnims); lg_bool ImportFrames(CLSkelEdit* pSkel); lg_bool CalculateAABBs(float fExtent); virtual lg_bool Load(LMPath szFile); virtual lg_bool Save(LMPath szFile); virtual lg_void Unload(); lg_void Render(); lg_void RenderAABB(); lg_void SetupFrame(lg_dword nAnim, lg_float fTime); lg_void SetupFrame(lg_dword nFrame1, lg_dword nFrame2, lg_float fTime); private: D3DCOLOR m_nColor; JointVertex* m_pSkel; BoneVertex m_vAABB[16]; ml_aabb m_aabb; }; #endif __LM_SKEL_EDIT_H__<file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/ls_wav.c /* ls_wav.c - Fucntions for reading WAVE files. Copyright (c) 2006, <NAME>. */ #include "common.h" #include <lf_sys.h> #include "ls_wav.h" #include "ls_load.h" #include "lg_err.h" L_bool Wav_OpenMMIO(WAVEFILE* lpWave); L_bool Wav_ReadMMIO(WAVEFILE* lpWave); WAVEFILE* Wav_CreateFromDisk(char* szFilename) { WAVEFILE* lpNew=L_null; MMIOINFO mmioInfo; lpNew=malloc(sizeof(WAVEFILE)); if(!lpNew) return L_null; memset(lpNew, 0, sizeof(WAVEFILE)); // Open the wave file from disk. memset(&mmioInfo, 0, sizeof(mmioInfo)); mmioInfo.pIOProc=LS_MMIOProc; lpNew->m_hmmio=mmioOpen(szFilename, &mmioInfo, MMIO_ALLOCBUF|MMIO_READ); if(lpNew->m_hmmio==L_null) { free(lpNew); return L_null; } if(!Wav_OpenMMIO(lpNew)) { mmioClose(lpNew->m_hmmio, 0); free(lpNew); return L_null; } return lpNew; } /* WAVEFILE* Wav_CreateFromData(void* lpData, L_dword dwDataSize) { WAVEFILE* lpNew=L_null; MMIOINFO mmioInfo; lpNew=malloc(sizeof(WAVEFILE)); if(!lpNew) return L_null; memset(lpNew, 0, sizeof(WAVEFILE)); memset(&mmioInfo, 0, sizeof(MMIOINFO)); mmioInfo.fccIOProc = FOURCC_MEM; mmioInfo.cchBuffer = dwDataSize; mmioInfo.pchBuffer = (char*)lpData; // Open the memory buffer lpNew->m_hmmio = mmioOpen(NULL, &mmioInfo, MMIO_READ); if(!lpNew->m_hmmio) { free(lpNew); return L_null; } if(!Wav_OpenMMIO(lpNew)) { mmioClose(lpNew->m_hmmio, 0); free(lpNew); return L_null; } return lpNew; } */ L_bool Wav_Delete(WAVEFILE* lpWave) { if(!lpWave->m_hmmio) return L_false; mmioClose(lpWave->m_hmmio, 0); free(lpWave); return L_true; } L_dword Wav_Read(WAVEFILE* lpWave, void* lpDest, L_dword dwSizeToRead) { MMIOINFO mmioinfoIn; //Current status of m_hmmio. //Data member specifying how many bytes to actually //read out of the wave file. L_dword dwDataIn=0; char* lpWaveBuffer=L_null; L_dword dwStreamRead=0; L_dword dwRead=0; L_dword dwCopySize=0; if(!lpWave || !lpDest) return 0; if(!lpWave->m_hmmio) return 0; if(0 != mmioGetInfo(lpWave->m_hmmio, &mmioinfoIn, 0)) return 0; //If were not decompressing data, we can directly //use the buffer passed in to this function. lpWaveBuffer=(char*)lpDest; dwDataIn=dwSizeToRead; if(dwDataIn > lpWave->m_ck.cksize) dwDataIn=lpWave->m_ck.cksize; lpWave->m_ck.cksize -= dwDataIn; while(dwRead<dwDataIn) { //Copy the bytes from teh io to the buffer. if(0 != mmioAdvance( lpWave->m_hmmio, &mmioinfoIn, MMIO_READ)) { return L_false; } if(mmioinfoIn.pchNext == mmioinfoIn.pchEndRead) { return L_false; } //Perform the copy. dwCopySize = mmioinfoIn.pchEndRead - mmioinfoIn.pchNext; dwCopySize = dwCopySize > (dwDataIn-dwRead) ? (dwDataIn-dwRead) : dwCopySize; memcpy(lpWaveBuffer+dwRead, mmioinfoIn.pchNext, dwCopySize); dwRead += dwCopySize; mmioinfoIn.pchNext += dwCopySize; } if(0 != mmioSetInfo( lpWave->m_hmmio, &mmioinfoIn, 0)) { return L_false; } if(lpWave->m_ck.cksize == 0) lpWave->m_bEOF=TRUE; return dwDataIn; } L_bool Wav_Reset(WAVEFILE* lpWave) { if(!lpWave) return L_false; lpWave->m_bEOF=L_false; if(lpWave->m_hmmio == L_null) return L_false; //Seek to the data. if(-1 == mmioSeek( lpWave->m_hmmio, lpWave->m_ckRiff.dwDataOffset + sizeof(FOURCC), SEEK_SET)) { return L_false; } //Search the input file for teh 'data' chunk. lpWave->m_ck.ckid = mmioFOURCC('d', 'a', 't', 'a'); if(0 != mmioDescend( lpWave->m_hmmio, &lpWave->m_ck, &lpWave->m_ckRiff, MMIO_FINDCHUNK)) { return L_false; } return L_true; } WAVEFORMATEX* Wav_GetFormat(WAVEFILE* lpWave, WAVEFORMATEX* lpFormat) { if(!lpWave || !lpWave->m_bLoaded) return L_false; if(lpFormat) { memcpy(lpFormat, &lpWave->m_Format, sizeof(WAVEFORMATEX)); return lpFormat; } else return &lpWave->m_Format; } L_dword Wav_GetSize(WAVEFILE* lpWave) { if(!lpWave) return 0; else return lpWave->m_dwSize; } L_bool Wav_IsEOF(WAVEFILE* lpWave) { if(!lpWave) return L_true; else return lpWave->m_bEOF; } L_bool Wav_OpenMMIO(WAVEFILE* lpWave) { if(!Wav_ReadMMIO(lpWave)) { return L_false; } //Reset the file to prepare for reading if(!Wav_Reset(lpWave)) { return L_false; } lpWave->m_dwSize=lpWave->m_ck.cksize; return L_true; } L_bool Wav_ReadMMIO(WAVEFILE* lpWave) { //Chunk info for general use. MMCKINFO ckIn; //Temp PCM structure to load in. PCMWAVEFORMAT pcmWaveFormat; //Make sure this structure has been deallocated. //SAFE_DELETE_ARRAY(m_pwfx); if(mmioSeek(lpWave->m_hmmio, 0, SEEK_SET) == -1) return L_false; if((0 != mmioDescend( lpWave->m_hmmio, &lpWave->m_ckRiff, NULL, 0))) { return L_false; } //Check to make sure this is a valid wave file. if((lpWave->m_ckRiff.ckid != FOURCC_RIFF) || (lpWave->m_ckRiff.fccType != mmioFOURCC('W', 'A', 'V', 'E'))) { return L_false; } //Search the input file for the 'fmt' chunk. ckIn.ckid = mmioFOURCC('f', 'm', 't', ' '); if(0 != mmioDescend( lpWave->m_hmmio, &ckIn, &lpWave->m_ckRiff, MMIO_FINDCHUNK)) { return L_false; } //The 'fmt ' chunk will be at least //as large as PCMWAVEFORMAT if there are //extra parameters at the end, we'll ignore them. if(ckIn.cksize < (LONG) sizeof(PCMWAVEFORMAT)) return L_false; //Read the 'fmt ' chunk into pcmWaveFormat. if(mmioRead( lpWave->m_hmmio, (HPSTR)&pcmWaveFormat, sizeof(PCMWAVEFORMAT)) != sizeof(PCMWAVEFORMAT)) { return L_false; } //Only handling PCM formats. if(pcmWaveFormat.wf.wFormatTag == WAVE_FORMAT_PCM) { memcpy( &lpWave->m_Format, &pcmWaveFormat, sizeof(PCMWAVEFORMAT)); lpWave->m_Format.cbSize = 0; } else { //NON PCM wave would be handled here. return L_false; } //Ascend teh input file out of the 'fmt ' chucnk. if(0 != mmioAscend(lpWave->m_hmmio, &ckIn, 0)) { //SAFE_DELETE(m_pwfx); return L_false; } lpWave->m_bLoaded=L_true; return L_true; } /* LS_MMIOProc is the mmio reading procedure that will read from the Legacy 3D file system. It should work I think. This code is not bug proof by any means so it still needs some work. */ LRESULT CALLBACK LS_MMIOProc(LPSTR lpmmioinfo, UINT uMsg, LPARAM lParam1, LPARAM lParam2) { LPMMIOINFO info=(LPMMIOINFO)lpmmioinfo; switch(uMsg) { case MMIOM_OPEN: { LF_FILE2 lpIn=L_null; /* When we open a wave file, we don't open it with the LFF_MEMBUF attribute, this is because we may want to stream from the disk. However if the file is opened from an archive it will be opened LFF_MEMBUF anyway, so long music soundtracks should not be archived in the game, they should be in their own directory. */ lpIn=File_Open((char*)lParam1, 0, LF_ACCESS_READ, LFCREATE_OPEN_EXISTING); if(!lpIn) return MMIOERR_CANNOTOPEN; info->dwReserved1=(L_dword)lpIn; return MMSYSERR_NOERROR; } case MMIOM_CLOSE: File_Close((LF_FILE2)info->dwReserved1); return 0; case MMIOM_READ: { L_dword nNumRead=0; nNumRead=File_Read((LF_FILE2)info->dwReserved1, lParam2, (int*)lParam1); return nNumRead; } case MMIOM_SEEK: { L_long nType=0; if(lParam2==SEEK_SET) nType=MOVETYPE_SET; else if(lParam2==SEEK_END) nType=MOVETYPE_END; else if(lParam2==SEEK_CUR) nType=MOVETYPE_CUR; File_Seek((LF_FILE2)info->dwReserved1, lParam1, nType); return 0; } case MMIOM_WRITE: case MMIOM_WRITEFLUSH: Err_Printf("Writing to MMIO is not supported in Legacy3D."); return -1; default: return -1; } return 0; }<file_sep>/games/Legacy-Engine/Source/game/test_game_main.cpp #include <string.h> #include <ML_lib.h> #include "lw_ai_test.h" #include "lw_ai_sdk.h" GAME_AI_GLOBALS g_Globals; CLWAIJack AI_Jack; CLWAIBlaine AI_Blaine; GAME_EXPORT void GAME_FUNC TestGame_Game_Init() { ML_Init(ML_INSTR_F); memset(&g_Globals, 0, sizeof(g_Globals)); } GAME_EXPORT void GAME_FUNC TestGame_Game_UpdateGlobals(const GAME_AI_GLOBALS* pIn) { g_Globals=*pIn; } GAME_EXPORT CLWAIBase* GAME_FUNC TestGame_Game_ObtainAI(lg_cstr szName) { CLWAIBase* m_pOut=LG_NULL; if(_stricmp(szName, "jack_basic_ai")==0) m_pOut=&AI_Jack; else if(_stricmp(szName, "blaine_basic_ai")==0) m_pOut=&AI_Blaine; return m_pOut; }<file_sep>/games/Legacy-Engine/Scrapped/old/lg_sys.h #ifndef __LEGACY3D_H__ #define __LEGACY3D_H__ #ifdef __cplusplus extern "C"{ #endif #include <d3d9.h> #include <dsound.h> #include "lg_err.h" #include "lv_con.h" #include "lv_font.h" #include <lc_sys.h> #include "common.h" #include "lv_test.h" #include "lg_engine.h" #define LGAME_NAME "Legacy Game Engine" #define LGAME_VERSION "1.00" /* typedef enum tagGAMESTATE{ GAMESTATE_UNKNOWN =0, GAMESTATE_NOTSTARTED =1, GAMESTATE_RUNNING =2, GAMESTATE_SHUTDOWN =3, GAMESTATE_FORCE_DWORD=0xFFFFFFFFl } GAMESTATE, *PGAMESTATE; typedef struct tagL3DVIDEO{ IDirect3D9* m_lpD3D; IDirect3DDevice9* m_lpDevice; IDirect3DSurface9* m_lpBackSurface; L_uint m_nAdapterID; D3DDEVTYPE m_nDeviceType; D3DFORMAT m_nBackBufferFormat; LVCON* m_lpVCon; LVT_OBJ* m_lpTestObj; }L3DVIDEO; typedef struct tagL3DSOUND{ L_bool m_bAvailable; IDirectSound8* m_lpDS; IDirectSoundBuffer* m_lpPrimaryBuffer; IDirectSoundBuffer8* m_lpTestSound; }L3DSOUND; typedef struct tagL3DGame{ //GAMESTATE m_nGamestate; HWND m_hwnd; HLCONSOLE m_Console; HCVARLIST m_cvars; L3DVIDEO v; L3DSOUND s; CVar* l_ShouldQuit; CVar* l_AverageFPS; L_dword m_dwLastUpdate; }L3DGame, *LPL3DGame; #define LG_OK (0x00000000l) #define LG_ERR (0x80000000l) #define LG_FAIL LG_ERR L_bool LG_GameLoop(HWND hwnd, L_bool bShutdownMsg, L_bool bActive); L3DGame* LG_GetGame(); #define LK_PAGEUP 1 #define LK_PAGEDOWN 2 #define LK_END 3 L_bool LG_OnChar(char c); */ #ifdef __cplusplus } #endif #endif /* __LEGACY3D_H__ */<file_sep>/games/Legacy-Engine/Scrapped/old/le_camera.h #ifndef __LE_CAMERA_H__ #define __LE_CAMERA_H__ #include <d3d9.h> #include "le_sys.h" #include "lv_sys.h" class CLCamera: public CLEntity, CElementD3D { private: ML_VEC3 m_v3Up; ML_VEC3 m_v3LookAt; ML_MAT m_matView; CLEntity* m_pAttachedEnt; ML_VEC3 m_v3AttachedOffset; float m_fDistance; lg_dword m_nMode; public: CLCamera(); ~CLCamera(); void SetPosition(ML_VEC3* pVec); void SetLookAt(ML_VEC3* pVec); void SetUp(ML_VEC3* pVec); void SetTransform(ML_MAT* pM); void SetYawPitchRoll(float yaw, float pitch, float roll); virtual void Update(); virtual void Render(); void RenderForSkybox(); void AttachToObject(CLEntity* pEntity, lg_dword mode, ML_VEC3* pv3Offset, float fDist); static const lg_dword CLCAMERA_ATTACH_FOLLOW=0x01000001; static const lg_dword CLCAMERA_ATTACH_EYE=0x01000002; }; #endif __LE_CAMERA_H__<file_sep>/samples/OpenGLDemo/OpenGLDemo.c #include <windows.h> #include <tchar.h> #include <gl\gl.h> #include <gl\glu.h> //#include <gl\glaux.h> HWND m_hwnd=NULL; HDC g_hdcOpenGL=NULL; HGLRC g_hRC=NULL; #pragma comment(lib, "opengl32.lib") #pragma comment(lib, "glu32.lib") BOOL InitOpenGL(HWND hwnd) { PIXELFORMATDESCRIPTOR pfd; g_hdcOpenGL=GetDC(hwnd); memset(&pfd, 0, sizeof(pfd)); pfd.nSize=sizeof(pfd); pfd.nVersion=1; pfd.dwFlags=PFD_DRAW_TO_WINDOW|PFD_SUPPORT_OPENGL|PFD_DOUBLEBUFFER; pfd.iPixelType=PFD_TYPE_RGBA; pfd.cColorBits=32; pfd.cDepthBits=16; pfd.iLayerType=PFD_MAIN_PLANE; SetPixelFormat(g_hdcOpenGL, ChoosePixelFormat(g_hdcOpenGL, &pfd), &pfd); g_hRC=wglCreateContext(g_hdcOpenGL); wglMakeCurrent(g_hdcOpenGL, g_hRC); return TRUE; } void ShutdownOpenGL() { wglMakeCurrent(NULL, NULL); wglDeleteContext(g_hRC); ReleaseDC(m_hwnd, g_hdcOpenGL); } void GameLoop() { int width=800, height=600; GLint nView[4]; glClearColor(0.2f, 0.2f, 1.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer glLoadIdentity(); //glViewport(0,0,width,height); // Reset The Current Viewport glMatrixMode(GL_PROJECTION); // Select The Projection Matrix glLoadIdentity(); // Reset The Projection Matrix // Calculate The Aspect Ratio Of The Window glGetIntegerv(GL_VIEWPORT, nView); gluPerspective(45.0f,(GLfloat)nView[2]/(GLfloat)nView[3],0.1f,100.0f); glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix glLoadIdentity(); glTranslatef(-1.5f,0.0f,-6.0f); // Move 1.5 Left And 6.0 Into The Screen. glBegin(GL_TRIANGLES); // Drawing Using Triangles glVertex3f( 0.0f, 1.0f, 0.0f); // Top glVertex3f(-1.0f,-1.0f, 0.0f); // Bottom Left glVertex3f( 1.0f,-1.0f, 0.0f); // Bottom Right glEnd(); // Finished Drawing glTranslatef(3.0f,0.0f,0.0f); // Move Right glBegin(GL_QUADS); // Draw A Quad glVertex3f(-1.0f, 1.0f, 0.0f); // Top Left glVertex3f( 1.0f, 1.0f, 0.0f); // Top Right glVertex3f( 1.0f,-1.0f, 0.0f); // Bottom Right glVertex3f(-1.0f,-1.0f, 0.0f); // Bottom Left glEnd(); SwapBuffers(g_hdcOpenGL); } LRESULT CALLBACK WndProc(HWND hwnd, UINT nMsg, WPARAM wParam, LPARAM lParam); int WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpCmdLine, int nShowCmd) { const TCHAR szAppName[]=_T("OpenGL Demo App"); MSG msg; WNDCLASS wc; HWND hwnd; wc.cbClsExtra=0; wc.cbWndExtra=0; wc.hbrBackground=(HBRUSH)GetStockObject(WHITE_BRUSH); wc.hCursor=LoadCursor(NULL, IDC_ARROW); wc.hIcon=LoadIcon(NULL, IDI_APPLICATION); wc.hInstance=hInst; wc.lpfnWndProc=WndProc; wc.lpszClassName=szAppName; wc.lpszMenuName=NULL; wc.style=CS_OWNDC; RegisterClass(&wc); hwnd=CreateWindow( szAppName, szAppName, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInst, NULL); if(!hwnd) { MessageBoxA(NULL, "This program requires Windows NT!", "OpenGLDemo", MB_OK|MB_ICONERROR); return 0; } ShowWindow(hwnd, nShowCmd); //Get the device context for OpenGL InitOpenGL(hwnd); do { if(PeekMessage(&msg, NULL, 0, 0, TRUE)) { if(msg.message==WM_QUIT) break; TranslateMessage(&msg); DispatchMessage(&msg); } else { GameLoop(); } }while(TRUE); ShutdownOpenGL(); return msg.wParam; } LRESULT CALLBACK WndProc(HWND hwnd, UINT nMsg, WPARAM wParam, LPARAM lParam) { switch(nMsg) { case WM_SIZE: glViewport(0, 0, LOWORD(lParam), HIWORD(lParam)); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hwnd, nMsg, wParam, lParam); } return 0l; }<file_sep>/games/Legacy-Engine/Source/lf_sys2/lf_mem.cpp /* Memory allocation. */ #include <malloc.h> #include "lf_sys2.h" LF_ALLOC_FUNC g_pMalloc=malloc; LF_FREE_FUNC g_pFree=free; extern "C" lf_void LF_SetMemFuncs(LF_ALLOC_FUNC pAlloc, LF_FREE_FUNC pFree) { g_pMalloc=pAlloc; g_pFree=pFree; } extern "C" lf_void* LF_Malloc(lf_size_t size) { if(g_pMalloc) return g_pMalloc(size); else return LF_NULL; } extern "C" lf_void LF_Free(lf_void* p) { if(g_pFree) return g_pFree(p); } #if 0 void* operator new (lf_size_t size) { return LF_Malloc(size); } void operator delete (void* p) { LF_Free(p); } #endif<file_sep>/Misc/GamepadToKey/GamepadToKey/GPTKXInputHandler.h #pragma once #include <windows.h> typedef void ( * GPTKKeyHandler )( DWORD Key , UINT Msg , void* Extra ); void GPTKXInputHandler_Init(); void GPTKXInputHandler_Deinit(); void GPTKXInputHandler_Update( float DeltaTime , GPTKKeyHandler Handler , void* CbExtra );<file_sep>/games/Explor2002/Source_Old/Beta 1/Readme.txt Explor: A New World v0.04b Copywrite (C) 2000 B.M. Software This foler includes: ExplorB.bat - The Executable for Explor. game.dat - The data for the game. Maps.dat - The maps used in the game. Explor.zip - A zip file containing earlier developments of the game. runprog.pro - A file that runs the program. Readme.txt - This file. ExplorB.exe - The installation file. Instructions: At the main menu you can press the button of the number corresponding to your choice. To play press 1. You will then be brought to the 3D screen. Use the arrow keys to move around. For more detailed instructions see the online instructions. You may also press M to activate the automap (Note in online instructions). Note: This program took up to much complicated memory stuff so it was not compiled. I use a .bat file to make it look as though it was anyhow. I'm currently working on some new artwork that's not so boring. I've also decide to make the game hallway based because I'm no artist and I could not develop artwork that looked good. ======================================================== === Version History === === for Explor: A New World === ======================================================== v0.04b (August 6, 2000) Added automap. Made it so automap can be turned off if the value is false. v0.03b (August 6, 2000) Now there is only one load () function. Fixed a bug that appeared while facing north v0.02b The Beta release of this software title. v0.00c A 2D version of the game before it was rendered 3D.<file_sep>/games/Legacy-Engine/Scrapped/tools/LMSHtoEMESH.cpp #pragma warning(disable:4996) #include "../../game_engine/ext_libs/Base64Conv.h" #include <stdio.h> #include <string.h> enum FLOAT_FORMAT: int{FF_TEXT, FF_BASE64}; void LMSHtoEMESH(FILE* fin, FILE* fout, FLOAT_FORMAT ff); int main(int argc, char *argv[], char *envp[]) { FILE *fin, *fout; FLOAT_FORMAT ff = FF_BASE64; char szIn[1024]; char szOut[1024]; printf("Legacy Mesh to Emergence Mesh Converter Utility 1.00\n"); if(argc>1) { sprintf(szIn, argv[1]); } else { printf("Usage: LMESHtoEMESH.exe \"lmesh file\" [\"emesh file\" [text|base-64]]\n"); return 0; } if(argc>2) { sprintf(szOut, argv[2]); } else { sprintf(szOut, "%s.emesh", argv[1]); } if(argc>3) { if(!stricmp("text", argv[3])) ff=FF_TEXT; else if(!stricmp("base=64", argv[3])) ff=FF_BASE64; } fin = fopen(szIn, ("rb")); fout = fopen(szOut, ("wb")); LMSHtoEMESH(fin, fout, ff); fclose(fin); fclose(fout); } void LMSHtoEMESH(FILE* fin, FILE* fout, FLOAT_FORMAT ff) { //Need just three base64 converters. CBase64Conv b64[3]; typedef float Vertex[8]; typedef unsigned short Triangle[3]; char szTL[1024]; char szString[1024]; unsigned long nTDW=0; float vertex[8]; unsigned short triangle[3]; szTL[0]=0; #define READDW fread(&nTDW, 1, 4, fin); #define READSTR(size) fread(szString, 1, size, fin); #define READVTX fread(vertex, 1, sizeof(float)*8, fin); #define READTRI fread(triangle, 1, 2*3, fin); #define WRITE fwrite(szTL, 1, strlen(szTL), fout); //Write the xml header. strcpy(szTL, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); WRITE sprintf(szTL, "<emesh\n"); WRITE ///////////// ///Header:/// ///////////// READDW //ID if(nTDW!=0x48534D4C) { return; } //May not really need the version information. READDW nTDW++; sprintf(szTL, "\tversion=\"%u\"\n", nTDW); WRITE READSTR(32) sprintf(szTL, "\tname=\"%s\"\n", szString); WRITE READDW int vertexes = nTDW; sprintf(szTL, "\tvertexes=\"%u\"\n", nTDW); WRITE READDW int triangles = nTDW; sprintf(szTL, "\ttriangles=\"%u\"\n", nTDW); WRITE READDW int meshes=nTDW; sprintf(szTL, "\tmeshes=\"%u\"\n", nTDW); WRITE READDW int materials=nTDW; sprintf(szTL, "\tmaterials=\"%u\"\n", nTDW); WRITE READDW int bones=nTDW; sprintf(szTL, "\tbones=\"%u\"\n", nTDW); WRITE if(FF_TEXT==ff) sprintf(szTL, "\tformat=\"text\"\n"); else sprintf(szTL, "\tformat=\"base64\"\n"); WRITE sprintf(szTL, ">\n"); WRITE ///////////////////// /// Read Vertexes /// //////////////////// Vertex* pVerts = new Vertex[vertexes]; for(int i=0; i<vertexes; i++) { READVTX memcpy(pVerts[i], vertex, sizeof(vertex)); } ////////////////////// /// Read Triangles /// ////////////////////// Triangle* pTris = new Triangle[triangles]; for(int i=0; i<triangles; i++) { READTRI memcpy(pTris[i], triangle, sizeof(triangle)); } //////////////////////// // Read vertex bones /// //////////////////////// unsigned long* pBoneList = new unsigned long[vertexes]; for(int i=0; i<vertexes; i++) { READDW pBoneList[i]=nTDW; } for(int i=0; i<bones; i++) { READSTR(32) sprintf(szTL, "\t<bone id=\"%u\" name=\"%s\"/>\n", i+1, szString); WRITE } sprintf(szTL, "\n"); WRITE for(int i=0; i<meshes; i++) { READSTR(32) sprintf(szTL, "\t<mesh id=\"%u\" name=\"%s\" ", i+1, szString); WRITE READDW sprintf(szTL, "first_triangle=\"%u\" ", (nTDW/3)+1); WRITE READDW sprintf(szTL, "triangles=\"%u\" ", nTDW); WRITE READDW sprintf(szTL, "material=\"%u\"/>\n", nTDW+1); WRITE } sprintf(szTL, "\n"); WRITE for(int i=0; i<materials; i++) { READSTR(32) sprintf(szTL, "\t<material id=\"%u\" name=\"%s\" ", i+1, szString); WRITE READSTR(260) sprintf(szTL, " texture=\"%s\"/>\n", szString); WRITE } sprintf(szTL, "\n"); WRITE float bb[6]; fread(bb, 1, sizeof(float)*6, fin); if(FF_TEXT==ff) { sprintf(szTL, "\t<bounds min=\"%g %g %g\" max=\"%g %g %g\"/>\n", bb[0], bb[1], bb[2], bb[3], bb[4], bb[5]); } else { unsigned long size=0; b64[0].Load((b64_byte*)&bb[0], sizeof(float)*3); b64[1].Load((b64_byte*)&bb[3], sizeof(float)*3); //char* szMin = ::ToBase64(&size, &bb[0], sizeof(float)*3); //char* szMax = ::ToBase64(&size, &bb[3], sizeof(float)*3); sprintf(szTL, "\t<bounds min=\"%s\" max=\"%s\"/>\n", b64[0].GetBase64String(NULL), b64[1].GetBase64String(NULL)); //::FreeToBase64(szMin); //::FreeToBase64(szMax); } WRITE ////////////////////////// /// Write the Vertexes /// ////////////////////////// sprintf(szTL, "\n"); WRITE for(int i=0; i<vertexes; i++) { if(FF_TEXT==ff) { sprintf(szTL, "\t<vertex id=\"%u\" position=\"%g %g %g\" normal=\"%g %g %g\" tex1=\"%g %g\" bone = \"%u\"/>\n", i+1, pVerts[i][0], pVerts[i][1], pVerts[i][2], pVerts[i][3], pVerts[i][4], pVerts[i][5], pVerts[i][6], pVerts[i][7], pBoneList[i]+1); } else { unsigned long size=0; b64[0].Load(&pVerts[i][0], sizeof(float)*3); b64[1].Load(&pVerts[i][3], sizeof(float)*3); b64[2].Load(&pVerts[i][6], sizeof(float)*2); sprintf(szTL, "\t<vertex id=\"%u\" position=\"%s\" normal=\"%s\" tex1=\"%s\" bone = \"%u\"/>\n", i+1, b64[0].GetBase64String(NULL), b64[1].GetBase64String(NULL), b64[2].GetBase64String(NULL), pBoneList[i]+1); } WRITE } /////////////////////// /// Write Triangles /// /////////////////////// sprintf(szTL, "\n"); WRITE for(int i=0; i<triangles; i++) { sprintf(szTL, "\t<triangle id=\"%u\" v1=\"%u\" v2=\"%u\" v3=\"%u\"/>\n", i+1, pTris[i][0]+1, pTris[i][1]+1, pTris[i][2]+1); WRITE } sprintf(szTL, "</emesh>"); WRITE delete[]pVerts; delete[]pBoneList; return; } <file_sep>/games/Legacy-Engine/Scrapped/old/lv_texmgr.h #ifndef __LV_TEXMGR_H__ #define __LV_TEXMGR_H__ #include <d3d9.h> #include "common.h" #ifndef __cplusplus IDirect3DTexture9* Tex_Load2(lg_cstr szFilename, lg_bool bForceNoMip); IDirect3DTexture9* Tex_Load2_Memory(lg_void* pBuffer, lg_dword nSize, lg_bool bForceNoMip); #else __cplusplus //extern "C" IDirect3DTexture9* Tex_Load2(lg_cstr szFilename, lg_bool bForceNoMip=LG_FALSE); //extern "C" IDirect3DTexture9* Tex_Load2_Memory(lg_void* pBuffer, lg_dword nSize, lg_bool bForceNoMip); class CLTexMgr { //friend IDirect3DTexture9* Tex_Load2(lg_cstr, lg_bool); //friend IDirect3DTexture9* Tex_Load2_Memory(lg_void*, lg_dword, lg_bool); private: static const lg_dword MAX_TEX_NAME=32; typedef struct _TEX_LINK { IDirect3DTexture9* pTex; lg_char szName[MAX_TEX_NAME+1]; struct _TEX_LINK* pNext; }TEX_LINK; private: IDirect3DDevice9* m_pDevice; IDirect3DTexture9* m_pDefaultTex; TEX_LINK* m_pFirst; IDirect3DTexture9* GetTexture(lg_cstr szFilename); public: CLTexMgr(); ~CLTexMgr(); void Init( IDirect3DDevice9* pDevice, lg_cstr szDefaultTex, lg_dword Flags, lg_uint nSizeLimit); void UnInit(); IDirect3DTexture9* LoadTexture(lg_cstr szFilename, lg_bool bForceNoMipMap=LG_FALSE); IDirect3DTexture9* LoadTexture(lg_void* pData, lg_dword nSize, lg_bool bForceNoMipMap=LG_FALSE); void ClearCache(); private: static class CLTexMgr* s_pTexMgr; }; #endif __cplusplus #endif __LV_TEXMGR_H__<file_sep>/games/Legacy-Engine/Source/lc_sys2/lc_sys2_UNICODE.cpp #if 0 #include <stdarg.h> #include <stdio.h> #include <string.h> #include "lc_sys2.h" #include "lc_con.h" #include "common.h" class CConsoleU { friend void LC_PrintfW(lg_wchar* szFormat, ...); friend void LC_SendCommandfW(lg_wchar* szFormat, ...); private: enum GET_LINE_MODE{GET_NONE=0, GET_OLDER, GET_NEWER}; struct LC_LINE{ lg_wchar szLine[LC_MAX_LINE_LEN+1]; LC_LINE* pOlder; LC_LINE* pNewer; }; struct LC_ARGS{ lg_dword nArgCount; lg_wchar szArg[LC_MAX_CMD_ARGS+1][LC_MAX_LINE_LEN+1]; }; private: LC_LINE* m_pNewestLine; LC_LINE* m_pOldestLine; lg_dword m_nLineCount; LC_CMD_FUNC m_pfnCmd; lg_void* m_pCmdExtra; GET_LINE_MODE m_nGetLineMode; LC_LINE* m_pGetLine; CDefsU m_Commands; void AddEntry(lg_wchar* szText); static void SimpleParse1(lg_wchar* szLine); public: CConsoleU(); ~CConsoleU(); void SetCommandFunc(LC_CMD_FUNC pfn, lg_void* pExtra); void Clear(); void Print(lg_wchar* szText); void Printf(lg_wchar* szFormat, ...); void SendCommand(lg_wchar* szCmd); void SendCommandf(lg_wchar* szFormat, ...); const lg_wchar* GetLine(lg_dword nRef, const lg_bool bStartWithNew); const lg_wchar* GetNewestLine(); const lg_wchar* GetOldestLine(); const lg_wchar* GetNextLine(); lg_bool RegisterCommand(const lg_wchar* szCommand, lg_dword nID, const lg_wchar* szHelpString); void ListCommands(); private: static lg_wchar s_szTemp[LC_MAX_LINE_LEN+1]; static lg_wchar s_szTemp2[LC_MAX_LINE_LEN+1]; //static lg_wchar s_szArgs[sizeof(lg_wchar)*(LC_MAX_CMD_ARGS+1)+LC_MAX_LINE_LEN+1]; static LC_ARGS s_Args; public: static const lg_wchar* GetArg(lg_dword nParam, lg_void* pParams); }; lg_wchar CConsoleU::s_szTemp[LC_MAX_LINE_LEN+1]; lg_wchar CConsoleU::s_szTemp2[LC_MAX_LINE_LEN+1]; //lg_wchar CConsoleU::s_szArgs[sizeof(lg_wchar)*(LC_MAX_CMD_ARGS+1)+LC_MAX_LINE_LEN+1]; CConsoleU::LC_ARGS CConsoleU::s_Args; CConsoleU::CConsoleU(): m_pNewestLine(LG_NULL), m_pOldestLine(LG_NULL), m_nLineCount(0), m_nGetLineMode(GET_NONE), m_pGetLine(LG_NULL), m_pCmdExtra(LG_NULL), m_pfnCmd(LG_NULL) { } CConsoleU::~CConsoleU() { Clear(); } void CConsoleU::ListCommands() { Print((lg_wchar*)L"Registered commands:"); for(lg_dword i=0; i<LC_DEF_HASH_SIZE; i++) { if(!m_Commands.m_pHashList[i].bDefined) continue; CDefsU::DEF* pDef=&m_Commands.m_pHashList[i]; while(pDef) { Printf((lg_wchar*)L" %s", pDef->szDef); pDef=pDef->pHashNext; } } } lg_bool CConsoleU::RegisterCommand(const lg_wchar* szCommand, lg_dword nID, const lg_wchar* szHelpString) { if(!m_Commands.AddDef(szCommand, nID, LC_DEF_NOREDEFINE)) { Printf((lg_wchar*)L"LC WARNING: \"%s\" is already a registered command.", szCommand); return LG_FALSE; } return LG_TRUE; } void CConsoleU::SetCommandFunc(LC_CMD_FUNC pfn, lg_void* pExtra) { m_pfnCmd=pfn; m_pCmdExtra=pExtra; } const lg_wchar* CConsoleU::GetLine(lg_dword nRef, const lg_bool bStartWithNew) { m_pGetLine=bStartWithNew?m_pNewestLine:m_pOldestLine; m_nGetLineMode=bStartWithNew?GET_OLDER:GET_NEWER; for(lg_dword i=0; m_pGetLine; i++) { if(i==nRef) return m_pGetLine->szLine; m_pGetLine=bStartWithNew?m_pGetLine->pOlder:m_pGetLine->pNewer; } return LG_NULL; } const lg_wchar* CConsoleU::GetNewestLine() { if(!m_pNewestLine) return LG_NULL; m_pGetLine=m_pNewestLine; m_nGetLineMode=GET_OLDER; return m_pGetLine->szLine; } const lg_wchar* CConsoleU::GetOldestLine() { if(!m_pOldestLine) return LG_NULL; m_pGetLine=m_pOldestLine; m_nGetLineMode=GET_NEWER; return m_pGetLine->szLine; } const lg_wchar* CConsoleU::GetNextLine() { if(!m_pGetLine) return LG_NULL; if(m_nGetLineMode==GET_NEWER) { m_pGetLine=m_pGetLine->pNewer; if(m_pGetLine) return m_pGetLine->szLine; else { m_nGetLineMode=GET_NONE; return LG_NULL; } } else if(m_nGetLineMode==GET_OLDER) { m_pGetLine=m_pGetLine->pOlder; if(m_pGetLine) return m_pGetLine->szLine; else { m_nGetLineMode=GET_NONE; return LG_NULL; } } return LG_NULL; } void CConsoleU::AddEntry(lg_wchar* szText) { LC_LINE* pNew=new LC_LINE; if(!pNew) return; wcsncpy((wchar_t*)pNew->szLine, (wchar_t*)szText, LC_MAX_LINE_LEN); pNew->pOlder=pNew->pNewer=LG_NULL; if(!m_pNewestLine) { m_pNewestLine=m_pOldestLine=pNew; } else { pNew->pOlder=m_pNewestLine; m_pNewestLine->pNewer=pNew; m_pNewestLine=pNew; } m_nLineCount++; return; } void CConsoleU::Clear() { for(LC_LINE* pLine=m_pNewestLine; pLine; ) { LC_LINE* pTemp=pLine->pOlder; delete pLine; pLine=pTemp; } m_pNewestLine=m_pOldestLine=LG_NULL; m_nLineCount=0; } void CConsoleU::Print(lg_wchar* szText) { AddEntry(szText); } void CConsoleU::Printf(lg_wchar* szFormat, ...) { va_list arglist; va_start(arglist, szFormat); _vsnwprintf((wchar_t*)s_szTemp, LC_MAX_LINE_LEN, (wchar_t*)szFormat, arglist); va_end(arglist); Print(s_szTemp); } void CConsoleU::SendCommand(lg_wchar* szCmd) { lg_dword nCurrent=0; wcsncpy((wchar_t*)s_szTemp, (wchar_t*)szCmd, LC_MAX_LINE_LEN); s_szTemp[LC_MAX_LINE_LEN]=0; lg_wchar* szTemp=L_strtokW(s_szTemp, (lg_wchar*)L" \t\r\n", '"'); while(szTemp[0]!=0) { wcsncpy((wchar_t*)s_Args.szArg[nCurrent], (wchar_t*)&szTemp[szTemp[0]=='"'?1:0], LC_MAX_LINE_LEN); lg_dword nLen=wcslen((wchar_t*)s_Args.szArg[nCurrent]); if(s_Args.szArg[nCurrent][nLen-1]=='"') { s_Args.szArg[nCurrent][nLen-1]=0; } nCurrent++; if(nCurrent>LC_MAX_CMD_ARGS) break; szTemp=L_strtokW(0, 0, 0); } s_Args.nArgCount=nCurrent; //If no arguments were found then the command //wasn't found so we just print a blank //line and that's it. if(s_Args.nArgCount<1) { Print((lg_wchar*)L""); return; } #if 0 for(lg_dword i=0; i<s_Args.nArgCount; i++) { printf("Arg[%d]=\"%s\"\n", i, s_Args.szArg[i]); } #endif lg_bool bResult; lg_dword nCmdID=m_Commands.GetDefUnsigned(s_Args.szArg[0], &bResult); if(!bResult) { Printf((lg_wchar*)L"\"%s\" is not recognized as a valid command.", s_Args.szArg[0]); return; } if(m_pfnCmd) bResult=m_pfnCmd(nCmdID, (lg_void*)&s_Args, m_pCmdExtra); else Printf((lg_wchar*)L"No command function specified."); } const lg_wchar* CConsoleU::GetArg(lg_dword nParam, lg_void* pParams) { LC_ARGS* pArgs=(LC_ARGS*)pParams; if(nParam>=pArgs->nArgCount) return LG_NULL; return pArgs->szArg[nParam]; } void CConsoleU::SendCommandf(lg_wchar* szFormat, ...) { va_list arglist; va_start(arglist, szFormat); _vsnwprintf((wchar_t*)s_szTemp, LC_MAX_LINE_LEN, (wchar_t*)szFormat, arglist); va_end(arglist); SendCommand(s_szTemp); } #endif<file_sep>/tools/fs_sys2/fs_lpk.cpp #include <string.h> #include <stdlib.h> #include "fs_lpk.h" #include "fs_bdio.h" #include "stdio.h" #include "fs_internal.h" CLArchive::CLArchive(): m_bOpen(FS_FALSE), m_pFileList(FS_NULL), m_nType(0), m_nVersion(0), m_nCount(0), m_nInfoOffset(0), m_File(FS_NULL), m_TempFile(FS_NULL), m_nMainFileWritePos(0), m_bHasChanged(FS_FALSE), m_nCmpThreshold(20), m_bWriteable(FS_FALSE) { } CLArchive::~CLArchive() { Close(); } fs_dword CLArchive::GetNumFiles() { return m_nCount; } fs_bool CLArchive::IsOpen() { return m_bOpen; } const LPK_FILE_INFO* CLArchive::GetFileInfo(fs_dword n) { if(n>=m_nCount) return FS_NULL; return &m_pFileList[n]; } fs_bool CLArchive::GetFileInfo(fs_dword nRef, LPK_FILE_INFO* pInfo) { if(nRef>=m_nCount) return FS_FALSE; *pInfo=m_pFileList[nRef]; return FS_TRUE; } fs_bool CLArchive::CreateNewW(fs_cstr16 szFilename) { Close(); m_File=BDIO_OpenW(szFilename, LF_CREATE_ALWAYS, LF_ACCESS_READ|LF_ACCESS_WRITE); if(!m_File) return FS_FALSE; m_bWriteable=FS_TRUE; m_TempFile=BDIO_OpenTempFileW(LF_CREATE_ALWAYS, LF_ACCESS_READ|LF_ACCESS_WRITE|LF_ACCESS_BDIO_TEMP); if(!m_TempFile) { BDIO_Close(m_File); m_File=NULL; m_TempFile=NULL; return FS_FALSE; } m_nType=LPK_TYPE; m_nVersion=LPK_VERSION; m_nCount=0; m_nInfoOffset=0; m_pFileList=FS_NULL; m_bOpen=FS_TRUE; m_bHasChanged=FS_TRUE; return m_bOpen; } fs_bool CLArchive::CreateNewA(fs_cstr8 szFilename) { Close(); m_File=BDIO_OpenA(szFilename, LF_CREATE_ALWAYS, LF_ACCESS_READ|LF_ACCESS_WRITE); if(!m_File) return FS_FALSE; m_bWriteable=FS_TRUE; m_TempFile=BDIO_OpenTempFileA(LF_CREATE_ALWAYS, LF_ACCESS_READ|LF_ACCESS_WRITE|LF_ACCESS_BDIO_TEMP); if(!m_TempFile) { BDIO_Close(m_File); m_File=NULL; m_TempFile=NULL; return FS_FALSE; } m_nType=LPK_TYPE; m_nVersion=LPK_VERSION; m_nCount=0; m_nInfoOffset=0; m_pFileList=FS_NULL; m_bOpen=FS_TRUE; m_bHasChanged=FS_TRUE; return m_bOpen; } fs_bool CLArchive::OpenW(fs_cstr16 szFilename, fs_dword Flags) { Close(); fs_dword dwAccess=LF_ACCESS_READ; if(FS_CheckFlag(Flags, LPK_OPEN_ENABLEWRITE)) { m_bWriteable=FS_TRUE; dwAccess|=LF_ACCESS_WRITE; } m_File=BDIO_OpenW(szFilename, LF_OPEN_ALWAYS, dwAccess); if(!m_File) { Close(); return FS_FALSE; } //If the archive is going to be writable then we open a temp file. //if a temp file can't be openened then the archive is set to read //only. if(m_bWriteable) { m_TempFile=BDIO_OpenTempFileW(LF_CREATE_ALWAYS, LF_ACCESS_READ|LF_ACCESS_WRITE|LF_ACCESS_BDIO_TEMP); if(!m_TempFile) m_bWriteable=FS_FALSE; } else m_TempFile=FS_NULL; if(!ReadArcInfo()) { Close(); return FS_FALSE; } m_bHasChanged=FS_FALSE; m_bOpen=FS_TRUE; return FS_TRUE; } fs_bool CLArchive::OpenA(fs_cstr8 szFilename, fs_dword Flags) { Close(); fs_dword dwAccess=LF_ACCESS_READ; if(FS_CheckFlag(Flags, LPK_OPEN_ENABLEWRITE)) { m_bWriteable=FS_TRUE; dwAccess|=LF_ACCESS_WRITE; } m_File=BDIO_OpenA(szFilename, LF_OPEN_ALWAYS, dwAccess); if(!m_File) { Close(); return FS_FALSE; } //If the archive is going to be writable then we open a temp file. //if a temp file can't be openened then the archive is set to read //only. if(m_bWriteable) { m_TempFile=BDIO_OpenTempFileA(LF_CREATE_ALWAYS, LF_ACCESS_READ|LF_ACCESS_WRITE|LF_ACCESS_BDIO_TEMP); if(!m_TempFile) m_bWriteable=FS_FALSE; } else m_TempFile=FS_NULL; if(!ReadArcInfo()) { Close(); return FS_FALSE; } m_bHasChanged=FS_FALSE; m_bOpen=FS_TRUE; return FS_TRUE; } fs_dword CLArchive::DoAddFile(BDIO_FILE fin, fs_cstr16 szNameInArc, fs_dword Flags) { LPK_FILE_INFO_EX Entry; Entry.nSize=BDIO_GetSize(fin); Entry.nCmpSize=Entry.nSize; //Entry.nOffset=BDIO_Tell(m_File); Entry.nType=FS_CheckFlag(Flags, LPK_ADD_ZLIBCMP)?LPK_FILE_TYPE_ZLIBCMP:LPK_FILE_TYPE_NORMAL; Entry.nInternalPosition=LPK_FILE_POS_MAIN; //Just in case a file with the same name already exists, go ahead //and add something onto the end of it (we'll add an X). wcsncpy(Entry.szFilename, szNameInArc, FS_MAX_PATH); while(GetFileRef(Entry.szFilename)!=0xFFFFFFFF) { wcscat(Entry.szFilename, L"X"); } fs_byte* pTemp=static_cast<fs_byte*>(FS_Malloc(sizeof(fs_byte)*Entry.nSize, LF_ALLOC_REASON_SCRATCH, "FS", __FILE__, __LINE__)); if(!pTemp) { return 0; } if(BDIO_Read(fin, Entry.nSize, pTemp)!=Entry.nSize) { FS_Free(pTemp, LF_ALLOC_REASON_SCRATCH ); return 0; } //Write the file to the end of the main file. BDIO_Seek(m_File, m_nMainFileWritePos, LF_SEEK_BEGIN); Entry.nOffset=BDIO_Tell(m_File); if(Entry.nType==LPK_FILE_TYPE_ZLIBCMP) { Entry.nCmpSize=BDIO_WriteCompressed(m_File, Entry.nSize, pTemp); fs_dword nCmp=(fs_dword)(100.0f-(float)Entry.nCmpSize/(float)Entry.nSize*100.0f); //If the compression did not occur, or if the compression //percentage was too low, we'll just write the file data. //By default the compression threshold is 20. if( (Entry.nCmpSize==0) || (nCmp<m_nCmpThreshold) ) { BDIO_Seek(m_File, Entry.nOffset, LF_SEEK_BEGIN); Entry.nCmpSize=BDIO_Write(m_File, Entry.nSize, pTemp); Entry.nType=LPK_FILE_TYPE_NORMAL; } } else { Entry.nCmpSize=BDIO_Write(m_File, Entry.nSize, pTemp); } m_nMainFileWritePos=BDIO_Tell(m_File); FS_Free(pTemp,LF_ALLOC_REASON_SCRATCH); pTemp = FS_NULL; LPK_FILE_INFO_EX* pNew=static_cast<LPK_FILE_INFO_EX*>(FS_Malloc(sizeof(LPK_FILE_INFO_EX)*(m_nCount+1), LF_ALLOC_REASON_FILE, "FS", __FILE__, __LINE__)); for(fs_dword i=0; i<m_nCount; i++) { pNew[i]=m_pFileList[i]; } pNew[m_nCount]=Entry; m_nCount++; if(m_pFileList){FS_Free(m_pFileList,LF_ALLOC_REASON_FILE);} m_pFileList=pNew; m_bHasChanged=FS_TRUE; return Entry.nCmpSize; } fs_dword CLArchive::AddFileW(fs_cstr16 szFilename, fs_cstr16 szNameInArc, fs_dword Flags) { if(!m_bOpen || !m_bWriteable) return 0; BDIO_FILE fin=BDIO_OpenW(szFilename, LF_OPEN_EXISTING, LF_ACCESS_READ); if(!fin) return 0; fs_pathW sFinalName; FS_FixCaseW(sFinalName, szNameInArc); fs_dword nSize=DoAddFile(fin, sFinalName, Flags); BDIO_Close(fin); return nSize; } fs_dword CLArchive::AddFileA(fs_cstr8 szFilename, fs_cstr8 szNameInArc, fs_dword Flags) { if(!m_bOpen || !m_bWriteable) return 0; BDIO_FILE fin=BDIO_OpenA(szFilename, LF_OPEN_EXISTING, LF_ACCESS_READ); if(!fin) return 0; fs_pathW szWideName; mbstowcs(szWideName, szNameInArc, FS_MAX_PATH); fs_pathW sFinalName; FS_FixCaseW(sFinalName, szWideName); fs_dword nSize=DoAddFile(fin, sFinalName, Flags); BDIO_Close(fin); return nSize; } fs_bool CLArchive::ReadArcInfo() { //Read the header info. It should be the last 16 bytes of //the file. BDIO_Seek(m_File, -16, LF_SEEK_END); BDIO_Read(m_File, 4, &m_nType); BDIO_Read(m_File, 4, &m_nVersion); BDIO_Read(m_File, 4, &m_nCount); BDIO_Read(m_File, 4, &m_nInfoOffset); if((m_nType!=LPK_TYPE) || (m_nVersion!=LPK_VERSION)) return FS_FALSE; //Seek to the beginning of the file data. BDIO_Seek(m_File, m_nInfoOffset, LF_SEEK_BEGIN); if(BDIO_Tell(m_File)!=m_nInfoOffset) return FS_FALSE; //Save the info offset as the main file write position, //as this will be where new files are written to. m_nMainFileWritePos=m_nInfoOffset; //Allocate memory for file data. m_pFileList=static_cast<LPK_FILE_INFO_EX*>(FS_Malloc(sizeof(LPK_FILE_INFO_EX)*m_nCount, LF_ALLOC_REASON_FILE, "FS", __FILE__, __LINE__)); if(!m_pFileList) return FS_FALSE; //Now read the data. for(fs_dword i=0; i<m_nCount; i++) { BDIO_Read(m_File, 256, &m_pFileList[i].szFilename); BDIO_Read(m_File, 4, &m_pFileList[i].nType); BDIO_Read(m_File, 4, &m_pFileList[i].nOffset); BDIO_Read(m_File, 4, &m_pFileList[i].nSize); BDIO_Read(m_File, 4, &m_pFileList[i].nCmpSize); m_pFileList[i].nInternalPosition=LPK_FILE_POS_MAIN; } return FS_TRUE; } fs_bool CLArchive::Save() { if(!m_bWriteable || !m_bOpen || !m_bHasChanged) return FS_FALSE; BDIO_Seek(m_File, m_nMainFileWritePos, LF_SEEK_BEGIN); BDIO_Seek(m_TempFile, 0, LF_SEEK_BEGIN); for(fs_dword i=0; i<m_nCount; i++) { if(m_pFileList[i].nInternalPosition==LPK_FILE_POS_TEMP) { BDIO_Seek(m_TempFile, m_pFileList[i].nOffset, LF_SEEK_BEGIN); m_pFileList[i].nOffset=BDIO_Tell(m_File); BDIO_CopyData(m_File, m_TempFile, m_pFileList[i].nCmpSize); m_pFileList[i].nInternalPosition=LPK_FILE_POS_MAIN; } else { //We don't need to do anything. } } m_nInfoOffset=BDIO_Tell(m_File); //Write the file info data. for(fs_dword i=0; i<m_nCount; i++) { BDIO_Write(m_File, 256, &m_pFileList[i].szFilename); BDIO_Write(m_File, 4, &m_pFileList[i].nType); BDIO_Write(m_File, 4, &m_pFileList[i].nOffset); BDIO_Write(m_File, 4, &m_pFileList[i].nSize); BDIO_Write(m_File, 4, &m_pFileList[i].nCmpSize); } BDIO_Seek(m_File, 0, LF_SEEK_END); //Write the header... BDIO_Write(m_File, 4, &m_nType); BDIO_Write(m_File, 4, &m_nVersion); BDIO_Write(m_File, 4, &m_nCount); BDIO_Write(m_File, 4, &m_nInfoOffset); BDIO_Seek(m_TempFile, 0, LF_SEEK_BEGIN); m_bHasChanged=FS_FALSE; return FS_TRUE; } void CLArchive::Close() { //If the file was writeable then everything will be written from the temp file. if(m_bWriteable && m_bOpen) { Save(); } if(m_File) BDIO_Close(m_File); if(m_TempFile) BDIO_Close(m_TempFile); if(m_pFileList) FS_Free(m_pFileList, LF_ALLOC_REASON_FILE); m_File=m_TempFile=0; m_pFileList=FS_NULL; m_bOpen=FS_FALSE; m_nType=0; m_nVersion=0; m_nCount=0; m_nInfoOffset=0; m_bHasChanged=FS_FALSE; } fs_dword CLArchive::GetFileRef(const fs_pathW szName) { for(fs_dword i=0; i<this->m_nCount; i++) { if(wcscmp(szName, m_pFileList[i].szFilename)==0) return i; } return 0xFFFFFFFF; } fs_byte* CLArchive::ExtractFile(fs_byte* pOut, fs_dword nRef) { if(nRef>=m_nCount) return FS_NULL; BDIO_FILE fin=FS_NULL; if(m_pFileList[nRef].nInternalPosition==LPK_FILE_POS_TEMP) fin=m_TempFile; else fin=m_File; BDIO_Seek(fin, m_pFileList[nRef].nOffset, LF_SEEK_BEGIN); fs_dword nRead=0; if(m_pFileList[nRef].nType==LPK_FILE_TYPE_ZLIBCMP) { nRead=BDIO_ReadCompressed(fin, m_pFileList[nRef].nSize, pOut); } else { nRead=BDIO_Read(fin, m_pFileList[nRef].nSize, pOut); } if(nRead!=m_pFileList[nRef].nSize) { //An error occured while reading. __debugbreak(); } return pOut; } <file_sep>/games/Legacy-Engine/Source/lm_sys/lm_skel_lg.cpp #include "lm_skel_lg.h" #include "lm_mesh_lg.h" #include "lf_sys2.h" lg_bool CLSkelLG::Load(LMPath szFile) { lg_bool bRes; Unload(); LF_FILE3 fin=LF_Open(szFile, LF_ACCESS_READ, LF_OPEN_EXISTING); if(!fin) return LG_FALSE; bRes=Serialize( fin, CLMeshLG::ReadFn, RW_READ); LF_Close(fin); if(bRes) { m_nFlags=LM_FLAG_LOADED; CalcExData(); } return bRes; } lg_bool CLSkelLG::Save(LMPath szFile) { //We don't save ingame skels... return LG_FALSE; }<file_sep>/games/Legacy-Engine/Source/engine/ls_sys.h #ifndef __LS_SYS_H__ #define __LS_SYS_H__ #include <al/al.h> #include <al/alc.h> #include "lg_types.h" #include "ls_stream.h" class CLSndMgr { private: lg_bool m_bSndAvailable; //OpenAL Interfaces ALCcontext* m_pAudioContext; ALCdevice* m_pAudioDevice; //The test sound. //ALuint m_TestSnd; //ALuint m_TestSndBuffer; //CLSndStream m_TestSnd2; //The background music track CLSndStream m_MusicTrack; public: static ALenum GetALFormat(lg_dword nChannels, lg_dword nBitsPerSample); public: CLSndMgr(); ~CLSndMgr(); //Sound initialziation stuff: lg_bool LS_Init(); void LS_Shutdown(); void Update(); void Music_Start(lg_str szPath); void Music_Pause(); void Music_Stop(); void Music_Resume(); void Music_UpdateVolume(); static lg_bool LS_LoadSoundIntoBuffer(ALuint sndBuffer, lg_str szFilename); }; #endif __LS_SYS_H__<file_sep>/games/Legacy-Engine/Scrapped/tools/Texview2/src/ChildView.cpp // ChildView.cpp : implementation of the CChildView class // #include "stdafx.h" #include "Texview2.h" #include "ChildView.h" #include "MainFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CChildView CChildView::CChildView(): m_nFilter(IMGFILTER_LINEAR), m_bAlphaChannel(FALSE), m_bShowImage(TRUE), m_bBlackBG(FALSE), m_nImageHeight(0), m_nImageWidth(0) { } CChildView::~CChildView() { } BEGIN_MESSAGE_MAP(CChildView,CWnd ) //{{AFX_MSG_MAP(CChildView) ON_WM_PAINT() ON_WM_SIZE() ON_WM_VSCROLL() ON_WM_HSCROLL() ON_COMMAND(ID_VIEW_ALPHACHANNEL, OnViewAlphachannel) ON_COMMAND(ID_VIEW_IMAGE, OnViewImage) ON_WM_MOVE() ON_COMMAND(ID_VIEW_BLACKBG, OnViewBlackbg) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CChildView message handlers BOOL CChildView::PreCreateWindow(CREATESTRUCT& cs) { if (!CWnd::PreCreateWindow(cs)) return FALSE; cs.dwExStyle |= WS_EX_CLIENTEDGE; cs.style &= ~WS_BORDER; cs.lpszClass = AfxRegisterWndClass(CS_HREDRAW|CS_VREDRAW|CS_DBLCLKS, ::LoadCursor(NULL, IDC_ARROW), HBRUSH(COLOR_APPWORKSPACE+1), 0); return TRUE; } void CChildView::OnPaint() { CPaintDC dc(this); // device context for painting RECT rc; int cx, cy; int x, y; m_texImage.GetBitmapDims(&cx, &cy); GetClientRect(&rc); dc.SetMapMode(MM_TEXT); dc.SetViewportOrg(0, 0); x=cx>rc.right?GetScrollPos(SB_HORZ):(cx-rc.right)/2; y=cy>rc.bottom?GetScrollPos(SB_VERT):(cy-rc.bottom)/2; m_texImage.DrawBitmap(x, y, &dc); } void CChildView::UpdateScrollBars(BOOL bResetToZero) { int width=0, height=0; m_texImage.GetBitmapDims(&width, &height); if(TRUE) { //BITMAP bm; //m_bmTexture.GetBitmap(&bm); //Setup the scroll information. RECT rcClient; GetClientRect(&rcClient); SCROLLINFO si; si.cbSize=sizeof(SCROLLINFO); si.nMin=0; si.nMax=width-1; si.nPos=bResetToZero?0:GetScrollPos(SB_HORZ); si.nPage=rcClient.right; si.fMask=SIF_ALL; SetScrollInfo(SB_HORZ, &si, TRUE); si.nMax=height-1; si.nPos=bResetToZero?0:GetScrollPos(SB_VERT); si.nPage=rcClient.bottom; si.fMask=SIF_ALL; SetScrollInfo(SB_VERT, &si, TRUE); } else { SCROLLINFO si; si.cbSize=sizeof(SCROLLINFO); si.fMask=SIF_RANGE|SIF_PAGE; si.nMax=0; si.nMin=0; si.nPage=0; SetScrollInfo(SB_HORZ, &si, TRUE); SetScrollInfo(SB_VERT, &si, TRUE); } } BOOL CChildView::LoadTexture(LPTSTR szFilename) { //Make sure no image is loaded. //m_bmTexture.DeleteObject(); m_texImage.Unload(); //Get the windows dc for loading the image. CDC* dc=GetDC(); //Load the image. //m_bmTexture.m_hObject=(HBITMAP)TGA_CreateDIBitmap(szFilename, dc->m_hDC); BOOL bLoaded=m_texImage.Load(szFilename); //Reset the alpha channel option to off. m_bAlphaChannel=FALSE; m_bShowImage=TRUE; CMenu* menu=GetParent()->GetMenu(); menu->CheckMenuItem(ID_VIEW_ALPHACHANNEL, MF_BYCOMMAND|MF_UNCHECKED); menu->CheckMenuItem(ID_VIEW_IMAGE, MF_BYCOMMAND|MF_CHECKED); menu->Detach(); //We set the bitmap size to 0, 0, which makes it the default size. SetBitmapSize(0, 0); //Get rid of the dc and return. ReleaseDC(dc); UpdateScrollBars(TRUE); RedrawWindow(); if(bLoaded) { TCHAR szWindowText[MAX_PATH+100]; _stprintf(szWindowText, _T("Texture Viewer 2 [%s]"), szFilename); GetParentFrame()->SetWindowText(szWindowText); int cx, cy; m_texImage.GetBitmapDims(&cx, &cy); ((CMainFrame*)GetParentFrame())->UpdateMenuTexSizes(cx, cy); return TRUE; } else { MessageBox(_T("Could not open texture.\nFile may not be valid."), _T("Texture Viewer 2"), MB_ICONINFORMATION); GetParentFrame()->SetWindowText(_T("Texture Viewer 2")); ((CMainFrame*)GetParentFrame())->UpdateMenuTexSizes(0, 0); return FALSE; } return TRUE; } void CChildView::OnSize(UINT nType, int cx, int cy) { CWnd::OnSize(nType, cx, cy); UpdateScrollBars(FALSE); } void CChildView::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { SCROLLINFO si; GetScrollInfo(SB_VERT, &si, SIF_ALL); int nOldPos=si.nPos; switch(nSBCode) { case SB_TOP: nPos=si.nMin; break; case SB_BOTTOM: si.nPos=si.nMax; break; case SB_LINEUP: si.nPos-=5; break; case SB_LINEDOWN: si.nPos+=5; break; case SB_PAGEUP: si.nPos-=si.nPage; break; case SB_PAGEDOWN: si.nPos+=si.nPage; break; case SB_THUMBPOSITION: si.nPos=nPos; break; case SB_THUMBTRACK: si.nPos=nPos; break; } SetScrollInfo(SB_VERT, &si, TRUE); ScrollWindow(0, nOldPos-GetScrollPos(SB_VERT), NULL, NULL); CWnd ::OnVScroll(nSBCode, nPos, pScrollBar); } void CChildView::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { SCROLLINFO si; GetScrollInfo(SB_HORZ, &si, SIF_ALL); int nOldPos=si.nPos; switch(nSBCode) { case SB_LEFT: nPos=si.nMin; break; case SB_RIGHT: si.nPos=si.nMax; break; case SB_LINELEFT: si.nPos-=5; break; case SB_LINERIGHT: si.nPos+=5; break; case SB_PAGELEFT: si.nPos-=si.nPage; break; case SB_PAGERIGHT: si.nPos+=si.nPage; break; case SB_THUMBPOSITION: si.nPos=nPos; break; case SB_THUMBTRACK: si.nPos=nPos; break; } SetScrollInfo(SB_HORZ, &si, TRUE); ScrollWindow(nOldPos-GetScrollPos(SB_HORZ), 0, NULL, NULL); CWnd::OnHScroll(nSBCode, nPos, pScrollBar); } void CChildView::SetBitmapSize(int cx, int cy) { CDC* pdc=GetDC(); m_nImageWidth=cx; m_nImageHeight=cy; UpdateImage(); m_texImage.GetBitmapDims(&m_nImageWidth, &m_nImageHeight); } void CChildView::SetFilter(IMGFILTER filter) { //If the filter hasn't changed we won't change it. if(filter == m_nFilter) return; m_nFilter=filter; UpdateImage(); } void CChildView::OnViewAlphachannel() { m_bAlphaChannel=!m_bAlphaChannel; DWORD nCheck=m_bAlphaChannel?MF_CHECKED:MF_UNCHECKED; CMenu* menu=GetParent()->GetMenu(); if(!m_bAlphaChannel) { m_bShowImage=TRUE; menu->CheckMenuItem(ID_VIEW_IMAGE, MF_BYCOMMAND|MF_CHECKED); } menu->CheckMenuItem(ID_VIEW_ALPHACHANNEL, MF_BYCOMMAND|nCheck); menu->Detach(); UpdateImage(); } void CChildView::OnViewImage() { m_bShowImage=!m_bShowImage; if(!m_bShowImage && !m_bAlphaChannel) { m_bShowImage=TRUE; return; } DWORD nCheck=m_bShowImage?MF_CHECKED:MF_UNCHECKED; CMenu* menu=GetParent()->GetMenu(); menu->CheckMenuItem(ID_VIEW_IMAGE, MF_BYCOMMAND|nCheck); menu->Detach(); UpdateImage(); } void CChildView::OnViewBlackbg() { m_bBlackBG=!m_bBlackBG; DWORD nCheck=m_bBlackBG?MF_CHECKED:MF_UNCHECKED; CMenu* menu=GetParent()->GetMenu(); menu->CheckMenuItem(ID_VIEW_BLACKBG, MF_BYCOMMAND|nCheck); menu->Detach(); if(!m_bAlphaChannel) return; UpdateImage(); } //Update Image takes all the stored values and resizes creates //the CBitmap to fit all the menu options that are selected. void CChildView::UpdateImage() { CDC* pdc=GetDC(); DWORD dwFlags=0; dwFlags|=m_bAlphaChannel?BC_ACHANNEL:0; dwFlags|=m_bShowImage?BC_IMAGE:0; dwFlags|=m_bBlackBG?0:BC_USEAPPBG; m_texImage.CreateCBitmap(m_nImageWidth, m_nImageHeight, m_nFilter, pdc, dwFlags); ReleaseDC(pdc); UpdateScrollBars(TRUE); Invalidate(); } <file_sep>/games/Legacy-Engine/Scrapped/libs/lc_sys1/lc_sys.c #include <stdio.h> #include "lg_malloc.h" #include <stdarg.h> #include "common.h" #include "lc_sys.h" #include "lc_private.h" #ifdef _DEBUG #include <windows.h> #include <stdlib.h> #include <crtdbg.h> #endif /*_DEBUG*/ unsigned long g_nNumEntries=0; /* ================================= Command Parsing Helper functions. =================================*/ /* CCParse_GetParam will get a parameter from the Parameter string, the way it works is that it assumes all parameters are separated by spaces, unless within qoutes, in which case spaces are ignored. */ int CCParse_GetParam( char* szParamOut, const char* szParams, unsigned long nParam) { unsigned long dwLen=L_strlen(szParams), i=0, j=0; int bFoundParam=0; int bInQuotes=0; szParamOut[0]=0; if(nParam<1) return 0; if(dwLen<1) return 0; nParam--; for(i=0, j=0, bFoundParam=0, bInQuotes=0; i<=dwLen; i++) { if(szParams[i]=='\"') { if(bInQuotes && (nParam==0)) break; bInQuotes=!bInQuotes; continue; } if(nParam==0) { if(szParams[i]==' ' && !bInQuotes) break; szParamOut[j]=szParams[i]; j++; } else { if((szParams[i]==' ') && (!bInQuotes)) nParam--; } } szParamOut[j]=0; if(L_strlen(szParamOut) < 1 ) return 0; else return 1; } /* CCParse_GetFloat converts a parameter to a float, see above. */ float CCParse_GetFloat( char* szParams, unsigned short wParam) { char szTemp[32]; if(!CCParse_GetParam(szTemp, szParams, wParam)) return 0.0f; return (float)L_atof(szTemp); } /* CCParse_GetInt converts a parameter to an int, see above. */ signed long CCParse_GetInt( char* szParams, unsigned short wParam) { char szTemp[32]; if(!CCParse_GetParam(szTemp, szParams, wParam)) return 0; return L_atol(szTemp); } /* CCParse_CheckParam - checks all params to see if any match a particular string. */ int CCParse_CheckParam( const char* szParams, const char* szAttrib, int nStart) { int i=nStart; char* szTemp; if(!szParams || !szAttrib) return 0; szTemp=LG_Malloc(L_strlen(szParams)+1); if(!szTemp) return LG_FALSE; while(CCParse_GetParam(szTemp, szParams, i)) { if(L_strnicmp(szTemp, (char*)szAttrib, 0)) { LG_Free(szTemp); return LG_TRUE; } szTemp[0]=0; i++; } LG_Free(szTemp); return LG_FALSE; } /* ========================================================== Legacy Console private functions, the user never calls these functions. ========================================================== */ /* Con_SimpleParse - does a few things to parse the text and identify the command, as well as the parameters. */ int Con_SimpleParse( char* szCommand, char* szParams, char* szIgnore, char* szLineIn, unsigned long dwMaxLen) { char* szTemp; unsigned long dwLen=0, i=0, j=0, k=0, dwSpaces=0; int bFoundChar=0, bIgnore=0, bInQuotes=0; unsigned long dwIgnoreLen=0; dwLen=L_strlen(szLineIn); dwIgnoreLen=L_strlen(szIgnore); if(dwLen<1) return 0; /* Allocate a temporary string for the output, this will be freed when the function exits. */ szTemp=LG_Malloc(dwMaxLen); if(szTemp==NULL) return 0; /* First thing to do is remove any excess spaces. */ for(i=0; i<dwLen; i++, bIgnore=0) { if(!bFoundChar) if((szLineIn[i]!=' ')) bFoundChar=1; if(bFoundChar) { if(szLineIn[i]=='\"') bInQuotes=!bInQuotes; for(k=0; k<dwIgnoreLen; k++) { if((szLineIn[i]==szIgnore[k]) && !bInQuotes) bIgnore=1; } if(bIgnore) { if(dwSpaces==0) { szTemp[j]=' '; j++; dwSpaces++; continue; } else { dwSpaces++; continue; } } else { dwSpaces=0; } szTemp[j]=szLineIn[i]; j++; } } szTemp[j]=0; dwLen=L_strlen(szTemp); /* Get the command (the first word). */ for(i=0, j=0; i<dwLen; i++, j++){ if(szTemp[i]==' ') break; szCommand[j]=szTemp[i]; } szCommand[j]=0; /* Get the parameters. */ j++; i++; for(j=0 ; i<dwLen; i++, j++){ szParams[j]=szTemp[i]; } szParams[j]=0; L_safe_free(szTemp); return 1; } /* Con_ClearOldestEntry - simply deletes the oldest entry in the console. Called when the number of allowed entries reaches it's max. */ int Con_ClearOldestEntry(HLCONSOLE hConsole) { LPLCENTRY lpCurrent=NULL; LPLCENTRY lpPrev=NULL; LPLCONSOLE lpConsole=(LPLCONSOLE)hConsole; if(!lpConsole) return 0; if(lpConsole->lpEntryList==NULL) return 0; lpCurrent=lpConsole->lpEntryList; if(lpCurrent->lpNext==NULL) return 1; while(lpCurrent->lpNext) { lpPrev=lpCurrent; lpCurrent=lpCurrent->lpNext; } /* Remove the last entry and set it's previous entry as the last entry. */ L_safe_free(lpCurrent->lpstrText); L_safe_free(lpCurrent); lpPrev->lpNext=NULL; g_nNumEntries--; lpConsole->dwNumEntries--; return 1; } /* Con_AddEntry - adds an entry to the console's text list. */ int Con_AddEntry(HLCONSOLE hConsole, char* szEntry) { LPLCENTRY lpCurrent=NULL; LPLCENTRY lpNew=NULL; LPLCONSOLE lpConsole=(LPLCONSOLE)hConsole; if(!lpConsole) return 0; lpCurrent=lpConsole->lpEntryList; lpNew=LG_Malloc(sizeof(LCENTRY)); if(lpNew==NULL) { return 0; } lpNew->lpstrText=LG_Malloc(sizeof(char)*lpConsole->nMaxStrLen); if(lpNew->lpstrText==NULL) { L_safe_free(lpNew); return 0; } lpNew->lpNext=lpConsole->lpEntryList; lpConsole->lpEntryList=lpNew; lpConsole->lpActiveEntry=lpConsole->lpEntryList; L_strncpy(lpConsole->lpEntryList->lpstrText, szEntry, lpConsole->nMaxStrLen); lpConsole->dwNumEntries++; g_nNumEntries++; if(lpConsole->dwNumEntries > lpConsole->nMaxEntries) Con_ClearOldestEntry(lpConsole); return 1; } /* ====================================================== Legacy Console Public Functions. ====================================================== */ /* Con_Create - Creates the console. */ HLCONSOLE Con_Create( LPCONCOMMAND lpCommandFunc, unsigned long nMaxStrlen, unsigned long nMaxEntries, unsigned long dwFlags, void* pExtraData) { /* Allocate the console to memory. */ LPLCONSOLE lpConsole=NULL; lpConsole=LG_Malloc(sizeof(LCONSOLE)); if(lpConsole==NULL) { /*printf("Failed to initialize Legacy Console!\n");*/ return NULL; } /* We have a few requirements for the console's limits, despite what the user asks for.*/ #define CMIN_REQUIRED (64) #define CMAX_ALLOWED (2048) /* Set the initial values for the console. */ lpConsole->CommandFunction=lpCommandFunc; lpConsole->pExtraData=pExtraData; lpConsole->dwNumEntries=0; lpConsole->lpActiveEntry=NULL; lpConsole->lpEntryList=NULL; lpConsole->nMaxEntries=nMaxEntries; /* Insure that the string lenth is greater than 64, but less than 1024. */ lpConsole->nMaxStrLen=nMaxStrlen<CMIN_REQUIRED ? CMIN_REQUIRED : (nMaxStrlen>CMAX_ALLOWED) ? CMAX_ALLOWED : nMaxStrlen; if((CONCREATE_USEINTERNAL&dwFlags)==CONCREATE_USEINTERNAL) lpConsole->bProcessInternal=1; /* Whether or not the conosle should process internal commands. */ else lpConsole->bProcessInternal=0; /* Add a blank entry. */ Con_AddEntry((HLCONSOLE)lpConsole, ""); lpConsole->cvarlist=NULL; lpConsole->commands=Defs_CreateDefs(); if(!lpConsole->commands) Con_SendMessage(lpConsole, "Could not register command defs, some functions may be unusable."); /* If using built in commands register them. */ if((CONCREATE_USEINTERNAL&dwFlags)==CONCREATE_USEINTERNAL) { #define CON_REG(a) Con_RegisterCmd(lpConsole, #a, CONF_##a) CON_REG(SET); CON_REG(GET); CON_REG(CLEAR); CON_REG(ECHO); CON_REG(DEFINE); CON_REG(CVARLIST); CON_REG(REGCVAR); CON_REG(CMDLIST); CON_REG(CVARUPDATE); } /* Check to see if we should create a cvarlist. */ /* if((CONCREATE_USECVARLIST&dwFlags)==CONCREATE_USECVARLIST) { lpConsole->cvarlist=CVar_CreateList(lpConsole); } */ /*#define COPYRIGHT_TEXT*/ #ifdef COPYRIGHT_TEXT Con_SendMessage((HLCONSOLE)lpConsole, "Legacy Console copyright (c) 2006, <NAME>."); #endif /* COPYRIGHT_TEXT */ /* Con_SendMessage((HLCONSOLE)lpConsole, "Successfully initialized Legacy Console."); */ return (HLCONSOLE)lpConsole; } /* Con_Delete - Deletes the console. */ int Con_Delete(HLCONSOLE hConsole) { LPLCENTRY lpCurrent=NULL, lpNext=NULL; LPLCONSOLE lpConsole=(LPLCONSOLE)hConsole; /* Delete the list of entrys. */ if(!hConsole) return 0; lpCurrent=((LPLCONSOLE)hConsole)->lpEntryList; while(lpCurrent!=NULL) { lpNext=lpCurrent->lpNext; /* Clear the text string. */ L_safe_free(lpCurrent->lpstrText); /* Clear the entry. */ L_safe_free(lpCurrent); lpConsole->dwNumEntries--; g_nNumEntries--; lpCurrent=lpNext; } Debug_printf("Console entries left: %i\n", g_nNumEntries); ((LPLCONSOLE)hConsole)->lpActiveEntry=NULL; /* Delete the bg, and font. */ ((LPLCONSOLE)hConsole)->CommandFunction=NULL; if(((LPLCONSOLE)hConsole)->commands) Defs_DeleteDefs(((LPLCONSOLE)hConsole)->commands); /* if(((LPLCONSOLE)hConsole)->cvarlist) CVar_DeleteList(((LPLCONSOLE)hConsole)->cvarlist); */ L_safe_free(hConsole); return 1; } /* Con_SendMessage - Adds a string to the console. */ int Con_SendMessage(HLCONSOLE hConsole, char* szMessage) { char* szTemp=NULL; int nResult=0; LPLCONSOLE lpConsole=(LPLCONSOLE)hConsole; if(!lpConsole) return 0; /* Allocate memory for the temporary string. We free this when the function returns. */ szTemp=LG_Malloc(lpConsole->nMaxStrLen); if((szTemp==NULL)) return 0; /* Note that when we copy strings, we do one less than the max string length, because the null terminating 0, is not counted as a character count in L_strncpy. */ L_strncpy(szTemp, lpConsole->lpActiveEntry->lpstrText, lpConsole->nMaxStrLen); /* Copy in the new line. */ L_strncpy(lpConsole->lpActiveEntry->lpstrText, szMessage, lpConsole->nMaxStrLen); /* Re-Add the old line. */ nResult=Con_AddEntry(lpConsole, szTemp); L_safe_free(szTemp); return nResult; } /* Con_SendErrorMessage, outputs formated text to the console. Use as you would sprintf except that the first paramter is the console, not a string.*/ int Con_SendErrorMsg(HLCONSOLE hConsole, char* format, ...) { char* szOutput=NULL; va_list arglist=NULL; int nResult=0; if(!hConsole) return 0; /* Allocate memory for output, we free when we exit the function. */ szOutput=LG_Malloc( ((LPLCONSOLE)hConsole)->nMaxStrLen ); if(!szOutput) return 0; /* We use _vsnprintf so we can print arguments, and also so we can limit the number of characters, put to the output buffer by the max string length allowed in the console. */ va_start(arglist, format); _vsnprintf(szOutput, ((LPLCONSOLE)hConsole)->nMaxStrLen-1, format, arglist); va_end(arglist); nResult=Con_SendMessage(hConsole, szOutput); L_safe_free(szOutput); return nResult; } /* Con_SendCommand - Sends a command to the console, if internal functions are active then it will attempt to process one of those, then it will send the function to the external command, the function command will be changed to the appropriate value, based of the definition. The parameters are all in one string.*/ int Con_SendCommand(HLCONSOLE hConsole, char* szCmdLine) { char* szParams=NULL; char* szCommand=NULL; char szParseIgnore[]=" ,()\n\r\t"; unsigned long dwLen=0; LPLCONSOLE lpConsole=NULL; int bResult=0; int nCommand=0; lpConsole=(LPLCONSOLE)hConsole; if(lpConsole==NULL) return 0; dwLen=L_strlen(szCmdLine); if(dwLen<1) { Con_SendMessage(hConsole, ""); } /* Allocate memory for the string buffers, we need to free these when the function exits. */ szParams=LG_Malloc(lpConsole->nMaxStrLen); szCommand=LG_Malloc(lpConsole->nMaxStrLen); if( (!szParams) || (!szCommand) ) { L_safe_free(szParams); L_safe_free(szCommand); return 0; } if(!Con_SimpleParse(szCommand, szParams, szParseIgnore, szCmdLine, lpConsole->nMaxStrLen)) { L_safe_free(szParams); L_safe_free(szCommand); return 0; } if((nCommand=Con_CmdNameToValue(hConsole, szCommand))==0) { Con_SendErrorMsg(hConsole, "\"%s\" not recognized as a valid command.", szCommand); L_safe_free(szParams); L_safe_free(szCommand); return 0; } /* First attempt to process the command if the command isn't prcoessed then attempt to process internal commands, if asked to if we process an internal command we return, if not we process the command function. */ if(lpConsole->CommandFunction) { bResult=lpConsole->CommandFunction(nCommand, szParams, hConsole, lpConsole->pExtraData); } else { Con_SendMessage(hConsole, "Warning: No CommandFunction registered."); } //If the command hasn't been processed and the console is supposed //to attempt to process commands... if(!bResult && lpConsole->bProcessInternal) { bResult=Con_InternalCommands(nCommand, szParams, hConsole); } //If the command was not processed we'll type out a warning. if(!bResult) Con_SendErrorMsg(hConsole, "Could not process \"%s\" command.", szCommand); L_safe_free(szParams); L_safe_free(szCommand); return bResult; } /* Con_SetCurrent - Sets the active entry. */ int Con_SetCurrent(HLCONSOLE hConsole, char* szText) { if(szText==NULL) return 0; if(hConsole==NULL) return 0; if(!((LPLCONSOLE)hConsole)->lpActiveEntry) return 0; L_strncpy( ((LPLCONSOLE)hConsole)->lpActiveEntry->lpstrText, szText, ((LPLCONSOLE)hConsole)->nMaxStrLen); return 1; } /* Con_EraseCurrent - Clears the active entry. */ int Con_EraseCurrent( HLCONSOLE lpConsole) { if(lpConsole==NULL) return 0; if(!((LPLCONSOLE)lpConsole)->lpActiveEntry) return 0; ((LPLCONSOLE)lpConsole)->lpActiveEntry->lpstrText[0]=0; return 1; } /* Con_Clear - clears all entries out of the console. */ int Con_Clear(HLCONSOLE hConsole) { LPLCENTRY lpCurrent=NULL; LPLCENTRY lpNext=NULL; LPLCONSOLE lpConsole=(LPLCONSOLE)hConsole; if(!lpConsole) return 0; lpCurrent=lpConsole->lpEntryList; while(lpCurrent!=NULL) { lpNext=lpCurrent->lpNext; /* Clear the text string. */ L_safe_free(lpCurrent->lpstrText); /* Clear the entry. */ L_safe_free(lpCurrent); lpCurrent=lpNext; } lpConsole->lpEntryList=NULL; lpConsole->lpActiveEntry=NULL; lpConsole->dwNumEntries=0; Con_AddEntry(lpConsole, ""); return 1; } /* Con_GetNumEntries - returns the number of strings currently in the console, this includes the active string. */ unsigned long Con_GetNumEntries(HLCONSOLE hConsole) { if(hConsole==NULL) return 0; return ((LPLCONSOLE)hConsole)->dwNumEntries; } /* Con_GetEntry - Gets the selected string from the console. */ char* Con_GetEntry(HLCONSOLE hConsole, unsigned long nEntry, char* szOut) { LPLCONSOLE lpConsole=NULL; LPLCENTRY lpCurrent=NULL; unsigned long i; if(hConsole==NULL) return NULL; lpConsole=(LPLCONSOLE)hConsole; if(nEntry>lpConsole->dwNumEntries) return NULL; lpCurrent=lpConsole->lpEntryList; if(lpCurrent==NULL) return NULL; if(nEntry<1) return NULL; if(nEntry==1) { if(szOut) L_strncpy( szOut, lpConsole->lpActiveEntry->lpstrText, L_strlen(lpConsole->lpActiveEntry->lpstrText)+1); return lpConsole->lpActiveEntry->lpstrText; } for(i=1; i<nEntry; i++) { lpCurrent=lpCurrent->lpNext; } if(szOut) L_strncpy(szOut, lpCurrent->lpstrText, lpConsole->nMaxStrLen); return lpCurrent->lpstrText; } /* Con_RegisterCmd is used to register a command name, with a value, the value will be passed to the CommandFunction as the command parameter, then the user can use a switch to find out what to do. */ int Con_RegisterCmd(HLCONSOLE hConsole, char* szCmdName, unsigned long nValue) { LPLCONSOLE lpConsole=(LPLCONSOLE)hConsole; if(!lpConsole) return 0; if(!lpConsole->commands) { Con_SendMessage(hConsole, "No command definitions loaded."); return 0; } if(!Defs_Add(lpConsole->commands, szCmdName, (float)nValue)) { Con_SendErrorMsg(hConsole, "Could not register command \"%s\", name may be invalid.", szCmdName); return 0; } return 1; } /* Con_CmdNameToValue will change a command name to it's value that was registered with Con_RegisterCmd. */ unsigned long Con_CmdNameToValue(HLCONSOLE hConsole, const char* szCmdName) { LPLCONSOLE lpConsole=(LPLCONSOLE)hConsole; int bGotValue=0; float fValue=0; if(!lpConsole) return 0; if(!lpConsole->commands) { Con_SendMessage(hConsole, "No command definitions loaded."); return 0; } fValue=Defs_Get(lpConsole->commands, (char*)szCmdName, &bGotValue); if(!bGotValue) { return 0; } return (unsigned long)fValue; } /* Con_OnChar does is for the user to call when a button is pressed, for most characters it will append it to the end of the active string, but for backspace it will delete one character, and for return it will send the line to the command function. A lot of characters are ignored, though.*/ int Con_OnChar( HLCONSOLE hConsole, unsigned short cChar) { unsigned long dwLen=0; LPLCONSOLE lpConsole=NULL; lpConsole=(LPLCONSOLE)hConsole; if(lpConsole==NULL) return 0; /* If no active entry, then add an entry. */ if(lpConsole->lpActiveEntry==NULL) Con_AddEntry(lpConsole, ""); dwLen=L_strlen(lpConsole->lpActiveEntry->lpstrText); /* Do any necessary actions depending on cChar. */ switch(cChar) { case '\r': Con_SendCommand(lpConsole, lpConsole->lpActiveEntry->lpstrText); Con_EraseCurrent(lpConsole); break; case '\b': if(dwLen>0) { /* Remove last char, and add null-termination. */ lpConsole->lpActiveEntry->lpstrText[dwLen-1]=0; } break; default: /* The funcion made it here if a standard key was pressed. */ /* Break if line has reached it's max limit. */ if(dwLen >= (lpConsole->nMaxStrLen-1)) return 0; /* Add the char into the string and a null-termination. */ if((cChar >= ' ') && (cChar <= '~')) { lpConsole->lpActiveEntry->lpstrText[dwLen]=(char)cChar; lpConsole->lpActiveEntry->lpstrText[dwLen+1]=0; } break; }; return 1; } int Con_AttachCVarList(HLCONSOLE hConsole, void* cvarlist) { LPLCONSOLE lpConsole=NULL; lpConsole=(LPLCONSOLE)hConsole; if(lpConsole==NULL) return 0; lpConsole->cvarlist=cvarlist; Con_SendErrorMsg(hConsole, "Attached cvarlist at address 0x%08X to console.", cvarlist); return 1; } /* void* Con_GetCVar(HLCONSOLE hConsole, char* name) { LPLCONSOLE lpConsole=NULL; lpConsole=(LPLCONSOLE)hConsole; if(lpConsole==NULL) return 0; return CVar_GetCVar(lpConsole->cvarlist, name); } void* Con_GetCVarList(HLCONSOLE hConsole) { LPLCONSOLE lpConsole=NULL; lpConsole=(LPLCONSOLE)hConsole; if(lpConsole==NULL) return 0; return lpConsole->cvarlist; } */ #ifdef _DEBUG extern unsigned long g_nBlocks; BOOL WINAPI DllMain(HINSTANCE hInst, DWORD fdwReason, LPVOID lpReserved) { static _CrtMemState s1, s2, s3; switch(fdwReason) { //case DLL_THREAD_ATTACH: case DLL_PROCESS_ATTACH: _CrtMemCheckpoint(&s1); break; //case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: Debug_printf("lc_sys Shutdown...\n"); OutputDebugString("MEMORY USAGE FOR \"lc_sys.dll\"\"\n"); _CrtMemCheckpoint(&s2); _CrtMemDifference(&s3, &s1, &s2); _CrtMemDumpStatistics(&s3); _CrtDumpMemoryLeaks(); Debug_printf("%u allocations left.\n", g_nBlocks); break; } return TRUE; } #endif /*_DEBUG*/ <file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/lg_sys.c /* Legacy3D.c - Core elements of Legacy3D engine. Copyright (c) 2006, <NAME>. */ #include "common.h" #include <d3d9.h> #include <d3dx9.h> #include "lg_sys.h" #include "lg_cmd.h" #include "lg_init.h" #include "lv_init.h" #include "lv_reset.h" #include <stdio.h> L3DGame* g_game=L_null; #define LG_SHUTDOWN 0x80000010l #define LG_V_OR_S_DISABLED 0x80000020l L_result LG_RenderGraphics(L3DGame* lpGame) { D3DMATRIX matProjection, matView, matWorld; L_result nResult=0; IDirect3DDevice9* lpDevice=lpGame->v.m_lpDevice; /* Validate the device. */ if(L_failed((nResult=LV_ValidateDevice(lpGame)))) { if(nResult==LVERR_CANTRECOVER) return LG_SHUTDOWN; else return LG_V_OR_S_DISABLED; } lpDevice->lpVtbl->Clear(lpDevice,0,0,D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER,0xFF5050FF,1.0f,0); lpDevice->lpVtbl->BeginScene(lpDevice); /* The following is all just test stuff to make sure rendering is done correctly.*/ D3DXMatrixIdentity(&matProjection); D3DXMatrixIdentity(&matView); D3DXMatrixIdentity(&matWorld); D3DXMatrixPerspectiveFovLH(&matProjection, D3DX_PI/4.0f, 4.0f/3.0f, 1.0f, 1000.0f); lpDevice->lpVtbl->SetTransform(lpDevice, D3DTS_PROJECTION, &matProjection); lpDevice->lpVtbl->SetTransform(lpDevice, D3DTS_VIEW, &matView); lpDevice->lpVtbl->SetTransform(lpDevice, D3DTS_WORLD, &matView); //#define TESTLIGHT #ifdef TESTLIGHT { POINT ps; D3DLIGHT9 Light; D3DMATERIAL9 mtrl; GetCursorPos(&ps); ScreenToClient(lpGame->m_hwnd, &ps); ps.x=ps.x-(L_long)CVar_GetValue(lpGame->m_cvars, "v_Width", L_null)/2; ps.y=(L_long)CVar_GetValue(lpGame->m_cvars, "v_Height", L_null)/2-ps.y; memset(&Light, 0, sizeof(D3DLIGHT9)); Light.Type=D3DLIGHT_POINT; Light.Diffuse.r=1.0f; Light.Diffuse.g=1.0f; Light.Diffuse.b=1.0f; Light.Diffuse.a=1.0f; Light.Specular.r=1.0f; Light.Specular.g=1.0f; Light.Specular.b=1.0f; Light.Specular.a=1.0f; Light.Ambient.r=1.0f; Light.Ambient.g=1.0f; Light.Ambient.b=1.0f; Light.Ambient.a=1.0f; Light.Position.x=(float)ps.x; Light.Position.y=(float)ps.y; Light.Position.z=-10.0f; Light.Range=200.0f; Light.Falloff=1.0f; Light.Attenuation0=0.0f; Light.Attenuation1=1.0f; Light.Attenuation2=0.0f; lpDevice->lpVtbl->SetLight(lpDevice, 0, &Light); lpDevice->lpVtbl->LightEnable(lpDevice, 0, L_true); memset( &mtrl, 0, sizeof(mtrl) ); mtrl.Diffuse.r = mtrl.Ambient.r = 1.0f; mtrl.Diffuse.g = mtrl.Ambient.g = 1.0f; mtrl.Diffuse.b = mtrl.Ambient.b = 1.0f; mtrl.Diffuse.a = mtrl.Ambient.a = 1.0f; lpDevice->lpVtbl->SetMaterial(lpDevice, &mtrl ); } #else lpDevice->lpVtbl->SetRenderState(lpDevice, D3DRS_LIGHTING, L_false); #endif LVT_Render(lpGame->v.m_lpTestObj, lpDevice); /* here is our 2d drawing demonstration. */ VCon_Render(lpGame->v.m_lpVCon, lpGame->v.m_lpDevice); { static char szFPS[11]; sprintf(szFPS, "%i", (L_long)lpGame->l_AverageFPS->value); Font_Begin2(lpGame->v.m_lpVCon->lpFont); if(lpGame->v.m_lpVCon && lpGame->v.m_lpVCon->lpFont) Font_DrawString2(lpGame->v.m_lpVCon->lpFont, szFPS, 0, 0); Font_End2(lpGame->v.m_lpVCon->lpFont); } lpGame->v.m_lpDevice->lpVtbl->EndScene(lpGame->v.m_lpDevice); lpGame->v.m_lpDevice->lpVtbl->Present(lpGame->v.m_lpDevice, NULL, NULL, NULL, NULL); return LG_OK; } L_result LG_ProcessGame(L3DGame* lpGame) { static L_dword dwLastFUpdate=0; static L_dword dwFrame=0; if(LG_RenderGraphics(lpGame)==LG_SHUTDOWN) return LG_SHUTDOWN; //lpGame->l_AverageFPS->value=(timeGetTime()-lpGame->dwLastUpdate)*1000; lpGame->m_dwLastUpdate=timeGetTime(); if((lpGame->m_dwLastUpdate-dwLastFUpdate)>250) { lpGame->l_AverageFPS->value=(float)dwFrame*4.0f; dwFrame=0; dwLastFUpdate=timeGetTime(); } dwFrame++; return LG_OK; } /* The game loop everything in the game controlled from here, or at least by one of the functions called from here. The parameter hwnd, is the handle of the games window, the nShutdownMsg is used to determine if windows is telling the game it should shutdown. GameLoop returns TRUE if the game is still running, if the game is not running it returns FALSE in which case the application should close itself.*/ L_bool LG_GameLoop(HWND hwnd, L_bool bShutdownMsg, L_bool bActive) { static L3DGame* lpGame=NULL; static GAMESTATE nGameState=GAMESTATE_NOTSTARTED; switch(nGameState) { case GAMESTATE_NOTSTARTED: { /* By default the game status will be not started, when we first start (see the declaration of GAMESTATE. So we need to start it up.*/ if(!(lpGame=LG_GameInit(".\\base", hwnd))) { g_game=L_null; nGameState=GAMESTATE_SHUTDOWN; return L_false; } nGameState=GAMESTATE_RUNNING; /* Fall through and start running the game. */ } case GAMESTATE_RUNNING: { if(!bActive) break; if(LG_ProcessGame(lpGame)==LG_SHUTDOWN) bShutdownMsg=L_true; break; } case GAMESTATE_SHUTDOWN: return L_false; default: break; } if(bShutdownMsg || lpGame->l_ShouldQuit->value) { L_result nResult=0; nResult=LG_GameShutdown(lpGame); lpGame=L_null; g_game=L_null; nGameState=GAMESTATE_SHUTDOWN; return L_false; } return L_true; } L_bool LG_OnChar(char c) { if(!g_game) return L_false; return VCon_OnChar(g_game->v.m_lpVCon, c); } L3DGame* LG_GetGame() { return g_game; } <file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/console/lconsoledemo/lconsoledemo.c #include <windows.h> #include <stdio.h> #include <direct.h> #include "..\lconsole\lc_sys.h" #ifdef _DEBUG #define DLIB_PATH "..\\lconsole\\debug\\lc_sys_d.dll" #else /*_DEBUG*/ #define DLIB_PATH "lc_sys.dll" #endif /*_DEBUG*/ extern ObtainFunctions(); typedef struct tagEXTRADATAEX{ HWND hwnd; }EXTRADATAEX, *LPEXTRADATAEX; #define CONF_QUIT 0x00000010 #define CONF_GETDIR 0x00000020 extern LPCON_CREATE pCon_Create; extern LPCON_DELETE pCon_Delete; extern LPCON_SENDMESSAGE pCon_SendMessage; extern LPCON_SENDERRORMSG pCon_SendErrorMsg; extern LPCON_SENDCOMMAND pCon_SendCommand; extern LPCON_SETCURRENT pCon_SetCurrent; extern LPCON_ERASECURRENT pCon_EraseCurrent; extern LPCON_CLEAR pCon_Clear; extern LPCON_GETNUMENTRIES pCon_GetNumEntries; extern LPCON_GETENTRY pCon_GetEntry; extern LPCON_REGISTERCMD pCon_RegisterCmd; extern LPCON_ONCHAR pCon_OnChar; extern LPCON_ATTACHCVARLIST pCon_AttachCVarList; extern LPCON_CREATEDLGBOX pCon_CreateDlgBox; extern LPCCPARSE_GETPARAM pCCParse_GetParam; extern LPCCPARSE_GETFLOAT pCCParse_GetFloat; extern LPCCPARSE_GETINT pCCParse_GetInt; extern LPCCPARSE_CHECKPARAM pCCParse_CheckParam; extern LPCVAR_CREATELIST pCVar_CreateList; extern LPCVAR_DELETELIST pCVar_DeleteList; extern LPCVAR_SET pCVar_Set; extern LPCVAR_SETVALUE pCVar_SetValue; extern LPCVAR_GET pCVar_Get; extern LPCVAR_GETVALUE pCVar_GetValue; extern LPCVAR_GETCVAR pCVar_GetCVar; extern LPCVAR_GETFIRSTCVAR pCVar_GetFirstCVar; extern LPCVAR_ADDDEF pCVar_AddDef; extern LPCVAR_GETDEF pCVar_GetDef; int ConsoleCommand( unsigned long nCommand, const char* szParams, HLCONSOLE hConsole, void* pExtraData) { switch(nCommand) { case CONF_QUIT: SendMessage(((LPEXTRADATAEX)pExtraData)->hwnd, WM_CLOSE, 0, 0); break; case CONF_GETDIR: { char szDir[1024]; _getdcwd(_getdrive(), szDir, 1024); pCon_SendErrorMsg(hConsole, "DIR=\"%s\"", szDir); break; } default: return 0; } return 1; } int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpCmdLine, int nShowCmd) { MSG msg; HWND hwnd=NULL; HLCONSOLE hConsole=NULL; HCVARLIST cvarlist=NULL; HMODULE hDllFile=NULL; HGLOBAL hDlg=NULL; EXTRADATAEX data={NULL}; /* Load the library and all the functions. */ hDllFile=LoadLibrary(DLIB_PATH); if(hDllFile==NULL) { MessageBox( NULL, "Failed to load "DLIB_PATH, "lconsoledemo.exe", MB_OK|MB_ICONERROR); return 0; } if(!ObtainFunctions(hDllFile)) { MessageBox( NULL, "Could not load functions from library!", "lconsoledemo.exe", MB_OK|MB_ICONERROR); FreeLibrary(hDllFile); return 0; } /* First thing to do is start the Legacy Console. */ if((hConsole=pCon_Create(ConsoleCommand, 256, 2048, CONCREATE_USEINTERNAL, &data))==0) return 0; /* Create a cvarlist and attach it to the console. */ cvarlist=pCVar_CreateList(hConsole); pCon_AttachCVarList(hConsole, cvarlist); /* Register our custom commands. */ pCon_RegisterCmd(hConsole, "QUIT", CONF_QUIT); pCon_RegisterCmd(hConsole, "GETDIR", CONF_GETDIR); /* Create our window, and attach the console too it. */ data.hwnd=hwnd=pCon_CreateDlgBox(); SendMessage(hwnd, WM_USER_INSTALLCONSOLE, 0, (LPARAM)hConsole); /* Not that if we send a message to the console, we have to tell the dialog box to update, or it won't know that it needs to. */ pCon_SendMessage(hConsole, "Successfully initialized lconsoledemo.exe!"); SendMessage(hwnd, WM_USER_UPDATE, 0 ,0); ShowWindow(hwnd, nShowCmd); UpdateWindow(hwnd); while(GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } /* Free our allocated resources. */ pCon_Delete(hConsole); pCVar_DeleteList(cvarlist); FreeLibrary(hDllFile); return msg.wParam; }<file_sep>/tools/Countdown/countdown.c #include <windows.h> #include <stdio.h> #include <string.h> #include <time.h> typedef enum tagWINDOWPOSITION {POS_UNKNOWN=0, UPPER_LEFT, UPPER_RIGHT, LOWER_LEFT, LOWER_RIGHT} WINDOWPOSITION; signed long ConvertCharToDate(struct tm * sDateOutput, char * szInput) { char szTemp[100]; struct tm sDate; ZeroMemory(&sDate, sizeof(struct tm)); if(szInput!=NULL) strcpy(szTemp, szInput); else strcpy(szTemp, "1/1/1900"); sDate.tm_mon=atoi(strtok(szTemp, "/"))-1; sDate.tm_mday=atoi(strtok(NULL, "/")); sDate.tm_year=atoi(strtok(NULL, "/"))-1900; sDate.tm_wday=0; sDate.tm_yday=0; sDate.tm_isdst=-1; sDate.tm_sec=0; sDate.tm_min=0; sDate.tm_hour=0; if(sDateOutput) memcpy(sDateOutput, &sDate, sizeof(struct tm)); return mktime(&sDate); } signed long SecondsLeft(char* szOutput, const time_t nDepartTime) { time_t nTime=0, nTimeLeft=0; char szBeginString[11]; nTime=time(NULL); nTimeLeft=nDepartTime-nTime; if(nTimeLeft>=0) strcpy(szBeginString, "Time Left"); else strcpy(szBeginString, "Time Since"); nTimeLeft=abs(nTimeLeft); sprintf(szOutput, "%s:\n\nSeconds: %i\nMinutes: %i\nHours: %i\nDays: %i\nWeeks: %i\nMonths: %.1f", szBeginString, nTimeLeft, nTimeLeft/60, nTimeLeft/60/60, nTimeLeft/60/60/24, nTimeLeft/60/60/24/7, (float)nTimeLeft/60/60/24/31); return (signed long)nDepartTime; } int GetInfo(char*szNameOut, time_t*nDate, WINDOWPOSITION*nType) { char szType[256]; char szDate[256]; char szName[256]; //char szTemp[256]; FILE * fIn=fopen("countdown.inf", "r"); if(fIn==NULL) return 0; if((szName==NULL) || (szDate==NULL) || (szType==NULL)){ fclose(fIn); return 0; } if(fgets(szName, 256, fIn)==NULL){ fclose(fIn); return 0; } if(fgets(szDate, 256, fIn)==NULL){ fclose(fIn); return 0; } if(fgets(szType, 256, fIn)==NULL){ fclose(fIn); return 0; } fclose(fIn); /* Probably should do some error checking for the following code. */ *nDate=ConvertCharToDate(NULL, szDate); if(strnicmp("ul", szType, 2)==0) *nType=UPPER_LEFT; else if(strnicmp("ur", szType, 2)==0) *nType=UPPER_RIGHT; else if(strnicmp("ll", szType, 2)==0) *nType=LOWER_LEFT; else if(strnicmp("lr", szType, 2)==0) *nType=LOWER_RIGHT; else *nType=POS_UNKNOWN; strcpy(szNameOut, szName); szNameOut[strlen(szNameOut)-1]=0; /* sprintf(szTemp, "Name: %s Date: %s Type: %i", szNameOut, ctime(nDate), *nType); MessageBox(0, szTemp, 0, 0); */ return 1; } HRESULT PaintWindow(HWND hwnd, HFONT hFont, const time_t nDepartTime) { char szText[256]; RECT rect; HDC hdc=NULL; PAINTSTRUCT ps; HFONT hOldFont=NULL; HPEN hOldPen=NULL; HPEN hpen=CreatePen(PS_SOLID, 3, 0x000000FF); GetClientRect(hwnd, &rect); /* Get the amount of seconds left. */ SecondsLeft(szText, nDepartTime); hdc=BeginPaint(hwnd, &ps); hOldPen=SelectObject(hdc, hpen); MoveToEx(hdc, 0, 0, NULL); LineTo(hdc, rect.right-2, 0); LineTo(hdc, rect.right-2, rect.bottom-2); LineTo(hdc, 0, rect.bottom-2); LineTo(hdc, 0, 0); hOldFont=SelectObject(hdc, hFont); rect.top+=8; rect.left+=8; DrawText(hdc, szText, strlen(szText), &rect, 0); SelectObject(hdc, hOldFont); SelectObject(hdc, hOldPen); /* Draw a border */ EndPaint(hwnd, &ps); DeleteObject(hpen); return S_OK; } LRESULT CALLBACK WndProc(HWND hwnd, UINT nMsg, WPARAM wParam, LPARAM lParam) { static HFONT hFont=NULL; static time_t nDepartTime=0; switch(nMsg) { case WM_CREATE: hFont=CreateFont( 16, 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE, ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH, "Courier"); //hFont=GetStockObject(ANSI_FIXED_FONT); SetTimer(hwnd, 1, 1000, NULL); nDepartTime=(time_t)(((LPCREATESTRUCT)lParam)->lpCreateParams); break; /* case WM_SYSCOMMAND: switch(wParam) { case SC_MINIMIZE: //don't do anything break; default: DefWindowProc(hwnd, nMsg, wParam, lParam); } break; */ case WM_LBUTTONDBLCLK: SendMessage(hwnd, WM_CLOSE, 0, 0); break; case WM_PAINT: PaintWindow(hwnd, hFont, nDepartTime); break; case WM_TIMER: InvalidateRect(hwnd, NULL, TRUE); break; case WM_CLOSE: if(MessageBox(hwnd, "Are you sure you want to quit?", "Countdown", MB_YESNO|MB_ICONINFORMATION)==IDNO) break; case WM_DESTROY: DeleteObject(hFont); PostQuitMessage(0); break; default: return DefWindowProc(hwnd, nMsg, wParam, lParam); } return 0l; } int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR szCmdLine, int nShowCmd) { HWND hwnd=NULL; WNDCLASSEX wc; MSG msg; static const TCHAR szAppName[] = TEXT("Countdown"); RECT rectDesktop={0, 0, 0, 0}; RECT rectSize={0, 0, 0, 0}; BOOL bBottomCornerPopup=FALSE; WINDOWPOSITION nWindowPos=POS_UNKNOWN; char szName[256], szWinText[256]; time_t nDate; wc.cbSize=sizeof(wc); wc.style = CS_HREDRAW|CS_VREDRAW|CS_DBLCLKS; wc.cbClsExtra=0; wc.cbWndExtra=0; wc.lpfnWndProc=WndProc; wc.hInstance=hInst; wc.hbrBackground=(HBRUSH)GetStockObject(WHITE_BRUSH); wc.hIcon = NULL; wc.hIconSm = wc.hIcon; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.lpszMenuName=NULL; wc.lpszClassName=szAppName; if(!RegisterClassEx(&wc)) { MessageBox(NULL,TEXT("This program requires Windows NT!"),TEXT("Notice"),MB_OK|MB_ICONERROR); return 0; } if(!GetInfo(szName, &nDate, &nWindowPos)){ MessageBox(NULL, "Error: Could not load setup values.", "Error", MB_OK|MB_ICONERROR); return 0; } if(nWindowPos==POS_UNKNOWN) bBottomCornerPopup=FALSE; else bBottomCornerPopup=TRUE; GetClientRect(GetDesktopWindow(), &rectDesktop); rectDesktop.bottom-=GetSystemMetrics(SM_CYCAPTION); //Set the window rect. #define DWINDOW_WIDTH (200+GetSystemMetrics(SM_CXFIXEDFRAME)*2) #define DWINDOW_HEIGHT (150+GetSystemMetrics(SM_CYFIXEDFRAME)*2) rectSize.bottom=DWINDOW_HEIGHT; rectSize.right=DWINDOW_WIDTH; if(bBottomCornerPopup){ switch(nWindowPos) { case UPPER_LEFT: rectSize.left=0; rectSize.top=0;//rectDesktop.right-DWINDOW_WIDTH; break; case UPPER_RIGHT: rectSize.top=0; rectSize.left=rectDesktop.right-DWINDOW_WIDTH; break; case LOWER_LEFT: rectSize.left=0; rectSize.top=rectDesktop.bottom-DWINDOW_HEIGHT; break; default: case LOWER_RIGHT: rectSize.left=rectDesktop.right-DWINDOW_WIDTH; rectSize.top=rectDesktop.bottom-DWINDOW_HEIGHT; break; } }else{ rectSize.top=CW_USEDEFAULT; rectSize.left=CW_USEDEFAULT; rectSize.right=DWINDOW_WIDTH; rectSize.bottom=DWINDOW_HEIGHT+GetSystemMetrics(SM_CYCAPTION); } hwnd = CreateWindowEx( (bBottomCornerPopup?WS_EX_TOOLWINDOW:0), szAppName, szAppName, (bBottomCornerPopup?WS_POPUP:(WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX)), rectSize.left, rectSize.top, rectSize.right, rectSize.bottom, GetDesktopWindow(), NULL, hInst, (void*)nDate); sprintf(szWinText, "Countdown [%s]", szName); SetWindowText(hwnd, szWinText); ShowWindow(hwnd, SW_SHOWNORMAL); UpdateWindow(hwnd); while(GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return msg.wParam; } <file_sep>/games/Legacy-Engine/Source/lm_sys/lm_mesh_lg.h /* CLMeshLG - The legacy game implementation of a Legacy Mesh. Copryight (c) 2008 <NAME> */ #ifndef __LM_MESH_LG_H__ #define __LM_MESH_LG_H__ #include "lm_mesh_anim.h" #include "lm_skin.h" #include <d3d9.h> #include "lg_tmgr.h" class CLMeshLG: public CLMeshAnim { friend class CLMeshNode; friend class CLSkelLG; friend class CLMeshTree; //Constants and flags: private: //m_nFlags flags: static const lg_dword LM_FLAG_D3D_READY=0x00010000; static const lg_dword LM_FLAG_D3D_VALID=0x00020000; //The vertex format: static const lg_dword LM_VERTEX_FORMAT=(D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX1); public: //MakeD3DReady flags: static const lg_dword D3DR_FLAG_LOAD_DEF_TEX=0x00000001; //Member variables: private: IDirect3DVertexBuffer9* m_pVB; IDirect3DIndexBuffer9* m_pIB; tm_tex* m_pTex; LMPath m_szMeshFilePath; //Methods: public: CLMeshLG(); ~CLMeshLG(); //Necessary overrides: virtual lg_bool Load(LMPath szFile); virtual lg_bool Save(LMPath szFile); virtual lg_void Unload(); //New functionality for the class: lg_void MakeD3DReady(lg_dword flags); lg_void Validate(); lg_void Invalidate(); lg_bool IsD3DReady(); lg_void Render(); lg_void Render(const CLSkin* pSkin); protected: //Necessary overrides: virtual MeshVertex* LockTransfVB(); virtual void UnlockTransfVB(); //Static (global) support methods: private: //The read function: static lg_uint __cdecl ReadFn(lg_void* file, lg_void* buffer, lg_uint size); //Static variables used by all instances: private: static IDirect3DDevice9* s_pDevice; public: static lg_void LM_Init(IDirect3DDevice9* pDevice); static lg_void LM_Shutdown(); static lg_void LM_SetRenderStates(); static lg_void LM_SetSkyboxRenderStates(); }; #endif __LM_MESH_LG_H__<file_sep>/Misc/DBXExporter/DBXExporter/oedbx/library/dbxMessageInfo.cpp //*************************************************************************************** #define AS_OE_IMPLEMENTATION #include <oedbx/dbxMessageInfo.h> //*************************************************************************************** const char * DbxMessageInfo::GetIndexText(int1 index) const { const char * text[MaxIndex] = { "message index" , "flags" , "time message created/send" , "body lines" , "message address" , "original subject" , "time message saved" , "message id" , "subject" , "sender eMail address and name" , "answered to message id" , "server/newsgroup/message number", "server" , "sender name" , "sender eMail address" , "id 0f" , "message priority" , "message text length" , "time message created/received", "receiver name" , "receiver eMail address" , "id 15" , "id 16" , "id 17" , "id 18" , "id 19" , "OE account name" , "OE account registry key" , "message text structure" , "id 1d" , "id 1e" , "id 1f" }; if(index<MaxIndex) return text[index]; throw DbxException("Wrong index !"); } //*************************************************************************************** IndexedInfoDataType DbxMessageInfo::GetIndexDataType(int1 index) const { IndexedInfoDataType dataType[MaxIndex] = { dtInt4 , dtInt4 , dtDateTime, dtInt4 , dtInt4 , dtString,dtDateTime, dtString, dtString, dtString, dtString , dtString, dtString, dtString, dtString , dtNone , dtInt4 , dtInt4 , dtDateTime, dtString, dtString, dtNone , dtInt4 , dtNone , dtInt4 , dtInt4 , dtString , dtString, dtData , dtNone , dtNone , dtNone }; if(index<MaxIndex) return dataType[index]; throw DbxException("Wrong index !"); } //*************************************************************************************** <file_sep>/games/Legacy-Engine/Scrapped/old/2006SeptEngine/legacy3d/lm_d3d.cpp #include "lm_d3d.h" #include "lv_tex.h" #include <lf_sys.h> #include "lm_math.h" #include <d3dx9.h> int __cdecl mesh_close(void* stream) { return File_Close(stream); } int __cdecl mesh_seek(void* stream, long offset, int origin) { return File_Seek(stream, offset, (LF_MOVETYPE) origin); } int __cdecl mesh_tell(void* stream) { return File_Tell(stream); } unsigned int __cdecl mesh_read(void* buffer, unsigned int size, unsigned int count, void* stream) { return File_Read(stream, size*count, buffer); } CLegacyMeshD3D::CLegacyMeshD3D() { m_lpDevice=L_null; m_lpVB=L_null; m_lppTexs=L_null; m_bD3DValid=L_false; m_pSkel=L_null; m_pAnimMats=L_null; } L_bool CLegacyMeshD3D::Create(char* szFilename, IDirect3DDevice9* lpDevice) { Unload(); LF_FILE2 model=File_Open(szFilename, 0, LF_ACCESS_READ, LFCREATE_OPEN_EXISTING); if(!model) return L_false; LMESH_CALLBACKS cb; char szPath[LMESH_MAX_PATH]={0}; cb.close=mesh_close; cb.read=mesh_read; cb.seek=mesh_seek; cb.tell=mesh_tell; if(Load(model, &cb, L_getfilepath(szPath, szFilename))) { if(!CreateD3DComponents(lpDevice)) { Unload(); return L_false; } return L_true; } else return L_false; } L_bool CLegacyMeshD3D::CreateD3DComponents(IDirect3DDevice9* lpDevice) { m_lpDevice=lpDevice; m_lpDevice->AddRef(); //Allocate memory for textures. m_lppTexs=new IDirect3DTexture9*[m_nNumMaterials]; m_pSkel=new JOINTVERTEX[m_cSkel.m_nNumJoints]; //We need the animation matrices to be the number //of joints*2 so we can store the matrices for //the first and second frame. m_pAnimMats=new D3DXMATRIX[m_cSkel.m_nNumJoints*2]; this->SetupSkeleton(0, 0, 0.0f); this->Validate(); return L_true; } L_bool CLegacyMeshD3D::Unload() { if(!m_bLoaded) return L_true; L_dword i=0; Invalidate(); L_safe_delete_array(m_lppTexs); L_safe_delete_array(m_pSkel); L_safe_delete_array(m_pAnimMats); L_safe_release(m_lpDevice); this->CLegacyMesh::Unload(); m_lpDevice=L_null; m_lpVB=L_null; m_lppTexs=L_null; m_bD3DValid=L_false; m_pSkel=L_null; return L_true; } L_bool CLegacyMeshD3D::Validate() { //If the device has not been set, then we can't validate. if(!m_lpDevice) return L_false; //If we are already valid we don't need to revalidate the object. if(m_bD3DValid) return L_true; //Create the vertex buffer and fill it with the default information. L_result nResult=0; nResult=m_lpDevice->CreateVertexBuffer( m_nNumVertices*sizeof(LMESH_VERTEX), D3DUSAGE_WRITEONLY, LMESH_VERTEX_FORMAT, D3DPOOL_DEFAULT, &m_lpVB, L_null); if(L_failed(nResult)) { return L_false; } // Now fill the vertex buffer with the default vertex data. // Note that animation data will be created and filled into // the vertex buffer on the fly. void* lpBuffer=L_null; nResult=m_lpVB->Lock(0, m_nNumVertices*sizeof(LMESH_VERTEX), &lpBuffer, 0); if(L_failed(nResult)) { L_safe_release(m_lpVB); return L_false; } memcpy(lpBuffer, m_pVertices, m_nNumVertices*sizeof(LMESH_VERTEX)); m_lpVB->Unlock(); //Load the textures. L_dword i=0; for(i=0; i<m_nNumMaterials; i++) { Tex_Load(m_lpDevice, m_pMaterials[i].szTexture, D3DPOOL_DEFAULT, 0xFFFFFFFF, L_false, &m_lppTexs[i]); } m_bD3DValid=L_true; return L_true; } L_bool CLegacyMeshD3D::Invalidate() { if(!m_bD3DValid) return L_false; L_dword i=0; L_safe_release(m_lpVB); for(i=0; i<m_nNumMaterials; i++) { L_safe_release(m_lppTexs[i]); } m_bD3DValid=L_false; return L_true; } L_bool CLegacyMeshD3D::PrepareFrame(L_dword dwFrame1, L_dword dwFrame2, float t) { if(!m_bD3DValid) return L_false; //Make sure that all of the function parameters are //within a valid range. dwFrame1=L_clamp(dwFrame1, 0, m_cSkel.m_nNumKeyFrames); dwFrame2=L_clamp(dwFrame2, 0, m_cSkel.m_nNumKeyFrames); t=L_clamp(t, 0.0f, 1.0f); //Lock the vertex buffer to prepare to write the data. LMESH_VERTEX* pVerts=L_null; if(L_failed(m_lpVB->Lock(0, m_nNumVertices*sizeof(LMESH_VERTEX), (void**)&pVerts, 0))) return L_false; L_dword i=0; //If the 0th frame is specified that is just the standard //default positioin. Should probably actually just set up //some normalized matrices. if(dwFrame1==0) { for(i=0; i<m_nNumVertices; i++) memcpy(&pVerts[i], &m_pVertices[i], sizeof(LMESH_VERTEX)); } else { D3DXMATRIX* pJointTrans=m_pAnimMats; //Prepare each joints final transformation matrix. for(i=0; i<m_cSkel.m_nNumJoints; i++) { //We already calculated the final transformation //matrices for each frame for each joint so we need //only interpolate the the matrices for the two frames. //Interpolate transformation matrices. L_matslerp( &pJointTrans[i], &m_cSkel.m_pKeyFrames[dwFrame1-1].pJointPos[i].Final, &m_cSkel.m_pKeyFrames[dwFrame2-1].pJointPos[i].Final, t); } //Now that the transformations are all set up, //all we have to do is multiply each vertex by the //transformation matrix for it's joint. for(i=0; i<m_nNumVertices; i++) { //Copy the vertex we want. memcpy(&pVerts[i], &m_pVertices[i], sizeof(LMESH_VERTEX)); //If the vertex's bone is -1 it means that it is //not attached to a joint so we don't need to transform it. if(m_pVertexBoneList[i]!=-1) { //Multiply each vertex by it's joints transform. D3DXVec3TransformCoord((D3DXVECTOR3*)&pVerts[i].x, (D3DXVECTOR3*)&pVerts[i].x, &pJointTrans[m_pVertexBoneList[i]]); //Do the same for each vertex's normal. D3DXVec3TransformCoord((D3DXVECTOR3*)&pVerts[i].nx, (D3DXVECTOR3*)&pVerts[i].nx, &pJointTrans[m_pVertexBoneList[i]]); } } } //We've written all the vertices so lets unlock the VB. m_lpVB->Unlock(); return L_true; } L_bool CLegacyMeshD3D::SetupSkeleton(L_dword nFrame1, L_dword nFrame2, float t) { L_dword i=0; if(!m_pSkel || !m_cSkel.m_pBaseSkeleton) return L_false; nFrame1=L_clamp(nFrame1, 0, m_cSkel.m_nNumKeyFrames); nFrame2=L_clamp(nFrame2, 0, m_cSkel.m_nNumKeyFrames); t=L_clamp(t, 0.0f, 1.0f); //If frame 0 is specifed that is the //default skeleton. if(nFrame1==0) { for(i=0; i<m_cSkel.m_nNumJoints; i++) { //To find the final location of a joint we need to (1) find the //relative location of the joint. (2) multiply that by all of //it parent/grandparent's/etc transformation matrices. //(1) m_pSkel[i].x=0.0f; m_pSkel[i].y=0.0f; m_pSkel[i].z=0.0f; m_pSkel[i].psize=4.0f; m_pSkel[i].color=0xFFFF0000; //(2) D3DXVec3TransformCoord((D3DXVECTOR3*)&m_pSkel[i].x, (D3DXVECTOR3*)&m_pSkel[i].x, &m_cSkel.m_pBaseSkeleton[i].Final); } } else { D3DXMATRIX* pJointTrans=m_pAnimMats; for(i=0; i<m_cSkel.m_nNumJoints; i++) { //Interpolate the matrices. //L_matslerp(&pJointTrans[i], &pJointTrans[i], &pJointTrans[i+m_nNumJoints], t); L_matslerp(&pJointTrans[i], &m_cSkel.m_pKeyFrames[nFrame1-1].pJointPos[i].Final, &m_cSkel.m_pKeyFrames[nFrame2-1].pJointPos[i].Final, t); //We have to multiply by the base skelton final because we already multipled //the final key frame by the inverse, and that only needs to be done for transforming //the vertices of the model, not for transforming the vertices for the skeleton //joints. pJointTrans[i]=m_cSkel.m_pBaseSkeleton[i].Final*pJointTrans[i]; } for(i=0; i<m_cSkel.m_nNumJoints; i++) { //To find the final location of a joint we need to (1) find the //relative location of the joint. (2) multiply that by all of //it parent/grandparent's/etc transformation matrices. //(1) m_pSkel[i].x=0.0f; m_pSkel[i].y=0.0f; m_pSkel[i].z=0.0f; m_pSkel[i].psize=4.0f; m_pSkel[i].color=0xFFFF0000; //(2) D3DXVec3TransformCoord((D3DXVECTOR3*)&m_pSkel[i].x, (D3DXVECTOR3*)&m_pSkel[i].x, &pJointTrans[i]); } } return L_true; } L_bool CLegacyMeshD3D::RenderSkeleton() { //We now want to render the skelton for testing purposes. L_dword i=0; //If there are no joints just return true cause there is nothing //to render. if(!m_cSkel.m_nNumJoints) return L_true; BONEVERTEX Line[2]; //We want to render the bones first, this //is simply a line from the bone to it's parent. //If it has no parent nothing gets rendered. m_lpDevice->SetRenderState(D3DRS_ZENABLE, FALSE); m_lpDevice->SetTexture(0, L_null); m_lpDevice->SetFVF(BONEVERTEX_FVF); for(i=0; i<m_cSkel.m_nNumJoints; i++) { memcpy(&Line[0].x, &m_pSkel[i].x, 12); Line[0].color=m_pSkel[i].color; if(m_cSkel.m_pBaseSkeleton[i].nParentBone) { memcpy(&Line[1].x, &m_pSkel[m_cSkel.m_pBaseSkeleton[i].nParentBone-1].x, 12); Line[1].color=m_pSkel[m_cSkel.m_pBaseSkeleton[i].nParentBone-1].color; m_lpDevice->DrawPrimitiveUP(D3DPT_LINELIST, 1, &Line, sizeof(BONEVERTEX)); } } //We can render all the joints at once since they are just points. m_lpDevice->SetFVF(JOINTVERTEX_FVF); m_lpDevice->DrawPrimitiveUP(D3DPT_POINTLIST, m_cSkel.m_nNumJoints, m_pSkel, sizeof(JOINTVERTEX)); m_lpDevice->SetRenderState(D3DRS_ZENABLE, TRUE); //L_safe_delete_array(pTest); return L_true; } L_bool CLegacyMeshD3D::Render() { //Test render the model. if(!m_bD3DValid) return L_false; //PrepareFrame should not be called here, but should be called //by the application prior to the call to Render(). //PrepareFrame(0, 1, 0.0f); m_lpDevice->SetFVF(LMESH_VERTEX_FORMAT); m_lpDevice->SetStreamSource(0, m_lpVB, 0, sizeof(LMESH_VERTEX)); L_dword i=0; L_bool bRenderMeshesSeparately=L_true; if(bRenderMeshesSeparately) { for(i=0; i<m_nNumMeshes; i++) { if(m_pMeshes[i].nMaterialIndex!=-1) { m_lpDevice->SetTexture(0, m_lppTexs[m_pMeshes[i].nMaterialIndex]); } else { m_lpDevice->SetTexture(0, L_null); } m_lpDevice->DrawPrimitive(D3DPT_TRIANGLELIST, m_pMeshes[i].nFirstVertex, m_pMeshes[i].nNumTriangles); } } else { //If we draw the whole thing at once we just set //the texture to the first material. m_lpDevice->SetTexture(0, m_lppTexs[0]); m_lpDevice->DrawPrimitive(D3DPT_TRIANGLELIST, 0, m_nNumVertices/3); } /* //For testing purposes draw the normals. m_lpDevice->SetTexture(0, L_null); m_lpDevice->SetFVF(BONEVERTEX_FVF); BONEVERTEX Normal[2]; for(i=0; i<this->m_nNumVertices; i++) { Normal[0].x=m_pVertices[i].x; Normal[0].y=m_pVertices[i].y; Normal[0].z=m_pVertices[i].z; Normal[0].color=0xFFFFFFFF; Normal[1].x=m_pVertices[i].nx; Normal[1].y=m_pVertices[i].ny; Normal[1].z=m_pVertices[i].nz; Normal[1].color=0xFFFFFFFF; m_lpDevice->DrawPrimitiveUP(D3DPT_LINELIST, 1, &Normal, sizeof(BONEVERTEX)); } */ return L_true; }
bd16a338966828c767093713b3f060c8673af8f9
[ "Markdown", "INI", "Java", "Text", "PHP", "C", "C++" ]
550
Text
beemfx/Beem.Media
a1a87e7c82dd9fb9c6e82a5f5cf3caa0be02ee7f
9aff548da389e7bdeff0f1925aa9a38aa0e09490
refs/heads/master
<file_sep># Instagram-Bot It will Increase the follower and can extract the data of specific hashtag. Auto Liker A bot that automatically opens a browser, logs in, searches for trending based on a particular hashtag given and likes all of them. Used Selenium and Gecko driver to automate this cool stuff! Note : Use Mozilla Fireox Web Browser to run it. <file_sep>from selenium import webdriver from selenium.webdriver.common.keys import Keys import time class instagram: def __init__(self, username, password): self.username = username self.password = <PASSWORD> self.driver = webdriver.Firefox() def closeBrowser(self): self.driver.close() def login1(self): driver = self.driver driver.get('https://www.instagram.com/') time.sleep(5) login_button = driver.find_element_by_xpath("//a[@href='/accounts/login/?source=auth_switcher']") login_button.click() time.sleep(2) user_name_elem=driver.find_element_by_xpath("//input[@name='username']") user_name_elem.clear() user_name_elem.send_keys(self.username) passworword_elem = driver.find_element_by_xpath("//input[@name='password']") passworword_elem.clear() passworword_elem.send_keys(<PASSWORD>) passworword_elem.send_keys(Keys.RETURN) time.sleep(2) def like_photo(self,hashtag): driver=self.driver driver.get("https://www.instagram.com/explore/tags/" + hashtag + "/") time.sleep(2) for i in range (1,3): driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") time.sleep(2) hrefs=driver.find_elements_by_tag_name('a') pic_hrefs=[elem.get_attribute('href') for elem in hrefs] # print(pic_hrefs) # print('\n\n\n\n\n\n\n') pic_hrefs=[href for href in pic_hrefs if 'p/B' in href] # print(pic_hrefs) # print('\n\n\n\n\n\n\n') print(hashtag + 'photos:' + str(len(pic_hrefs))) for posts in pic_hrefs: driver.get(posts) time.sleep(3) # butt = driver.find_elements_by_class_name('dCJp8 afkep _0mzm-') # for tags in butt: # if tags.find_element_by_xpath("//span[@class='glyphsSpriteHeart__outline__24__grey_9 u-__7']"): # print("Liked!") # tags.click() # time.sleep(3) try: time.sleep(2) like_button = lambda: driver.find_element_by_xpath('//span[@aria-label="Like"]') like_button().click() time.sleep(3) except Exception as e: time.sleep(2) ed = instagram('Username', '<PASSWORD>') ed.login1() ed.like_photo('hashtag')
34d8adc2662d63e81063eb6834702a47b2a414fa
[ "Markdown", "Python" ]
2
Markdown
NANDISHSHAH/Instagram-Bot
15bbd3be98e635722ee51f56fbb7a5f7e66046a5
cbd167ada2145f0fd2e87abfe2c49dd56d0c82fd
refs/heads/main
<repo_name>mccurcio/mccurcio.github.io<file_sep>/_draft/2021-12-17-Count-words-in-file.md --- title: "Python: Count words in file" tags: - "one liners" - "count words" --- ### Count words in file Returns the number of words in a text file, - `open('test.txt', 'r').read()` gets us the text of the file. - We get the word using `.split()`, splits the text by any whitespace and returns a list of words. - Empty strings are removed from the results. - `len` gives us the count of the words. ``` len(open('Dictionary-Merges.md', 'r').read().split()) ``` <file_sep>/_draft/skew-eda-article/skew-partOf6Steps.rmd --- title: "Why Do EDA At All" author: "mcc" date: '2022-03-28' output: html_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` Boxplots and Histograms are the first tools taught with statistical software, but why? Many courses gloss over the "why" assuming everyone knows the answer. Since my discussion was with a journalist, I was reminded of the 5 W's of reporting: 1. Who 2. What 3. When 4. Where 5. Why - How might a journalist think of the 5 W's when analyzing a dataset. - Can these 5 questions be useful when carrying out a Data Analysis? In short, **Yes**. **And**, they should be asked by Data Scientists too. - **Why** did your research come to find this result? - Why is this data being analyzed at all? - Are we hypothesis testing? - Are we looking for a correlation or a regression line? - Is the data normally distributed? </br> - **When** and **Where** was the data collected? - If a political poll is asked in 2 cities, is it reasonable to assume that you can apply 'your poll' to the entire country? - Could the time, day, or season the data was collected change over time? </br> - Is it important, **Who** gathered this data? - What prejudices did that person or group have while collecting the data? </br> - And finally, **What** can be learned from the dataset? --- <NAME> and <NAME> have their angle on Data Science, 'What is the Question?' ![](jleek-ds.png) In the flowchart above, Data Science and Statistics can be broken down into 6 categories. In this article, I will be focusing on Exploraotry Data Analysis (EDA). 1. Descriptive Statistics - simply describe the circumstances - Circumstance #1: A statistician may find themselves working in a manufacturing department within a company making electronic boards. The statistician may be part of a 'Process-Control' team. - If you are measuring the voltages of the boards on an assembly line your job could be to sample a number of boards and find what percentage are in/out of specification. For example: Sampling 40 boards gives: | Descriptive Statistic | Value | | :-------------------- | :--------- | | n | 40 | | mean | 3.12 Volts | | meadian | 3.5 Volts | | mode | 3.4 Volts | | standard deviation | 0.25 Volts | 1. Exploratory 1. Inferential 1. Predictive 2. Causual 1. Mechanistic Commonly, the first topic in statistics classes is to discuss where bias can be introduced into a study. - What is wrong with the data? - Is there anything wrong with your study? - Is it possible to fix the study or data? - Can the mistake even be fixed? Exploratory Data Analysis is the first review of your data and information. <!-- Conversely, can Data Scientists learn from Journalists? Are Data Scientists acting similarly to investigative reporters, who look for problems with the goal being to bring a story to light? --> I plan to investigate two mathematical perturbations that can be interpreted using Boxplots and Histograms. Two common measures for distributions are skew and kurtosis. >Perturbation, in mathematics, a method for solving a problem by comparing it with a similar one for which the solution is known. Usually the solution found in this way is only approximate. > >https://www.britannica.com/science/perturbation-mathematics But first, let us prepare some good and bad data. #### Generate a dataset ```{r} # Create data names <- c(rep("A", 15) , rep("B", 15) , rep("C", 15)) value <- c( rpois(15, 5) , rnorm(15, mean=10, sd=15) , rnorm(15, mean=40, sd=10) ) data <- data.frame(names,value) boxplot(data$value ~ data$names , col=terrain.colors(4), horizontal = T ) ``` Square Values ```{r} skewed_1 = (1/2)*(data$value)^2 data <- cbind(data, skewed_1) boxplot(data$skewed_1 ~ data$names , col=terrain.colors(4), horizontal = T ) ``` https://statisticsglobe.com/jitter-r-function-example/ https://stackoverflow.com/questions/23675735/how-to-add-boxplots-to-scatterplot-with-jitter https://www.data-to-viz.com/caveat/boxplot.html <file_sep>/_draft/skew-eda-article/skew_test.rmd --- title: "Boxplots Vs Histograms WRT Distributions" author: "mcc" date: '2022-04-06' output: html_document --- I was discussing Data Science with a journalist recently, and a question came up; - Why are Boxplots so important with respect to Exploratory Data Analysis? Boxplots and histograms are the first tools taught when learning statistical software, but why? **AND**, many online-courses (I've seen) gloss over the "*WHY*." In this article, I suggest using [Quantile-Quantile plots](https://en.wikipedia.org/wiki/Q%E2%80%93Q_plot) and Histograms compared to Boxplots. Boxplots do not always tell the full story. [Quantile-Quantile plots](https://en.wikipedia.org/wiki/Q%E2%80%93Q_plot) are normally called Q-Q plots. > For more on Exploratory Data Analysis, I recommend [Exploratory Data Analysis with R](https://leanpub.com/exdata) by <NAME>, and it's FREE. Even if you don't use R (yet) it has some nuggets. Boxplots, Histrograms, Strip-Charts and Q-Q plots are used to help a statistician visualize three items; ## Skew, Outliers & Kurtosis 1. Skew - How symmetrical is *your* distribution. - Does the data look even on the left side as it does on the right. - First question shold be, Is the data skewed to the left or right or not all? - The way I learned skew was by thinking of a duck's bill. https://towardsdatascience.com/top-3-methods-for-handling-skewed-data-1334e0debf45 ```{r echo=FALSE, message=FALSE, warning=FALSE} library("PearsonDS") #skew left moments <- c(mean = 5, variance = 1, skewness = 1.5, kurtosis = 5) data <- rpearson(100, moments = moments) hist(data, main="Postive Skew") boxplot(data, main="Postive Skew", horizontal = T) #skew right moments <- c(mean = 9, variance = 1, skewness = -1.5, kurtosis = 5) data2 <- rpearson(100, moments = moments) hist(data2, main="Negative Skew") boxplot(data2, main="Negative Skew", horizontal = T) ``` 2. Outliers - Outliers are outside the arms and whiskers of a boxplot. - - 3. Kurtosis Skewness is a measure of symmetry, or we could say the lack of symmetry. A distribution, or data set, is symmetric if it looks the same to the left and right of the center point. Kurtosis is a measure of whether the data are heavy-tailed or light-tailed relative to a normal distribution. That is, data sets with high kurtosis tend to have heavy tails, or outliers. Data sets with low kurtosis tend to have light tails, or lack of outliers. A uniform distribution would be the extreme case. ## Why carry out an Exploratory Data Analysis? The major elements of Exploratory Data Analysis can be written out like a check list. 1. Formulate your question(s) 2. Check your data - Read in your data - Check the data for missing values this mean imputations - data structures, for example, numbers converted to strings, categorical data converted to strings, etc. - Use the Linux or MacOS command `less` - missing commas, or quotes for strings 3. Validate your data with at least one external source 4. Try the easy solution first 5. Challenge your solution 6. Repeat any and all if necessary Examination of numerical data is useful Are there outliers missing values Check Boxplots and Histograms For this article, we will focus on 'why use Boxplots and Histograms.' One ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` #### Generate a dataset ```{r} # Create data fish <- rpois(200, 5) guassian <- rnorm(200, mean=10, sd=15) penny_toss <- rbinom(0:200, 10, 0.33) print("fish") print(fish) print("guassian") print(guassian) print("penny_toss") print(penny_toss) ``` ```{r} boxplot(fish, col=terrain.colors(4), main="Poisson Distribution", horizontal = T) boxplot(guassian, col=terrain.colors(4), main="Normal Distribution", horizontal = T) boxplot(penny_toss, col=terrain.colors(4), main="Binomial Distribution", horizontal = T) ``` Histograms ```{r} hist(fish) hist(guassian) hist(penny_toss) ``` Square Values ```{r} fish_skewed = (1/2)*(fish)^2 guassian_skewed = (1/2)*(guassian)^2 penny_toss_skewed = (1/2)*(penny_toss)^2 boxplot(fish_skewed, main="Fish", horizontal = T) boxplot(guassian_skewed, main="Normal", horizontal = T) boxplot(penny_toss_skewed, main="Binomial", horizontal = T) ``` Histograms ```{r} hist(fish_skewed, breaks=50, freq = F) hist(guassian_skewed, breaks=20, freq = F) hist(penny_toss_skewed, breaks=50, freq = F) ``` , xlim=c(0,1500), ylim=c(0,200) ```{r} # Histogram Colored (blue and red) hist(fish_skewed, col=rgb(1,0,0,0.5), xlim=c(0,250), ylim=c(0,100), main="Overlapping Histogram", xlab="Variable") hist(penny_toss_skewed, col=rgb(0,0,1,0.5), add=T) box() ``` <file_sep>/_docs/chapters/support-vector-machines-for-binary-classification.md --- title: "Learning Support Vector Machines" date: 2019-06-01 10:00:00 tags: SVM Data_Science --- {% include_relative /support-vector-machines-1.html %} <file_sep>/_docs/chapters/exploratory-data-analysis.md --- title: "Beginning Exploratory Data Analysis" tags: Data_Science EDA --- {% include_relative eda.html %} <file_sep>/_posts/r/2020-12-31-r-complete-kmeans.md --- title: "The Complete Algorthym for K-means" tags: R Kmeans --- ```{r} require (ggplot2) x <- round ( rnorm ( 1000, 100, 15 )) + rnorm (1000)*15 dens.x <- density (x) empir.df <- data.frame ( type = 'empir', x = dens.x$x, density = dens.x$y) norm.df <- data.frame ( type = 'normal', x = 50:150, density = dnorm (50:150,100,15)) df <- rbind ( empir.df, norm.df) m <- ggplot ( data = df, aes (x,density)) m + geom_line ( aes (linetype = type, colour = type)) K-Means - kmeans_mehdi.R mcc29th November 2021 at 9:23pm K-Means algorithm from kmeans_mehdi.R #k = 3 # the number of K's max = 5000 # the maximum number for generating random points n = 100 # the number of points maxIter = 10 # maximum number of iterations threshold = 0.1 # difference of old means and new means # Randomly generate points in the form of (x,y) x <- sample(1:max, n) y <- sample(1:max, n) # put point into a matrix z <- c(x,y) m = matrix(z, ncol=2) ks <- c(1, 2, 4, 8, 10, 15, 20) # different Ks for(k in ks) { myKmeans(m, k, max) } myKmeans <- function(m, k, max) { #initialization for k means: the k-first points in the list x <- m[, 1] y <- m[, 2] d=matrix(data=NA, ncol=0, nrow=0) for(i in 1:k) { d <- c(d, c(x[i], y[i])) } init <- matrix(d, ncol=2, byrow=TRUE) dev.new() plotTitle <- paste("K-Means Clustering K = ", k) plot(m, xlim=c(1,max), ylim=c(1,max), xlab="X", ylab="Y", pch=20, main="plotTitle") par(new=T) plot(init, pch=2, xlim=c(1,max), ylim=c(1,max), xlab="X", ylab="Y") par(new=T) oldMeans <- init oldMeans cl <- Clustering(m, oldMeans) cl means <- UpdateMeans(m, cl, k) thr <- delta(oldMeans, means) itr <- 1 while(thr > threshold){ cl <- Clustering(m, means) oldMeans <- means means <- UpdateMeans(m, cl, k) thr <- delta(oldMeans, means) itr <- itr+1 } cl thr means itr for(km in 1:k){ group <- which(cl == km) plot(m[group,],axes=F, col=km, xlim=c(1,max), ylim=c(1,max), pch=20, xlab="X", ylab="Y") par(new=T) } plot(means, axes=F, pch=8, col=15, xlim=c(1,max), ylim=c(1,max), xlab="X", ylab="Y") par(new=T) dev.off() } # end function myKmeans # function distance dist <- function(x,y) { d<-sqrt( sum((x - y) **2 )) } createMeanMatrix <- function(d) { matrix(d, ncol=2, byrow=TRUE) } # compute euclidean distance euclid <- function(a,b) { d<-sqrt(a**2 + b**2) } euclid2 <- function(a) { d<-sqrt(sum(a**2)) } # compute difference between new means and old means delta <- function(oldMeans, newMeans) { a <- newMeans - oldMeans max(euclid(a[, 1], a[, 2])) } Clustering <- function(m, means) { clusters = c() n <- nrow(m) for(i in 1:n) { distances = c() k <- nrow(means) for(j in 1:k) { di <- m[i,] - means[j,] ds <- euclid2(di) distances <- c(distances, ds) } minDist <- min(distances) cl <- match(minDist, distances) clusters <- c(clusters, cl) } return (clusters) } UpdateMeans <- function(m, cl, k) { means <- c() for(c in 1:k) { # get the point of cluster c group <- which(cl == c) # compute the mean point of all points in cluster c mt1 <- mean(m[group,1]) mt2 <- mean(m[group,2]) vMean <- c(mt1, mt2) means <- c(means, vMean) } means <- createMeanMatrix(means) return(means) } ``` <file_sep>/_posts/bash/2017-12-20-bash-dna.md --- title: "Bash - Print Codons" tags: Bash --- Print all Codons Print all possible 3-mer DNA sequence combinations ``` echo {A,C,T,G}{A,C,T,G}{A,C,T,G} ``` <file_sep>/_posts/misc/2021-01-01-variability.md --- title: "Source of Variability" tags: Statistics InProgess --- Does this look good?? | Source of Variability | Sum of Squares | Degrees of Freedom | Mean Squares | F-value | |--:|--:|--:|--:|--:| | Treatment Variability | SSB<br>Sum of Squares Between Columns | Columns - 1 | MSB<br>Sum of Squares Within Columns | [[F-Critical Value|http://mathworld.wolfram.com/F-Distribution.html]] | | Variability Due To Error | SSW<br> S.S. Within Treatment<br>{SSE-Sum of Squares of Error} | __(R-1)*C__<br>(Rows-1)*Columns | MSW<br>MSW = Variance = s^^2^^ | | | Total | TSS<br>Total Sum of Squares<br>TSS = SSB + SSE | __(R*C)-1__<br>Rows*Columns - 1 | | | <file_sep>/_draft/rmd_files/2019-04-14-probability-puzzle.rmd --- title: "Ask Statistics Guy" author: "MCC" date: '2019-10-14' output: html_document --- The puzzle: Consider a normally distributed random variable with an expected value of 20 and standard deviation of 4. If you determine the value of this variable 8 times, then what is the chance that the 8 sample values yield an improved standard deviation between 4.9 and 5.3? [See Question](https://www.reddit.com/r/AskStatistics/comments/dgvcq0/can_anyone_help_me_with_this_question_about_the/?%24deep_link=true&correlation_id=8d023e0e-cae3-4a55-b070-aa7c17047ecd&ref=email_digest&ref_campaign=email_digest&ref_source=email&%243p=e_as&%24original_url=https%3A%2F%2Fwww.reddit.com%2Fr%2FAskStatistics%2Fcomments%2Fdgvcq0%2Fcan_anyone_help_me_with_this_question_about_the%2F%3F%24deep_link%3Dtrue%26correlation_id%3D8d023e0e-cae3-4a55-b070-aa7c17047ecd%26ref%3Demail_digest%26ref_campaign%3Demail_digest%26ref_source%3Demail%26utm_content%3Dpost_title%26utm_medium%3Ddigest%26utm_name%3Dtop_posts%26utm_source%3Demail%26utm_term%3Dday&_branch_match_id=711018267596211740) ```{r} obs = 10000 # rows tests = matrix(0, nrow = obs, ncol = 8) # 8 cols = 8 runs set.seed(1003) # populate with random values, mean = 20, sd = 4 for (i in 1:obs) { for (j in 1:8) { tests[i,j] <- rnorm(1, mean = 20, sd = 4) } } #Find sd of each row sds = apply(tests, 1, sd) # Filled Density Plot d <- density(sds) plot(d, main="Kernel Density of Std. Dev.") polygon(d, col="red") abline(v = 4.9, col= "black") abline(v = 5.3, col= "black") ``` ```{r} # Counts for standard deviation between 4.9 and 5.3 counts = vector(mode = "integer", length = obs) for (k in 1:obs) { if ((sds[k] >= 4.9) & (sds[k] <= 5.3)) { counts[k] <- 1 } } total = sum(counts) print((sum(counts)/obs)) ``` **The percent probability of this event occuring is 7.04%.** Small but not significant. <file_sep>/_posts/python/2021-12-17-python-strings.md --- title: "Python - Strings" date: 2021-12-17 21:00:00 tags: Python InProgress --- <hr> Convert repeated spaces to one space: - Using Regex - The snippet below clears out the repeated spaces in a text and replaces it with single space. - `re` is a regular expression module to find more than one occurrences of space with ‘[ ]+’. ``` import re re.sub(r"[ ]+", ' ', 'this sentence has non-uniform spaces') ``` <file_sep>/_posts/data_science/2019-06-01-k-means.md --- title: "K-Means Clustering Example" date: 2019-06-01 10:00:00 tags: K_Means Data_Science --- {% include_relative k-means.html %} <file_sep>/pages/about.md --- title: About <NAME> permalink: /about/ --- # Welcome I am a Scientist, Sales-Specialist, Patient Educator, and a Data Scientist. Among my qualities are Dilgence, Inquistiveness and Resourcefulness. My tools include Writing, Presentation, Statistics, Data Science, R, and Python to impart ideas. *Matt* ## Have a Question? - <a href="mailto:<EMAIL>?subject=Greetings from a new friend">Send An Email</a> <file_sep>/_posts/bash/2017-12-17-bash-scripting.md --- title: "Bash - Scripting" tags: Bash InProgress --- Run command on multiple files at once ``` for FILE in $(ls *); do command $FILE; done ``` Warning: this assumes there are no spaces in the lines in your file. If they do # contain spaces, you need to add proper escaping using quotes. **See**: [Advanced Bash-Scripting Guide](http://tldp.org/LDP/abs/html/), **GOOD**! <file_sep>/_draft/2020-12-31-TEMPLATE-4-POSTS.MD --- title: "Template For Posts" tags: Some --- <hr> Title1 [Man_Page](https://) ``` cut -f1-3,5,7 input.txt > ouput.txt ``` Cut column/field 3 separated by a comma ``` cut -d"," -f 3 input.txt > output.txt ``` <file_sep>/_posts/misc/2017-06-14-sci-words.md --- title: "Various choices for scientific language" date: 2016-06-14 21:00:00 tags: Words --- ![](/assets/img/sci-words.png) <file_sep>/_draft/skew-eda-article/test.r library("PearsonDS") #skew left moments <- c(mean = 10,variance = 1,skewness = 1.5, kurtosis = 5) data <- rpearson(100, moments = moments) hist(data) boxplot(data, horizontal = T) #skew right moments <- c(mean = 10, variance = 1, skewness = -1.5, kurtosis = 5) data2 <- rpearson(100, moments = moments) hist(data2) boxplot(data2, horizontal = T) <file_sep>/_docs/resources/research-topics.md --- title: "Looking For Topic & Ideas" date: 2022-03-10 13:30:00 tags: Ideas --- ## Need Inspiration & Ideas - This list is meant to inspire you! *A good presenter does **NOT** have to be:* 1. an expert on the topic 2. an experienced speaker 3. a "*rockstar*" or "*ninja*" *Instead, A good speaker **is**:* 1. interested in communicating effectively 1. enthusiastic about the topic, and helping others 1. willing to do some homework to pull together demos and/or visuals --- ## Ideas - [Who, what, where, when, why and how] - Talking DS to a Journalist - Python - Setting up your enviroment (versions for window, linux or that other OS) - working with Conda or - venv - Documenting your work - the PEP-8 way - Exploring `<insert your favorite library>` - Git, github, and source control (how to make your repo look professional) - How to OOP with Python - Talking to databases - Exploratory Data Analysis Examples/ Reporting - How to compare/run multiple ML models. - Flask - Dash - Django - Automating Reports and reporting - R-library: [Usethis](https://usethis.r-lib.org/) - How to open source contributions - How to work with OSS - Overview of data types in Python - Overview of an interesting algorythm - Approaches to logging - What is type hinting and should I be using it? - Helpful `__dunder__` methods - How I wrote a text adventure game in Python - Building a simple game (Hangman, tic-tac-toe, or something similar) - Debugging tales (lightning talks) - Meet & greet (opportunity for all attendees to introduce themselves) - I'm teaching myself X, and it's really _______ <file_sep>/_draft/2022-03-2-Day-33-datacamp.md --- layout: post title: "Day 33: Working on DataCamp" date: 2022-03-02 13:00:00 -0500 categories: DataCamp --- - Working on DataCamp SQL, Intermeidate Python and Plotly/Dash courses <file_sep>/_posts/r/2019-04-14-probability-puzzle.md --- title: "Ask Statistics Guy - A Probability Puzzle" tags: R --- {% include_relative 2019-04-14-probability-puzzle.html %} <file_sep>/_docs/chapters/logistic-regression-for-binary-classification.md --- title: "Learning Logistic Regression" tags: Data_Science Logit --- {% include_relative logistic-regression-1.html %} <file_sep>/_draft/2020-01-01-bash-compgen-norc.md --- title: "List All Local Bash Commands" tags: Bash --- List all Bash commands with compgen in Shell - `compgen` - is a helpful command when you are up against a new server and not sure of the commands you are allowed to run. | Command | Action | |:--------|:-------| | compgen -a | view **aliases** | | compgen -a | view **aliases** | | compgen -a | view **aliases** | <file_sep>/_draft/2021-12-17-Countlines.md --- title: "Python: Count Lines in file" tags: - "one liners" - "count lines" --- Returns the number of lines in a text file, - `open('test.txt', 'r').read()` gets us the text of the file. - `.split('\n')`, which splits the text at every new line character `\n` and returns a list. - `len` gives us the count of the words. ``` len(open('data/test.txt', 'r').read().split('\n')) ``` <file_sep>/_docs/resources/r-book-resources.md --- title: "R Book Resources" date: 2022-04-09 18:30:00 tags: Books Resources R --- ## Free R Books & Material - [R4ds by <NAME>](https://r4ds.had.co.nz/) - [Advanced_r by <NAME>](https://adv-r.hadley.nz/) - [DS_In_Education_Using_r](https://datascienceineducation.com/) - [RStudio For Education](https://rstudio4edu.github.io/rstudio4edu-book/) - [epgs](https://engineering-shiny.org/) - [GGplot2](https://ggplot2-book.org/index.html) - [Mastering Shiny](https://mastering-shiny.org/) - [Modern Dive, Statistical Inference via Data Science](https://moderndive.com/) - [R_packages](https://r-pkgs.org/) - [Regression and Other Stories](https://avehtari.github.io/ROS-Examples/) - [tmwr](https://tmwr.org) - [tidytext](https://www.tidytextmining.com/) - [Bookdown, blogdown, Rmarkdown](https://bookdown.org) - [Geocomputation with R](https://geocompr.robinlovelace.net/) - [Handling Strings With R](http://www.gastonsanchez.com/r4strings/) Misc. - Swirl is an excellent beginner tool for learning R: (https://swirlstats.com/) <file_sep>/_draft/_2021-12-09-draft-obsidian-artcle.md --- title: "Article on Obsidian" author: "<NAME>" date: '2021-12-09' slug: Anaconda tags: - Anaconda - Python categories: Anaconda --- Article on Obsidian so I installed it and tried a bit <file_sep>/_posts/misc/2021-12-12-quotes-ch.md --- title: "Hitchens Quotes" tags: Quotes --- Burden of Proof >That which can be asserted with out evidence can be dismissed without evidence. >The burden of proof is on the claimant. >If the claimant makes a claim it is up to that person to prove it. > ><NAME>, 13 April 1949 – 15 December 2011 <file_sep>/_posts/bash/2021-11-01-bash-find-file-w-grep.md --- title: "Bash - Grep - Find file name in sub directories" tags: Bash Grep --- Find a specific file name in large directories Find text inside a list of files and output the filename when a match occurs. Recurse and case-insensitive: -i - Ignore case distinctions -r - Recursive -l - Suppress normal output; instead print the name of each input file from which output would normally have been printed. The scanning will stop on the first match. ``` grep Documentation grep -irl foo* ``` <file_sep>/_posts/misc/2022-04-27-quotes.md --- title: "<NAME> Quote" --- >An approximate answer to the right question is worth a great deal more than a precise answer to the wrong question. > >Paraphrased in Super Freakonomics ><NAME> (1915-2000) American mathematician and statistician >“The future of data analysis,” Annals of Mathematical Statistics 33 (1) (1962) <file_sep>/_posts/misc/2020-02-11-quotes.md --- title: "Quotes" --- <NAME> (1915-2000) American mathematician and statistician “The future of data analysis,” Annals of Mathematical Statistics 33 (1) (1962) Paraphrased in Super Freakonomics as: "An approximate answer to the right question is worth a great deal more than a precise answer to the wrong question."<file_sep>/_posts/r/2018-02-11-ggplot-histogram.md --- title: "The Basic GGPlot Histogram" subtitle: "& why-you-need-to-practice-it" tags: Ggplot R --- {% include_relative 2018-02-11-ggplot-histogram.html %} <file_sep>/_posts/misc/2022-04-15-horizontal-line-css.md --- title: "How to horizontal line in CSS" tags: CSS --- How to change horizontal line in css `<hr>` ``` hr { margin-top: 0.5rem; margin-bottom: 0.5rem; border: 0; border-top: 1px solid rgba(0, 0, 0, .1) /* Change: 2-3 px AND/OR alpha=.2 or .3 } ``` <file_sep>/_draft/2021-12-11-alwaysAI-Company-Notes.md --- title: "Investigating Always AI" author: "<NAME>" tags: - Company Notes - AlwaysAI - YOLO --- ### Company Notes: Investigating alwaysAI Date: 5/10/21 [alwaysAI](https://alwaysai.co/) ### Executive Summary: - alwaysAI (aai) is a startup out of San Diego, CA that helps developers quickly get edge devices (IOT) started and deployed quickly using open-source AI models (for example [YOLO](https://pjreddie.com/darknet/yolo/) to assist companies with machine learning tasks such as: 1. image classification 2. object detection 3. object tracking 4. tracking & counting 5. semantic segmentation 6. pose estimation #### alwaysAI mind map(s) <a href="url"><img src="https://github.com/mccurcio/60_days_of_learning/blob/main/assets/alwaysAI.small.mind.map.svg" align="center" ></a> - [Freeplane mind map file](assets/alwaysAI.mm) #### CEO, <NAME> video - [Co-founder, ceo, <NAME>](https://youtu.be/H_TosL08h0Y) - edge deployment is better than cloud deployment, inference on the edge with pre-made models is quicker than on the cloud. - What is **Projects & Teams**? This is on road-map as of July 2020. - Benefits of working with aai is that they have trained “increasingly” scarce computer vision programmers. #### First saw Manu Dwivedi presentation - Temperature checking for patients in hospital, Danbery, ct. -Computer Vision Improves COVID-19 Vaccine Distribution - Wait Time - id people waiting and count how long wait time is - Analytics - determine how many vials have bee used, how many vaccinated - post inoculation - look adverse side effects from sick people - https://alwaysai.co/blog #### News - 3/16/21 Added: <NAME>is/sales, Liz Oz/marketing #### Interesting white paper by <NAME> - [Advantages of Implementing CV on the Edge](https://learn.alwaysai.co/hubfs/alwaysAI_whitepaper.pdf) #### aai partnered with - [Nvidia Jetson Nano](https://www.nvidia.com/en-us/autonomous-machines/embedded-systems/jetson-nano/) - qualcomm - arm - balena; helpful with fleet deployment of iot - twilio; voice and sms communication abilities #### Three Steps for deployment: 1. model building - made easier - ~60 models for quick spin-up - ~12 models pre-trained 2. API libraries - customize app development 3. deploy and run edge devices - arm, raspberry pi, Jetson Nano, etc #### aai has a training toolkit 1. data collection can be done ON edge device 2. data annotation is made easy with [Computer Vision Annotation Tool](https://github.com/openvinotoolkit/cvat). 4. transfer learning-model training capabilities, train model and tweek it **Benefits**: Code free, train on your local machine, cpu or gpu for real-time feedback, FREE acts available for easy development. #### Competitors - neurala - PR robotics - more ... <file_sep>/pages/index.md --- layout: page title: Matt's D.S. Study Site permalink: / --- ## MC's Data Science Study Site **Goals for this site**: 1. Share my learning journey via - [Articles](docs) - [Presentations](docs/resources/mcc-presentations) - [Posts by title](archive) 2. Share my code snippets, and my own coding notes - I got inspiration from <NAME>'s [website](https://chrisalbon.com), Thanks Chris 👏 3. Spur discussion and interactivity - Thanks to [vsoch](https://vsoch.github.io/docsy-jekyll/) for designing the Docsy-Jekyll theme 👏 --- I am in the process of migrating and rewriting my material. *My writing is a little formal (like myself at times), BUT I am striving to make it appealing*. 😉 ## Have a Question? - <a href="mailto:<EMAIL>?subject=A question from the web">Send An Email</a>, Or interact via GitHub issues, on the right. *I look foward to meeting*.<file_sep>/_draft/2020-01-01-R-machine-settings.md --- title: "R Machine Settings" tags: R --- TEST <!-- {% include_relative /_posts/html/R-machine-settings.html %} --> <file_sep>/_draft/rmd_files/2019-06-01-kmeans-example.rmd --- title: "K-Means Clustering Example" author: "MCC" date: '2019-06-01' output: html_document --- >[K-means is an unsupervised algorithm.] k-means clustering is a method of vector quantization, originally from signal processing, that aims to partition n observations into k clusters in which each observation belongs to the cluster with the nearest mean (cluster centers or cluster centroid). k-means clustering minimizes within-cluster variances (squared Euclidean distances), but not regular Euclidean distances, which would be the more difficult Weber problem: the mean optimizes squared errors, whereas only the geometric median minimizes Euclidean distances. For instance, better Euclidean solutions can be found using k-medians and k-medoids. > >The problem is computationally difficult (NP-hard). These are usually similar to the expectation-maximization algorithm for mixtures of Gaussian distributions via an iterative refinement approach employed by both k-means and Gaussian mixture modeling. They both use cluster centers to model the data; however, k-means clustering tends to find clusters of comparable spatial extent, while the Gaussian mixture model allows clusters to have different shapes. > >[Wikipedia](https://en.wikipedia.org/wiki/K-means_clustering) ```{r} require(graphics) # Generate 2-dimensional data x <- rbind(matrix(rnorm(100, sd = 0.3), ncol = 2), matrix(rnorm(100, mean = 1, sd = 0.3), ncol = 2)) colnames(x) <- c("x", "y") (cl <- kmeans(x, 2)) ``` ```{r} plot(x, col=cl$cluster, main="K-means using random data separated into two clusters" ) points(cl$centers, col = 1:2, pch = 8, cex = 2) # Asterisk indicates centroid ``` This indicates that the first 6 points are in cluster #2 centered at x = 0.002265857 and y = 0.03744441. ```{r} # sum of squares ss <- function(x) sum(scale(x, scale = FALSE)^2) ## cluster centers "fitted" to each obs.: fitted.x <- fitted(cl); head(fitted.x) ``` This calculation indicates that the clusters have similar squared-summed error between samples, within samples and total error. ```{r} resid.x <- x - fitted(cl) ## Equalities : ---------------------------------- cbind(cl[c("betweenss", "tot.withinss", "totss")], # the same two columns c(ss(fitted.x), ss(resid.x), ss(x))) ``` ```{r} stopifnot(all.equal(cl$ totss, ss(x)), all.equal(cl$ tot.withinss, ss(resid.x)), ## these three are the same: all.equal(cl$ betweenss, ss(fitted.x)), all.equal(cl$ betweenss, cl$totss - cl$tot.withinss), ## and hence also all.equal(ss(x), ss(fitted.x) + ss(resid.x)) ) kmeans(x,1)$withinss # trivial one-cluster, (its W.SS == ss(x)) ``` The set of data was then broken into 5 sets of clusters with different centroids. ```{r} ## random starts do help here with too many clusters ## (and are often recommended anyway!): (cl <- kmeans(x, 5, nstart = 25)) ``` ```{r} plot(x, col = cl$cluster, main="K-means clustering with 5 clusters of sizes 18, 27, 21, 11, 23" ) points(cl$centers, col = 1:5, pch = 8) ``` <file_sep>/_posts/bash/2020-06-01-bash-uniq.md --- title: "Bash - uniq" tags: Bash InProgress --- uniq 1. Find and then remove duplicate elements - In uniq -d is used to find duplicates and -u is used to find unique records. ``` uniq -d movies.csv ``` 2. Remove duplicate records - In uniq -d is used to find duplicates and -u is used to find unique records. ``` uniq -u movies.csv > uniq_movie.csv ``` 3. Crosscheck the new file for duplicates ``` uniq -d uniq_movie.csv ``` <file_sep>/_docs/chapters/neural-networks-for-binary-classification.md --- title: "Learning Neural Networks" tags: Data_Science --- {% include_relative neural-networks-1.html %} <file_sep>/_docs/chapters/principle-component-analysis-of-a-binary-classification-system.md --- title: "Learning Principle Component Analysis" tags: Data_Science PCA --- {% include_relative principle-component-analysis-1.html %} <file_sep>/_draft/hr.note.md To change horizontal line goto main.css then change hr hr { margin-top: 1rem; margin-bottom: 1rem; border: 0; border-top: 1px solid rgba(0, 0, 0, .1) /* change to 2 or 3 px and alpha=.2 or .3<file_sep>/_draft/code.md How to list ALL 'Conda or pip packages 15th August 2018 at 10:21am conda list conda list | sort > conda_list.txt pip list pip list | sort > conda_list.txt ----------- print('Converting strings to ints') try: print(int('x')) except: print('Conversion Failed') else: print('Conversion scuccessful') print('Done') ------------------ Check For Anagrams 15th December 2018 at 10:56pm from collections import Counter def is_anagram(word1, word2): """Checks whether the words are anagrams. word1: string word2: string returns: boolean """ return Counter(str1) == Counter(str2) -------------- Evaluate a String as R Code mcc29th November 2021 at 9:47pm Evaluate a String as R Code ''.eval <- function (evaltext,envir=sys.frame()) {'' >''eval (parse (text=evaltext), envir=envir)'' >''}'' ------------ Extended unpacking (Python-3 only) - Tip 15th August 2018 at 10:12am Goal: Get the smallest and largest cities from a list # ordered by population cities = ['Providence', 'Boston', 'Los Angeles', 'New York'] # Bad Example cities = smallest, _, _, largest # Better example smallest = cities[0] largest = cities[-1] Best Example # Even Better way cities = smallest, *rest, largest print('smallest: %s' % smallest) print('largest: %s' % largest) ----------- File reading using 'with' - Tip 25th November 2018 at 5:45pm Bad example f = open('some.txt') text = f.read() for line in text.split('\n'): print(line) f.close() Better example with open('some.txt') as f: for line in f: print(line) ------------- Finding dna motifs 15th August 2018 at 10:13am Given some DNA, print out the most frequent 5-mer motifs. k = 5 dna = "acdtcgctatcgtatcgatcgctagctagctagtc" kmer = {} for i in range(len(DNA) - k + 1): motif = dna[i:i+k] if not motif in kmers: kmers[motif] = 0 kmers[motif] += 1 all = sorted(kmers.items(), key = operator.itemgetter(1)) print all[1:5] -------------- For ... else - Tip 15th August 2018 at 10:13am needle = 'd' haystack = ['a', 'b', 'c'] Bad example found = False for letter in haystack: if needle == letter: print('Found') found = True break if not found: print('Not found') Better example for letter in haystack: if needle == letter: print('Found') break else: # if no break found: print('Not found') ---------------- Convert csv to json mcc29th November 2021 at 11:51am import csv,json;reader = csv.DictReader(open('data/example.csv', 'r'), fieldnames=( "User","Country","Age")) out=open('data/out.json','w'); out.write(json.dumps([row for row in reader])) JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. Converts a given file of comma separated values to json and store it in another file. The csv used here doesn’t contain headers for the columns. csv.DictReader(open('data/example.csv', 'r'), fieldnames=( "User","Country","Age")) gets us the DictReader object from the csv file with three columns specified as fieldnames. json.dumps([row for row in reader]), converts the json object to string for writing it in output file and out.write() method writes the data into the file. To run it for arbitrary files $ python -c "import csv,json,sys;reader = csv.DictReader(open(sys.argv[1], 'r'), fieldnames=( "User","Country","Age"));out=open('data/out.json','w'); out.write(json.dumps([row for row in reader]))" data/example.csv ---------------------- Get alternate lines from files starting from the top 21st November 2018 at 11:43pm Creates a new file with alternate lines of the input file. Here, slicing operation, [::2], is defined with a step=2. Which will extract every 2nd item of the list. Thus, creating a list of every alternate line from a file. python -c "import sys; c = open('alternate.txt','w'); c.write('\n'.join([x for x in open(sys.argv[1], 'r').read().split('\n')[::2]])); c.close()" data/100west.txt ------------------ How to merge 2 Dictionarys in Python 3 19th November 2018 at 11:51pm x = {'a': 1, 'b': 3} y = {'c': 5, 'b': 3} z = {**x, **y} ------------ Ggplot2 Code Example mcc15th August 2018 at 10:27am require (ggplot2) x <- round ( rnorm ( 1000, 100, 15 )) + rnorm (1000)*15 dens.x <- density (x) empir.df <- data.frame ( type = 'empir', x = dens.x$x, density = dens.x$y) norm.df <- data.frame ( type = 'normal', x = 50:150, density = dnorm (50:150,100,15)) df <- rbind ( empir.df, norm.df) m <- ggplot ( data = df, aes (x,density)) m + geom_line ( aes (linetype = type, colour = type)) ---------------- K-Means - kmeans_mehdi.R mcc29th November 2021 at 9:23pm K-Means algorithm from kmeans_mehdi.R #k = 3 # the number of K's max = 5000 # the maximum number for generating random points n = 100 # the number of points maxIter = 10 # maximum number of iterations threshold = 0.1 # difference of old means and new means # Randomly generate points in the form of (x,y) x <- sample(1:max, n) y <- sample(1:max, n) # put point into a matrix z <- c(x,y) m = matrix(z, ncol=2) ks <- c(1, 2, 4, 8, 10, 15, 20) # different Ks for(k in ks) { myKmeans(m, k, max) } myKmeans <- function(m, k, max) { #initialization for k means: the k-first points in the list x <- m[, 1] y <- m[, 2] d=matrix(data=NA, ncol=0, nrow=0) for(i in 1:k) { d <- c(d, c(x[i], y[i])) } init <- matrix(d, ncol=2, byrow=TRUE) dev.new() plotTitle <- paste("K-Means Clustering K = ", k) plot(m, xlim=c(1,max), ylim=c(1,max), xlab="X", ylab="Y", pch=20, main="plotTitle") par(new=T) plot(init, pch=2, xlim=c(1,max), ylim=c(1,max), xlab="X", ylab="Y") par(new=T) oldMeans <- init oldMeans cl <- Clustering(m, oldMeans) cl means <- UpdateMeans(m, cl, k) thr <- delta(oldMeans, means) itr <- 1 while(thr > threshold){ cl <- Clustering(m, means) oldMeans <- means means <- UpdateMeans(m, cl, k) thr <- delta(oldMeans, means) itr <- itr+1 } cl thr means itr for(km in 1:k){ group <- which(cl == km) plot(m[group,],axes=F, col=km, xlim=c(1,max), ylim=c(1,max), pch=20, xlab="X", ylab="Y") par(new=T) } plot(means, axes=F, pch=8, col=15, xlim=c(1,max), ylim=c(1,max), xlab="X", ylab="Y") par(new=T) dev.off() } # end function myKmeans # function distance dist <- function(x,y) { d<-sqrt( sum((x - y) **2 )) } createMeanMatrix <- function(d) { matrix(d, ncol=2, byrow=TRUE) } # compute euclidean distance euclid <- function(a,b) { d<-sqrt(a**2 + b**2) } euclid2 <- function(a) { d<-sqrt(sum(a**2)) } # compute difference between new means and old means delta <- function(oldMeans, newMeans) { a <- newMeans - oldMeans max(euclid(a[, 1], a[, 2])) } Clustering <- function(m, means) { clusters = c() n <- nrow(m) for(i in 1:n) { distances = c() k <- nrow(means) for(j in 1:k) { di <- m[i,] - means[j,] ds <- euclid2(di) distances <- c(distances, ds) } minDist <- min(distances) cl <- match(minDist, distances) clusters <- c(clusters, cl) } return (clusters) } UpdateMeans <- function(m, cl, k) { means <- c() for(c in 1:k) { # get the point of cluster c group <- which(cl == c) # compute the mean point of all points in cluster c mt1 <- mean(m[group,1]) mt2 <- mean(m[group,2]) vMean <- c(mt1, mt2) means <- c(means, vMean) } means <- createMeanMatrix(means) return(means) } -------------------------------------- Lambda functions 15th August 2018 at 10:22am The lambda keyword in Python provides a shortcut for declaring small and anonymous functions: >>> add = lambda x, y: x + y >>> add(5, 3) 8 You could declare the same add() function with the def keyword: >>> def add(x, y): ... return x + y >>> add(5, 3) 8 So what's the big fuss about? Lambdas are *function expressions*: >>> (lambda x, y: x + y)(5, 3) 8 Lambda functions are single-expression functions that are not necessarily bound to a name (they can be anonymous). Lambda functions can't use regular Python statements and always include an implicit return statement. ------------------------- Measure the execution time of small bits of Python code with the "timeit" 15th August 2018 at 10:22am The "timeit" module lets you measure the execution time of small bits of Python code >>> import timeit >>> timeit.timeit('"-".join(str(n) for n in range(100))', number=10000) 0.3412662749997253 >>> timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000) 0.2996307989997149 >>> timeit.timeit('"-".join(map(str, range(100)))', number=10000) 0.24581470699922647 --------------------- Pad Numeric Vars to Strings of Specified Size mcc29th November 2021 at 9:54pm Pad Numeric Vars to Strings of Specified Size pad0 <- function(x,mx=NULL,fill=0) { lx <- nchar(as.character(x)) mx.calc <- max(lx,na.rm=TRUE) if (!is.null(mx)) { if (mx<mx.calc) { stop("number of maxchar is too small") } } else { mx <- mx.calc } px <- mx-lx paste(sapply(px,function(x) paste(rep(fill,x),collapse="")),x,sep="") ------------------------- Pronounceable passwords 25th November 2018 at 6:44pm Creates a random ‘-‘ separated 4 word password from the given input text file to be used as a password import random words = open('/usr/share/dict/words').read().split() ".1.".join([random.choice(words) for _ in range(3)]) ------------------------- R - Reserved Letters mcc15th August 2018 at 10:44am R has reserved letters which cannot be used for variable names c( ) Combine t( ) Transpose (matrices) q( ) Quit /t Tab C( ) Sets a contrast attribute D( ) Computes derivatives I( ) Inhibits a change in the class of a value F FALSE T TRUE ------------------------- R - Significant Figures mcc14th August 2018 at 7:11pm result <- c(9.50863385275955e-05, 4.05702267762077, pi, sqrt(2)) signif (result, digits = 4) # Significant Figures command ------------------------- R Performance Tip 21st December 2018 at 3:18pm From <NAME>, @winston_chang rstats performance tip: If you must grow a vector in a loop, make sure there's only one reference to it so that R doesn't have to make a copy on each iteration. # 6 seconds: x <- integer() for(i in 1:5e4) x <- c(x, i) # 0.02 seconds: x <- integer() for(i in 1:5e4) x[i] <- i # For timing ptm <- proc.time() # //code// proc.time() - ptm -------------------- R Set Functions mcc15th August 2018 at 10:39am Function Description union (x, y) Performs set unions, intersections, (asymmetric!) difference, equality and membership on two vectors. While setequal will discard any duplicated values in the arguments. intersect (x, y) setdiff (x, y) is.element (el, set) setequal (x, y) ------------------------- Time Code in R 20th August 2018 at 4:17pm # Start the clock! ptm <- proc.time() # Code to measure for (i in 1:100000){ h[i] <- g[i] + 1 } # Stop the clock proc.time() - ptm - ------------------------- Using 'itertools.chain' in Python 19th November 2018 at 11:45pm Use itertools.chain to iterate over items in separate lists: from itertools import chain x = [1, 2, 3] y = [5, 6, 7] z = ['a', 'b'] for item in chain(x, y, z): print(item) ----------------- Using carriage return in print makes the line replaceable 19th November 2018 at 11:39pm Using carriage return in print makes the line replaceable for i in range(20): print(f'Number {i}', end='\r') Useful for creating something like progress bar! for i in range(10): print(f'{i//10*100}% complete!', end='\r') ------------------------- Using zip() - Tip 15th August 2018 at 10:19am x_list = [1,2,3] y_list = [4,5,6] Bad example for i in range(len(x_list)): x = x_list[i] y = y_list[i] print(x, y) Better example for x, y in zip(x_list, y_list): print(x, y) ------------------------- Working with Collections - Tip 15th August 2018 at 10:18am Goal: Create a dict where butterfly-species names are keys and the observation counts are values. Next, print out the number of times that a non-observed species (eg Palmfly) are observed (0 times). import collections butterfly_observations = { 'Brown_Clipper' :2, 'Common Mormom' :11, 'Giant Atlas Moth' :1, 'Blue Peacock' :3 } Bad Example if 'Palmfly' in butterfly_observations: palmfly_observations = butterfly_observations['Palmfly'] else: palmfly_observations = 0 Better way palmfly_observations = butterfly_observations.get('Palmfly', 0) # Best Example d = collections.defaultdict(lambda: 0) d.update(butterfly_observations) palmfly_observations = d['Palmfly'] print('Palmfly observations: %d % palmfly_observations) ------------------------- ML Questions for MCC mcc29th November 2021 at 9:08pm 1. What is machine learning? 2. Name applications of machine learning. 3. Explain the following machine learning areas and tasks: supervised learning, unsupervised learning, reinforcement learning, classification, regression, clustering, feature selection, feature extraction, and topic modeling. 4. Explain the following machine learning approaches: decision tree learning, artificial neural networks, and Bayesian networks. 5. What are the advantages and disadvantages of the various approaches? 6. Which kinds of products can be used for machine learning in practice? 7. How to engineer a machine learning application? 8. Explain precision, recall, and F-measure 9. Why to separate training data set and test data set for validation? ------------------------- Make a random DNA sequence, consisting of a 100 random selections of the letters C,A,G,T, and paste the result together into one character string. set.seed(123) dna <- c("c","a","g", "t","n") dna100 <- sample(dna, size=100, replace=TRUE) paste(dna100) ------------------------- http://datasciencemasters.org/ ------------------------- rbind Vs. cbind Vs. matrix mcc29th November 2021 at 9:59pm rbind ( ) # Binds rows together, FILLS ROWS FIRST: rbind (c(56,8,4,7,86), c(2,16, 32, 54, 86)) ------------------------- collections.defaultdict - Tip 14th August 2018 at 5:33pm import collections import string cities = ['providence', 'boston', 'los angeles', 'new york'] populations = [250_000, 750_000, 3_900_000, 9_000_000] Good example d = collections.defaultdict() print(d) ---------------------- https://jeffdelaney.me/blog/useful-snippets-in-pandas/ <NAME>EYrésuméprojectsblog 19 Essential Snippets in Pandas Aug 26, 2016 After playing around with Pandas Python Data Analysis Library for about a month, I’ve compiled a pretty large list of useful snippets that I find myself reusing over and over again. These tips can save you some time sifting through the comprehensive Pandas docs. For this article, we are starting with a DataFrame filled with Pizza orders. If you’re brand new to Pandas, here’s a few translations and key terms. DataFrame - Indexed rows and columns of data, like a spreadsheet or database table. Series = Single column of data. Axis - 0 == Rows, 1 == Columns Shape - (number_of_rows, number_of_columns) in a DataFrame 1. Importing a CSV File ------------------------- Sort Linux Commands 27th November 2021 at 10:33pm 1. sort a space-delimited file based on its first column, then the second if the first is the same, and so on: sort input.txt 2. sort a huge file (GNU sort ONLY): sort -S 1500M -t $HOME/tmp input.txt > sorted.txt 3. sort starting from the third column, skipping the first two columns: sort +2 input.txt 4. sort the second column as numbers, descending order; if identical, sort the 3rd as strings, ascending order: sort -k2,2nr -k3,3 input.txt 5. sort starting from the 4th character at column 2, as numbers: sort -k2.4n input.txt 6. Sort and remove duplicate lines in a file in one step without intermediary files Explanation We open a file with vi and run two vi commands (specified with +): %!sort | uniq % = range definition, it means all the lines in the current buffer. ! = run filter for the range specified. Filter is an external program, in this example sort | uniq wq = write contents to file and quit. vi +'%!sort | uniq' +wq file.txt ------------------------- | ''Source of Variability'' | ''Sum of Squares'' | ''Degrees of Freedom'' | ''Mean Squares'' | ''F-value'' | |!|>|>|>|>| | ''Treatment Variability'' | ''SSB''<br>Sum of Squares Between Columns | Columns - 1 | ''MSB''<br>Sum of Squares Within Columns | [[F-Critical Value|http://mathworld.wolfram.com/F-Distribution.html]] | | ''Variability Due To Error'' | ''SSW''<br> S.S. Within Treatment<br>{''SSE''-Sum of Squares of Error} | __(R-1)*C__<br>(Rows-1)*Columns | ''MSW''<br>''MSW = Variance = s^^2^^'' | | | ''Total'' | ''TSS''<br>Total Sum of Squares<br>''TSS = SSB + SSE'' | __(R*C)-1__<br>Rows*Columns - 1 | | | ------------------------- ------------------------- ------------------------- ------------------------- ------------------------- <file_sep>/_draft/2022-02-13-Day-9-data-science-study-group.md --- layout: post title: "Day 13: The Data-Science-Study-Group" date: 2022-02-13 21:45:31 -0500 categories: 100DaysOfDS, studygroup --- I spent most of the entire day working on a GitHub site for my Data Science Study Group. I placed several ads on 3 or 4 Slack channels looking for study buddies and got several hits. I need to contact them! So, In anticipation of finding a group, I put together a group markdown site for GitHub. [The Data-Science-Study-Group](https://github.com/mccurcio/Data-Science-Study-Group). <file_sep>/_draft/python_material/Python Pronounceable passwords.md ### This Python code produces a randomly chosen word password of any given length. - Linux Mint dictionaries are commonly placed `/usr/share/dict`. You may need to insert your own dictionary location. ```python import random words = open('/usr/share/dict/words').read().split() "-".join([random.choice(words) for _ in range(3)]) ``` 'Websters-conducting-attitudinizes' ### I insert random numbers between the words. ```python ``` <file_sep>/README.md ## https://mccurcio.github.io - This site uses the [Jekyll-Ruby](https://jekyllrb.com/) static site generator. - The theme in [Docsy-Jekyll](https://vsoch.github.io/docsy-jekyll/), Thanks to [vsoch](https://github.com/vsoch). ### 1. Adding posts/news pages - To add pages, save to the **_posts** directory. - Use Format: **2022-03-10-title.md** ### 2. Add YML-Frontmatter YML to page ```yml --- title: "Title" date: 2022-03-10 categories: jekyll update tags: pca logit badges: - type: primary tag: primary-badge --- ``` ### 3. Badges For news posts, you are able to tag the post with a "warning" or "alert." Therefore you may put badges in the Frontmatter section. ### 4. Buttons with the tne message text Here is a code basic example for buttons, where you may want to vary the `.btn-<tag>` to get different classes. ```html <button class="btn btn-success">.btn-success</button> <button class="btn btn-info">.btn-info</button> <button class="btn btn-secondary">.btn-secondary</button> <button class="btn btn-primary">.btn-primary</button> <button class="btn btn-danger">.btn-danger</button> <button class="btn btn-warning">.btn-warning</button> ``` ### 5. Serve your site locally - Open **bash shell**: ```bash bundle exec jekyll serve # or jekyll serve ``` <file_sep>/_posts/r/2020-12-31-r-time-code.md --- title: "Time Your R Code" tags: R InProgress --- ``` start <- proc.time() # Code to measure for (i in 1:100000){ h[i] <- g[i] + 1 } # Stop the clock proc.time() - start ``` ### [Man_Page](https://) <file_sep>/_draft/nueron_numbers/2021-12-02-nueron_numbers.rmd --- title: "How Many Cats = One Human?" author: "<NAME>" date: "2021-12-02" slug: "Neural Networks" tags: - "Neural Networks" - Nuerons - Chart output: html_document: default --- ```{r setup, message=FALSE, warning=FALSE, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` ### How Many Cats = One Human? Or so what do we know about Neurons anyway. Have you ever wondered how smart your cat or dog is? *Haha, I always do.* To be fair and add context, I was reading about Neural Networks. In many academic articles, the writer launches into a description of the model neuron. How it works. Its size. Its morphology and *Oh, by the way,* that's all we know about the brain or even the neuron. As a scientist, I started to wonder how accurate is this picture. How many neurons does one person have? For that matter, how many neurons do humans AND animals have? You shouldn't be surprised to learn; the world has that information. Volumes and masses estimates have been known for decades. But some of the first studies on the number of neurons were only made in circa 1975. [^1] Isn't it amazing that humans have known about farming and tools between 7,000-10,000 years. While, study of the human brain has only occurred in the last 20 years? **Looking at Table 1**: Organisms Vs. The number Of Neuronal Cells, it is easy to see that humans have the most Neuronal Cells of any animal. But is that all there is to how smart we are? [^1]:Lange, W. 1975 Cell number and cell density in the cerebellar cortex of man and other mammals. Cell Tiss. Res. 157: 115–24 ### Table 1: Organisms Vs Number Of Neuronal Cells | Organism | Common Name | Approx. Number of Neurons | Ratio to Human | | :--------------------- | ------------: | ------------------------: | -------------: | | Homo sapien sapien | modern humans | 100,000,000,000 | 1 | | Canis lupus familiaris | dog | 2,300,000,000 | 44 | | Felis silvestris | cat | 760,000,000 | 130 | | Mus musculus | mouse | 71,000,000 | 1,400 | | Apis linnaeus | honey bee | 960,000 | 10,000,000 | | Chrysaora fuscescens | jellyfish | 5,600 | 18,000,000 | | Caenorhabditis elegans | roundworm | 302 | 330,000,000 | Table 1: Organisms Vs Number Of Neuronal Cells [^2] [^3] [^4] --- **One more thing**, Using this chart as a guide, humans should be 44 times smarter than dogs and 130 times smarter than cats. That makes me feel better all ready. [^2]:[Wikipedia](https://en.wikipedia.org/wiki/List_of_animals_by_number_of_neurons) [^3]:https://www.wormatlas.org/hermaphrodite/nervous/Neuroframeset.html [^4]:<NAME>. (2004), The synaptic organization of the brain (5th ed.), Oxford University Press, New York. <file_sep>/_posts/misc/2016-06-14-big-data-rice.md --- title: "Big data & rice?" date: 2016-06-14 21:00:00 tags: Data_Science --- ![](/assets/img/rice-data.png)<file_sep>/_posts/misc/2018-02-11-math-art.md --- title: "Math Art in R" --- This site has some great math-art. - [https://fronkonstin.com/2017/12/23/tiny-art-in-less-than-280-characters/](https://fronkonstin.com/2017/12/23/tiny-art-in-less-than-280-characters/) Props to 'fronkonstin' {% include_relative 2018-02-11-math-art.html %} <file_sep>/_draft/rmd_files/2020-03-11-histogram-of-10k-dna-fragments.rmd --- title: "Histogram of 10k {X2 / c} For Fragments of DNA(1000b)" author: "MCC" date: '2020-3-11' output: html_document --- This simulation produces a DNA fragment 1000 bases long. It then calculates the Chi square value for each new fragment to produce X2 / c. It does this simulation 10k times and plots a histogram of the X2 / c values. ```{r} GCContent <- function() { # Produce 1000 bases of DNA x = c("A", "C", "T", "G") seq = sample(x, 1000, replace = TRUE) # count GC content count = 0 for (i in 1:999) { if (seq[i] == "C" && seq[i + 1] == "G") { count = count + 1 } } # Calc chi sq / c cgnum <- (((count/1000) - 0.09)^2)/0.0657 # cat(cgnum) return(cgnum) } # Initialize var chisims = vector(mode = "numeric", length = 10000) # Calculate 1000 x Chi^2/c for (i in 1:10000) { chisims[i] <- GCContent() } # Plot of 10k chi square simulations hist(x = chisims, breaks = seq(0, 0.05, length.out = 100), freq = TRUE, xlim = c(0, 0.05), xlab = "X^2 / c", main = "Histogram of 10k {X^2 / c}\nFor Fragments of DNA(1000b)") x = seq(from = 0, to = 0.05, by = 0.005) curve(dchisq(x, df = 1), 0, 0.05, add = TRUE) ```<file_sep>/_draft/2021-12-17-primeNumbers.md --- title: "Primes in R" tags: Primes --- Is this really the best algo???? ``` flag = 1 n = int(input('Enter the number: ')) for i in range(2, sqrt(n)): if (n % i == 0): print('%d is not a prime number' % n) flag = 0 break if (flag == 1): print('%d is a prime number' % n) ``` <file_sep>/Gemfile source "https://rubygems.org" ruby RUBY_VERSION # Hello! This is where you manage which Jekyll version is used to run. # When you want to use a different version, change it below, save the # file and run `bundle install`. Run Jekyll with `bundle exec`, like so: # # bundle exec jekyll serve # # This will help ensure the proper Jekyll version is running. # gem "jekyll", "4.2.2" # Careful GitHub uses 3.9 #Set up your project gems. # Note that the Kramdown parse must be installed explicitly in Jekyll 3.9 # (but no 3.8 or 4.x). source "https://rubygems.org" gem "jekyll", "~> 3.9" gem "kramdown-parser-gfm", "~> 1.1" #Both Method#1 & 2 work well with Ubuntu based systems. #Method #1 # Then run: #bundle config set --local path vendor/bundle #bundle install # This is the default theme for new Jekyll sites. # You may change this to anything you like. # gem "minima" # If you want to use GitHub Pages, remove the "gem "jekyll"" above and # uncomment the line below. #Method #2 ### To upgrade, run: #bundle update github-pages #gem "github-pages", group: :jekyll_plugins # If you have any plugins, put them here! # group :jekyll_plugins do # gem "jekyll-github-metadata", "~> 1.0" # end <file_sep>/_docs/chapters/what-is-ml.html <div id="introduction---what-is-machine-learning" class="section level1"> <h1>Introduction - What is Machine Learning?</h1> <p>At the intersection between Applied Mathematics, Computer Science, and Biological Sciences is a subset of knowledge known as Bioinformatics. Some find Bioinformatics and its cousin Data Science difficult to define. However, the most ubiquitous pictograph of Bioinformatics and Data Science may say a thousand words even if we cannot. See Figure 1. What separates these two pursuits is the domain knowledge that each focus on. Where Data Science may focus on understanding buying habits of individuals, Bioinformatics tends to focus on the understanding of DNA and its relevance to disease. It is now common to find new fields emerging such as the study of chemistry using applied mathematics and computers which beget the field of Chemo-informatics.<a href="#fn1" class="footnote-ref" id="fnref1"><sup>1</sup></a> <a href="#fn2" class="footnote-ref" id="fnref2"><sup>2</sup></a> Today, since hospitals are warehouses of modern medical records and knowledge they make career paths such as Healthcare-Informatics possible.<a href="#fn3" class="footnote-ref" id="fnref3"><sup>3</sup></a></p> <div class="figure"> <img src="00-data/10-images/Venn-diagram-original-768x432.png" alt="Venn Diagrams of Bioinformatics And Data Science" /> <p class="caption">Venn Diagrams of Bioinformatics And Data Science</p> </div> <p><a href="#fn4" class="footnote-ref" id="fnref4"><sup>4</sup></a></p> <p>Generally speaking, Bioinformatics derives its knowledge from various items. To start our data may consist of numbers, text and even pictures as input. Numerical values may be from scientific sensors or instrumentation, such as Next Generation<a href="#fn5" class="footnote-ref" id="fnref5"><sup>5</sup></a> DNA sequence data.<a href="#fn6" class="footnote-ref" id="fnref6"><sup>6</sup></a> Text data is sourced from articles/books or even databases of scientific articles like PubMed which show the inter-connectivity of thought and research.<a href="#fn7" class="footnote-ref" id="fnref7"><sup>7</sup></a> Graphics and pictures include graphical forms, such as relationship data that appears in genomic or proteomic or metabolic databases.<a href="#fn8" class="footnote-ref" id="fnref8"><sup>8</sup></a></p> <p>However, Bioinformatics and Data Science imply a process as well. One piece of this process is Reproducible Research.<a href="#fn9" class="footnote-ref" id="fnref9"><sup>9</sup></a> Reproducible Research and replication are linked but it goes beyond the ability of the work to be <em>independently verified</em>. The computer code and data must be provided. There locations explicitly spelled out such that other scientists may find and carry on the work and check all its calculations and methodology. Now that computers play such a large role procedurally the smallest error in a spreadsheet may plague the overall conclusion. Such is the case of the University of Mass. at Amherst found errors in a Harvard research paper.<a href="#fn10" class="footnote-ref" id="fnref10"><sup>10</sup></a></p> <div id="machine-learning-is" class="section level2"> <h2><span class="header-section-number">2.1</span> Machine Learning Is?</h2> <blockquote> <p>“Machine learning is essentially a form of applied statistics with increased emphasis on the use of computers to statistically estimate complicated functions and a decreased emphasis on proving confidence intervals around these functions”</p> <p>— <NAME>, et al<a href="#fn11" class="footnote-ref" id="fnref11"><sup>11</sup></a></p> </blockquote> <div id="what-is-predictive-modeling" class="section level3"> <h3><span class="header-section-number">2.1.1</span> What is Predictive Modeling?</h3> <p>Although what this paper discusses is Predictive Modeling, it is under the umbrella of Machine Learning. The term ‘Predictive Modeling’ should bring to mind work in the computer science field, also called Machine Learning (ML), Artificial Intelligence (AI), Data Mining, Knowledge discovery in databases (KDD), and possibly even encompassing Big Data as well.</p> <blockquote> <p>“Indeed, these associations are appropriate, and the methods implied by these terms are an integral piece of the predictive modeling process. But predictive modeling encompasses much more than the tools and techniques for uncovering patterns within data. The practice of predictive modeling defines the process of developing a model in a way that we can understand and quantify the model’s prediction accuracy on future, yet-to-be-seen data.”</p> <p><NAME><a href="#fn12" class="footnote-ref" id="fnref12"><sup>12</sup></a></p> </blockquote> <p>As an aside, I use <code>Predictive Modeling</code> and <code>Machine Learning</code> interchangeably in this document.</p> <p>In the booklet entitled “The Elements of Data Analytic Style,” <a href="#fn13" class="footnote-ref" id="fnref13"><sup>13</sup></a> there is an useful checklist for the uninitiated into the realm of science report writing and, indeed, scientific thinking. A shorter, more succinct listing of the steps, which I prefer, and is described by <NAME> in his book, The Art Of Data Science. The book lists what he describes as the “Epicycle of Analysis.” <a href="#fn14" class="footnote-ref" id="fnref14"><sup>14</sup></a></p> <p><strong>The Epicycle of Analysis</strong></p> <ol style="list-style-type: decimal"> <li>Stating and refining the question,</li> <li>Exploring the data,</li> <li>Building formal statistical models,</li> <li>Interpreting the results,</li> <li>Communicating the results.</li> </ol> <div style="page-break-after: always;"></div> <p><strong>Predictive Modeling</strong></p> <p>In general, there are three types of Predictive Modeling or Machine Learning approaches;</p> <ol style="list-style-type: decimal"> <li>Supervised,</li> <li>Unsupervised,</li> <li>Reinforcement.</li> </ol> <p>Due to the fact this paper only uses Supervised &amp; Unsupervised learning and for the sake of this brevity, I discuss only the first two types of Predictive Models.</p> </div> <div id="supervised-learning" class="section level3"> <h3><span class="header-section-number">2.1.2</span> Supervised Learning</h3> <p>In supervised learning, data consists of observations <span class="math inline">\(x_i\)</span> (where <span class="math inline">\(X\)</span> may be a matrix of <span class="math inline">\(\Re\)</span> values) AND a corresponding label, <span class="math inline">\(y_i\)</span>. The label <span class="math inline">\(y\)</span> maybe anyone of <span class="math inline">\(C\)</span> classes. In our case of a binary classifier, we have {‘Is myoglobin’, ‘Is control’}.</p> <p><strong>Data set</strong>:</p> <ul> <li><p><span class="math inline">\((X_1, y_1), (X_2 , y_2), ~. . ., ~(X_N , y_N);\)</span></p></li> <li><p><span class="math inline">\(y \in \{1, ..., ~C\}\)</span>, where <span class="math inline">\(C\)</span> is the number of classes</p></li> </ul> <p>A machine learning algorithm determines a pattern from the input information and groups this with its necessary title or classification.</p> <p>One example might be that we require a machine that separates red widgets from blue widgets. One predictive algorithm is called a K-Nearest Neighbor (K-NN) algorithm. K-NN looks at an unknown object and then proceeds to calculate the distance (most commonly, the euclidean distance) to the <span class="math inline">\(K\)</span> nearest neighbors. If we consider the figure below and choose <span class="math inline">\(K\)</span> = 3, we would find a circumstance as shown. In the dark solid black on the K-Nearest-Neighbor figure, we find that the green widget is nearest to two red widgets and one blue widget. In the voting process, the K-NN algorithm (2 reds vs. 1 blue) means that the consignment of our unknown green object is red.</p> <p>For the K-NN algorithm to function, the data optimally most be complete with a set of features and a label of each item. Without the corresponding label, a data scientist would need different criteria to track the widgets.</p> <p>Five of the six algorithms that this report investigates are supervised. Logit, support vector machines, and the neural network that I have chosen require labels for the classification process.</p> <div class="figure"> <img src="00-data/10-images/K-Nearest-Neighbor.50.png" alt="Example of K-Nearest-Neighbor" /> <p class="caption">Example of K-Nearest-Neighbor</p> </div> <p><a href="#fn15" class="footnote-ref" id="fnref15"><sup>15</sup></a></p> <div id="what-is-a-shallow-learner" class="section level4 unnumbered"> <h4>What is a shallow learner?</h4> <p>Let us investigate the K-NN algorithm and figure 2.2 (K-Nearest-Neighbor) a little further. If we change our value of <span class="math inline">\(K\)</span> to 5, then we see a different result. By using <span class="math inline">\(K = 5\)</span>, we consider the out dashed-black line. This more considerable <span class="math inline">\(K\)</span> value contains three blue widgets and two red widgets. If we ask to vote on our choice, we find that 3 blue beats the 2 red, and we assign the unknown a BLUE widget. This assignment is the opposite of the inner circle.</p> <p>If a researcher were to use K-NN, then the algorithm would have to test many possible <span class="math inline">\(K\)</span> values and compare the results, then choose the <span class="math inline">\(K\)</span> with the highest accuracy. However, this is where K-NN falters. The K-NN algorithm needs to keep all data points used for its initial training (accuracy testing). Any new unknowns could be conceivably tested against any or all the previous data points. The K-NN does use a generalized rule that would make future assignments quick on the contrary. It must memorize all the points for the algorithm to work. K-NN cannot delete the points until it is complete. It is true that the algorithm is simple but not efficient. Matter and fact, as the number of feature dimensions increases, this causes the complexity (also known as Big O) to rise. The complexity of K-NN is <span class="math inline">\(O\)</span>(K-NN) <span class="math inline">\(\propto nkd\)</span>.</p> <p>Where <span class="math inline">\(n\)</span> is the number of observations, <span class="math inline">\(k\)</span> is the number of nearest neighbors it must check, and d is the number of dimensions.<a href="#fn16" class="footnote-ref" id="fnref16"><sup>16</sup></a></p> <p>Given that K-NN tends to ‘memorize’ its data to complete its task, it is considered a lazy and shallow learner. Lazy indicates that the decision is left to the moment a new point is learned of predicted. If we were to use a more generalized rule, such as {Blue for (<span class="math inline">\(x \leq 5\)</span>)} this would be a more dynamic and more in-depth approach by comparison.</p> </div> </div> <div id="unsupervised-learning" class="section level3"> <h3><span class="header-section-number">2.1.3</span> Unsupervised Learning</h3> <p>In contrast to the supervised learning system, unsupervised learning does not require or use a <strong>label</strong> or <strong>dependent variable</strong>.</p> <p><strong>Data set</strong>:</p> <ul> <li><p><span class="math inline">\((X_1), (X_2), ~. . ., ~(X_N)\)</span></p></li> <li><p><strong>No Y</strong></p></li> </ul> <p>where <span class="math inline">\(X\)</span> may represent a matrix of <span class="math inline">\(m\)</span> observations by <span class="math inline">\(n\)</span> features with <span class="math inline">\(\Re\)</span> values.</p> <p>Principal Component Analysis is an example of unsupervised learning, which we discuss in more detail in chapter 3. The data, despite or without its labels, are transformed to provide maximization of the variances in the dataset. Yet another objective of Unsupervised learning is to discover “interesting structures” in the data.<a href="#fn17" class="footnote-ref" id="fnref17"><sup>17</sup></a> There are several methods that show structure. These include clustering, knowledge discovery of latent variables, or discovering graph structure. In many instances and as a subheading to the aforementioned points, unsupervised learning can be used for dimension reduction or feature selection.</p> <p>Among the simplest unsupervised learning algorithms is K-means. K-means does not rely on the class labels of the dataset at all. K-means may be used to determine any number of classes despite any predetermined values. K-means can discover clusters later used in classification or hierarchical feature representation. K-means has several alternative methods but, in general, calculates the distance (or conversely the similarity) of observations to a mean value of the <span class="math inline">\(K\)</span>th grouping. The mean value is called the center of mass, the Physics term that provides an excellent analogy since the center of mass is a weighted average. By choosing a different number of groupings (values of <span class="math inline">\(K\)</span>, much like the K-NN), then comparing the grouping by a measure of accuracy, one example being, mean square error.</p> <div class="figure"> <img src="00-data/10-images/k-means-2.50.png" alt="Example of K-Means" /> <p class="caption">Example of K-Means</p> </div> <p><a href="#fn18" class="footnote-ref" id="fnref18"><sup>18</sup></a></p> </div> <div id="five-challenges-in-predictive-modeling" class="section level3"> <h3><span class="header-section-number">2.1.4</span> Five Challenges In Predictive Modeling</h3> <p>To many predictive modeling is a panacea for all sorts of issues. Although it does show promise, some hurdles need research. <NAME><a href="#fn19" class="footnote-ref" id="fnref19"><sup>19</sup></a> has summarized four points that elucidate current problems in the field that need research. To this list, I have added one more point, which is commonly called the <em>Vaiance-Bias Tradeoff</em>.</p> <p><strong>Problem 1:</strong> The vast majority of information in the world is unlabeled, so it would be advantageous to have a good Unsupervised machine learning algorithms to use,</p> <p><strong>Problem 2:</strong> Algorithms are very specialized, too specific,</p> <p><strong>Problem 3:</strong> Transfer learning to new environments,</p> <p><strong>Problem 4:</strong> Scale, the scale of information is vast in reality, and we have computers that work in gigabytes, not the Exabytes that humans may have available to them. The scale of distributed Big Data,</p> <p>The specific predictive models which are executed in this report are discussed in further detail in their own sections.</p> <p><strong>Problem 5:</strong> Bias-Variance Trade-Off.</p> <p>The ability to generalize is a key idea in predictive modeling. This idea harkens back to freshman classes where one studied Student’s t-test and analysis of variance.</p> <p><span class="math display">\[\begin{equation} E \left[ \left( y_0 - \hat f(x_0) \right )^2 \right ] = Var ( \hat f(x_0)) + \left [Bias (\hat f(x_0)) \right]^2 + Var(\epsilon) \end{equation}\]</span></p> <hr /> <div class="figure"> <img src="00-data/10-images/bias-variance-tradeoff.50.png" alt="Bias-Variance Tradeoff" /> <p class="caption">Bias-Variance Tradeoff</p> </div> <p>The bias-variance dilemma can be stated as follows.<a href="#fn20" class="footnote-ref" id="fnref20"><sup>20</sup></a></p> <blockquote> <ol style="list-style-type: decimal"> <li><p>Models with too few parameters are inaccurate because of a large bias: they lack flexibility.</p></li> <li><p>Models with too many parameters are inaccurate because of a large variance: they are too sensitive to the sample details (changes in the details will produce huge variations).</p></li> <li><p>Identifying the best model requires controlling the “model complexity”, i.e., the proper architecture and number of parameters, to reach an appropriate compromise between bias and variance.</p></li> </ol> </blockquote> <p>One very good example is seen in figure 2.4, <em>Bias-Variance Tradeoff</em>. By considering the yellow-orange line we find a simple slope intercept model (<span class="math inline">\(y \propto k \cdot x\)</span>) where the variance is high but the bias low and is not flexible enough. This is called underfitting. Looking at the green-blue line we see it follows the data set much more closely, e.g. (<span class="math inline">\(y \propto k \cdot x^8\)</span>). Here the variance is very low but common sense tells us that the line is overfit and would not generalize well in a real world setting. Finally leaving us with the black line which does not appear to have too many parameters, (<span class="math inline">\(y \propto k \cdot x^3\)</span>).</p> </div> </div> <div id="research-description" class="section level2"> <h2><span class="header-section-number">2.2</span> Research Description</h2> <p>Is there a correlation between the data points, which are outliers from principal component analysis (PCA), and six types of predictive modeling?</p> <p>This experiment is interested in determining if PCA would provide information on the false-positives and false-negatives that were an inevitable part of model building and optimization. The six predictive models that have chosen for this work are Logistic Regression, Support Vector Machines (SVM) linear, polynomial kernel, and radial basis function kernel, and a Neural Network.</p> <p>I have studied six different M.L. algorithms using protein amino acid percent composition data from two classes. Class number 1 is my positive control which is a set of Myoglobin proteins, while the second class is a control group of human proteins that do not have Fe binding centers.</p> <table> <thead> <tr class="header"> <th align="left">Group</th> <th align="right">Class</th> <th align="right">Number of Class</th> <th align="right">Range of Groups</th> </tr> </thead> <tbody> <tr class="odd"> <td align="left">Controls</td> <td align="right">0 or (-)</td> <td align="right">1216</td> <td align="right">1, …, 1216</td> </tr> <tr class="even"> <td align="left">Myoglobin</td> <td align="right">1 or (+)</td> <td align="right">1124</td> <td align="right">1217, …, 2340</td> </tr> </tbody> </table> <p>It is common for Data Scientists to test their data sets for feature importance and feature selection. One test that has interested this researcher is Principal component analysis. It can be a useful tool. PCA is an unsupervised machine learning technique which “reduces data by geometrically projecting them onto lower dimensions called principal components (PCs), with the goal of finding the best summary of the data using a limited number of PCs.” <a href="#fn21" class="footnote-ref" id="fnref21"><sup>21</sup></a> However, the results that it provides may not be immediately intuitive to the layperson.</p> <p>How do the advantages and disadvantages of using PCA compare with other machine learning techniques? The advantages are numerable. They include dimensionality reduction and filtering out noise inherent in the data, and it may preserve the global structure of the data. Does the global and graphical structure of the data produced by the first two principal components provide any insights into how the predictive models of Logistic Regression, Neural Networks utilizing auto-encoders, Support Vector Machines, and Random Forest? In essence, is PCA sufficiently similar to any of the applied mathematics tools of more advanced approaches? Also, this work is to teach me machine learning or predictive modeling techniques.</p> <p>The data for this study is from the Uniprot database. From the Uniprot database was queried for two protein groups. The first group was Myoglobin, and the second was a control group comprised of human proteins not related to Hemoglobin or Myoglobin. See Figure 1.5, <em>Percent Amino Acid Composition</em>. There have been a group of papers that are striving to classify types of proteins by their amino acid structure alone. The most straightforward classification procedures involve using the percent amino acid composition (AAC). The AAC is calculated by using the count of an amino acid over the total number in that protein.</p> <ul> <li>Percent Amino Acid Composition:</li> </ul> <p><span class="math display">\[\begin{equation} \%AAC_X ~=~ \frac{N_{Amino~Acid~X}}{Total ~ N ~ of ~ AA} \end{equation}\]</span></p> <p>The Exploratory Data Analysis determines if features were skewed and needed must be transformed. In a random system where amino acids were chosen at random, one would expect the percent amino acid composition to be close to 5%. However, this is far from the case for the Myoglobin proteins or the control protein samples. On top of this the differences between the myoglobin and control proteins can be as high as approximately 5% with the amino acid Lysine, K.</p> <div class="figure"> <img src="00-data/10-images/c_m_Mean_AAC.png" alt="Mean Percent Amino Acid Compositions For Control And Myoglobin" /> <p class="caption">Mean Percent Amino Acid Compositions For Control And Myoglobin</p> </div> <div id="exploratory-data-analysis-eda" class="section level3"> <h3><span class="header-section-number">2.2.1</span> Exploratory Data Analysis (EDA)</h3> <p>During EDA, the data is checked for irregularities, such as missing data, outliers among features, skewness, and visually for normality using QQ-plots. The only irregularity that posed a significant issue was the skewness of the amino acid features. Many of 20 amino acid features had a significant number of outliers, as seen by Boxplot analysis. However, only three features had skew, which might have presented a problem. Dealing with the skew of the AA was necessary since Principal Component Analysis was a significant aspect of this experiment.</p> <p>Testing determined earlier that three amino acids (C, F, I) from the single amino acid percent composition needs transformation by using the square root function. The choice of transformations was natural log, log base 10, squaring (<span class="math inline">\(x^2\)</span>), and using the reciprocal (<span class="math inline">\(1 / x\)</span>) of the values. The square root transformation lowered the skewness to values of less than 1.0 from high points of greater than 2 in all three cases to {-0.102739 <span class="math inline">\(\leq\)</span> skew after transformation <span class="math inline">\(\leq\)</span> 0.3478132}.</p> <table> <thead> <tr class="header"> <th align="left">Amino Acid</th> <th align="center">Initial skewness</th> <th align="center">Skew after square root transform</th> </tr> </thead> <tbody> <tr class="odd"> <td align="left">C, Cysteine</td> <td align="center">2.538162</td> <td align="center">0.347813248</td> </tr> <tr class="even"> <td align="left">F, Phenolalanine</td> <td align="center">2.128118</td> <td align="center">-0.102739748</td> </tr> <tr class="odd"> <td align="left">I, Isoleucine</td> <td align="center">2.192145</td> <td align="center">0.293474879</td> </tr> </tbody> </table> <p>Three transformations take place for this dataset.</p> <p><code>~/00-data/02-aac_dpc_values/c_m_TRANSFORMED.csv</code> and used throughout the rest of the analysis.</p> <p>All work uses R<a href="#fn22" class="footnote-ref" id="fnref22"><sup>22</sup></a>, RStudio<a href="#fn23" class="footnote-ref" id="fnref23"><sup>23</sup></a> and a machine learning library/framework <code>caret</code>.<a href="#fn24" class="footnote-ref" id="fnref24"><sup>24</sup></a></p> </div> <div id="caret-library-for-r" class="section level3"> <h3><span class="header-section-number">2.2.2</span> Caret library for R</h3> <p>The R/caret library is attractive to use for many reasons. It currently allows 238 machine learning models that use different options and data structures.<a href="#fn25" class="footnote-ref" id="fnref25"><sup>25</sup></a> The utility of caret is that it organizes the input and output into a standard format making the need for learning only one grammar and syntax. Caret also harmonizes the use of hyper-parameters. Work becomes reproducible. Setting up the training section for caret, for this experiment, can be broken into three parts.</p> </div> <div id="tuning-hyper-parameters" class="section level3"> <h3><span class="header-section-number">2.2.3</span> Tuning Hyper-parameters</h3> <p>The <code>tune.grid</code> command set allows a researcher to experiment by varying the hyper-parameters of the given model to investigate optimum values. Currently, there are no algorithms that allow for the quick and robust tuning of parameters. Instead of searching, a sizable experimental space test searches an n-dimensional grid in a full factorial design if desired.</p> <p>Although some models have many parameters, the most common one is to search along a cost hyper-parameter.</p> <blockquote> <p>“The function we want to minimize or maximize is called the objective function or criterion. When we are minimizing it, we may also call it the cost function, loss function, or error function.”<a href="#fn26" class="footnote-ref" id="fnref26"><sup>26</sup></a></p> </blockquote> <p>The cost function (a term derived from business modeling, i.e., optimizing the cost) is an estimate as to how well models predicted value fits from the actual value. A typical cost function is the squared error function.</p> <p>Example Cost Function: <a href="#fn27" class="footnote-ref" id="fnref27"><sup>27</sup></a> <span class="math display">\[\begin{equation} Cost ~=~ \left ( y_i - \hat f(x_i) \right )^2 \end{equation}\]</span></p> <p>It may be important to search the literature to determine if other researchers have used a specific range of optimum value, which may speed a search. For example, <NAME> et al. suggest using a broad range of 20 orders of magnitude of powers of 2,</p> <div style="page-break-after: always;"></div> <p><strong>R Code:</strong> Using TuneGrid command to test sequences of number such that the optimal cost function can be sought.</p> <pre><code># tuneGrid = svmLinearGrid svmLinearGrid &lt;- expand.grid(C = c(2^(seq(-5, 15, 2))))</code></pre> <p><code>expand.grid</code> will produce a sequence of numbers (in our case) from <span class="math inline">\(2^{-5}, 2^{-3} ~to~ 2^{15}\)</span> to be tested as values for the cost function.</p> <p>Then switch to 4 or 5 orders of magnitude with 1/4 log steps,<a href="#fn28" class="footnote-ref" id="fnref28"><sup>28</sup></a></p> <p>e.g. cost = <code>expand.grid(c(2^(seq(1, 5, 0.25))))</code></p> <p>for a finer search gird.</p> </div> <div id="k-fold-cross-validation-of-results" class="section level3"> <h3><span class="header-section-number">2.2.4</span> K-Fold Cross validation of results</h3> <p>Another valuable option that caret has is the ability to cross-validate results.</p> <p>Cross-validation is a statistical method used to estimate the skill of machine learning models.<a href="#fn29" class="footnote-ref" id="fnref29"><sup>29</sup></a></p> <blockquote> <p>“The samples are randomly partitioned into k sets of roughly equal size. A model is fit using all samples except the first subset (called the first fold). The held-out samples are used for prediction by the recent model. The performance estimate measures the accuracy of the <em>out of bag</em> or <em>held out</em> samples. The first subset is returned to the training set, and the procedure repeats with the second subset held out, and so on. The k resampled estimates of performance are summarized (usually with the mean and standard error) and used to understand the relationship between the tuning parameter(s) and model utility.”<a href="#fn30" class="footnote-ref" id="fnref30"><sup>30</sup></a></p> </blockquote> <p>Cross-validation has the advantage of using the entire dataset for training and testing, increasing the opportunity that more training samples produce a better model.</p> <p><strong>R Code:</strong> 10 Fold cross-validation repeated 5 times</p> <pre><code>fitControl &lt;- trainControl(method = &quot;repeatedcv&quot;, # Type of Cross-Validation number = 10, # Number of splits repeats = 5, # Produce 5 replicates savePredictions = &quot;final&quot;) # Save FP/FN predictions</code></pre> </div> <div id="train-command" class="section level3"> <h3><span class="header-section-number">2.2.5</span> Train command</h3> <p>The training command produces an object of the model. The first line should point out the “formula,” which is modeled. The dependent variable is first. The <code>~</code> (Tilda sign) indicates a model is called. Then the desired features can be listed or abbreviated with the all (.) sign.</p> <p><strong>R Code:</strong> Train command</p> <pre><code>model_object &lt;- train(Class ~ ., # READ: Class is modeled by all features. data = training_set, # Data used trControl = fitControl, # Cross Validation setup method = &quot;svmLinear&quot;, # Use caret ML method tune.Grid = Grid) # Hyperparameter grid exploration</code></pre> </div> <div id="analysis-of-results" class="section level3"> <h3><span class="header-section-number">2.2.6</span> Analysis of results</h3> <p>In binary classification, a two by two contingency table describes predicted versus actual value classifications. This table is also known as a confusion matrix for machine learning students. It is also known as a two by two contingency table in statistics.</p> <table> <thead> <tr class="header"> <th align="center">2 x 2 Confusion Matrix</th> <th align="center">Actual = 0</th> <th align="center">Actual = 1</th> </tr> </thead> <tbody> <tr class="odd"> <td align="center">Predicted = 0</td> <td align="center">True-Negatives</td> <td align="center">False-Negatives</td> </tr> <tr class="even"> <td align="center">Predicted = 1</td> <td align="center">False-Positives</td> <td align="center">True-Positives</td> </tr> </tbody> </table> <p>There are many ways to describe the results further using this confusion matrix. However, Accuracy is used for all comparisons.</p> <p><span class="math display">\[\begin{equation} Accuracy ~=~ \frac{TP + TN}{N_{Total}} \end{equation}\]</span></p> <p>The second goal of this experiment is to produce the False Positives and False-Negatives and evaluating these by comparing them to the Principal Component Analysis Biplot of the first two Principal Components.</p> <div class="footnotes"> <hr /> <ol start="1"> <li id="fn1"><p><a href="https://www.acs.org/content/acs/en/careers/college-to-career/chemistry-careers/cheminformatics.html" class="uri">https://www.acs.org/content/acs/en/careers/college-to-career/chemistry-careers/cheminformatics.html</a><a href="introduction-what-is-machine-learning.html#fnref1" class="footnote-back">↩</a></p></li> <li id="fn2"><p><a href="https://jcheminf.biomedcentral.com/" class="uri">https://jcheminf.biomedcentral.com/</a><a href="introduction-what-is-machine-learning.html#fnref2" class="footnote-back">↩</a></p></li> <li id="fn3"><p><a href="https://www.usnews.com/education/best-graduate-schools/articles/2014/03/26/consider-pursuing-a-career-in-health-informatics" class="uri">https://www.usnews.com/education/best-graduate-schools/articles/2014/03/26/consider-pursuing-a-career-in-health-informatics</a><a href="introduction-what-is-machine-learning.html#fnref3" class="footnote-back">↩</a></p></li> <li id="fn4"><p><a href="http://omgenomics.com/what-is-bioinformatics/" class="uri">http://omgenomics.com/what-is-bioinformatics/</a><a href="introduction-what-is-machine-learning.html#fnref4" class="footnote-back">↩</a></p></li> <li id="fn5"><p>What is Next-Generation DNA Sequencing?, <a href="https://www.ebi.ac.uk/training/online/course/ebi-next-generation-sequencing-practical-course/what-you-will-learn/what-next-generation-dna-" class="uri">https://www.ebi.ac.uk/training/online/course/ebi-next-generation-sequencing-practical-course/what-you-will-learn/what-next-generation-dna-</a><a href="introduction-what-is-machine-learning.html#fnref5" class="footnote-back">↩</a></p></li> <li id="fn6"><p><a href="http://www.genome.ucsc.edu/" class="uri">http://www.genome.ucsc.edu/</a><a href="introduction-what-is-machine-learning.html#fnref6" class="footnote-back">↩</a></p></li> <li id="fn7"><p><a href="https://arxiv.org/" class="uri">https://arxiv.org/</a><a href="introduction-what-is-machine-learning.html#fnref7" class="footnote-back">↩</a></p></li> <li id="fn8"><p><a href="https://www.ebi.ac.uk/training/online/course/proteomics-introduction-ebi-resources/what-proteomics" class="uri">https://www.ebi.ac.uk/training/online/course/proteomics-introduction-ebi-resources/what-proteomics</a><a href="introduction-what-is-machine-learning.html#fnref8" class="footnote-back">↩</a></p></li> <li id="fn9"><p><NAME>, The Real Reason Reproducible Research is Important, <a href="https://simplystatistics.org/2014/06/06/the-real-reason-reproducible-research-is-important/" class="uri">https://simplystatistics.org/2014/06/06/the-real-reason-reproducible-research-is-important/</a><a href="introduction-what-is-machine-learning.html#fnref9" class="footnote-back">↩</a></p></li> <li id="fn10"><p><a href="https://www.chronicle.com/article/UMass-Graduate-Student-Talks/138763" class="uri">https://www.chronicle.com/article/UMass-Graduate-Student-Talks/138763</a><a href="introduction-what-is-machine-learning.html#fnref10" class="footnote-back">↩</a></p></li> <li id="fn11"><p><NAME>, <NAME>, <NAME>, ‘Deep Learning’, MIT Press, 2016, <a href="http://www.deeplearningbook.org" class="uri">http://www.deeplearningbook.org</a><a href="introduction-what-is-machine-learning.html#fnref11" class="footnote-back">↩</a></p></li> <li id="fn12"><p><NAME>, <NAME>, Applied Predictive Modeling, Springer, <a href="ISBN:978-1-4614-6848-6" class="uri">ISBN:978-1-4614-6848-6</a>, 2013<a href="introduction-what-is-machine-learning.html#fnref12" class="footnote-back">↩</a></p></li> <li id="fn13"><p><NAME>, The Elements of Data Analytic Style, A guide for people who want to analyze data., Leanpub Books, <a href="http://leanpub.com/datastyle" class="uri">http://leanpub.com/datastyle</a>, 2015<a href="introduction-what-is-machine-learning.html#fnref13" class="footnote-back">↩</a></p></li> <li id="fn14"><p><NAME> and <NAME>, The Art of Data Science, A Guide for Anyone Who Works with Data, Leanpub Books, <a href="http://leanpub.com/artofdatascience" class="uri">http://leanpub.com/artofdatascience</a>, 2015<a href="introduction-what-is-machine-learning.html#fnref14" class="footnote-back">↩</a></p></li> <li id="fn15"><p><a href="https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm" class="uri">https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm</a><a href="introduction-what-is-machine-learning.html#fnref15" class="footnote-back">↩</a></p></li> <li id="fn16"><p><NAME>, Machine Learning in Computer Vision, <a href="http://www.csd.uwo.ca/courses/CS9840a/Lecture2_knn.pdf" class="uri">http://www.csd.uwo.ca/courses/CS9840a/Lecture2_knn.pdf</a><a href="introduction-what-is-machine-learning.html#fnref16" class="footnote-back">↩</a></p></li> <li id="fn17"><p><NAME>, Machine learning a probabilistic perspective, 2012, ISBN 978-0-262-01802-9<a href="introduction-what-is-machine-learning.html#fnref17" class="footnote-back">↩</a></p></li> <li id="fn18"><p><a href="https://www.slideshare.net/teofili/machine-learning-with-apache-hama/20-KMeans_clustering_20" class="uri">https://www.slideshare.net/teofili/machine-learning-with-apache-hama/20-KMeans_clustering_20</a><a href="introduction-what-is-machine-learning.html#fnref18" class="footnote-back">↩</a></p></li> <li id="fn19"><p><a href="https://www.machinelearning.ai/machine-learning/4-big-challenges-in-machine-learning-ft-martin-jaggi-2/" class="uri">https://www.machinelearning.ai/machine-learning/4-big-challenges-in-machine-learning-ft-martin-jaggi-2/</a><a href="introduction-what-is-machine-learning.html#fnref19" class="footnote-back">↩</a></p></li> <li id="fn20"><p><NAME>, <NAME>, <NAME>, The Elements of Statistical Learning; Data Mining, Inference, and Prediction, <a href="https://web.stanford.edu/~hastie/ElemStatLearn/" class="uri">https://web.stanford.edu/~hastie/ElemStatLearn/</a>, 2017<a href="introduction-what-is-machine-learning.html#fnref20" class="footnote-back">↩</a></p></li> <li id="fn21"><p><NAME>, <NAME>, <NAME>, Principal component analysis, Nature Methods, Vol.14 No.7, July 2017, 641-2<a href="introduction-what-is-machine-learning.html#fnref21" class="footnote-back">↩</a></p></li> <li id="fn22"><p><a href="https://cran.r-project.org/" class="uri">https://cran.r-project.org/</a><a href="introduction-what-is-machine-learning.html#fnref22" class="footnote-back">↩</a></p></li> <li id="fn23"><p><a href="https://rstudio.com/" class="uri">https://rstudio.com/</a><a href="introduction-what-is-machine-learning.html#fnref23" class="footnote-back">↩</a></p></li> <li id="fn24"><p><a href="http://topepo.github.io/caret/index.html" class="uri">http://topepo.github.io/caret/index.html</a><a href="introduction-what-is-machine-learning.html#fnref24" class="footnote-back">↩</a></p></li> <li id="fn25"><p><a href="http://topepo.github.io/caret/available-models.html" class="uri">http://topepo.github.io/caret/available-models.html</a><a href="introduction-what-is-machine-learning.html#fnref25" class="footnote-back">↩</a></p></li> <li id="fn26"><p><NAME>, <NAME>, <NAME>, Deep Learning, MIT Press, <a href="http://www.deeplearningbook.org" class="uri">http://www.deeplearningbook.org</a>, 2016<a href="introduction-what-is-machine-learning.html#fnref26" class="footnote-back">↩</a></p></li> <li id="fn27"><p><NAME> and <NAME>, The LION way. Machine Learning-Intelligent Optimization, LIONlab, University of Trento, Italy“, 2017”, <a href="http://intelligent-optimization.org/LIONbook" class="uri">http://intelligent-optimization.org/LIONbook</a><a href="introduction-what-is-machine-learning.html#fnref27" class="footnote-back">↩</a></p></li> <li id="fn28"><p><NAME>, et al., A Practical Guide to Support Vector Classification, 2016, <a href="http://www.csie.ntu.edu.tw/~cjlin" class="uri">http://www.csie.ntu.edu.tw/~cjlin</a><a href="introduction-what-is-machine-learning.html#fnref28" class="footnote-back">↩</a></p></li> <li id="fn29"><p><a href="https://machinelearningmastery.com/k-fold-cross-validation/" class="uri">https://machinelearningmastery.com/k-fold-cross-validation/</a><a href="introduction-what-is-machine-learning.html#fnref29" class="footnote-back">↩</a></p></li> <li id="fn30"><p><NAME>, <NAME>, Applied Predictive Modeling, 2013, ISBN 978-1-4614-6848-6<a href="introduction-what-is-machine-learning.html#fnref30" class="footnote-back">↩</a></p></li> </ol> </div> <!-- dynamically load mathjax for compatibility with self-contained --> <script> (function () { var script = document.createElement("script"); script.type = "text/javascript"; var src = "true"; if (src === "" || src === "true") src = "https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-MML-AM_CHTML"; if (location.protocol !== "file:") if (/^https?:/.test(src)) src = src.replace(/^https?:/, ''); script.src = src; document.getElementsByTagName("head")[0].appendChild(script); })(); </script> <file_sep>/_draft/new.md --- --- Control ping in Alias mcc29th November 2021 at 8:22pm Stop after sending count ECHO_REQUEST packets # alias ping='ping -c 5' Do not wait interval 1 second, go fast # alias fastping='ping -c 100 -s.2' --- title: tags: --- Bash One-Liners mcc29th November 2021 at 8:52pm subtract a small file from a bigger file grep -vf filesmall filebig sort a bed file by chrom, position sort -k1,1 -k2,2n file.bed > file.sort.bed strip header tail +2 file > file.noheader find and replace over multiple files perl -pi -w -e 's/255,165,0/255,69,0/g' *.wig print line 83 from a file sed -n '83p' insert a header line sed -i -e '1itrack name=test type=bedGraph' file.bed grep \> file_name | wc -l grep -c "^>" With bash, you can use pattern substitution: for f in *.fasta ; do mv $f ${f/fasta/fa} ; done. It is more than twice faster than calling for sed (on a set of 1000 files). -------------------- Change bash output to symbols 14th August 2018 at 2:04pm Shows happy face or sad face depending on command completion ^b^ = 'happy, command worked', O_O = 'sad, command did not work' PS1="\`if [ \$? = 0 ]; then echo \[\e[33m\]^b^\[\e[0m\]; else echo \[\e[31m\]O_O\[\e[0m\]; fi\`[\u@\h:\w]\\$ " -------------- dos2unix, sed, grep, cat mcc29th November 2021 at 8:23pm Removing return characters: cat 1.txt | tr -d "\n" > 2.txt Match contents of one file in another: grep -f 1.txt 2.txt > 3.txt Removing matching lines from a file: grep -v "match" 1.txt > 2.txt Before any linux command line processing do this: dos2unix 1.txt > 2.txt --------------- du -k --max-depth=1 mcc29th November 2021 at 11:05am #!/bin/sh # du -k | sort -nr | awk ' # Can use this too. du -k --max-depth=1 "$@" | sort -nr | awk ' BEGIN { split("KB,MB,GB,TB", Units, ","); } { u = 1; while ($1 >= 1024) { $1 = $1 / 1024; u += 1 } $1 = sprintf("%.1f %s", $1, Units[u]); print $0; } ' > du_sorted.txt <file_sep>/_draft/2020-01-01-list-installed-r-packages.md --- title: "List Installed R Packages" tags: R --- TEST <file_sep>/_draft/2021-12-02-hugo-r-tutorial.md --- title: "A Step-by-step Tutorial On Using Hugo with R" tags: Tutorial Hugo R Netlify --- I discovered [Step-by-step Tutorial On Using Hugo with R tutorial](https://www.apreshill.com/blog/2020-12-new-year-new-blogdown/) on **blogdown** written by Alison. This is a great **blogdown** tutorial. ![Alison's blogdown tutorial](https://www.apreshill.com/blog/2020-12-new-year-new-blogdown/03-blogdown-2021.png) NOTE: I have based my blog on the minimal Hugo template at https://xmin.yihui.org/. <file_sep>/_draft/rmd_files/2022-01-11-How-To-Find-R-Machine-Settings.rmd --- title: "How To Find R And Machine Settings" author: "MCC" date: '2020-01-11' output: html_document --- A good practice is to add R and Linux machine settings for reproducible data manipulation. Machine Settings: ```{r} Sys.info()[c(1:3,5)] ``` R Settings: ```{r} sessionInfo() ``` <file_sep>/_draft/rmd_files/2018-02-11-cool-r-art.rmd --- output: html_document --- ```{r} library(ggplot2) n=300 t1 = 1:n t0 = seq(3, 2*n+1, 2) %% n t2 = t0 + (t0 == 0)*n df = data.frame(x = cos((t1-1)*2*pi/n), y = sin((t1-1)*2*pi/n), x2 = cos((t2-1)*2*pi/n), y2 = sin((t2-1)*2*pi/n)) ggplot(df, aes(x, y, xend=x2, yend=y2)) + geom_segment(alpha=.1) + theme_void() ``` See: https://fronkonstin.com/2017/12/23/tiny-art-in-less-than-280-characters/<file_sep>/_draft/rmd_files/2018-02-11-The-Basic-GGPlot-Histrogram.rmd --- title: "The Basic GGPlot Histrogram" subtitle: "& why-you-need-to-practice-it" author: "MCC" date: '2018-02-11' output: html_document --- ```{r} library(ggplot2) ``` CREATE VARIABLE, NORMALLY DISTRIBUTED ```{r} # set "seed" for random numbers set.seed(42) # create variable xvar_rand_norm <- rnorm(1000, mean = 1) # CREATE DATA FRAME FROM VARIABLE df.xvar <- data.frame(xvar_rand_norm) # CALCULATE MEAN # we'll use this in an annotation xvar_mean <- mean(xvar_rand_norm) ``` PLOT Here, we’re going to plot the histogram We’ll also add a line at the calculated mean and also add an annotation to specify the value of the calculated mean. ```{r message=FALSE, warning=FALSE} ggplot(data = df.xvar, aes(x = xvar_rand_norm)) + geom_histogram() + geom_vline(xintercept = xvar_mean, color = "dark red") + annotate("text", label = paste("Mean: ", round(xvar_mean,digits = 2)), x = xvar_mean, y = 30, color = "white", size = 5) ```<file_sep>/_docs/chapters/introduction-what-is-machine-learning.md --- title: "What Is Machine Learning" tags: Data_Science --- {% include_relative what-is-ml.html %} <file_sep>/_posts/python/2018-08-15-python-conda.md --- title: "Python - conda packages" date: 2018-08-15 tags: Python Conda --- How to list ALL `conda` or `pip` packages `` conda list | sort > ~/Desktop/conda_list.txt # OR pip list | sort > ~/Desktop/conda_list.txt ``` <file_sep>/_posts/bash/2021-01-01-bash-aliases.md --- title: "Matt's Bash Aliases" tags: Bash --- Matt's Aliases ``` ## Bash aliases alias rm='rm -i' alias cp='cp -i' alias mv='mv -i' alias edit='gedit' alias up='cd ..' alias cd..='cd ..' alias ...='cd ../../../' alias ....='cd ../../../../' alias .....='cd ../../../../' alias ping='ping -c 5' alias reboot='sudo reboot' alias update='sudo apt-get update' ## Git alias gits="git status" alias gita="git add ." alias gitcm="git commit -m" alias gpush="git push" alias gpull="git pull" ## User Specific aliases ## alias home='cd /home/mcc/' alias drop='cd /home/mcc/Dropbox/' alias dropbox='cd /home/mcc/Dropbox/' alias down='cd /home/mcc/Downloads/' alias desk='cd /home/mcc/Desktop/' alias docs='cd /home/mcc/Documents/' ## Anaconda alias jupy='jupyter notebook' alias condaup='conda update -y --prefix /home/mcc/anaconda3 anaconda' alias navi='conda update -y --prefix /home/mcc/anaconda3 anaconda && anaconda-navigator' ```<file_sep>/_posts/bash/2017-12-20-bash-rename.md --- title: "Bash - Rename files names to lowercase" tags: Bash InProgress --- Scripting Rename All files in directory to Lowercase An elegant way to rename all files in a directory to lowercase ``` for i in `ls -1`; do mv $i "${i,,}" ; done ``` Explanation: There is a lower/upper case modification build-in bash using for, for looping files through directory. <file_sep>/_draft/skew-eda-article/skew-eda.rmd --- title: "Why Do EDA" author: "MCC" output: html_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` <!-- https://data36.com/statistical-bias-types-explained/ https://online.hbs.edu/blog/post/types-of-statistical-bias https://towardsdatascience.com/what-is-statistical-bias-and-why-is-it-so-important-in-data-science-80e02bf7a88d --> I was discussing Data Science with a Journalist the other day, and a question came up, Why are Boxplots important with respect to Exploratory Data Analysis? Boxplots and Histograms are the first tools taught when learning statistical software, but why? Many online-courses (I've seen) gloss over the "WHY." >For more on Exploratory Data Analysis, I recommend [Exploratory Data Analysis with R](https://leanpub.com/exdata) by <NAME>, and it's FREE. >Even if you don't use R (yet) it has some nuggets. ## What is wrong with your data? Since this discussion started with a journalist co-worker, I was reminded of the 5 W's of reporting: 1. Who 2. What 3. When 4. Where 5. Why - How might a journalist think of the five W's when analyzing a dataset. - Can these five questions be useful when carrying out a Data Analysis? In short, **Yes**. **And**, I believe the five W's should be asked by Data Scientists too. - **Why** is this data being analyzed? - Are we hypothesis testing? - Are we looking for a correlation or a regression line? - Is the data normally distributed? </br> - **When** and **Where** was the data collected? - If a political poll is asked in 2 cities, is it reasonable to assume that the entire country will poll the same way? - Could the time of day? day of the week? or season of the year change the data collected? </br> - **Who** gathered this data? - Is it important what prejudices that person or group had collecting the data? </br> - And finally, **What** can be learned from the dataset? What do these examples of asking the five W's have in common? In my mind, they all dive deep into the story or (in this case) the data bias. >Bias - Inclined to one side; swelled on one side; an inclination; to give a particular direction to; to influence; to prejudice; to prepossess. > >Webster, 1913 I believe the five W's are a good way to focus ones skepticism. The five W's give a roadmap that scientists can use too. - Is there anything wrong with your data? - What is its source? - Who or what compiles your data? - Where and when was it generated? - As Data Scientists, can we understand where biases can be introduced? #### Why does a Data Science need to understand bias? In much of the world of scientific research, people study the simplest, smallest pieces. Cell biologists design experiments based a single cell type. This reductionist approach is common is science. But what happens when people are studied? What happens when a political poll is asked of a number of people in *two cities*. Can that poll be generalized to include everyone in that county, state, and country? Exploratory Data Analysis is the first review of your data and information. EDA is a first attempt to investigate what is right and wrong with your dataset. There are two types of bias. 1. Conscious Bias 1. Unconscious Bias, also called implicit bias >Bias: Favorable or unfavorable attitudes, or beliefs about a group [or subject] that informs how we perceive, interact, behave toward the group that are automatically activated. > >https://libraryguides.saic.edu/learn_unlearn/foundations6 Unconscious bias >In an unbiased random sample, every case in the population should have an equal likelihood of being part of the sample. > ><NAME>, [HBS Online](https://online.hbs.edu/blog/post/types-of-statistical-bias) #### Sampling Bias If we think of a political poll, the study should have about the same fraction (percent, proportion, ratio) of college educated vs non-college educated volunteers. If the poll is carried out at a high school will we find the same percent of college-educated versus non-educated in a school of 13-18 year-olds and only several dozen teachers? 3 Ways to Avoid Sampling Bias: 1. Consider sample size. - Having a *"large"* pool could provide enough randomness in your study to smooth out problems. How much is *"large"*? Good question. 2. Define a target population. - Make online surveys as short and accessible as possible. - Follow up with non-responders. - Avoid convenience sampling. ##### Bias in Assignment Assignment bias can also be called selection bias. Pretend you are a teacher. You ask for student volunteers to check the spelling or grammar of several papers. Ask your yourself, will this teacher find the students with an average grammar or spelling skills? Probably not. In most studies the 'volunteers' are themselves chosen from select groups that have a similar ratio English majors as Chemistry majors as in the school population. --- <NAME> and <NAME> have an interesting view of Data Science in the article, 'What is the Question?'[^1] [^1]:Science, 20 MARCH 2015, VOL 347, ISSUE 6228, P. 1314 ![](jleek-ds.png) In the flowchart above, Data Science and Statistics can be broken down into 6 categories. In this piece, I will be focusing on Exploratory Data Analysis (EDA). <!-- Conversely, can Data Scientists learn from Journalists? Are Data Scientists acting similarly to investigative reporters, who look for problems with the goal being to bring a story to light? --> I plan to investigate two mathematical perturbations that can be interpreted using Boxplots and Histograms. Two common measures for distributions are skew and kurtosis. >Perturbation, in mathematics, a method for solving a problem by comparing it with a similar one for which the solution is known. Usually the solution found in this way is only approximate. > >https://www.britannica.com/science/perturbation-mathematics But first, let us prepare some good and bad data. #### Generate a dataset ```{r} # Create data names <- c(rep("A", 15) , rep("B", 15) , rep("C", 15)) value <- c( rpois(15, 5) , rnorm(15, mean=10, sd=15) , rnorm(15, mean=40, sd=10) ) data <- data.frame(names,value) boxplot(data$value ~ data$names , col=terrain.colors(4), horizontal = T ) ``` Square Values ```{r} skewed_1 = (1/2)*(data$value)^2 data <- cbind(data, skewed_1) boxplot(data$skewed_1 ~ data$names , col=terrain.colors(4), horizontal = T ) ``` https://statisticsglobe.com/jitter-r-function-example/ https://stackoverflow.com/questions/23675735/how-to-add-boxplots-to-scatterplot-with-jitter https://www.data-to-viz.com/caveat/boxplot.html <file_sep>/_posts/bash/2020-06-01-bash-gsub.md --- title: "Linux - sub,gsub" tags: Bash InProgress --- regex - sub - gsub - grep sub (pattern, replacement, x) sub ("little", "big", "Mary has a little lamb.") # Substitutes the first occurrence of the word "little" by another word "big". "Mary has a big lamb." --- grep: search for matches to the argument ‘pattern’ within each element of a character vector sub & gsub perform replacement of the first and all matches respectively. Usage: grep(pattern, x, ignore.case = FALSE, perl = FALSE, value = FALSE, fixed = FALSE, useBytes = FALSE, invert = FALSE) sub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE, fixed = FALSE, useBytes = FALSE) gsub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE, fixed = FALSE, useBytes = FALSE) <file_sep>/_draft/2020-01-01-R-stat-tests.md --- title: "R - Statistical Tests" tags: R Statistical Tests --- |test | b | |:--|:--| | cor.test | Tests for association between paired samples, using either<br> __Pearson's__ product moment correlation coefficient,<br> __Kendall's__ tau,<br> __Spearman's__ rho | | aov ( )<br>anova ( )<br>lm ( )<br>glm ( ) | Linear & non-linear models | | t.test (X) | [[t-test]],<br>[[Student's t Distribution]],<br>[[1 & 2 Sample t-tests]] | | prop.test ( )<br>binom.test ( ) | Sign test | | chisq.test (X) | Chi-square test on matrix X | | fisher.test ( ) | Fisher exact test |
51570489de13f2a07cbb9101703217ce114788bc
[ "Ruby", "HTML", "Markdown", "R", "RMarkdown" ]
63
Markdown
mccurcio/mccurcio.github.io
5a3d71f883de7dd74917f8a1c0315a2fb8d333f4
601019e21d871b9446da4f04e4bfeac6f027ef07
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace OfficeOnline.Demo_DSOframer { public partial class webtest4 : System.Web.UI.Page { protected string DocUrl { get { return "http://" + Request.Url.Authority + "/Demo_DSOframer/Doc/111.doc"; } } protected void Page_Load(object sender, EventArgs e) { } } }
8b4cef32466cf234451aefa523aef193c9e685cb
[ "C#" ]
1
C#
xaccc/OfficeTools.OnlineEditWord
0ab7b0e3009625800bf01a165852b508068202f4
79d76892b0682f9916b89774b61b97ebddbc8098
refs/heads/master
<repo_name>prozz/nested<file_sep>/nested.go package nested // Resolve allows for easy lookups in deeply nested structs. // In case of any unwanted nil, it just returns defaultValue. func Resolve(defaultValue interface{}, accessFunc func() interface{}) (v interface{}) { defer func() { recover() }() v = defaultValue v = accessFunc() return v } <file_sep>/nested_test.go package nested import ( "github.com/stretchr/testify/assert" "testing" ) // Imagine we have slices inside structs inside slices and structs. // Wanted just easy example here. type Nested struct { Foo []struct { Bar int } } func TestNestedDots_Empty(t *testing.T) { s := &Nested{} value := Resolve(666, func() interface{} { return s.Foo[0].Bar }) assert.Equal(t, 666, value) } func TestNestedDots_Filled(t *testing.T) { s := &Nested{ Foo: []struct{ Bar int }{{Bar: 5}}, } value := Resolve(666, func() interface{} { return s.Foo[0].Bar }) assert.Equal(t, 5, value) }
4e65f40eb8e8fcb7c8ec058f6d1a1f268af99788
[ "Go" ]
2
Go
prozz/nested
fc453774c98f408ede20bc66ac439c078927d1ff
74152ca1d0117b033cf9da22cf8ed4710edf768f
refs/heads/main
<repo_name>a252937166/spring-boot-hystrix-demo<file_sep>/src/test/java/com/ouyanglol/hytrixdemo/HystrixTest.java package com.ouyanglol.hytrixdemo; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; /** * @author ouyangduning * @date 2020/11/25 15:12 */ @Slf4j public class HystrixTest extends HystrixDemoApplicationTests { @Autowired private HystrixTestBean hystrixTestBean; @Test public void t() throws InterruptedException { log.info(hystrixTestBean.normal()); log.info(hystrixTestBean.normal2()); log.info(hystrixTestBean.timeOut()); log.info(hystrixTestBean.timeOut2()); log.info(hystrixTestBean.error()); } } <file_sep>/src/main/java/com/ouyanglol/hytrixdemo/HytrixDemoApplication.java package com.ouyanglol.hytrixdemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class HytrixDemoApplication { public static void main(String[] args) { SpringApplication.run(HytrixDemoApplication.class, args); } } <file_sep>/README.md [![Build Status](https://travis-ci.org/a252937166/spring-boot-hystrix-demo.svg?branch=main)](https://travis-ci.org/a252937166/spring-boot-hystrix-demo) [![codecov](https://codecov.io/gh/a252937166/spring-boot-hystrix-demo/branch/main/graph/badge.svg?token=USFMCL7WYR)](https://codecov.io/gh/a252937166/spring-boot-hystrix-demo) [![GitHub license](https://img.shields.io/github/license/a252937166/spring-boot-hystrix-demo)](https://github.com/a252937166/spring-boot-hystrix-demo/blob/main/LICENSE) # spring-boot-hystrix-demo 参考了大多数文章,大多使用的是spring-cloud的整合方式,如果只是单独使用spring-boot的话,这种方式引用了太多无用的依赖,而且没有明明没有使用spring-cloud,pom中有个spring-cloud开头的依赖,有强迫症的我实在接受不了,所以花了些时间自己研究了一下如何快速简洁地单独整合hystrix。 # maven ```xml <dependency> <groupId>com.netflix.hystrix</groupId> <artifactId>hystrix-javanica</artifactId> <version>1.5.2</version> </dependency> ``` hystrix-javanica中包含了hystrix-core,并且提供了`@HystrixCommand`等注解,如果只hystrix-core是没法使用`@HystrixCommand`等注解的。 # config ```java import com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class HystrixConfig { @Bean public HystrixCommandAspect hystrixCommandAspect() { return new HystrixCommandAspect(); } } ``` 我们看其源码: ```java @Aspect public class HystrixCommandAspect { private static final Map<HystrixCommandAspect.HystrixPointcutType, HystrixCommandAspect.MetaHolderFactory> META_HOLDER_FACTORY_MAP; public HystrixCommandAspect() { } @Pointcut("@annotation(com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand)") public void hystrixCommandAnnotationPointcut() { } @Pointcut("@annotation(com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser)") public void hystrixCollapserAnnotationPointcut() { } @Around("hystrixCommandAnnotationPointcut() || hystrixCollapserAnnotationPointcut()") public Object methodsAnnotatedWithHystrixCommand(ProceedingJoinPoint joinPoint) throws Throwable { ... } } ``` 其中定义了`HystrixCommand`这个切入点,这就是`hystrix`最简单的原理,在有`@HystrixCommand`注解的方法前后进行增强处理。 至此,第一步整合已经成功了,随便写一个方法测验,返回`fail`。 ```java @HystrixCommand(commandProperties = { // @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000") },fallbackMethod = "fail1" ) public String t() throws InterruptedException { Thread.sleep(5000); return tService.t(); } private String fail1() { System.out.println("fail1"); return "fail1"; } ``` # 实现可读取配置文件 此时,我们在配置文件中进行设置: ```profile hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=6000 ``` 在默认时间`1000ms`之后,还是返回`fail`,说明配置没有生效,但是如果我们直接引用`spring-cloud-starter-netflix-hystrix`依赖的话,配置是生效的,那么`spring-cloud-starter-netflix-hystrix`是如何读取的配置文件,并且修改的默认参数,这个就需要我们阅读源码,并且手动`debug`慢慢研究了。 我大概花了3-4小时的时间,对两种jar包的引用方式作对比。这简单说明一下。 我们的切入口是`HystrixPropertiesCommandDefault`这个类,每个有`HystrixCommand`注解的方法,第一次执行时,会通过这个类初始化配置参数。 设置参数的入口是`HystrixCommandProperties`的`getProperty`方法: ```java private static HystrixProperty<Integer> getProperty(String propertyPrefix, HystrixCommandKey key, String instanceProperty, Integer builderOverrideValue, Integer defaultValue) { return forInteger() .add(propertyPrefix + ".command." + key.name() + "." + instanceProperty, builderOverrideValue) .add(propertyPrefix + ".command.default." + instanceProperty, defaultValue) .build(); } ``` 然后一步一步debug,最终到`ConcurrentCompositeConfiguration`的`getList()`方法时发现:`spring-cloud-starter-netflix-hystrix`的`configList`比`hystrix-javanica`的`configList`多一个`ConfigurableEnvironmentConfiguration`。 ```java @Override public List getList(String key, List defaultValue) { List<Object> list = new ArrayList<Object>(); // add all elements from the first configuration containing the requested key Iterator<AbstractConfiguration> it = configList.iterator(); if (overrideProperties.containsKey(key)) { appendListProperty(list, overrideProperties, key); } ... } ``` ![enter image description here](https://qiniu.ouyanglol.com/blog/springboot%E6%9C%80%E7%AE%80%E6%96%B9%E5%BC%8F%E6%95%B4%E5%90%88hystrix%E4%BB%A5%E5%8F%8A%E6%A0%B9%E6%8D%AE%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E8%AE%BE%E7%BD%AE%E9%BB%98%E8%AE%A4%E5%8F%82%E6%95%B01.png) <center>图(1)</center> ![enter image description here](https://qiniu.ouyanglol.com/blog/springboot%E6%9C%80%E7%AE%80%E6%96%B9%E5%BC%8F%E6%95%B4%E5%90%88hystrix%E4%BB%A5%E5%8F%8A%E6%A0%B9%E6%8D%AE%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E8%AE%BE%E7%BD%AE%E9%BB%98%E8%AE%A4%E5%8F%82%E6%95%B02.png) <center>图(2)</center> 经查询,`ConfigurableEnvironmentConfiguration`在`spring-cloud-netflix-archaius`,还是有`spring-cloud`的命名,不想直接引入,看其源码后,发现这个bean并不复杂,可以直接复制到我们的项目中,删除掉多余的代码就行了。 ArchaiusAutoConfiguration: ```java package com.ouyanglol.hytrixdemo.archaius;/* * Copyright 2013-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import com.netflix.config.AggregatedConfiguration; import com.netflix.config.ConcurrentCompositeConfiguration; import com.netflix.config.ConfigurationManager; import com.netflix.config.DynamicProperty; import com.netflix.config.DynamicPropertyFactory; import com.netflix.config.DynamicURLConfiguration; import org.apache.commons.configuration.AbstractConfiguration; import org.apache.commons.configuration.ConfigurationBuilder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfigureOrder; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Lazy; import org.springframework.core.Ordered; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; import org.springframework.util.ReflectionUtils; import javax.annotation.PreDestroy; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; @Lazy(false) @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ConcurrentCompositeConfiguration.class, ConfigurationBuilder.class}) @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) public class ArchaiusAutoConfiguration { private static final Log log = LogFactory.getLog(ArchaiusAutoConfiguration.class); private static final AtomicBoolean initialized = new AtomicBoolean(false); private static DynamicURLConfiguration defaultURLConfig; @PreDestroy public void close() { if (defaultURLConfig != null) { defaultURLConfig.stopLoading(); } setStatic(ConfigurationManager.class, "instance", null); setStatic(ConfigurationManager.class, "customConfigurationInstalled", false); setStatic(DynamicPropertyFactory.class, "config", null); setStatic(DynamicPropertyFactory.class, "initializedWithDefaultConfig", false); setStatic(DynamicProperty.class, "dynamicPropertySupportImpl", null); initialized.compareAndSet(true, false); } @Bean public static ConfigurableEnvironmentConfiguration configurableEnvironmentConfiguration(ConfigurableEnvironment env, ApplicationContext context) { Map<String, AbstractConfiguration> abstractConfigurationMap = context.getBeansOfType(AbstractConfiguration.class); List<AbstractConfiguration> externalConfigurations = new ArrayList<>(abstractConfigurationMap.values()); ConfigurableEnvironmentConfiguration envConfig = new ConfigurableEnvironmentConfiguration(env); configureArchaius(envConfig, env, externalConfigurations); return envConfig; } protected static void configureArchaius(ConfigurableEnvironmentConfiguration envConfig, ConfigurableEnvironment env, List<AbstractConfiguration> externalConfigurations) { if (initialized.compareAndSet(false, true)) { ConcurrentCompositeConfiguration config = new ConcurrentCompositeConfiguration(); if (externalConfigurations != null) { for (AbstractConfiguration externalConfig : externalConfigurations) { config.addConfiguration(externalConfig); } } config.addConfiguration(envConfig, ConfigurableEnvironmentConfiguration.class.getSimpleName()); defaultURLConfig = new DynamicURLConfiguration(); addArchaiusConfiguration(config); } else { // TODO: reinstall ConfigurationManager log.warn( "Netflix ConfigurationManager has already been installed, unable to re-install"); } } private static void addArchaiusConfiguration( ConcurrentCompositeConfiguration config) { if (ConfigurationManager.isConfigurationInstalled()) { AbstractConfiguration installedConfiguration = ConfigurationManager .getConfigInstance(); if (installedConfiguration instanceof ConcurrentCompositeConfiguration) { ConcurrentCompositeConfiguration configInstance = (ConcurrentCompositeConfiguration) installedConfiguration; configInstance.addConfiguration(config); } else { installedConfiguration.append(config); if (!(installedConfiguration instanceof AggregatedConfiguration)) { log.warn( "Appending a configuration to an existing non-aggregated installed configuration will have no effect"); } } } else { ConfigurationManager.install(config); } } private static void setStatic(Class<?> type, String name, Object value) { // Hack a private static field Field field = ReflectionUtils.findField(type, name); ReflectionUtils.makeAccessible(field); ReflectionUtils.setField(field, null, value); } @Configuration(proxyBeanMethods = false) @ConditionalOnProperty(value = "archaius.propagate.environmentChangedEvent", matchIfMissing = true) protected static class PropagateEventsConfiguration { @Autowired private Environment env; } } ``` ConfigurableEnvironmentConfiguration: ```java /* * Copyright 2013-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ouyanglol.hytrixdemo.archaius; import org.apache.commons.configuration.AbstractConfiguration; import org.springframework.core.env.CompositePropertySource; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.EnumerablePropertySource; import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertySource; import org.springframework.core.env.StandardEnvironment; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * EnvironmentConfiguration wrapper class providing further configuration possibilities. * * @author <NAME> */ public class ConfigurableEnvironmentConfiguration extends AbstractConfiguration { private final ConfigurableEnvironment environment; public ConfigurableEnvironmentConfiguration(ConfigurableEnvironment environment) { this.environment = environment; } @Override protected void addPropertyDirect(String key, Object value) { } @Override public boolean isEmpty() { return !getKeys().hasNext(); // TODO: find a better way to do this } @Override public boolean containsKey(String key) { return this.environment.containsProperty(key); } @Override public Object getProperty(String key) { return this.environment.getProperty(key); } @Override public Iterator<String> getKeys() { List<String> result = new ArrayList<>(); for (Map.Entry<String, PropertySource<?>> entry : getPropertySources() .entrySet()) { PropertySource<?> source = entry.getValue(); if (source instanceof EnumerablePropertySource) { EnumerablePropertySource<?> enumerable = (EnumerablePropertySource<?>) source; for (String name : enumerable.getPropertyNames()) { result.add(name); } } } return result.iterator(); } private Map<String, PropertySource<?>> getPropertySources() { Map<String, PropertySource<?>> map = new LinkedHashMap<>(); MutablePropertySources sources = (this.environment != null ? this.environment.getPropertySources() : new StandardEnvironment().getPropertySources()); for (PropertySource<?> source : sources) { extract("", map, source); } return map; } private void extract(String root, Map<String, PropertySource<?>> map, PropertySource<?> source) { if (source instanceof CompositePropertySource) { for (PropertySource<?> nest : ((CompositePropertySource) source) .getPropertySources()) { extract(source.getName() + ":", map, nest); } } else { map.put(root + source.getName(), source); } } } ``` 至此,配置文件中的hystrix的相关配置就生效了。
79019e22ff89c67d306af64502036db94c512e92
[ "Markdown", "Java" ]
3
Java
a252937166/spring-boot-hystrix-demo
ca934d152aae1ec3cabf2f9fb7d28211867b0abd
c1522f3bb13dde56cb3f9f34cd9678d49dcbe32a
refs/heads/master
<repo_name>omoman/To-be-named<file_sep>/www/js/services.js function map () { var map; var curLoc; var markers = []; function initialize () { navigator.geolocation.getCurrentPosition(function(pos){ var latlng = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude); var myOptions = { zoom: 11, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); curLoc = {lat:pos.coords.latitude, long:pos.coords.longitude}; addMarker(pos.coords.latitude, pos.coords.longitude, true); }); } function addMarker(lat,long,is_start) { var latlng = new google.maps.LatLng(lat, long); if (is_start === true) { var marker = new google.maps.Marker({ position: latlng, map: map, icon: 'img/RivCode.png' }); markers.push(marker); } else { var marker = new google.maps.Marker({ position: latlng, map: map, icon: 'img/trashbin.png' }); markers.push(marker); } } // Sets the map on all markers in the array. function setAllMap(map) { for (var i = 0; i < markers.length; i++) { markers[i].setMap(map); } markers = []; } // Removes the markers from the map, but keeps them in the array. function clearMarkers() { setAllMap(null); } function getLoc (){ return curLoc; } return { initialize : initialize, getLoc : getLoc, addMarker : addMarker, clearMarkers: clearMarkers }; } <file_sep>/www/js/controllers.js function FacilitiesFrontCtl ($http,$scope, map) { $scope.initialize = map.initialize; $scope.arr = []; $scope.runFunc = function(num){ var path; if( num == 1 ) path = './greenwaste.json'; else if(num==2) path = './constructionWaste.json' else path = './hazardous.json' $http.post('/data', {loc:map.getLoc(),path:path}) .success(function(data){ $scope.arr = data; map.clearMarkers(); for (var i = 0; i < data.length; ++i) map.addMarker(data[i].latitude,data[i].longitude); map.addMarker(map.getLoc().lat, map.getLoc().long, true); }); } } function InfoCtl ($scope) { $scope.infoPages = [ { "name": "Additional Resources", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/88661-AdditionalResources.pdf" }, { "name": "American Flag Proper Disposal", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/88662-AmericanFlag.pdf" }, { "name": "Animal Carcass Waste", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70744-AnimalCarcass.pdf" }, { "name": "Animal Excrement", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70745-AnimalExcrement.pdf" }, { "name": "Appliances", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70746-Appliances.pdf" }, { "name": "Asbestos and Asbestos Containing Material", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70747-Asbestos.pdf" }, { "name": "Ash", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70748-Ash.pdf" }, { "name": "Batteries, Household and Rechargeable", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70767-UniversalWaste.pdf" }, { "name": "Batteries, Motor Vehicle (Lead Acid)", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70749-BatteriesLeadAcid-motorvehicles.pdf" }, { "name": "Bottles and Cans", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/88667-BottlesandCans.pdf" }, { "name": "Carpet", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/88668-Carpet.pdf" }, { "name": "Cell Phones", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70767-UniversalWaste.pdf" }, { "name": "Computer Disk, Video Cassette and Compact Disc", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/88687-ComputerDisc-VideoCassette-CD-Recycling.pdf" }, { "name": "Computer Monitors, Cathode Ray Tubes(CRTs) and TVs", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70767-UniversalWaste.pdf" }, { "name": "Compressed Gas Cylinders", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70750-CompressedGasCylinders.pdf" }, { "name": "Construction, Demolition and Renovation Waste", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70751-Construction-Demolition-Renovation-Waste.pdf" }, { "name": "Cooking Oil", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70755-FoodWaste.pdf" }, { "name": "Designated Waste", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70752-DesignatedWaste.pdf" }, { "name": "Dirt, Contaminated", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70739-Soil.pdf" }, { "name": "Dirt, Non-Contaminated", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70739-Soil.pdf" }, { "name": "Drywall and Gypsum Board", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70758-GypsumBoard-Drywall.pdf" }, { "name": "Electronic and Home Electronic Devices", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70767-UniversalWaste.pdf" }, { "name": "Explosive Waste, Hazardous Device", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70753-ExplosiveWaste-HazardousDevices.pdf" }, { "name": "Eyeglasses", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/88691-EyeglassRecyclers.pdf" }, { "name": "Fire Debris", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70754-FireDebris-StructureFires.pdf" }, { "name": "Fire Extinguisher", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/88692-FireExtinguisher.pdf" }, { "name": "Five R's of Responsible Waste Management", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/88827-FiveRsofResponsibleWasteManagement.pdf" }, { "name": "Food Crops and Food Banks", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70755-FoodWaste.pdf" }, { "name": "Food Waste", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70755-FoodWaste.pdf" }, { "name": "Grease and Grease Trap Waste", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70756-GreaseandGreaseTrapWaste.pdf" }, { "name": "Green Holiday Suggestions", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/96399-GreenHolidaySuggestions.pdf" }, { "name": "Green Waste", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70743-Yard-Waste-GreenWaste.pdf" }, { "name": "Grit and Screenings Waste", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70757-GritScreenings.pdf" }, { "name": "Hazardous Waste - Business", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70759-HazardousWaste-Business.pdf" }, { "name": "Hazardous Waste - Household", "url": "http://www.rivcowm.org/opencms/hhw/pdf/HHWEventFlyerPDFs/91709-MASTERHHWSchedule.pdf" }, { "name": "Hearing Aid Donation", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70767-UniversalWaste.pdf" }, { "name": "Human Excrement", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70760-HumanExcrement.pdf" }, { "name": "Lamps (Light Bulbs)", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70767-UniversalWaste.pdf" }, { "name": "Lawn and Garden Equipment", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70746-Appliances.pdf" }, { "name": "Lead-Painted Building Materials", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70751-Construction-Demolition-Renovation-Waste.pdf" }, { "name": "Matteresses", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/88695-Mattresses.pdf" }, { "name": "Medical Waste (Commercial)", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70761-MedicalWaste-Commercial.pdf" }, { "name": "Medical Waste (Household)", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70762-MedicalWaste-Household.pdf" }, { "name": "Mercury Containing Equipment", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70767-UniversalWaste.pdf" }, { "name": "Metal Recycling", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/88696-MetalRecycling.pdf" }, { "name": "Needles/Sharps", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/88697-Needles-Sharps.pdf" }, { "name": "Nursery Pots and Buckets", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/88699-NurseryPotsandBuckets.pdf" }, { "name": "Packaging Material Recycling", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/88700-PackagingMaterialRecyclers.pdf" }, { "name": "Paper Recycling and Junk Mail Reduction", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/88702-PaperRecyclingandJunkMailReduction.pdf" }, { "name": "Pharmaceutical Waste", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70763-Phamarceutical.pdf" }, { "name": "Propane Tanks", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70750-CompressedGasCylinders.pdf" }, { "name": "Reusable Items and Household Goods", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/88704-ReusableItemsandHouseholdGoods.pdf" }, { "name": "Small Appliances and Electronics", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70767-UniversalWaste.pdf" }, { "name": "Sewage Waste (Commercial)", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70766-SewageWaste-Commercial.pdf" }, { "name": "Sewage Waste (Recreational Vehicle, RV)", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70765-SewageWaste-RV.pdf" }, { "name": "Sharp Waste", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/88697-Needles-Sharps.pdf" }, { "name": "Shoe Donations", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/88705-ShoeDonations.pdf" }, { "name": "Smoke Detectors", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70767-UniversalWaste.pdf" }, { "name": "Soil", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70739-Soil.pdf" }, { "name": "Televisions", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70767-UniversalWaste.pdf" }, { "name": "Tires", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/89120-Tires.pdf" }, { "name": "Toner and Inkjet Recycling", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/88710-TonerandInkjetRecycling.pdf" }, { "name": "Treated Wood Waste", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70741-TreatedWoodWaste.pdf" }, { "name": "Universal Waste", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70767-UniversalWaste.pdf" }, { "name": "Used Oil and Oil Filters", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/88711-UsedOilandOilFilters.pdf" }, { "name": "Vehicles, Trailers and Boats", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70742-Vehicles-Trailers-and-Boats.pdf" }, { "name": "Yard Waste", "url": "http://www.rivcowm.org/opencms/landfill_info/pdf/FactSheets/70743-Yard-Waste-GreenWaste.pdf" }]; $scope.currentPdf = $scope.infoPages[0].url; $scope.setPdf = function (url){ $scope.currentPdf = url; } } function EventsCtl($scope){ $scope.eventAddr = [ { "region":"Thousand Palms", "location":"Della S. Lindley Elementary School", "date":"TBD", "time": "8:00 am - 12:00 PM", "address":"31-495 Robert Rd.\nThousand Palms, California 92276", "latitude":"33.82012558400049", "longitude":"-116.39688834099968" } , {"region":"Highgrove", "location":"Highgrove Elementary", "date":"TBD", "time": "8:00 am - 12:00 PM", "address":"690 Center St.\nRiverside, California 92507", "latitude":"34.01565734300044", "longitude":"-117.32644194999972"} , {"region":"Bermuda Dunes", "location":"Curbside Cleanup", "date":"TBD", "time": "8:00 am - 12:00 PM", "address":"Curbside Cleanup\nBermuda Dunes, California 92203", "latitude":"33.74656215600049", "longitude":"-116.2424199889997"} , {"region":"Sky Valley", "location":"Vacant Lot - APN#654190003", "date":"TBD", "time": "8:00 am - 12:00 PM", "address":"70-075 Dillon Rd.\nDesert Hot Springs, California 92241", "latitude":"33.92518353100047", "longitude":"-116.43879023299968"} , {"region":"Indio Hills", "location":"Indio Hills Community Center", "date":"TBD", "time": "8:00 am - 12:00 PM", "address":"80-400 Dillon Rd.\nIndio Hills, California 92241", "latitude":"33.854166730000486", "longitude":"-116.25960360299968"} , {"region":"Winchester", "location":"Vacant Lot ", "date":"TBD", "time": "8:00 am - 12:00 PM", "address":"625 South Pico Avenue\nSan Jacinto, California 92583", "latitude":"33.78152057300048", "longitude":"-116.95995649699972"} , {"region":"Mesa Verde", "location":"Vacant Lot", "date":"TBD", "time": "8:00 am - 12:00 PM", "address":"Corner of Mesa Verde Dr. and Bellwood Dr.\nMesa Verde, California 92225", "latitude":"33.61149331500047", "longitude":"-114.60558689699968"} , {"region":"Nuevo/Lakeview", "location":"Valley View Elementary School", "date":"TBD", "time": "8:00 am - 12:00 PM", "address":"21220 Maurice St.\nNuevo, California 92567", "latitude":"33.81201556700046", "longitude":"-117.1075457719997"} , {"region":"North Shore", "location":"North Shore Beach and Yacht Club", "date":"TBD", "time": "8:00 am - 12:00 PM", "address":"99-155 Sea View Drive\nNorth Shore, California 92254", "latitude":"33.519631038000455", "longitude":"-115.9371726499997"} , {"region":"Meadowbrook", "location":"Vacant Lot", "date":"TBD", "time": "8:00 am - 12:00 PM", "address":"Hwy. 74 and Meadowbrook Ave.\nPerris, California 92570","latitude": "33.79593010900044", "longitude":"-117.29748725999968"} , {"region":"Ripley", "location":"Vacant Lot", "date":"TBD", "time": "8:00 am - 12:00 PM", "address":"24300 Neighbours Blvd.\nRipley, California 92225", "latitude":"33.528080616000466", "longitude":"-114.6562870089997"} , {"region":"Desert Hot Springs", "location":"Bubbling Wells Elementary Schoold", "date":"TBD", "time": "8:00 am - 12:00 PM", "address":"67501 Camino Campanero\nDesert Hot Springs, California 92240", "latitude":"33.93940440700044", "longitude":"-116.4852597149997"} , {"region":"Mead Valley", "location":"Thomas Rivera Middle School", "date":"TBD", "time": "8:00 am - 12:00 PM", "address":"21675 Martin St.\nMead Valley, California 95956", "latitude":"39.936574307000456", "longitude":"-121.0599795979997"} , {"region":"Gavilan Hills", "location":"Gavilan Hills Ranch Market", "date":"TBD", "time": "8:00 am - 12:00 PM", "address":"22060 Gavilan Rd.\nPerris, California 92570", "latitude":"33.799204993000444", "longitude":"-117.35913686599969"} , {"region":"Warm Springs", "location":"Temescal Canyon High School", "date":"5/17/14", "time": "8:00 am - 12:00 PM", "address":"28775 El Toro Rd.\nLake Elsinore, California 92532", "latitude":"33.70212110800048", "longitude":"-117.34678089199969"} , {"region":"Valle Vista/East Hemet", "location":"Valle Vista Assembly of God", "date":"9/6/14", "time": "8:00 am - 12:00 PM", "address":"45252 E. Florida Ave.\nValle Vista, California 92544", "latitude":"33.747520187000475", "longitude":"-116.87040788099972"} , {"region":"Home Gardens", "location":"Our Lady of Tepeyac", "date":"9/20/14", "time": "8:00 am - 12:00 PM", "address":"13462 Magnolia Ave.\nHome Gardens, California 92879", "latitude":"33.878415935000476", "longitude":"-117.5194846019997"} , {"region":"Lakeland Village", "location":"Lakeland Village Middle School", "date":"9/27/14", "time": "8:00 am - 12:00 PM", "address":"18730 Grand Ave.\nLakeland Village, California ", "latitude":"33.615213895000466", "longitude":"-117.30616983499971"} ]; } <file_sep>/www/partials/facilities-front.html <div id='menu'> <input type="hidden" name="option" value="" id="btn-input" /> <h4>Choose a waste type:</h4> <div class="btn-group" data-toggle="buttons-radio"> <button id="btn-one" type="button" ng-click='runFunc(1)'data-toggle="button" name="option" value="1" class="btn btn-warning">Green</button> <button id="btn-two" type="button" ng-click='runFunc(2)' data-toggle="button" name="option" value="2" class="btn btn-warning">Construction/Demolition</button> <button id="btn-two" type="button" ng-click='runFunc(3)' data-toggle="button" name="option" value="3" class="btn btn-warning">Hazardous</button> </div> <h4> Your top 10 closest results: </h4> <ul id='results'> <ol ng-repeat='element in arr'> <br> Name: {{element.name}}<br> Address: {{element.address}}<br> PhoneNumber: {{element.phoneNum}}<br> Distance: {{element.distance}}<br><br> </ol> </ul> </div> <div id='map_canvas' ng-init='initialize()'></div> <file_sep>/www/js/app.js var app = angular.module('binit',['ngRoute']); app.config(function($routeProvider){ $routeProvider .when('/', { controller : 'MainCtl' , templateUrl : '../partials/main.html' }) .when('/facilities-front', { controller : 'FacilitiesFrontCtl' , templateUrl : '../partials/facilities-front.html' }) .when('/info', { controller : 'InfoCtl' , templateUrl : '../partials/info.html' }) .when('/events', { controller : 'EventsCtl' , templateUrl : '../partials/events.html' }) .otherwise({ redirectTo : '/'}); }); app.directive('embedSrc', function () { return { restrict: 'A', link: function (scope, element, attrs) { var current = element; scope.$watch(function() { return attrs.embedSrc; }, function () { var clone = element .clone() .attr('src', attrs.embedSrc); current.replaceWith(clone); current = clone; }); } }; }); app.factory('map', [map]); app.controller('MainCtl', function(){}); app.controller('InfoCtl', InfoCtl); app.controller('FacilitiesFrontCtl', ['$http','$scope', 'map', FacilitiesFrontCtl]);
dca1cdea649e04500196e270b9cc6e366a7b4ee4
[ "JavaScript", "HTML" ]
4
JavaScript
omoman/To-be-named
aa965097362e7d468e5dabc9097b4e655bbad08a
239278225708cd8185b12cfee7faee229fe6a12d
refs/heads/master
<file_sep><?php namespace Home\Controller; Class AliController extends BaseController { /** * 绑定列表 * @return [type] [description] */ public function index() { $map['uid'] = $this->mid; $map['is_del'] = 0; $res = D('userAlipay') -> field('ali_name, ali_num') -> where($map) -> find(); $this->return['data'] = $res; $this->goJson($this->return); } /** * 用户绑定 * @return [type] [description] */ public function bind() { $data['ali_num'] = I('post.alipay_num'); if(!$data['ali_num']) { $this->return['code'] = 1003; $this->return['message'] = L('alipay_num_error'); $this->goJson($this->return); } $data['ali_name'] = I('post.alipay_name'); if(!$data['ali_name']) { $this->return['code'] = 1004; $this->return['message'] = L('alipay_name_error'); $this->goJson($this->return); } $data['uid'] = $this->mid; $info['status'] = 3; $info['ctime'] = time(); D('userAlipayTmp')->where('status = 1 and uid='.$this->mid)->save($info); D('userAlipayTmp')->add($data); $this->return['message'] = L('wait_moment'); $this->goJson($this->return); } }<file_sep><?php /** * 取一个二维数组中的每个数组的固定的键知道的值来形成一个新的一维数组 * @param $pArray 一个二维数组 * @param $pKey 数组的键的名称 * @return 返回新的一维数组 */ function getSubByKey($pArray, $pKey="", $pCondition=""){ $result = array(); if(is_array($pArray)){ foreach($pArray as $temp_array){ if(is_object($temp_array)){ $temp_array = (array) $temp_array; } if((""!=$pCondition && $temp_array[$pCondition[0]]==$pCondition[1]) || ""==$pCondition) { $result[] = (""==$pKey) ? $temp_array : isset($temp_array[$pKey]) ? $temp_array[$pKey] : ""; } } return $result; }else{ return false; } } /** * 根据经纬度计算距离 * @param [type] $lat1 用户a的纬度 * @param [type] $lng1 用户a的经度 * @param [type] $lat2 用户b的纬度 * @param [type] $lng2 用户b的经度 * @return [type] 距离(米) */ function getDistance($lat1, $lng1, $lat2, $lng2) { //地球半径 $R = 6378137; //将角度转为狐度 $radLat1 = deg2rad($lat1); $radLat2 = deg2rad($lat2); $radLng1 = deg2rad($lng1); $radLng2 = deg2rad($lng2); //结果 $s = acos(cos($radLat1)*cos($radLat2)*cos($radLng1-$radLng2)+sin($radLat1)*sin($radLat2))*$R; //精度 $s = round($s* 10000)/10000; return round($s); } /** * 生成唯一订单号 * @return [type] [description] */ function build_order_no(){ return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8); } ?><file_sep><?php namespace Home\Model; use Think\Model; class TagsModel extends Model { /** * 获取全部语言 * @return [type] [description] */ public function getAllTags() { $all = F('allTags'); if (!$all) { $res = $this->field('tid, tag_name')->select(); foreach($res as $v){ $all[ $v['tid'] ] = $v['tag_name']; } F('allTags', $all); } return $all; } } ?><file_sep><?php namespace Home\Model; use Think\Model; class AdModel extends Model { /** * 获取广告 * @return [type] [description] */ public function getAd($post) { $return = D('ad')->field('pic, url')->where('is_del = 0 and type="'.$post['type'].'"')->order('sort Desc, aid Desc')->limit($post['limit'])->select(); foreach($return as $k=>$v) { if($v['pic']) { $return[$k]['pic'] = C('WEBSITE_URL').D('Picture') -> where('id='.$v['pic']) -> getField('path'); } } return $return; } }<file_sep><?php namespace Admin\Controller; use User\Api\UserApi; /** * 前台用户控制器 * @author 麦当苗儿 <<EMAIL>> */ class QuserController extends AdminController { /** * 前台用户首页 * @return [type] [description] */ public function index() { $map = array(); $nickname = I('nickname'); if(is_numeric($nickname)){ $map['uid|search_key']= array(intval($nickname),array('like','%'.$nickname.'%'),'_multi'=>true); }else{ $map['search_key'] = array('like', '%'.(string)$nickname.'%'); } $list = $this->lists('userinfo', $map); $all_language = D('Home/Language')->getAllLanguage(); foreach($list as &$v){ $v['language_name'] = $all_language[$v['cur_language']]; $v['uname'] = $v['uname'] ? $v['uname'] : '<font style="color:red">第三方未绑定用户</font>'; } $this->assign('_list', $list); $this->meta_title = '用户列表'; $this->display(); } /** * 绑定支付宝账号 * @return [type] [description] */ public function alipay() { $map['status'] = 1; $list = $this->lists('userAlipayTmp', $map); foreach( $list as &$v) { $tmp = D('userAlipay') -> field('ali_name as alipay_name, ali_num as alipay_num') -> where('is_del = 0 and uid ='.$v['uid']) -> find(); $tmp['uname'] = $this->redis->HGET('Userinfo:uid'.$v['uid'], 'uname'); if(!$tmp['uname']) { A('Home/User')->getUserinfoData($tmp['uid']); } $v = array_merge($v, $tmp); } $this->assign('_list', $list); $this->meta_title = '支付宝绑定审核'; $this->display(); } /** * 审核支付宝账户 * @param [type] $id [description] * @param [type] $status [description] * @return [type] [description] */ public function checkAlipay($id, $status) { if($id && $status) { if($status == 2) { $info = D('userAlipayTmp')->field('ali_num, ali_name, uid')->where('id='.$id)->find(); $save['is_del'] = 1; $save['status'] = 2; $info['ctime'] = $save['ctime'] = time(); D('userAlipay')->where('uid='.$info['uid'].' and is_del=0')->save($save); D('userAlipayTmp')->where('id='.$id)->save($save); unset($save); D('userAlipay')->add($info); } else { $info['status'] = $status; $info['ctime'] = time(); D('userAlipayTmp')->where('id='.$id)->save($info); } $res['status'] = 1; $res['info'] = '操作成功'; } else { $res['status'] = 2; $res['info'] = '操作失败,请稍后重试'; } die(json_encode($res)); } /** * 支付宝绑定记录 * @return [type] [description] */ public function bindLog() { $list = $this->lists('userAlipayTmp', array()); foreach( $list as &$v) { $v['uname'] = $this->redis->HGET('Userinfo:uid'.$v['uid'], 'uname'); $v['ctime'] = date('Y-m-d H:i:s', $v['ctime']); switch ($v['status']) { case '1': $v['status'] = '待审核'; break; case '2': $v['status'] = '<font style="color:green">已通过</font>'; break; case '3': $v['status'] = '重复提交,系统自动判定失败'; break; case '4': $v['status'] = '审核不通过'; break; } if(!$v['uname']) { A('Home/User')->getUserinfoData($tmp['uid']); } } $this->assign('_list', $list); $this->meta_title = '支付宝绑定记录'; $this->display(); } }<file_sep><?php return array( 'mobile_error' => '手机号格式不正确', 'mobile_has' => '该手机号已被注册', 'token_error' => 'token验证不通过', 'uname_null' => '昵称不能为空', 'pwd_null' => '<PASSWORD>', 'reg_error' => '注册失败', 'reg_success' => '注册成功', 'sex_error' => '性别出错', 'regSubAccount_error' => '容联注册失败', 'no_register' => '该手机号尚未注册', 'login_error' => '手机号或密码错误', 'pwd_error' => '两次密码不一致', 'param_error' => '参数错误', 'upload_success'=> '上传成功', 'token_lose' => 'token过期', 'token_error' => 'token错误', 'FILE_FORMAT' => '文件格式: {$format},文件大小:{$size}', 'follow_me' => '不能关注自己', 'unfollow_me' => '不能取消关注自己', 'cid_error' => '聊天id错误', 'from_id_error' => '评论发起人错误', 'score_error' => '评分错误', 'content_null' => '评论内容为空', 'comment_has' => '已经评论过', 'suggest_null' => '意见/建议为空', 'latng_error' => '经纬度不存在', 'otype_error' => '第三方登录类型错误', 'unionid_null' => 'unionid为空', 'access_token_null' => 'access_token为空', 'Adtype_null' => '广告位置出错', 'chongzhi' => '语加充值', 'chongzhi_des' => '为{$uname}充值{$money}元', 'money_error' => '金额有误', 'opera_error' => '操作失败', 'orderType_error' => '订单类型出错', 'user_error' => '用户出错', 'orderId_null' => '订单id不存在', 'alipay_num_error' => '支付宝账号必填', 'alipay_name_error' => '支付宝用户名称必填', 'wait_moment' => '已提交,请等待客服审核', 'ali_info_error' => '支付宝信息暂未通过审核,请通过后再来提现', ); ?><file_sep><?php /** * 广告设置 * @Author zbq */ namespace Admin\Controller; Class AdController extends AdminController { /** * 广告位置列表 * @return [type] [description] */ public function index() { $list = $this->lists('adPos', array()); foreach($list as &$v) { switch ($v['type']) { case '1': $v['type'] = '图片幻灯片'; break; } $v['count'] = D('ad')->where('position='.$v['id'])->count('aid'); } $this->assign('_list', $list); $this->display(); } /** * 广告列表 * @return [type] [description] */ public function adList() { $map['pos'] = I('pos'); $list = $this->lists('ad', $map, 'sort'); foreach($list as &$v) { $v['path'] = D('picture') -> where('id='.$v['pic']) -> getField('path'); $v['purl'] = C('website_url').$v['path']; } $this->assign('_list', $list); $this->display(); } /** * 编辑广告 * @return [type] [description] */ public function adEdit() { $aid = I('id'); $info['type'] = 1; if($aid) { $info = D('ad')->where('aid='.$aid)->find(); } $this->assign('info', $info); $this->display(); } /** * 保存广告 * @return [type] [description] */ public function adSave() { $info = I('post.'); if(I('aid')) { $res = D('ad')->save($info); } else { $res = D('ad')->add($info); } if($res) { $this->success('保存成功!', U('adList')); } else { $error = D('ad')->getError(); $this->error(empty($error) ? '未知错误!' : $error); } } }<file_sep><?php namespace Home\Controller; //use Think\Controller; class IndexController extends BaseController { public function index() { $this->display(); } public function test() { //echo $this->redis->FLUSHALL(); //dump($this->redis->del('Userinfo:uid2')); // dump(A('Home/User')->getUserinfoData(2)); //dump($this->redis->del('Userinfo:uid11')); dump($this->redis->get('Token:uid2')); dump($this->redis->HGetall('Userinfo:uid2')); // dump($this->redis->del('Userinfo:uid3')); // dump(A('Home/User')->getUserinfoData(3)); // dump($this->redis->del('Userinfo:uid9')); // dump(A('Home/User')->getUserinfoData(9)); // //D('userinfo')->getSearchList(); } } <file_sep><?php /** * 广告类 * Author: zbq */ namespace Home\Controller; Class AdController extends BaseController { /** * 获取广告内容 * @return [type] [description] */ public function getAd() { $post['type'] = I('post.type'); if ( !$post['type'] ) { $this->return['code'] = 1003; $this->return['message'] = L('Adtype_null'); $this->goJson($this->return); } $post['limit'] = I('post.limit') ? I('post.limit') : 10; $res = D('ad')->getAd($post); $this->return['data']['ad'] = $res; $this->goJson($this->return); } }<file_sep><?php namespace Home\Controller; class OrderController extends BaseController { /** * 获取订单号 * @return [type] [description] */ public function getOrder() { $info['money'] = number_format(I('post.money'),2); if($info['money'] < 0.01) { $this->return['code'] = 1003; $this->return['message'] = L('money_error'); $this->goJson($this->return); } $data['orderId'] = $info['orderId'] = build_order_no(); $info['ctime'] = time(); $info['type'] = 1; $info['uid'] = $this->mid; $info['note'] = '充值'.$info['money'].'元'; $id = D('mlog')->add($info); if($id) { $data['notifyUrl'] = C('WEBSITE_URL').'/index.php/Home/Order/ali_status'; $data['title'] = L('chongzhi'); $data['des'] = L('chongzhi_des',array('uname' => $this->redis->Hget('Userinfo:uid'.$this->mid, 'uname'),'money' => $info['money'])); $this->return['data'] = $data; } else { $this->return['code'] = 1004; $this->return['message'] = L('opera_error'); } $this->goJson($this->return); } /** * 支付宝返回数据 * @return [type] [description] */ public function ali_status() { $info = $_REQUEST; F('alipay', $info); } /** * [支付成功] * @return [type] [description] */ public function orderSuccess() { $orderId = I('post.orderId'); $res = D('mlog')->field('id, uid, money, status')->where('orderId="'.$orderId.'"')->find(); if(!$res['id']) { $this->return['code'] = 1003; $this->return['message'] = L('orderId_null'); $this->goJson($this->return); } if($res['uid'] != $this->mid) { $this->return['code'] = 1004; $this->return['message'] = L('user_error'); $this->goJson($this->return); } if($res['status'] != 1) { $this->return['code'] = 1005; $this->return['message'] = L('orderType_error'); $this->goJson($this->return); } $info['status'] = 2; D('mlog') -> where('id='.$res['id']) -> save($info); $flag = D('umoney') -> where('uid='.$this->mid) -> field('totalmoney, id') -> find(); if($flag['id']) { D('umoney')->where('id='.$flag['id'])->setInc('totalmoney', $res['money']); } else { $info['uid'] = $this->mid; $info['totalmoney'] = $res['money']; D('umoney') -> add($info); } $this->goJson($this->return); } /** * 提现订单 * @return [type] [description] */ public function tixian() { $info['money'] = I('post.money'); $umoney = D('umoney')->field('totalmoney, not_tixian')->where('uid='.$this->mid)->find(); if($info['money'] < 100 || $info['money'] > ($umoney['totalmoney']-$umoney['not_tixian']) ) { $this->return['code'] = 1003; $this->return['message'] = L('money_error'); $this->goJson($this->return); } $map['uid'] = $this->mid; $map['is_del'] = 0; $ali_info = D('userAlipay') -> where($map) -> getField('id'); if(!$ali_info) { $this->return['code'] = 1004; $this->return['message'] = L('ali_info_error'); $this->goJson($this->return); } $info['orderId'] = build_order_no(); $info['ctime'] = time(); $info['type'] = 3; $info['uid'] = $this->mid; $info['note'] = '提现'.$info['money'].'元'; $id = D('mlog')->add($info); D('umoney')->where('uid='.$this->mid)->setInc('not_tixian', $info['money']); $this->return['message'] = L('wait_moment'); $this->goJson($this->return); } }<file_sep><?php namespace Home\Controller; Class PassportController extends BaseController { /** * 登录 * @return {[type]} [description] */ public function login() { $mobile = I('post.mobile'); if(strlen($mobile) != 11) { $this->return['code'] = 1001; $this->return['message'] = L('mobile_error'); $this->goJson($this->return); } $uid = D('userinfo')->getUid($mobile); if(!$uid) { $this->return['code'] = 1002; $this->return['message'] = L('no_register'); $this->goJson($this->return); } $res = $this->redis->HGETALL('Userinfo:uid'.$uid); if(!$res) { $res = D('userinfo')->getUserInfo($uid); $this->redis->HMSET('Userinfo:uid'.$uid, $res); } if(md5(md5(I('post.pwd')).$res['login_salt']) != $res['password']) { $this->return['code'] = 1003; $this->return['message'] = L('login_error'); $this->goJson($this->return); } $res['token'] = $this->create_unique($uid); $this->redis->SETEX('Token:uid'.$uid, 2592000, $res['token']); $tmp['headimg'] = json_decode($this->redis->HGET('Userinfo:uid'.$uid, 'headimg'), true); $tmp['headimg'] = $tmp['headimg'][0]['url']; $return = array('uid'=>$uid, 'token'=>$res['token'], 'voipaccount'=>$res['voipaccount'], 'voippwd'=>$res['voippwd'], 'subaccountid'=>$res['subaccountid'], 'subtoken'=>$res['subtoken'], 'uname'=>$res['uname'], 'mobile'=>$res['mobile'], 'sex'=>$res['sex'],'headimg'=>$tmp['headimg']); $this->redis->SADD('Userinfo:online', $uid); //在线用户列表 if($res['sex'] == 1){ $this->redis->SADD('Userinfo:sex', $uid); //男性用户列表 } $this->redis->SADD('Userinfo:country'.$res['country'], $uid); //用户国籍列表 unset($res); $this->return['data'] = $return; $this->goJson($this->return); } /** * 生成token * @param [type] $uid [description] * @return [type] [description] */ private function create_unique($uid) { $data = $_SERVER['HTTP_USER_AGENT'].$_SERVER['REMOTE_ADDR'].time().rand().$uid; return sha1($data); } /** * 修改密码 * @return [type] [description] */ public function changePwd() { $pwd = I('post.pwd'); $repwd = I('post.repwd'); if($pwd != $repwd || $pwd == '') { $this->return['code'] = 1002; $this->return['message'] = L('pwd_error'); $this->goJson($this->return); } if(!$this->mid) { $mobile = I('post.mobile'); if(strlen($mobile) != 11) { $this->return['code'] = 1001; $this->return['message'] = L('mobile_error'); $this->goJson($this->return); } $uid = D('userinfo')->getUid($mobile); } else { $uid = $this->mid; } $login_salt = $this->redis->HGET('Userinfo:uid'.$uid, 'login_salt'); $info['password'] = md5(md5($pwd).$login_<PASSWORD>); D('userinfo')->where('uid='.$uid)->save($info); $this->redis->HSET('Userinfo:uid'.$uid, 'password', $info['password']); $this->goJson($this->return); } /** * 第三方登录 (step1) * @return [type] [description] */ public function ologin() { $post = I('post.'); if(!$post['unionid']) { $this->return['code'] = 1003; $this->return['message'] = L('unionid null'); $this->goJson($this->return); } if(!$post['access_token']) { $this->return['code'] = 1004; $this->return['message'] = L('access_token null'); $this->goJson($this->return); } if(!$post['type'] || !in_array($post['type'], array('wx', 'wb', 'qq'))) { $this->return['code'] = 1005; $this->return['message'] = L('type error'); $this->goJson($this->return); } $uid = D('userOlogin') -> where('type="'.$post['type'].'" and unionid="'.$post['unionid'].'"') -> getField('uid'); if($uid) { $res = $this->redis->HGETALL('Userinfo:uid'.$uid); if(!$res) { $res = D('userinfo')->getUserInfo($uid); $this->redis->HMSET('Userinfo:uid'.$uid, $res); } if( !$res['uname'] ) { $flag = 1; $this->redis->DEL('Userinfo:uid'.$uid); } } else { $flag = 1; $info['ctime'] = time(); $info['mobile'] = time(); $uid = D('userinfo')->add($info); $post['uid'] = $uid; D('userOlogin')->add($post); } $res['token'] = $this->create_unique($uid); $this->redis->SETEX('Token:uid'.$uid, 2592000, $res['token']); if($flag == 1) { $return = array('uid'=>$uid, 'token'=>$res['token'], 'uname'=>''); } else { $tmp['headimg'] = json_decode($this->redis->HGET('Userinfo:uid'.$uid, 'headimg'), true); $tmp['headimg'] = $tmp['headimg'][0]['url']; $return = array('uid'=>$uid, 'token'=>$res['token'], 'voipaccount'=>$res['voipaccount'], 'voippwd'=>$res['voippwd'], 'subaccountid'=>$res['subaccountid'], 'subtoken'=>$res['subtoken'], 'uname'=>$res['uname'], 'mobile'=>$res['mobile'], 'sex'=>$res['sex'],'headimg'=>$tmp['headimg']); } $this->redis->SADD('Userinfo:online', $uid); //在线用户列表 if($res['sex'] == 1 && $flag != 1){ $this->redis->SADD('Userinfo:sex', $uid); //男性用户列表 $this->redis->SADD('Userinfo:country'.$res['country'], $uid); //用户国籍列表 } unset($res); $this->return['data'] = $return; $this->goJson($this->return); } /** * 退出登录 * @return [type] [description] */ public function logout() { $this->redis->SREM('Userinfo:online', $this->mid); $this->redis->DEL('Token:uid'.$this->mid); $this->goJson($this->return); } } ?><file_sep><?php namespace Home\Model; use Think\Model; class LanguageModel extends Model { /** * 获取全部语言 * @return [type] [description] */ public function getAllLanguage() { $all = F('allLanguage'); if (!$all) { $res = $this->field('lid, language_name')->select(); foreach($res as $v){ $all[ $v['lid'] ] = $v['language_name']; } F('allLanguage', $all); } return $all; } } ?><file_sep><?php namespace Home\Controller; Class ChatController extends BaseController { /** * 开始聊天之前,记录信息 * @return [type] [description] */ public function chatStart() { $post = I('post.'); $post['stime'] = time(); $cid = D('chat')->add($post); $this->return['data']['cid'] = $cid; //将两个用户加入正在聊天中队列 $this->redis->SADD('Userinfo:chating', $post['from_id']); $this->redis->SADD('Userinfo:chating', $post['to_id']); //将对方加入关注表 D('friend')->addUser($post['from_id'], $post['to_id'], 2); D('friend')->addUser($post['to_id'], $post['from_id'], 2); $this->redis->SADD('Userinfo:friend2:'.$post['from_id'], $post['to_id']); $this->redis->SADD('Userinfo:friend2:'.$post['to_id'], $post['from_id']); //将对方加入聊过的列表,然后进行聊天次数累加 $res1 = $this->redis->SADD('Userinfo:spoken'.$post['from_id'], $post['to_id']); if($res1){ D('userinfo')->where('uid='.$post['from_id'])->setInc('spoken_num'); } $res2 = $this->redis->SADD('Userinfo:spoken'.$post['to_id'], $post['from_id']); if($res2){ D('userinfo')->where('uid='.$post['to_id'])->setInc('spoken_num'); } $this->goJson($this->return); } /** * 结束聊天,记录信息 * @return [type] [description] */ public function chatEnd() { $cid = I('post.cid'); //判断该聊天是否已经完成,如完成,直接跳出,不做任何处理 $zetime = D('chat')->where('cid='.$cid)->getField('etime'); if(!$zetime) { $info['etime'] = time(); //保存聊天信息,并将两人从聊天用于队列中删除 $res = D('chat')->field('from_id, to_id, stime, type')->where('cid='.$cid)->find(); D('chat')->where('cid='.$cid)->save($info); $this->redis->SREM('Userinfo:chating', $res['from_id']); $this->redis->SREM('Userinfo:chating', $res['to_id']); $timelong_seconed = ($info['etime']-$res['stime']); // 聊天时长(秒) //将聊天时长分别加入两人信息中 D('userinfo')->where('uid='.$res['from_id'].' or uid='.$res['to_id'])->setInc('spoken_long', $timelong_seconed); //更新redis缓存 $this->redis->HINCRBY('Userinfo:uid'.$res['from_id'], 'spoken_long', $timelong_seconed); $this->redis->HINCRBY('Userinfo:uid'.$res['to_id'], 'spoken_long', $timelong_seconed); $this->redis->HINCRBY('Userinfo:uid'.$res['from_id'], 'spoken_num', 1); $this->redis->HINCRBY('Userinfo:uid'.$res['to_id'], 'spoken_num', 1); //写入得分记录 $timelong = floor($timelong_seconed/60); $score = json_decode($this->redis->GET('score_setting'), true); $score = $res['type'] == 1 ? $score['achat_score'] : $score['vchat_score']; $score_value = $score*$timelong; //分值 D('scoreLog')->saveLog($score_value, array($res['from_id'], $res['to_id']), $res['type']); $this->redis->HINCRBY('Userinfo:uid'.$res['from_id'], 'grow_score', $score_value); $this->redis->HINCRBY('Userinfo:uid'.$res['to_id'], 'grow_score', $score_value); //扣费 $price = $this->redis->HGET('Userinfo:uid'.$res['to_id'], 'price'); $fmoney = D('umoney')->field('id, totalmoney, not_tixian')->where('uid='.$res['from_id'])->find(); if($fmoney['totalmoney'] - $price >= $fmoney['not_tixian']) { D('umoney') -> where('id='.$fmoney['id']) -> setDec('totalmoney', $price); } else { $fmoneyInfo['totalmoney'] = $fmoney['totalmoney'] - $price; $fmoneyInfo['not_tixian'] = $fmoneyInfo['totalmoney'] > 0 ? $fmoneyInfo['totalmoney'] : 0; D('umoney') -> where('id='.$fmoney['id']) -> save($fmoneyInfo); } $mlog['money'] = round(( $price / 60 ) * $timelong_seconed, 2); $mlog['status'] = 2; $mlog['uid'] = $res['from_id']; $mlog['ctime'] = time(); $mlog['type'] = 3; $mlog['note'] = '聊天消费'.$mlog['money'].'元'; $mlog['orderId'] = $cid; D('mlog')->add($mlog); //赚钱计费 D('umoney') -> where('uid='.$res['to_id']) -> setInc('totalmoney', $price); $mlog['uid'] = $res['to_id']; $mlog['orderId'] = $cid; $mlog['type'] = 4; $mlog['note'] = '聊天收入'.$mlog['money'].'元'; D('mlog')->add($mlog); } $this->goJson($this->return); } /** * 评论接口 * @return [type] [description] */ public function comment() { $data['cid'] = I('post.cid'); $res = D('chat')->field('from_id, to_id, comment')->where('cid='.$data['cid'])->find(); if(!$data['cid'] || !is_numeric($data['cid']) || !$res) { $this->return['code'] = 1003; $this->return['message'] = L('cid_error'); $this->goJson($this->return); } $data['from_id'] = $this->mid; if($res['from_id'] != $data['from_id'] && $res['to_id'] != $data['from_id']) { $this->return['code'] = 1004; $this->return['message'] = L('from_id_error'); $this->goJson($this->return); } $data['score'] = intval(I('post.score') ); if(!$data['score'] || $data['score']>5 || $data['score']<1 || !is_numeric($data['score'])) { $this->return['code'] = 1005; $this->return['message'] = L('score_error'); $this->goJson($this->return); } $data['content'] = trim(I('post.content')); if(!$data['content']) { $this->return['code'] = 1006; $this->return['message'] = L('content_null'); $this->goJson($this->return); } $id = D('comment')->where('cid='.$data['cid'].' and from_id='.$data['from_id'])->getField('id'); if($id) { $this->return['code'] = 1007; $this->return['message'] = L('comment_has'); $this->goJson($this->return); } $data['ctime'] = time(); $data['uid'] = $res['from_id'] == $data['from_id'] ? $res['to_id'] : $res['from_id']; if($res['comment'] == 0){ if($res['from_id'] == $data['from_id']) { $info['comment'] = 1; } else { $info['comment'] = 2; } } else { $info['comment'] = 3; } D('comment') -> add($data); D('chat')->where('cid='.$data['cid'])->save($info); //重新计算等级 $level = D('userLanguage')->field('self_level, sys_level')->where('type=4 and uid='.$data['uid'])->find(); if($level) { $levelInfo['sys_level'] = ($level['sys_level']+$data['score'])/2; D('userLanguage')->where('type=4 and uid='.$data['uid'])->save($levelInfo); $userLevel['level'] = ($level['self_level'])/2+$levelInfo['sys_level']; D('userinfo')->where('uid='.$data['uid'])->save($userLevel); $userLevel['level'] = round($userLevel['level']); $this->redis->HSET('Userinfo:uid'.$data['uid'], 'level', $userLevel['level']); } $this->goJson($this->return); } }<file_sep><?php namespace Home\Controller; use Think\Controller; Class BaseController extends Controller { protected $return = array('code'=>0,'message'=>'','data'=>array()); protected $redis = ''; public function _initialize() { import("Common.Util.RedisPool"); $this->redis = \RedisPool::getconnect(); //TODO: 用户登录检测 $not_login = array( 'Index' => array('index'=>1, 'test'=>1), 'Public' => array('getbaselanguage'=>1, 'gettags'=>1), 'Passport' => array('login'=>1, 'changepwd'=>1, 'ologin'=>1), 'User' => array('index'=>1, 'comment'=>1), 'Reg' => array('getmobilecode'=>1, 'register'=>1), 'Square' => array('topic'=>1, 'nearby'=>1, 'topicuser'=>1, 'charts'=>1), 'Ad' => array('getad'=>1), ); if(!$not_login[CONTROLLER_NAME][ACTION_NAME]) { $this->mid = I('post.userId'); $token = I('post.token'); $server_token = $this->redis->GET('Token:uid'.$this->mid); if(!$server_token) { $this->return['code'] = 401; $this->return['message'] = L('token_lose'); $this->goJson($this->return); }elseif($server_token != $token) { $this->return['code'] = 401; $this->return['message'] = L('token_error'); $this->goJson($this->return); } } } /** * 生成json格式并返回 * @param [type] $arr [description] * @return [type] [description] */ protected function goJson( $arr ) { echo json_encode($arr, JSON_UNESCAPED_UNICODE); die(); } } ?> <file_sep><?php namespace Admin\Controller; use User\Api\UserApi; /** * 支付宝log控制器 * @author 麦当苗儿 <<EMAIL>> */ class alipayController extends AdminController { public function log() { $type = I('type'); $uid = I('uid'); if($uid) { $map['uid'] = $uid; } if($type) { $map['type'] = $type; } $list = $this->lists('mlog', $map); foreach($list as &$v){ $v['uname'] = $this->redis->HGET('Userinfo:uid'.$v['uid'], 'uname'); if(!$v['uname']) { A('Home/User')->getUserinfoData($v['uid']); } switch ($v['status']) { case 1: $v['status'] = '未支付'; break; case 2: $v['status'] = '已支付'; break; case 3: $v['status'] = '打款中'; break; case 4: $v['status'] = '系统出错,失败'; break; case 5: $v['status'] = '提现失败,未通过审核'; break; } } switch ($type) { case 1: $page_title = '充值记录'; break; case 2: $page_title = '提现记录'; break; case 3: $page_title = '聊天消费记录'; break; case 4: $page_title = '聊天赚取记录'; break; } $this->assign('page_title', $page_title); $this->assign('_list', $list); $this->meta_title = '用户信息'; $this->display(); } /** * 提现审核列表 * @return [type] [description] */ public function tixian() { $map['type'] = 2; $map['status'] = 1; $list = $this->lists('mlog', $map); foreach($list as &$v){ $v['uname'] = $this->redis->HGET('Userinfo:uid'.$v['uid'], 'uname'); if(!$v['uname']) { A('Home/User')->getUserinfoData($v['uid']); } $v['ctime'] = date('Y-m-d H:i:s', $v['ctime']); $v['smoney'] = round($v['money']*C('ZHEKOU'), 2); $tmp = D('umoney') -> field('totalmoney, not_tixian') -> where('uid='.$v['uid']) -> find(); $v = array_merge($v, $tmp); } $this->assign('_list', $list); $this->meta_title = '提现审核'; $this->display(); } /** * 提现通过审核 * @return [type] [description] */ public function pass() { $id = I('id'); if ($id) { $info = D('mlog')->field('type, orderId, status, money, uid')->where('id='.$id)->find(); //判断是提现模式且未支付 if($info['type'] == 2 && $info['status'] == 1) { $aliInfo = D('userAlipay')->field('ali_num, ali_name')->where('is_del=0 and uid='.$info['uid'])->find(); //判断已绑定支付宝信息 if($aliInfo) { $zzmoney = round($info['money']*C('ZHEKOU'), 2); $zzinfo = $info['orderId'].'^'.$aliInfo['ali_num'].'^'.$aliInfo['ali_name'].'^'.$zzmoney.'^提现'; $res = $this->zhuanzhang($zzmoney, 1, $zzinfo); echo $res; die(); } else { $this->error('支付宝未绑定'); } } } $this->error('参数有误'); } /** * 批量提现 * @return [type] [description] */ public function batch_pass() { $ids = I('id'); if ($ids) { $i = $count_money = 0; $zzinfo = ''; foreach($ids as $id){ if($id) { $info = D('mlog')->field('type, orderId, status, money, uid')->where('id='.$id)->find(); //判断是提现模式且未支付 if($info['type'] == 2 && $info['status'] == 1) { $aliInfo = D('userAlipay')->field('ali_num, ali_name')->where('is_del=0 and uid='.$info['uid'])->find(); //判断已绑定支付宝信息 if($aliInfo) { $zzmoney = round($info['money']*C('ZHEKOU'), 2); $zzinfo .= $info['orderId'].'^'.$aliInfo['ali_num'].'^'.$aliInfo['ali_name'].'^'.$zzmoney.'^语加提现|'; $count_money += $zzmoney; $i++; } } else { continue; } } } $res = $this->zhuanzhang($count_money, $i, rtrim($zzinfo, '|')); echo $res; die(); } $this->error('参数有误'); } /** * 支付宝转账私有方法 * @param [type] $WIDbatch_fee 总金额 * @param [type] $WIDbatch_num 总笔数 * @param [type] $WIDdetail_data 详细信息 * @return [type] [description] */ private function zhuanzhang($batch_fee, $batch_num, $detail_data) { $parameter = array( "service" => "batch_trans_notify", "partner" => C('ALIPAY_PARAM.partner'), "notify_url" => C('WEBSITE_URL').U('Public/notify'), "email" => C('ALIPAY_PARAM.EMAIL'), "account_name" => C('ALIPAY_PARAM.ACCOUNT_NAME'), "pay_date" => date('Ymd'), "batch_no" => date('YmdHis'), "batch_fee" => $batch_fee, "batch_num" => $batch_num, "detail_data" => $detail_data, "_input_charset" => C('ALIPAY_PARAM.input_charset') ); import("Common.Util.AlipaySubmit"); $alipaySubmit = new \AlipaySubmit(C('ALIPAY_PARAM')); $html_text = $alipaySubmit->buildRequestForm($parameter,"get", "确认"); return $html_text; } }<file_sep><?php namespace Home\Controller; Class RegController extends BaseController { /** * 获取短信验证码 * @return [json] 返回代码 * @Auth : zbq 2015.11.04 **/ public function getMobileCode() { $mobile = I('post.mobile'); if(strlen($mobile) != 11) { $this->return['code'] = 1001; $this->return['message'] = L('mobile_error'); $this->return['data']['mobile'] = $mobile; $this->return['data']['len'] = strlen($mobile); $this->goJson($this->return); } $server_token = md5('yj+' . I('post.timestamp') . '<PASSWORD>'); if ( strtolower($server_token) != strtolower(I('post.token')) ) { $this->return['code'] = 1002; $this->return['message'] = L('token_error'); $this->goJson($this->return); } $verify = rand(1000,9999); $datas = array($verify, C('smsTime')); $this->return['data']['verify'] = intval( $verify ); //$mobile = '18601995223'; //获取模板id $mobanId = strtolower(I('post.type')) == 'forgotpwd' ? 50642 : 47024; $this->sendTemplateSMS($mobile, $datas, $mobanId); } /** * 发送短信接口 * @param [type] $to [description] * @param [type] $datas [description] * @param [type] $tempId [description] * @return [type] [description] */ private function sendTemplateSMS($to,$datas,$tempId) { import("Common.Util.CCPRestSmsSDK"); // 初始化REST SDK $rest = new \REST( C('smsServerIP'), C('smsServerPort'), C('smsSoftVersion') ); $rest->setAccount( C('smsAccountSid'), C('smsAccountToken') ); $rest->setAppId( C('smsAppId') ); // 发送模板短信 $result = $rest->sendTemplateSMS($to,$datas,$tempId); if($result == NULL ) { $this->return['code'] = 1003; $this->return['message'] = "result error!"; break; } if($result->statusCode!=0) { $this->return['code'] = intval( $result->statusCode ) ; $this->return['message'] = "error msg :" . $result->statusMsg ; //TODO 添加错误处理逻辑 }else{ // 获取返回信息 $smsmessage = (array) $result->TemplateSMS; $this->return['data']["dateCreated"] = $smsmessage['dateCreated']; $this->return['data']["smsMessageSid"] = $smsmessage['smsMessageSid']; //TODO 添加成功处理逻辑 } $this->goJson($this->return); } /** * 用户注册 */ public function Register ( ) { $post = I('post.'); // 验证手机号 $mobile = I('post.mobile'); if(strlen($mobile) != 11) { $this->return['code'] = 1001; $this->return['message'] = L('mobile_error'); $this->goJson($this->return); } if($this->checkMobile($mobile)) { $this->return['code'] = 1002; $this->return['message'] = L('mobile_has'); $this->goJson($this->return); } // 验证昵称 if(!$post['uname']) { $this->return['code'] = 1003; $this->return['message'] = L('uname_null'); $this->goJson($this->return); } // 验证性别 if($post['sex'] != 1 && $post['sex'] != 2) { $this->return['code'] = 1004; $this->return['message'] = L('sex_error'); $this->goJson($this->return); } load("@.user"); $post['first_letter'] = getFirstLetter($post['uname']); //如果包含中文将中文翻译成拼音 if ( preg_match('/[\x7f-\xff]+/', $post['uname'] ) ){ import("Common.Util.PinYin"); $pinyinClass = new \PinYin(); $pinyin = $pinyinClass->Pinyin( $post['uname'] ); //昵称和呢称拼音保存到搜索字段 $post['search_key'] = $post['uname'].' '.$pinyin; } else { $post['search_key'] = $post['uname']; } // 密码 if(!$post['password']) { $this->return['code'] = 1004; $this->return['message'] = L('pwd_null'); $this->goJson($this->return); } $post['login_salt'] = rand(11111, 99999); $post['password'] = md5(md5($post['password']).$post['login_salt']); $post['ctime'] = time(); $post['level'] = $post['self_level']; $post['cur_language'] = $post['lid']; $uid = D('userinfo')->add($post); if(!$uid) { $this->return['code'] = 1005; $this->return['message'] = L('reg_error'); $this->goJson($this->return); } else { $language_info['uid'] = $uid; $language_info['lid'] = $post['lid']; $language_info['type'] = 4; $language_info['self_level'] = $post['self_level']; D('userLanguage')->add($language_info); /*$location = explode('/', $post['location']); $info = array('uid'=>$uid, 'uname'=>$post['uname'], 'mobile'=>$post['mobile'], 'sex'=>$post['sex'], 'country'=>$post['country'], 'province'=>$post['province'], 'city'=>$post['city'], 'country_name'=>$location[0], 'province_name'=>$location[1], 'city_name'=>$location[2]);*/ $this->redis->Sadd('User:sex'.$post['sex'], $uid); $this->createSubAccount('yujia'.$uid, $uid); $this->goJson($this->return); } } /** * 注册容联子账号 * @param [type] $friendlyName [description] * @return [type] [description] */ private function createSubAccount($friendlyName, $uid) { import("Common.Util.CCPRestSDK"); // 初始化REST SDK $rest = new \REST(C('smsServerIP'), C('smsServerPort'), C('smsSoftVersion')); $rest->setAccount(C('smsAccountSid'), C('smsAccountToken')); $rest->setAppId(C('smsAppId')); $result = $rest->CreateSubAccount($friendlyName); if($result == NULL ) { $this->return['code'] = 1006; $this->return['message'] = L('regSubAccount_error'); $this->goJson($this->return); } if($result->statusCode!=0) { $result = (array) $result; $this->return['code'] = $result['statusCode']; $this->return['message'] = $result['statusMsg']; $this->goJson($this->return); }else { // 获取返回信息 把云平台子帐号信息存储在您的服务器上 $subaccount = (array) $result->SubAccount; $info["subAccountid"] = $subaccount['subAccountSid']; $info["subToken"] = $subaccount['subToken']; $info["dateCreated"] = $subaccount['dateCreated']; $info["voipAccount"] = $subaccount['voipAccount']; $info["voipPwd"] = $subaccount['voipPwd']; D('userinfo')->where('uid='.$uid)->save($info); $this->return['message'] = L('reg_success'); } } /** * 完善第三方登录用户信息 * @return [type] [description] */ public function ologinPrefect() { $post = I('post.'); // 验证手机号 $mobile = I('post.mobile'); if(strlen($mobile) != 11) { $this->return['code'] = 1001; $this->return['message'] = L('mobile_error'); $this->goJson($this->return); } if($this->checkMobile($mobile)) { $this->return['code'] = 1002; $this->return['message'] = L('mobile_has'); $this->goJson($this->return); } // 验证昵称 if(!$post['uname']) { $this->return['code'] = 1003; $this->return['message'] = L('uname_null'); $this->goJson($this->return); } // 验证性别 if($post['sex'] != 1 && $post['sex'] != 2) { $this->return['code'] = 1004; $this->return['message'] = L('sex_error'); $this->goJson($this->return); } load("@.user"); $post['first_letter'] = getFirstLetter($post['uname']); //如果包含中文将中文翻译成拼音 if ( preg_match('/[\x7f-\xff]+/', $post['uname'] ) ){ import("Common.Util.PinYin"); $pinyinClass = new \PinYin(); $pinyin = $pinyinClass->Pinyin( $post['uname'] ); //昵称和呢称拼音保存到搜索字段 $post['search_key'] = $post['uname'].' '.$pinyin; } else { $post['search_key'] = $post['uname']; } // 密码 if(!$post['password']) { $this->return['code'] = 1004; $this->return['message'] = L('pwd_null'); $this->goJson($this->return); } $post['login_salt'] = rand(11111, 99999); $post['password'] = md5(md5($post['password']).$post['login_salt']); $post['ctime'] = time(); $post['level'] = $post['self_level']; $post['cur_language'] = $post['lid']; D('userinfo')->where('uid='.$this->mid)->save($post); $language_info['uid'] = $this->mid; $language_info['lid'] = $post['lid']; $language_info['type'] = 4; $language_info['self_level'] = $post['self_level']; D('userLanguage')->add($language_info); $this->redis->Sadd('User:sex'.$post['sex'], $this->mid); $this->redis->SADD('Userinfo:online', $this->mid); //在线用户列表 $this->createSubAccount('yujia'.$this->mid, $this->mid); $res = D('userinfo')->getUserInfo($this->mid); $this->redis->HMSET('Userinfo:uid'.$this->mid, $res); $res['token'] = I('post.token'); $tmp['headimg'] = json_decode($this->redis->HGET('Userinfo:uid'.$this->mid, 'headimg'), true); $tmp['headimg'] = $tmp['headimg'][0]['url']; $return = array('uid'=>$this->mid, 'token'=>$res['token'], 'voipaccount'=>$res['voipaccount'], 'voippwd'=>$res['voippwd'], 'subaccountid'=>$res['subaccountid'], 'subtoken'=>$res['subtoken'], 'uname'=>$res['uname'], 'mobile'=>$res['mobile'], 'sex'=>$res['sex'],'headimg'=>$tmp['headimg']); $this->return['data'] = $return; $this->goJson($this->return); } /** * 检测手机号是否注册过 * @return [type] [description] */ public function checkMobileUser() { $mobile = I('post.mobile'); if(strlen($mobile) != 11) { $this->return['code'] = 1001; $this->return['message'] = L('mobile_error'); $this->goJson($this->return); } $res = $this->checkMobile($mobile); $this->return['data']['isUser'] = $res ? 1 : 0; $this->goJson($this->return); } /** * 检测手机号是否已经注册过 * @param [type] $mobile 手机号 * @return [type] [description] */ private function checkMobile($mobile) { $uid = D('userinfo')->where('mobile="'.$mobile.'"')->getField('uid'); return $uid; } } ?> <file_sep><?php namespace Home\Model; use Think\Model; class FriendModel extends Model { /** * 添加关注信息 * @param [type] $from_id 关注者id * @param [type] $to_id 被关注者id * @param [type] $type 类型(1.点击按钮关注2.聊天3.聊天+关注) */ public function addUser($from_id, $to_id, $type) { $res = $this->where('from_id='.$from_id.' and to_id='.$to_id)->field('id, type')->select(); if(!$res){ $info['from_id'] = $from_id; $info['to_id'] = $to_id; $info['type'] = $type; $info['ctime'] = time(); $this->add($info); }else { if($res['type'] != 3 && $res['type'] != $type) { $info['type'] = 3; $this->where('id='.$res['id'])->save($info); } } return $info['type']; } /** * 获取用户列表 * @param [type] $map [description] * @return [type] [description] */ public function getFriend($map) { $res = $this->field('to_id')->where($map)->order('id desc')->select(); return $res; } }<file_sep><?php /** * 用户个人中心 (资料修改及编辑) */ namespace Home\Controller; Class UserController extends BaseController { //用户个人主页 public function index() { $uid = I('post.uid'); $res = $this->getUserinfoData($uid); //是否已关注 if($this->mid != $uid) { $friendtype = D('friend')->where('from_id='.$this->mid.' and to_id='.$uid)->getField('type'); $res['friendflag'] = in_array($friendtype, array(1, 3)) ? 1 : 0; } else { $res['friendflag'] = 1; } //瞬间 $res['shunjian']['totalCount'] = D('shunjian')->where('uid='.$uid)->count(); $shunjianlist = D('shunjian')->field('url, type, cover')->where('uid='.$uid)->order('rid desc')->limit(6)->select(); if($shunjianlist) { foreach ($shunjianlist as $key => $value) { $shunjianlist[$key]['url'] = C('WEBSITE_URL').$value['url']; if($value['cover']) { $shunjianlist[$key]['cover'] = C('WEBSITE_URL').$value['cover']; } } $res['shunjian']['datalist'] = $shunjianlist; } //粉丝 $res['follow']['totalCount'] = D('friend')->where('to_id='.$uid)->count(); $followlist = D('friend')->field('from_id')->where('to_id='.$uid)->order('id desc')->limit(10)->select(); if($followlist) { foreach ($followlist as $v) { $tmp['uid'] = $v['from_id']; if(!$this->redis->HLEN('Userinfo:uid'.$tmp['uid'])) { $this->getUserinfoData($tmp['uid']); } $tmp['headimg'] = json_decode($this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'headimg'), true); $tmp['headimg'] = $tmp['headimg'][0]['url']; $res['follow']['datalist'][] = $tmp; } } //评论 $res['comment']['totalCount'] = D('comment')->where('uid='.$uid)->count(); $commentlist = D('comment')->field('ctime, from_id, content')->where('uid='.$uid)->order('id desc')->limit(10)->select(); if($commentlist) { foreach ($commentlist as $k=>$v) { unset($tmp); $tmp['uid'] = $v['from_id']; $tmp['ctime'] = $v['ctime']; $tmp['content'] = $v['content']; if(!$this->redis->HLEN('Userinfo:uid'.$tmp['uid'])) { $this->getUserinfoData($tmp['uid']); } $tmp['headimg'] = json_decode($this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'headimg'), true); $tmp['headimg'] = $tmp['headimg'][0]['url']; $tmp['uname'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'uname'); $location = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'location'); $location = explode('/', $location); $tmp['location'] = $location[0].' '.$location[1]; $res['comment']['datalist'][] = $tmp; } } $tmp_location = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'location'); $tmp_location = explode('/', $tmp_location); $res['country'] = $tmp_location[0]; $res['voipaccount'] = $res['voipAccount'] ? $res['voipAccount'] : $res['voipaccount']; unset($res['voippwd'], $res['subaccountid'], $res['subtoken'], $res['province'], $res['city'], $res['location'], $res['first_letter'], $res['voipAccount']); $this->return['data'] = $res; $this->goJson($this->return); } /** * 通过voip获取用户信息 * @return [type] [description] */ public function voipToInfo() { $voipaccount = I('post.voipaccount'); if($voipaccount) { $tmp['uid'] = D('userinfo')->where('voipAccount="'.$voipaccount.'"')->getField('uid'); } if(!$voipaccount || !$tmp['uid']) { $this->return['code'] = 1003; $this->return['message'] = L('param_error'); $this->goJson($this->return); } if(!$this->redis->HLEN('Userinfo:uid'.$tmp['uid'])) { $this->getUserinfoData($tmp['uid']); } $tmp['uname'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'uname'); $tmp['price'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'price'); $location = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'location'); $location = explode('/', $location); $tmp['location'] = $location[0].' '.$location[1]; $tmp['language'] = json_decode($this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'language'), true); $tmp['tags'] = json_decode($this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'tags'), true); $tmp['level'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'level'); $tmp['headimg'] = json_decode($this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'headimg'), true); $tmp['headimg'] = $tmp['headimg'][0]['url']; $tmp['intro'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'intro'); //$tmp['first_letter'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'first_letter'); //$tmp['voipaccount'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'voipaccount'); $tmp['sex'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'sex'); $this->return['data'] = $tmp; $this->goJson($this->return); } /** * 获取瞬间 分页 * @return [type] [description] */ public function shunjian() { $shunjian['index'] = I('post.index') ? I('post.index') : 1; $shunjian['pageSize'] = I('post.pageSize') ? I('post.pageSize') : 6; $uid = I('post.uid'); if(!$uid) { $this->return['code'] = 1003; $this->return['message'] = L('param_error'); $this->goJson($this->return); } $start = ($shunjian['index']-1)*$shunjian['pageSize']; $shunjian['totalCount'] = D('shunjian')->where('uid='.$uid)->count(); $shunjianlist = D('shunjian')->field('url, type, cover')->where('uid='.$uid)->order('rid desc')->limit($start, $shuanjian['pageSize'])->select(); if($shunjianlist) { foreach ($shunjianlist as $key => $value) { $shunjianlist[$key]['url'] = C('WEBSITE_URL').$value['url']; if($value['cover']) { $shunjianlist[$key]['cover'] = C('WEBSITE_URL').$value['cover']; } } $shunjian['datalist'] = $shunjianlist; } $this->return['data'] = $shunjian; $this->goJson($this->return); } /** * 获取评论列表 分页 * @return [type] [description] */ public function comment() { $comment['index'] = I('post.index') ? I('post.index') : 1; $comment['pageSize'] = I('post.pageSize') ? I('post.pageSize') : 10; $uid = I('post.uid'); if(!$uid) { $this->return['code'] = 1003; $this->return['message'] = L('param_error'); $this->goJson($this->return); } $start = ($comment['index']-1)*$comment['pageSize']; $comment['totalCount'] = D('comment')->where('uid='.$uid)->count(); $commentlist = D('comment')->field('ctime, from_id, content')->where('uid='.$uid)->order('id desc')->limit($start, $comment['pageSize'])->select(); if($commentlist) { foreach ($commentlist as $k=>$v) { unset($tmp); $tmp['uid'] = $v['from_id']; $tmp['ctime'] = $v['ctime']; $tmp['content'] = $v['content']; if(!$this->redis->HLEN('Userinfo:uid'.$tmp['uid'])) { $this->getUserinfoData($tmp['uid']); } $tmp['headimg'] = json_decode($this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'headimg'), true); $tmp['headimg'] = $tmp['headimg'][0]['url']; $tmp['uname'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'uname'); $location = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'location'); $location = explode('/', $location); $tmp['location'] = $location[0].' '.$location[1]; $comment['datalist'][] = $tmp; } } $this->return['data'] = $comment; $this->goJson($this->return); } /** * 获取粉丝列表 分页 * @return [type] [description] */ public function followlist(){ $follow['index'] = I('post.index') ? I('post.index') : 1; $follow['pageSize'] = I('post.pageSize') ? I('post.pageSize') : 10; $uid = I('post.uid'); if(!$uid) { $this->return['code'] = 1003; $this->return['message'] = L('param_error'); $this->goJson($this->return); } $start = ($follow['index']-1)*$follow['pageSize']; $follow['totalCount'] = D('friend')->where('to_id='.$uid)->count(); $followlist = D('friend')->field('from_id')->where('to_id='.$uid)->order('id desc')->limit(10)->select(); if($followlist) { foreach ($followlist as $v) { $tmp['uid'] = $v['from_id']; if(!$this->redis->HLEN('Userinfo:uid'.$tmp['uid'])) { A('Home/User')->getUserinfoData($tmp['uid']); } $tmp['uname'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'uname'); $tmp['price'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'price'); $location = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'location'); $location = explode('/', $location); $tmp['location'] = $location[0].' '.$location[1]; $tmp['language'] = json_decode($this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'language'), true); $tmp['tags'] = json_decode($this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'tags'), true); $tmp['level'] = intval($this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'level')); $tmp['headimg'] = json_decode($this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'headimg'), true); $tmp['headimg'] = $tmp['headimg'][0]['url']; $tmp['intro'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'intro'); $follow['datalist'][] = $tmp; } } $this->return['data'] = $follow; $this->goJson($this->return); } /** * 获取用户数据Api * @return [type] [description] */ public function getUserinfo() { $uid = I('post.uid'); $res = $this->getUserinfoData($uid); $res['followCount'] = D('friend')->where('to_id='.$uid)->count(); $this->return['data'] = $res; $this->goJson($this->return); } /** * 保存用户信息 * @return [type] [description] */ public function saveInfo() { $post = I('post.'); $o_info = $this->redis->HGETALL('Userinfo:uid'.$this->mid); $info = array(); //头像 $o_headimg = json_decode($o_info['headimg'], true) ? json_decode($o_info['headimg'], true) : array(); $o_headimg_ids = getSubByKey($o_headimg, 'rid'); $o_headimg_str = $o_headimg_ids ? implode(',', $o_headimg_ids) : ''; if($o_headimg_str != trim($post['headimg'],',') && isset($post['headimg']) ) { $info['headimg'] = trim($post['headimg'],','); $headimg_arr = explode(',', $info['headimg']); foreach($headimg_arr as $v) { $photo_res = array(); $photo_res['rid'] = $v; $photo_res['url'] = C('WEBSITE_URL').D('picture')->where('id='.$v)->getField('path'); $photo[] = $photo_res; } $this->redis->HSET('Userinfo:uid'.$this->mid, 'headimg', json_encode($photo, JSON_UNESCAPED_UNICODE)); $new_photo = explode(',', trim($post['headimg'], ',')) ? explode(',', trim($post['headimg'], ',')) : array(); $o_headimg_ids = $o_headimg_ids ? $o_headimg_ids : array(); $add_photo = array_diff($new_photo, $o_headimg_ids); if($add_photo){ $sj_log['uid'] = $this->mid; $sj_log['type'] = 1; foreach($add_photo as $v){ $sj_log['url'] = D('picture')->where('id='.$v)->getField('path'); D('shunjian')->add($sj_log); } } } //昵称 if ($post['uname'] != $o_info['uname'] && isset($post['uname'])) { if($post['uname'] == ''){ $this->return['code'] == 1004; $this->return['message'] == L('uname_null'); $this->goJson($this->return); } $info['uname'] = $post['uname']; load("@.user"); $info['first_letter'] = getFirstLetter($post['uname']); //如果包含中文将中文翻译成拼音 if ( preg_match('/[\x7f-\xff]+/', $post['uname'] ) ){ import("Common.Util.PinYin"); $pinyinClass = new \PinYin(); $pinyin = $pinyinClass->Pinyin( $post['uname'] ); //昵称和呢称拼音保存到搜索字段 $info['search_key'] = $post['uname'].' '.$pinyin; } else { $info['search_key'] = $post['uname']; } } // 性别 if ($post['sex'] != $o_info['sex'] && isset($post['sex'])) { if($post['sex'] != 1 && $post['sex'] != 2) { $this->return['code'] == 1003; $this->return['message'] == L('sex_error'); $this->goJson($this->return); } $info['sex'] = $post['sex']; $sex_flag = $post['sex'] == 1 ? 2 : 1; $this->redis->sRem('User:sex'.$sex_flag,$this->mid); $this->redis->sAdd('User:sex'.$info['sex'],$this->mid); } // 个性签名 if ($post['intro'] != $o_info['intro'] && isset($post['intro'])) { $info['intro'] = $post['intro']; } // 视频介绍 $o_info['video_profile'] = json_decode($o_info['video_profile'], true) ? json_decode($o_info['video_profile'], true) : array(); if ($post['video_profile'] != $o_info['video_profile']['rid'] && isset($post['video_profile'])) { $info['video_profile'] = $post['video_profile']; $video = D('file')->field('savepath, savename')->where('id='.$post['video_profile'])->find(); $video_profile['rid'] = $post['video_profile']; $video_profile['url'] = C('WEBSITE_URL').'/Uploads/File/'.$video['savepath'].$video['savename']; $this->redis->HSET('Userinfo:uid'.$this->mid, 'video_profile', json_encode($video_profile, JSON_UNESCAPED_UNICODE)); $video_profile_data['type'] = 2; $video_profile_data['url'] = '/Uploads/File/'.$video['savepath'].$video['savename']; $video_profile_data['uid'] = $this->mid; D('shunjian')->add($video_profile_data); unset($video_profile_data); } // 音频介绍 $o_info['audio_profile'] = json_decode($o_info['audio_profile'], true) ? json_decode($o_info['audio_profile'], true) : array(); if ($post['audio_profile'] != $o_info['audio_profile']['rid'] && $post['audio_profile']) { $info['audio_profile'] = $post['audio_profile']; $audio = D('file')->field('savepath, savename')->where('id='.$post['audio_profile'])->find(); $audio_profile['rid'] = $post['audio_profile']; $audio_profile['url'] = C('WEBSITE_URL').'/Uploads/File/'.$audio['savepath'].$audio['savename']; $this->redis->HSET('Userinfo:uid'.$this->mid, 'audio_profile', json_encode($audio_profile, JSON_UNESCAPED_UNICODE)); } // 国家,省,城市信息 if(isset($post['country']) && $post['country'] != 0){ if ($post['country'] != $o_info['country'] ) { $info['country'] = $post['country']; $info['province'] = $post['province']; $info['city'] = $post['city']; $info['location'] = $post['location']; } elseif ($post['province'] != $o_info['province'] && isset($post['province'])) { $info['province'] = $post['province']; $info['city'] = $post['city']; $info['location'] = $post['location']; } elseif ($post['city'] != $o_info['city'] && isset($post['city'])) { $info['city'] = $post['city']; $info['location'] = $post['location']; } } //语言 更改 $o_language = json_decode($o_info['language'], true) ? json_decode($o_info['language'], true) : array(); if($post['language']['lid'] != $o_language['lid'] && isset($post['language']['lid'])) { $info['cur_language'] = $language['lid'] = $post['language']['lid']; } if($post['language']['self_level'] != $o_language['self_level'] && isset($post['language']['self_level'])) $info['level'] = $language['self_level'] = $post['language']['self_level']; if(count($language)) { D('userLanguage')->where('uid='.$this->mid)->save($language); $language = D('userLanguage')->where('uid='.$this->mid)->field('lid, type, sys_level, self_level')->select(); $allLanguage = D('language')->getAllLanguage(); foreach($language as $k=>$v){ $language[$k]['language_name'] = $allLanguage[ $v['lid'] ]; } $this->redis->HSET('Userinfo:uid'.$this->mid, 'language', json_encode($language, JSON_UNESCAPED_UNICODE)); } if(count($info)){ D('userinfo')->where('uid='.$this->mid)->save($info); unset($info['video_profile'], $info['headimg'], $info['audio_profile']); foreach($info as $k=>$v) { $this->redis->HSET('Userinfo:uid'.$this->mid ,$k ,$v); } } //标签 if(isset($post['tags'])){ $o_tags = json_decode($o_info['tags']) ? json_decode($o_info['tags'], true) : array(); $o_tag_ids = getSubByKey($o_tags, 'tid'); $tags_post = explode(',', $post['tags']); if(!count($tags_post)){ D('userTags')->where('uid='.$this->mid)->delete(); } else { $tags['uid'] = $this->mid; //有新增标签 $add_tags = array_diff($tags_post, $o_tag_ids); if(count($add_tags)) { foreach($add_tags as $v) { $tags['tid'] = $v; D('userTags')->add($tags); } } //有删除标签 $delete_tags = array_diff($o_tag_ids, $tags_post); if(count($delete_tags)) { foreach($delete_tags as $v) { D('userTags')->where('uid='.$this->mid.' and tid='.$v)->delete(); } } //如果有变化,取出该用户全部标签进行缓存 if(count($delete_tags) || count($add_tags)) { $allTags = D('tags')->getAllTags(); $tags_res = D('userTags')->field('tid')->where('uid='.$this->mid)->select(); foreach($tags_res as $k=>$val) { $tags_res[$k]['tag_name'] = $allTags[ $val['tid'] ]; } $this->redis->HSET('Userinfo:uid'.$this->mid, 'tags', json_encode($tags_res, JSON_UNESCAPED_UNICODE)); } } } //$this->return['data'] = $this->getUserinfoData($this->mid); $this->goJson($this->return); } /** * 加关注 * @return [type] [description] */ public function friend() { $uid = I('post.uid'); if($this->mid == $uid) { $this->return['code'] = 1003; $this->return['message'] = L('follow_me'); $this->goJson($this->return); } D('friend')->addUser($this->mid, $uid, 1); $this->redis->SADD('Userinfo:friend1:'.$this->mid, $uid); $this->goJson($this->return); } /** * 取消关注接口 * @return [type] [description] */ public function unFriend() { $uid = I('post.uid'); if($this->mid == $uid) { $this->return['code'] = 1003; $this->return['message'] = L('unfollow_me'); $this->goJson($this->return); } $res = D('friend')->field('id, type')->where('from_id='.$this->mid.' and to_id='.$uid)->find(); if($res['type'] == 3) { $info['type'] = 2; D('friend') -> where('id='.$res['id'])->save($info); $this->redis->sRem('Userinfo:friend1:'.$this->mid,$uid); } elseif($res['type'] == 1) { D('friend')->where('id='.$res['id']) ->delete(); $this->redis->sRem('Userinfo:friend1:'.$this->mid,$uid); } else { $this->return['code'] = 1004; $this->return['message'] = L('param_error'); $this->goJson($this->return); } $this->goJson($this->return); } /** * 关注用户列表 * @return [type] [description] */ public function friendList() { $data['index'] = I('post.index') ? I('post.index') : 1; $ftype = I('post.type') == 1 ? 1 : 2; //1为关注的人,2为聊天过的人 $data['pageSize'] = I('post.pageSize') ? I('post.pageSize') : 10; $follow = $this->redis->sMembers('Userinfo:friend'.$ftype.':'.$this->mid); rsort($follow); if (!count($follow)) { $map['from_id'] = array('eq',$this->mid); $uArray = array(3); $uArray[] = $ftype; $map['type'] = array('in', $uArray); $res = D('friend')->getFriend($map); foreach($res as $v){ $follow[] = $v['to_id']; $this->redis->SADD('Userinfo:friend'.$ftype.':'.$this->mid, $v['to_id']); } } $start = ($data['index']-1)*$data['pageSize']; $end = $data['pageSize']*$data['index']; for($start; $start<$end; $start++){ if (!$follow[$start]) { break; } else { $tmp['uid'] = $follow[$start]; if(!$this->redis->HLEN('Userinfo:uid'.$tmp['uid'])) { $this->getUserinfoData($tmp['uid']); } $tmp['uname'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'uname'); $tmp['price'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'price'); $location = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'location'); $location = explode('/', $location); $tmp['location'] = $location[0].' '.$location[1]; $tmp['language'] = json_decode($this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'language'), true); $tmp['tags'] = json_decode($this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'tags'), true); $tmp['level'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'level'); $tmp['headimg'] = json_decode($this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'headimg'), true); $tmp['headimg'] = $tmp['headimg'][0]['url']; $tmp['intro'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'intro'); $tmp['first_letter'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'first_letter'); $tmp['voipaccount'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'voipaccount'); $tmp['sex'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'sex'); $data['datalist'][] = $tmp; } } $data['totalCount'] = count($follow); $this->return['data'] = $data; $this->goJson($this->return); } /** * 获取用户数据(不含password) * @param [int] $uid [description] * @return [array] [description] */ public function getUserinfoData($uid) { $res = $this->redis->HGETALL('Userinfo:uid'.$uid); if(!$res) { $res = D('userinfo')->getUserInfo($uid); $res['voipaccount'] = $res['voipAccount']; unset($res['voipAccount']); if($res['sex'] == 1 || $res['sex'] == 2){ $this->redis->Sadd('User:sex'.$res['sex'], $uid); } $this->redis->HMSET('Userinfo:uid'.$uid, $res); } $res['tags'] = json_decode($res['tags'], true); $res['language'] = json_decode($res['language'], true); $res['headimg'] = json_decode($res['headimg'], true); $res['video_profile'] = (object) json_decode($res['video_profile']); $res['audio_profile'] = (object) json_decode($res['audio_profile']); unset($res['password'], $res['pwd'], $res['search_key'], $res['login_salt'], $res['datecreated'], $res['lati'], $res['longi'], $res['level'], $res['cur_language']); return $res; } /** * 用户成长值 * @return [type] [description] */ public function userScore() { $data['totalScore'] = $this->redis->HGET('Userinfo:uid'.$this->mid, 'grow_score'); $data['index'] = I('post.index') ? I('post.index') : 1; $data['pageSize'] = I('post.pageSize') ? I('post.pageSize') : 10; $start = ($data['index']-1)*$data['pageSize']; $data['totalCount'] = D('scoreLog')->where('uid='.$this->mid)->count('id'); $res = D('scoreLog')->field('ctime, type, score, info')->where('uid='.$this->mid)->order('id desc')->limit($start, $data['pageSize'])->select(); foreach($res as $k=>$v) { $res[$k]['score'] = $v['score'] > 0 ? '+'.$v['score'] : $v['score']; } $data['datalist'] = $res; $this->return['data'] = $data; $this->goJson($this->return); } /** * 充值取现记录 * @return [type] [description] */ public function mlog() { //账户余额 $data = D('umoney')->field('totalmoney, not_tixian')->where('uid='.$this->mid)->find(); $data['totalmoney'] = $data['totalmoney'] ? $data['totalmoney'] : 0; $data['not_tixian'] = $data['not_tixian'] ? $data['not_tixian'] : 0; $data['can_use'] = $data['totalmoney']-$data['not_tixian']; //取现,充值记录 $wheretype = ''; if( I('post.type') ) { $wheretype = ' and type ='.I('post.type'); } $data['index'] = I('post.index') ? I('post.index') : 1; $data['pageSize'] = I('post.pageSize') ? I('post.pageSize') : 10; $start = ($data['index']-1)*$data['pageSize']; $data['totalCount'] = D('mlog')->where('status=2 and uid='.$this->mid.$wheretype)->count('id'); $res = D('mlog')->field('money, ctime, note, type')->where('status=2 and uid='.$this->mid.$wheretype )->order('id desc')->limit($start, $data['pageSize'])->select(); $data['datalist'] = $res; $this->return['data'] = $data; $this->goJson($this->return); } /** * 意见反馈内容 * @return [type] [description] */ public function suggest() { $data['content'] = I('post.content'); if($data['content'] == '') { $this->return['code'] = 1003; $this->return['message'] = L('suggest_null'); $this->goJson($this->return); } $data['uid'] = $this->mid; $data['ctime'] = time(); D('suggest')->add($data); $this->goJson($this->return); } }<file_sep><?php /** * LBS核心类 * @author name <<EMAIL>> */ class LBS { //索引长度 6位 protected $index_len = 6; protected $redis; protected $geohash; public function __construct($redis, $geohash) { //redis $this->redis = $redis; //geohash $this->geohash = $geohash; } /** * 更新用户信息 * @param mixed $latitude 纬度 * @param mixed $longitude 经度 */ public function upinfo($user_id,$latitude,$longitude) { //原数据处理 //获取原Geohash $o_hashdata = $this->redis->hGet($user_id,'geo'); if (!empty($o_hashdata)) { //原索引 $o_index_key = substr($o_hashdata, 0, $this->index_len); //删除 $this->redis->sRem($o_index_key,$user_id); } //新数据处理 //纬度 $this->redis->hSet('Position:uid'.$user_id,'lati',$latitude); //经度 $this->redis->hSet('Position:uid'.$user_id,'longi',$longitude); $this->redis->hSet('Position:uid'.$user_id, 'ctime', time()); //Geohash $hashdata = $this->geohash->encode($latitude,$longitude); $this->redis->hSet('Position:uid'.$user_id,'geo',$hashdata); //索引 $index_key = substr($hashdata, 0, $this->index_len); //存入 //dump($index_key); $this->redis->sAdd($index_key,$user_id); return true; } /** * 获取附近用户 * @param mixed $latitude 纬度 * @param mixed $longitude 经度 */ public function serach($latitude,$longitude) { //Geohash $hashdata = $this->geohash->encode($latitude,$longitude); //索引 $index_key = substr($hashdata, 0, $this->index_len); //取得 $user_id_array = $this->redis->sMembers($index_key); //取出周边8个区块 $neighbors = $this->geohash->neighbors($index_key); foreach($neighbors as $v){ $tmp_user = $this->redis->sMembers($v) ? $this->redis->sMembers($v) : array(); $user_id_array = array_merge($user_id_array, $tmp_user); } return $user_id_array; } } ?><file_sep><?php namespace Home\Model; use Think\Model; class ScoreLogModel extends Model { /** * 记录信息 * @param [type] $score 分值 * @param [type] $userList 用户列表 * @param [type] $type 加分类型(1语音聊天2视频聊天) * @param integer $cid 聊天id * @return [type] [description] */ public function saveLog($score, $userList, $type, $cid=0) { $typeArr = array(1=>'语音聊天', 2=>'视频聊天'); $zheng = array(1,2); $flag = in_array($type, $zheng) ? 1 : 2; $info['score'] = $flag == 1 ? $score : '-'.$score; $info['type'] = $type; $info['cid'] = $cid; $info['ctime'] = time(); $info['info'] = $typeArr[$type]; foreach($userList as $v) { $info['uid'] = $v; $this->save($info); if($flag == 1) { D('userinfo') -> where('uid='.$v)->setInc('grow_score', $score); } else { D('userinfo') -> where('uid='.$v)->setDec('grow_score', $score); } } } } ?><file_sep><?php namespace Home\Model; use Think\Model; class UserinfoModel extends Model { protected $redis = ''; public function _initialize() { import("Common.Util.RedisPool"); $this->redis = \RedisPool::getconnect(); } /** * 获取uid * @param [string] $mobile 手机号 * @return [string] uid */ public function getUid($mobile) { $uid = $this->where('mobile="'.$mobile.'"')->getField('uid'); return $uid; } /** * 获取用户信息 * @param [int] $uid 用户id * @return [array] 用户信息 */ public function getUserInfo($uid) { $res = $this->where('uid='.$uid)->find(); //音频介绍介绍 if($res['audio_profile']) { $audio_profile['rid'] = $res['audio_profile']; $audio = D('file')->field('savepath, savename')->where('id='.$res['audio_profile'])->find(); $audio_profile['url'] = C('WEBSITE_URL').'/Uploads/File/'.$audio['savepath'].$audio['savename']; } else { $audio_profile = array(); } $res['audio_profile'] = json_encode($audio_profile, JSON_UNESCAPED_UNICODE); //视频介绍地址 if($res['video_profile']) { $video_profile['rid'] = $res['video_profile']; $video = D('file')->field('savepath, savename')->where('id='.$res['video_profile'])->find(); $video_profile['url'] = C('WEBSITE_URL').'/Uploads/File/'.$video['savepath'].$video['savename']; }else{ $video_profile = array(); } $res['video_profile'] = json_encode($video_profile, JSON_UNESCAPED_UNICODE); //头像原图 if($res['headimg']) { $photo_arr = explode(',', $res['headimg']); foreach($photo_arr as $v) { $photo_res = array(); $photo_res['rid'] = $v; $photo_res['url'] = C('WEBSITE_URL').(D('picture')->where('id='.$v)->getField('path')); $photo[] = $photo_res; } }else{ $photo = array(); } $res['headimg'] = json_encode($photo, JSON_UNESCAPED_UNICODE); //用户语言 $res['language'] = D('userLanguage')->field('lid, type, self_level, sys_level')->where('uid='.$uid)->select(); if($res['language']) { $allLanguage = D('language')->getAllLanguage(); foreach($res['language'] as $k=>$v) { $res['language'][$k]['language_name'] = $allLanguage[ $v['lid'] ]; } }else{ $res['language'] = array(); } $res['language'] = json_encode($res['language'], JSON_UNESCAPED_UNICODE); //用户标签 $usertags = D('userTags')->field('tid')->where('uid='.$uid)->select(); if($usertags){ $allTags = D('tags')->getAllTags(); foreach($usertags as $k=>$v){ $usertags[$k]['tag_name'] = $allTags[$v['tid']]; } } else { $usertags = array(); } $res['tags'] = json_encode($usertags, JSON_UNESCAPED_UNICODE); $res['level'] = round($res['level']); return $res; } /** * 搜索用户 * @return [type] [description] */ public function getSearchList($uid, $field = '*', $search = '', $whereRand = '') { $where = $join = ''; //昵称筛选 if ($search['uname']) { $where .= ' u.search_key like "%'.$search['uname'].'%" and'; } //性别筛选 if ($search['sex']) { $where .= ' u.sex='.I($search['sex']).' and'; } //等级筛选 if ($search['min_level']) { $where .= ' u.level >='.$search['min_level'].' and'; } if ($search['max_level']) { $where .= ' u.level <='.$search['max_level'].' and'; } //地区筛选 if ($search['city']) { $where .= ' u.city = '.$search['city'].' and'; } elseif ($search['province']) { $where .= ' u.province ='.$search['province'].' and'; } elseif ($search['country']) { $where .= ' u.country ='.$search['country'].' and'; } //语言筛选 if ($search['lid']) { $where .= ' u.cur_language='.$search['lid'].' and'; } //时长筛选 if ($search['time']) { $where .= ' u.spoken_long >='.$search['time'].' and'; } //付费筛选 if ($search['price']) { $where .= ' u.price >= 0.1 and'; } //音频视频筛选 if ($search['intro'] == 1) { $where .= ' u.audio_profile != 0 and'; } elseif ($search['intro'] == 2) { $where .= ' u.video_profile != 0 and'; } //标签搜索 if ($search['tid']) { $where .= ' ut.tid = '.$search['tid'].' and'; $join .= '__USER_TAGS__ as ut ON u.uid = ut.uid'; } //范围搜索 if ($search['range'] == 'yuban') { if(isset($search['isfriend'])) { if($search['isfriend']) { $map['from_id'] = array('eq',$uid); $map['type'] = array('eq', 3); } else { $map['from_id'] = array('eq',$uid); $map['type'] = array('eq', 2); } $res = D('friend')->getFriend($map); foreach($res as $v){ $follow[] = $v['to_id']; } } else { $follow = $this->redis->sMembers('Userinfo:friend2:'.$uid); if (!count($follow)) { $map['from_id'] = array('eq',$uid); $map['type'] = array('in', array(2,3)); $res = D('friend')->getFriend($map); foreach($res as $v){ $follow[] = $v['to_id']; $this->redis->SADD('Userinfo:friend2:'.$uid, $v['to_id']); } } } $uids = join(',', $follow); $where .= ' u.uid in ("'.$uids.'") and'; } else { $follow = $this->redis->sMembers('Userinfo:friend1:'.$uid); if (!count($follow)) { $map['from_id'] = array('eq',$uid); $map['type'] = array('in', array(1,3)); $res = D('friend')->getFriend($map); foreach($res as $v){ $follow[] = $v['to_id']; $this->redis->SADD('Userinfo:friend1:'.$uid, $v['to_id']); } } $uids = join(',', $follow); $where .= ' u.uid not in ("'.$uids.'") and'; } $where .= ' u.uname != "" and u.uid != '.$uid.$whereRand ; if($search['pageSize']) { $data['index'] = $search['index'] ? $search['index'] : 1; $data['pageSize'] = $search['pageSize']; $start = ($data['index']-1)*$data['pageSize']; $limit = $start.','.$data['pageSize']; } else { $limit = 0; } $data['totalCount'] = M('userinfo as u')->where($where)->count('u.uid'); $data['ulist'] = M('userinfo as u')->join($join)->field($field)->where($where)->limit($limit)->select(); if($search['index']) { $data['index'] = $search['index']; $data['pageSize'] = $search['pageSize']; } //dump(M('userinfo as u')->getLastSql()); return $data; } } ?><file_sep><?php /** * 广场功能 (发现) * Auth: zbq */ namespace Home\Controller; Class SquareController extends BaseController { /** * 附近的人 * @return [type] [description] */ public function nearBy() { $data['lati'] = I('post.lati'); $data['longi'] = I('post.longi'); if(!$data['lati'] || !$data['longi']) { $this->return['code'] = 1003; $this->return['message'] = L('latng_error'); } $data['ctime'] = time(); $data['uid'] = $this->mid; D('userPosition')->add($data); import("Common.Util.LBS"); import("Common.Util.Geohash"); $geohash = new \Geohash(); $this->lbs = new \LBS($this->redis, $geohash); $this->lbs->upinfo($this->mid, $data['lati'], $data['longi'] ); $re = $this->lbs->serach($data['lati'],$data['longi']); $stime = time()-7200; //两小时过期,时间早于该时刻的都不算 //取出全部语言 $allLanguage = D('language')->getAllLanguage(); $data = array(); //取出基础信息和算出实际距离 foreach($re as $key=>$val) { $tmp_userinfo = array(); if($val == $this->mid) { continue; } $zposition = $this->redis->HGETALL('Position:uid'.$val); if($zposition['ctime'] < $stime) { continue; } // $distance = getDistance($lati, $longi, $tmp_userinfo['lati'], $tmp_userinfo['longi']); //基础信息 $tmp_userinfo = $this->redis->HGETALL('Userinfo:uid'.$val); $data['uid'] = $val; $data['uname'] = $tmp_userinfo['uname']; $data['sex'] = $tmp_userinfo['sex']; $tmp['headimg'] = json_decode($this->redis->HGET('Userinfo:uid'.$val, 'headimg'), true); $data['headimg_src'] = $tmp['headimg'][0]['url']; $data['lname'] = $allLanguage[$tmp_userinfo['cur_language']]; $data['level'] = $tmp_userinfo['level']; $data['intro'] = $tmp_userinfo['intro']; $data['price'] = $tmp_userinfo['price']; $data['location']['lati'] = $zposition['lati']; $data['location']['longi'] = $zposition['longi']; //距离米 // $data[$key]['distance'] = $distance; //排序列 // $sortdistance[$key] = $distance; $this->return['data']['list'][] = $data; } //距离排序 // array_multisort($sortdistance,SORT_ASC,$data); $this->goJson($this->return); } /** * 搜索找人 * @return [type] [description] */ public function search() { $search = I('post.'); $field = 'u.uid'; $data = D('userinfo')->getSearchList($this->mid, $field, $search); if($data['ulist']) { foreach( $data['ulist'] as $v){ if($v) { $tmp['uid'] = $v['uid']; if(!$this->redis->HLEN('Userinfo:uid'.$tmp['uid'])) { A('Home/User')->getUserinfoData($tmp['uid']); } $tmp['uname'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'uname'); $tmp['price'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'price'); $location = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'location'); $location = explode('/', $location); $tmp['location'] = $location[0].' '.$location[1]; $tmp['language'] = json_decode($this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'language'), true); $tmp['tags'] = json_decode($this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'tags'), true); $tmp['level'] = intval($this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'level')); $tmp['headimg'] = json_decode($this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'headimg'), true); $tmp['headimg'] = $tmp['headimg'][0]['url']; $tmp['intro'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'intro'); $tmp['sex'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'sex'); $data['datalist'][] = $tmp; } else { break; } } } unset($data['ulist']); $this->return['data'] = $data; $this->goJson($this->return); } /** * 排行榜 * @return [type] [description] */ public function charts() { $data['index'] = I('post.index') ? I('post.index') : 1; $data['pageSize'] = I('post.pageSize'); $start = ($data['index']-1)*$data['pageSize']; $data['totalCount'] = D('userinfo')->count('uid'); $data['totalCount'] = $data['totalCount'] >= 100 ? 100 : $data['totalCount']; $limit = $start+$data['pageSize']-1 > 99 ? 99-$start : $data['pageSize']; $sortSQL = ''; if( I('post.sort') == 'long' ) { $sortSQL = 'spoken_long desc ,'; } elseif ( I('post.sort') == 'num' ) { $sortSQL = 'spoken_num desc ,'; } $sortSQL .= 'level desc'; $res = D('userinfo')->field('uid')->order($sortSQL)->limit($start, $limit)->select(); if($res) { foreach( $res as $v){ if($v) { $tmp['uid'] = $v['uid']; if(!$this->redis->HLEN('Userinfo:uid'.$tmp['uid'])) { A('Home/User')->getUserinfoData($tmp['uid']); } $tmp['uname'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'uname'); $tmp['price'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'price'); $location = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'location'); $location = explode('/', $location); $tmp['location'] = $location[0].' '.$location[1]; $tmp['language'] = json_decode($this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'language'), true); $tmp['tags'] = json_decode($this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'tags'), true); $tmp['level'] = intval($this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'level')); $tmp['headimg'] = json_decode($this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'headimg'), true); $tmp['headimg'] = $tmp['headimg'][0]['url']; $tmp['intro'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'intro'); $tmp['sex'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'sex'); $tmp['spoken_long'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'spoken_long'); $tmp['spoken_num'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'spoken_num'); $data['datalist'][] = $tmp; } else { break; } } } $this->return['data'] = $data; $this->goJson($this->return); } /** * 话题广场 * @return [type] [description] */ public function topic() { $tags = F('tags'); if(!$tags) { $tags = D('tags')->field('tid, tag_name')->select(); F('tags', $tags); } if($this->mid) { if(!$this->redis->HLEN('Userinfo:uid'.$this->mid)) { A('Home/User')->getUserinfoData($this->mid); } $topic = json_decode($this->redis->HGET('Userinfo:uid'.$this->mid, 'tags')); if(!$topic) { $topic = $tags; } }else{ $topic = $tags; } $this->return['data']['topic'] = $topic; $this->goJson($this->return); } /** * 获取话题用户 * @return [type] [description] */ public function topicUser() { $data['tid'] = I('post.tid') ? I('post.tid') : 1; $data['index'] = I('post.index') ? I('post.index') : 1; $data['pageSize'] = I('post.pageSize'); $start = ($data['index']-1)*$data['pageSize']; $where = $this->mid ? ' and uid!='.$this->mid : ''; $data['totalCount'] = D('userTags')->where('tid='.$data['tid'].$where)->count('ut_id'); $res = D('userTags')->field('uid')->where('tid='.$data['tid'].$where)->limit($start, $data['pageSize'])->select(); if($res) { foreach( $res as $v) { if($v) { $tmp['uid'] = $v['uid']; if(!$this->redis->HLEN('Userinfo:uid'.$tmp['uid'])) { A('Home/User')->getUserinfoData($tmp['uid']); } $tmp['uname'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'uname'); $tmp['price'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'price'); $location = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'location'); $location = explode('/', $location); $tmp['location'] = $location[0].' '.$location[1]; $tmp['language'] = json_decode($this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'language'), true); $tmp['tags'] = json_decode($this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'tags'), true); $tmp['level'] = intval($this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'level')); $tmp['headimg'] = json_decode($this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'headimg'), true); $tmp['headimg'] = $tmp['headimg'][0]['url']; $tmp['intro'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'intro'); $tmp['sex'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'sex'); $data['datalist'][] = $tmp; } else { break; } } } $this->return['data'] = $data; $this->goJson($this->return); } /** * 语加首页 * @return [type] [description] */ public function yujia() { $uid = $this->randuid($this->mid); $tmp['uid'] = $uid; if(!$this->redis->HLEN('Userinfo:uid'.$tmp['uid'])) { A('Home/User')->getUserinfoData($tmp['uid']); } $tmp['uname'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'uname'); $tmp['price'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'price'); $location = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'location'); $location = explode('/', $location); $tmp['location'] = $location[0].' '.$location[1]; $tmp['language'] = json_decode($this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'language'), true); $tmp['level'] = intval($this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'level')); $tmp['headimg'] = json_decode($this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'headimg'), true); $tmp['headimg'] = $tmp['headimg'][0]['url']; $tmp['voipaccount'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'voipaccount'); $tmp['sex'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'sex'); $this->return['data'] = $tmp; $this->goJson($this->return); } private function randuid($uid) { $rand = $this->redis->SRANDMEMBER("Userinfo:online"); if($rand == $uid){ $rand = $this->randuid($uid); } return $rand; } /** * 语加搜索结果 * @return [type] [description] */ public function yujiaSearch() { $search = I('post.'); $search['pageSize'] = 20; $field = 'u.uid'; $whereRand = ' and uid>='.$this->randuid($this->mid); $data = D('userinfo')->getSearchList($this->mid, $field, $search, $whereRand); if(!$data['ulist']) { $data = D('userinfo')->getSearchList($this->mid, $field, $search); } if($data['ulist']) { foreach( $data['ulist'] as $v){ if($v) { $tmp['uid'] = $v['uid']; if(!$this->redis->HLEN('Userinfo:uid'.$tmp['uid'])) { A('Home/User')->getUserinfoData($tmp['uid']); } $tmp['uname'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'uname'); $tmp['price'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'price'); $location = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'location'); $location = explode('/', $location); $tmp['location'] = $location[0].' '.$location[1]; $tmp['language'] = json_decode($this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'language'), true); $tmp['level'] = intval($this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'level')); $tmp['headimg'] = json_decode($this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'headimg'), true); $tmp['headimg'] = $tmp['headimg'][0]['url']; $tmp['voipaccount'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'voipaccount'); $tmp['sex'] = $this->redis->HGET('Userinfo:uid'.$tmp['uid'], 'sex'); $data['datalist'][] = $tmp; } else { break; } } unset($data['ulist']); } $this->return['data'] = $data; $this->goJson($this->return); } }<file_sep><?php // +---------------------------------------------------------------------- // | OneThink [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2013 http://www.onethink.cn All rights reserved. // +---------------------------------------------------------------------- // | Author: 麦当苗儿 <<EMAIL>> <http://www.zjzit.cn> // +---------------------------------------------------------------------- namespace Admin\Controller; use User\Api\UserApi; /** * 后台首页控制器 * @author 麦当苗儿 <<EMAIL>> */ class PublicController extends \Think\Controller { /** * 后台用户登录 * @author 麦当苗儿 <<EMAIL>> */ public function login($username = null, $password = null, $verify = null){ if(IS_POST){ /* 检测验证码 TODO: */ if(!check_verify($verify)){ $this->error('验证码输入错误!'); } /* 调用UC登录接口登录 */ $User = new UserApi; $uid = $User->login($username, $password); if(0 < $uid){ //UC登录成功 /* 登录用户 */ $Member = D('Member'); if($Member->login($uid)){ //登录用户 //TODO:跳转到登录前页面 $this->success('登录成功!', U('Index/index')); } else { $this->error($Member->getError()); } } else { //登录失败 switch($uid) { case -1: $error = '用户不存在或被禁用!'; break; //系统级别禁用 case -2: $error = '密码错误!'; break; default: $error = '未知错误!'; break; // 0-接口参数错误(调试阶段使用) } $this->error($error); } } else { if(is_login()){ $this->redirect('Index/index'); }else{ /* 读取数据库中的配置 */ $config = S('DB_CONFIG_DATA'); if(!$config){ $config = D('Config')->lists(); S('DB_CONFIG_DATA',$config); } C($config); //添加配置 $this->display(); } } } /* 退出登录 */ public function logout(){ if(is_login()){ D('Member')->logout(); session('[destroy]'); $this->success('退出成功!', U('login')); } else { $this->redirect('login'); } } public function verify(){ $verify = new \Think\Verify(); $verify->entry(1); } /** * 支付结果通知 * @return [type] [description] */ public function notify() { import("Common.Util.alipay_notify"); //计算得出通知验证结果 $alipayNotify = new \AlipayNotify(C('ALIPAY_PARAM')); $verify_result = $alipayNotify->verifyNotify(); if($verify_result) {//验证成功 $success_details = I('success_details'); if($success_details) { $sInfo['status'] = 2; $success_details_arr = explode('|', $success_details); foreach($success_details_arr as $v) { if($v) { $tmp = explode('^', $v); $tmpRes = D('mlog')->field('uid, money, id')->where('orderId='.$tmp[0])->find(); $info['msg'] = 'id为'.$tmpRes['id'].'提现完成'; D('alilog')->add($info); D('mlog')->where('id='.$tmpRes['id'])->save($sInfo); D('umoney')->where('uid='.$tmpRes['uid'])->setDec('totalmoney', $tmpRes['money']); D('umoney')->where('uid='.$tmpRes['uid'])->setDec('not_tixian', $tmpRes['money']); } } } //批量付款数据中转账失败的详细信息 $fail_details = I('fail_details'); if($fail_details) { $sInfo['status'] = 4; $fail_details_arr = explode('|', $fail_details); foreach($fail_details_arr as $v) { if($v) { $tmp = explode('^', $v); $tmpRes = D('mlog')->field('uid, money, id')->where('orderId='.$tmp[0])->find(); $info['msg'] = 'id为'.$tmpRes['id'].'提现失败'; D('alilog')->add($info); D('mlog')->where('id='.$tmpRes['id'])->save($sInfo); D('umoney')->where('uid='.$tmpRes['uid'])->setDec('not_tixian', $tmpRes['money']); } } } //判断是否在商户网站中已经做过了这次通知返回的处理 //如果没有做过处理,那么执行商户的业务程序 //如果有做过处理,那么不执行商户的业务程序 } else { $info['msg'] = json_encode($_POST, JSON_UNESCAPED_UNICODE).'失败'; D('alilog')->add($info); } } } <file_sep><?php /* * 标签 */ namespace Admin\Controller; /** * 标签 * @author huajie <<EMAIL>> */ class TagsController extends AdminController { /** * 行为日志列表 * @author huajie <<EMAIL>> */ public function index(){ $tree = D('Tags')->getTree(0,'tid, tag_name, pid, status'); $this->assign('tree', $tree); C('_SYS_GET_TAGS_TREE_', true); //标记系统获取分类树模板 $this->meta_title = '标签管理'; $this->display(); } /** * 显示分类树,仅支持内部调 * @param array $tree 分类树 * @author 麦当苗儿 <<EMAIL>> */ public function tree($tree = null){ C('_SYS_GET_TAGS_TREE_') || $this->_empty(); $this->assign('tree', $tree); $this->display('tree'); } /** * 编辑标签 * @param [type] $id [description] * @param integer $pid [description] * @return [type] [description] */ public function edit($id = null, $pid = 0){ $tags = D('Tags'); if(IS_POST){ //提交表单 if(false !== $tags->update()){ $this->success('编辑成功!', U('index')); } else { $error = $tags->getError(); $this->error(empty($error) ? '未知错误!' : $error); } } else { $tag = ''; if($pid){ /* 获取上级分类信息 */ $tag = $tags->info($pid, 'tid, tag_name, pid, status'); if(!($tag && 1 == $tag['status'])){ $this->error('指定的上级标签不存在或被禁用!'); } } /* 获取标签信息 */ $info = $id ? $tags->info($id) : ''; $this->assign('info', $info); $this->assign('tags', $tag); $this->meta_title = '编辑标签'; $this->display(); } } /** * 新增标签 */ public function add($pid = 0) { $tags = D('Tags'); if(IS_POST){ //提交表单 if(false !== $tags->update()){ $this->success('新增成功!', U('index')); } else { $error = $tags->getError(); $this->error(empty($error) ? '未知错误!' : $error); } } else { $tag = array(); if($pid){ /* 获取上级分类信息 */ $tag = $tags->info($pid, 'tid, tag_name, pid, status'); if(!($tag && 1 == $tag['status'])){ $this->error('指定的上级标签不存在或被禁用!'); } } /* 获取分类信息 */ $this->assign('tags', $tag); $this->meta_title = '新增分类'; $this->display('edit'); } } /** * 删除一个标签 * @author huajie <<EMAIL>> */ public function remove(){ $tid = I('id'); if(empty($tid)){ $this->error('参数错误!'); } //判断该分类下有没有子分类,有则不允许删除 $child = M('Tags')->where(array('pid'=>$tid))->field('tid')->select(); if(!empty($child)){ $this->error('请先删除该标签下的子标签'); } //删除该分类信息 $res = M('Tags')->delete($tid); if($res !== false){ //记录行为 action_log('update_tags', 'tags', $tid, UID); $this->success('删除标签成功!'); }else{ $this->error('删除标签失败!'); } } }<file_sep><?php // 获取字串首字母 function getFirstLetter($s0) { $firstchar_ord = ord(strtoupper($s0{0})); if($firstchar_ord >= 65 and $firstchar_ord <= 91) return strtoupper($s0{0}); if($firstchar_ord >= 48 and $firstchar_ord <= 57) return '#'; $s = iconv("UTF-8", "gb2312", $s0); $asc = ord($s{0}) * 256 + ord($s{1}) - 65536; if($asc>=-20319 and $asc<=-20284) return "A"; if($asc>=-20283 and $asc<=-19776) return "B"; if($asc>=-19775 and $asc<=-19219) return "C"; if($asc>=-19218 and $asc<=-18711) return "D"; if($asc>=-18710 and $asc<=-18527) return "E"; if($asc>=-18526 and $asc<=-18240) return "F"; if($asc>=-18239 and $asc<=-17923) return "G"; if($asc>=-17922 and $asc<=-17418) return "H"; if($asc>=-17417 and $asc<=-16475) return "J"; if($asc>=-16474 and $asc<=-16213) return "K"; if($asc>=-16212 and $asc<=-15641) return "L"; if($asc>=-15640 and $asc<=-15166) return "M"; if($asc>=-15165 and $asc<=-14923) return "N"; if($asc>=-14922 and $asc<=-14915) return "O"; if($asc>=-14914 and $asc<=-14631) return "P"; if($asc>=-14630 and $asc<=-14150) return "Q"; if($asc>=-14149 and $asc<=-14091) return "R"; if($asc>=-14090 and $asc<=-13319) return "S"; if($asc>=-13318 and $asc<=-12839) return "T"; if($asc>=-12838 and $asc<=-12557) return "W"; if($asc>=-12556 and $asc<=-11848) return "X"; if($asc>=-11847 and $asc<=-11056) return "Y"; if($asc>=-11055 and $asc<=-10247) return "Z"; return '#'; } ?><file_sep><?php namespace Home\Controller; Class PublicController extends BaseController { /** * 获取母语语言列表 * @return [type] [description] */ public function getBaseLanguage() { $this->return['data']['language'] = F('baseLanguage'); if(!$this->return['data']['language']) { $this->return['data']['language'] = D('language')->where('type=1')->field('lid, language_name')->select(); F('baseLanguage', $this->return['data']['language']); } $this->goJson($this->return); } /** * 获取标签 * @return [type] [description] */ public function getTags() { $this->return['data']['tags'] = F('tags'); if(!$this->return['data']['tags']) { $this->return['data']['tags'] = D('tags')->field('tid, tag_name')->select(); F('tags', $this->return['data']['tags']); } $this->goJson($this->return); } /* 文件上传 */ public function upload(){ /* 调用文件上传组件上传文件 */ $File = D('File'); $file_driver = C('DOWNLOAD_UPLOAD_DRIVER'); $info = $File->upload( $_FILES, C('DOWNLOAD_UPLOAD'), C('DOWNLOAD_UPLOAD_DRIVER'), C("UPLOAD_{$file_driver}_CONFIG") ); /* 记录附件信息 */ if($info){ if(!$info['file']) { foreach($info as $v){ $this->return['data']['file'][] = array('url'=>C('WEBSITE_URL').'/Uploads/File/'.$v['savepath'].$v['savename'], 'rid'=>$v['id']); } } else { $this->return['data']['file'][] = array('url'=>C('WEBSITE_URL').'/Uploads/File/'.$info['file']['savepath'].$info['file']['savename'], 'rid'=>$info['file']['id']); } $this->return['message'] = L('upload_success'); } else { $this->return['code'] = 1001; $this->return['message'] = $File->getError(); } /* 返回JSON数据 */ $this->goJson($this->return); } /** * 上传图片 * @author huajie <<EMAIL>> */ public function uploadPicture(){ /* 调用文件上传组件上传文件 */ $Picture = D('Picture'); $pic_driver = C('PICTURE_UPLOAD_DRIVER'); $info = $Picture->upload( $_FILES, C('PICTURE_UPLOAD'), C('PICTURE_UPLOAD_DRIVER'), C("UPLOAD_{$pic_driver}_CONFIG") ); //TODO:上传到远程服务器 /* 记录图片信息 */ if($info){ if(!$info['file']){ foreach($info as $v){ $this->return['data']['pic'][] = array('url'=>C('WEBSITE_URL').$v['path'], 'rid'=>$v['id']); } } else { $this->return['data']['pic'][] = array('url'=>C('WEBSITE_URL').$info['file']['path'], 'rid'=>$info['file']['id']); } $this->return['message'] = L('upload_success'); } else { $return['code'] = 1003; $this->return['message'] = $Picture->getError(); } /* 返回JSON数据 */ $this->goJson($this->return); } } ?>
6a796b08c1158bbee9529b3e3336a96b9b5121cb
[ "PHP" ]
26
PHP
a349944418/yuban
5d2d4f4e8d0d9f5b0b600f4a30c1b487c69a9190
621f603d52048b5fbedbc5629c2e8eb4afa622bf
refs/heads/master
<repo_name>karopeter/series-library<file_sep>/src/app/graphy/graphy.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-graphy', templateUrl: './graphy.component.html', styleUrls: ['./graphy.component.scss'] }) export class GraphyComponent implements OnInit { constructor() { } ngOnInit(): void { } } <file_sep>/src/app/graphy/graphy.component.html <section class="section-features"> <div class="container"> <p class="long__copy"> Calyx Containers are the highest quality, affordable <br class="hidden-xs"> marijuana packaging and inventory solution on the <br class="hidden-xs"> market. Series Eight worked with the Calyx team to <br class="hidden-xs"> create a highly visual experience through UI design, <br class="hidden-xs"> bespoke iconography and creative front-end <br class="hidden-xs"> development to market their new products. </p> </div> </section>
2a38879edd479a4922921768ed0285163deb4cef
[ "TypeScript", "HTML" ]
2
TypeScript
karopeter/series-library
d404cf5e99861bfc330481631b8a12e2fb99d9c0
ea85474cd85e5703f5ffcade5090cf6379b49470
refs/heads/master
<repo_name>Naveenkota55/selenium_testsuite<file_sep>/testsuite/package1/TC_LoginTest.py import unittest class LoginTest(unittest.TestCase): def test_twitter(self): print("This is login by twitter") self.assertTrue(True) def test_facebook(self): print("this is login by facebook") self.assertTrue(True) def test_apple(self): print("this is login by apple") self.assertTrue(True) if __name__=="__main__": unittest.main()<file_sep>/checkboxes_test.py #just made modifications from find_elements.py #changes are >Added is_selected from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.ui import WebDriverWait import time driver=webdriver.Firefox(executable_path="/usr/local/bin/geckodriver") driver.maximize_window() driver.get("https://fs2.formsite.com/meherpavan/form2/index.html?1537702596407") status=driver.find_element(By.ID,"RESULT_RadioButton-7_0").is_selected() if status==False: driver.find_element(By.ID,"RESULT_RadioButton-7_0").click() else: pass driver.quit() <file_sep>/unittest_2.py import unittest from selenium import webdriver import time def setUpModule(): print("start of module") def tearDownModule(): print("end of module") class searchengine(unittest.TestCase): @classmethod def setUp(self): print("this is setup") @classmethod def tearDown(self): print("this is teardown") @classmethod def tearDownClass(hi): print("end of class") @classmethod def setUpClass(hi): print("start of class") @unittest.SkipTest def test_google(self): self.driver=webdriver.Chrome(executable_path="/usr/local/bin/chromedriver") self.driver.get("http://google.com") print(self.driver.title) self.driver.close() @unittest.skip("skipped cause test case is not completed") def test_bing(self): self.driver=webdriver.Chrome(executable_path="/usr/local/bin/chromedriver") self.driver.get("https://bing.com") print(self.driver.title) self.driver.close() @unittest.skipIf(1==2,"wiki skipped") def test_wiki(self): self.driver=webdriver.Chrome(executable_path="/usr/local/bin/chromedriver") self.driver.get("http://wikipedia.com") print(self.driver.title) self.driver.close() def test_yahoo(self): self.driver=webdriver.Chrome(executable_path="/usr/local/bin/chromedriver") self.driver.get("https://yahoo.co.in") print(self.driver.title) self.driver.close() def test_duck(self): self.driver=webdriver.Chrome(executable_path="/usr/local/bin/chromedriver") self.driver.get("https://duckduckgo.com/") print(self.driver.title) self.driver.close() if __name__=="__main__": unittest.main() <file_sep>/selenium_test.py '''from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver=webdriver.Safari() driver.get('https://phptravels.org/clientarea.php') usr_name=driver.find_element_by_name('username') print(usr_name.is_displayed()) usr_name.send_keys('hi') time.sleep(2) driver.close()''' #retesting the click option ''' from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver=webdriver.Safari() driver.get('https://www.premiumexam.net/cybersecurity-essentials-1-1/cybersecurity-essentials-1-1-chapter-3-quiz-answers-100-2018/') click_opt=driver.find_element_by_xpath('//*[@id="categories-2"]/ul/li[1]/a') print(click_opt.is_displayed()) driver.maximize_window() time.sleep(4) click_opt.click() time.sleep(2) driver.quit() ''' #automation of web from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver=webdriver.Firefox(executable_path='/usr/local/bin/geckodriver') driver.maximize_window() driver.get('https://www.saucedemo.com') driver.find_element_by_id('user-name').send_keys('standard_<PASSWORD>') driver.find_element_by_id('password').send_keys('<PASSWORD>') driver.find_element_by_class_name('btn_action').click() driver.find_element_by_xpath('//*[@id="inventory_container"]/div/div[1]/div[3]/button').click() #click cart button driver.find_element_by_css_selector('.svg-inline--fa > path:nth-child(1)').click() time.sleep(3) #check weather the item is added to cart or not check_item_add=driver.find_element_by_css_selector('button.btn_secondary').is_displayed() if check_item_add==True: driver.find_element_by_css_selector('.btn_action').click() time.sleep(2) #entering details driver.find_element_by_id('first-name').send_keys('Naveen') driver.find_element_by_id('last-name').send_keys('kota') driver.find_element_by_id('postal-code').send_keys('B3j2k9') #click continue driver.find_element_by_css_selector('.btn_primary').click() time.sleep(2) #final confi driver.find_element_by_css_selector('.btn_action').click() #showing the order placed successfully if (driver.find_element_by_css_selector('html body.main-body div#page_wrapper.page_wrapper div#contents_wrapper div#checkout_complete_container.checkout_complete_container h2.complete-header').is_displayed())==True: print('order_placed successfully') print('test_completed_successfully') time.sleep(3) driver.quit() <file_sep>/explict_2.py #explicit wait 2 practice #working test_1 #second test msy not work everytime cause amazon seems to update the webpage every time with new suggestion but first will work cause i am using search bar id ''' from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait import time driver=webdriver.Firefox(executable_path="/usr/local/bin/geckodriver") driver.maximize_window() #get web page driver.get("https://www.amazon.ca") #implicit wait driver.implicitly_wait(5) #actions on search bar search_bar=driver.find_element(By.ID,"twotabsearchtextbox") search_bar.click() search_bar.clear() search_bar.send_keys("books") search_bar.send_keys(Keys.ENTER) #implimenting wait wait=WebDriverWait(driver,10) element=wait.until(EC.element_to_be_clickable((By.XPATH,"//*[@id='p_85/5690392011']/span/a/div/label/i"))) element.click() time.sleep(2) driver.quit()''' #second test example on amazon from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait import time #automation through firefox driver=webdriver.Firefox(executable_path='/usr/local/bin/geckodriver') #get website in this case amazon driver.get("https://www.amazon.ca") #selection of electronic store just to load other page #css selector/ xpath both seems to change evertime loading amazon webpage,it is expected behaviour that may not work everytime driver.find_element(By.CSS_SELECTOR,"#nav-xshop > a:nth-child(4)") #selection of wearable electonics #implimenting explict wait with expected conditions wait=WebDriverWait(driver,10) element=wait.until(EC.element_to_be_clickable((By.XPATH,"//*[@id='leftNav']/ul[1]/ul/div/li[15]/span/a/span"))) element.click() #explicit wait by time module time.sleep(5) #closing browser driver.close() <file_sep>/selenium.py from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver=webdriver.Safari() driver.get('https://phptravels.org/clientarea.php') usr_name=driver.find_element_by_name('username') print(usr_name.is_displayed()) usr_name.send_keys('hi') time.sleep(2) driver.close()<file_sep>/drag_drop.py #following script contains actions related to drag and drop from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.common.by import By import time driver=webdriver.Chrome(executable_path="/usr/local/bin/chromedriver") driver.maximize_window() driver.get("http://testautomationpractice.blogspot.com") src_element=driver.find_element(By.XPATH,"//*[@id='draggable']")#get the source and destination dest_element=driver.find_element(By.XPATH,"//*[@id='droppable']") actions=ActionChains(driver) actions.drag_and_drop(src_element,dest_element).perform()#use drag and drop in action chain time.sleep(5) driver.close()<file_sep>/testsuite/AllTestSuites.py #following script imports testcases from other python file created earlier #and create test suites and runs based on choise import unittest #import test cases from package1.TC_LoginTest import LoginTest from package1.TC_SignupTest import SignupTest from package2.TC_Payment import Payment from package2.TC_PaymentReturn import PaymentReturn tc1=unittest.TestLoader().loadTestsFromTestCase(LoginTest) #load testcases tc2=unittest.TestLoader().loadTestsFromTestCase(SignupTest) tc3=unittest.TestLoader().loadTestsFromTestCase(PaymentReturn) tc4=unittest.TestLoader().loadTestsFromTestCase(Payment) sanity_test=unittest.TestSuite([tc2,tc1]) #create test suite funitional_test=unittest.TestSuite([tc3,tc4]) master_test=unittest.TestSuite([tc1,tc2,tc3,tc4]) option=int(input("enter a OPTION 1. Sanity 2. funtional 3. Master :")) #choose a option fro test if option==1: print("Sanity_test selected") unittest.TextTestRunner().run(sanity_test) elif option==2: print("functional test selected") unittest.TextTestRunner().run(funitional_test) elif option==3: print("master test selected") unittest.TextTestRunner(verbosity=2).run(master_test) else: print("invaild option")<file_sep>/drop_down.py # working with dropdown #options test #all the imported modules are not used*just imported for practise from selenium import webdriver from selenium.webdriver.support.select import Select from selenium.webdriver.common.by import By import time driver=webdriver.Firefox(executable_path="/usr/local/bin/geckodriver") driver.maximize_window() driver.get("https://fs2.formsite.com/meherpavan/form2/index.html?1537702596407") element=driver.find_element(By.ID,"RESULT_RadioButton-9") drp=Select(element) # dropdown menus can be selected by 3 option values, visiable_text,Values #drp.select_by_visible_text("Morning") #drp.select_by_index(1) drp.select_by_value("Radio-1") #to find how many options are availble print(len(drp.options)) #to print all the options for texts in drp.options: print(texts.text) time.sleep(2) driver.quit() <file_sep>/scrolling.py from selenium import webdriver from selenium.webdriver.common.by import By import time driver=webdriver.Firefox(executable_path="/usr/local/bin/geckodriver") driver.get("https://www.countries-ofthe-world.com/flags-of-the-world.html") driver.execute_script("window.scrollBy(0,1000)","") flag=driver.find_element(By.XPATH,"//*[@id='content']/div[2]/div[2]/table[1]/tbody/tr[35]/td[1]/img") driver.execute_script("arguments[0].scrollIntoView();",flag)<file_sep>/testsuite/package2/TC_PaymentReturn.py import unittest class PaymentReturn(unittest.TestCase): def test_original(self): print("payment returned to original mode of payment") self.assertTrue(True) def test_credit(self): print("payment returned to credit card") self.assertTrue(True) def test_debit(self): print("payment returned to debit card") self.assertTrue(True) if __name__=="__main__": unittest.main()<file_sep>/window_handles.py #this script contains the window handles, switching between them and also closing from selenium import webdriver from selenium.webdriver.common.by import By import time driver=webdriver.Firefox(executable_path="/usr/local/bin/geckodriver") driver.maximize_window() driver.get("http://testautomationpractice.blogspot.com") print(driver.current_window_handle) driver.find_element_by_xpath("//*[@id='Wikipedia1_wikipedia-search-form']/div/span[1]/a/img").click() handles=driver.window_handles print(handles) '''driver.switch_to.window(handles[1]) #switching the window print(driver.current_window_handle) print(driver.title)''' for handle in handles: #to get all the windows handles , title,and also switching driver.switch_to.window(handle) print (handle) print(driver.title) if driver.title=='Automation Testing Practice': driver.close() #closing specific window time.sleep(3) driver.quit()<file_sep>/frames_1.py #swithces between frames from selenium import webdriver from selenium.webdriver.common.by import By import time driver=webdriver.Firefox(executable_path="/usr/local/bin/geckodriver") driver.get("https://www.selenium.dev/selenium/docs/api/java/") #get website driver.implicitly_wait(3) driver.switch_to.frame("packageListFrame") #switching to first_frame driver.find_element_by_link_text("org.openqa.selenium").click() driver.switch_to.default_content() #swiching to default frame driver.switch_to.frame("packageFrame") #swich to second frame driver.find_element_by_link_text("Rotatable").click() driver.switch_to.default_content() time.sleep(3) driver.switch_to.frame("classFrame")#switch to third frame driver.find_element(By.XPATH,"/html/body/div[2]/div[2]/ul[1]/li[5]/a").click() time.sleep(2) driver.close()<file_sep>/html_table.py #this script contains how to read table contents, find rows &coloums from selenium import webdriver from selenium.webdriver.common.by import By driver=webdriver.Firefox(executable_path="/usr/local/bin/geckodriver") driver.get("http://testautomationpractice.blogspot.com") rows=len(driver.find_elements(By.XPATH,"//*[@id='HTML1']/div[1]/table/tbody/tr"))#to find number of rows print("number of rows in table =",rows) coloums=len(driver.find_elements(By.XPATH,"//*[@id='HTML1']/div[1]/table/tbody/tr[1]/th"))#to find number of columns print("number of rows in table =",coloums) for r in range(2,rows+1):#to print the table for header we can just use regular print command, below code just retrives table contents for c in range(1,coloums+1): key=driver.find_element(By.XPATH,"//*[@id='HTML1']/div[1]/table/tbody/tr["+str(r)+"]/td["+str(c)+"]").text print(key,end=" ") print() driver.quit() <file_sep>/assertion.py #following script contains the assert commands import unittest from selenium import webdriver import time class assert_1(unittest.TestCase): def test_google(self): self.driver=webdriver.Chrome(executable_path="/usr/local/bin/chromedriver") self.driver.get("https://www.google.com/") webtitle=self.driver.title #self.assertEqual("Google",webtitle,"webtitle not equal")#check if the webtitle is same self.assertNotEqual("Google",webtitle,"webtitle equal") self.driver.close() if __name__=="__main__": unittest.main() <file_sep>/wait_impl.py #test the wait implicit from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver=webdriver.Firefox(executable_path='/usr/local/bin/geckodriver') driver.get("https://edel.fa.us2.oraclecloud.com/hcmUI/CandidateExperience/en/sites/CX/my-profile/<KEY>") #implict wait for 5 sec driver.implicitly_wait(10) time.sleep(2) driver.quit()<file_sep>/testsuite/package1/TC_SignupTest.py import unittest class SignupTest(unittest.TestCase): def test_twitter(self): print("This is signup by twitter") self.assertTrue(True) def test_facebook(self): print("this is signup by facebook") self.assertTrue(True) def test_apple(self): print("this is signup by apple") self.assertTrue(True) if __name__=="__main__": unittest.main()<file_sep>/unittest_1.py import unittest class test1(unittest.TestCase): def test_1(self): print("hi") if __name__=="__main__": unittest.main()<file_sep>/wait_exp.py #explict_wait from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait import time driver=webdriver.Firefox(executable_path='/usr/local/bin/geckodriver') driver.get("https://expedia.com/") driver.maximize_window() driver.implicitly_wait(4) driver.find_element(By.XPATH,"//*[@id='tab-flight-tab-hp']").click() driver.find_element(By.XPATH,"//*[@id='flight-type-one-way-label-hp-flight']").click() driver.find_element(By.ID,"flight-origin-hp-flight").send_keys("YHZ") driver.find_element(By.ID,'flight-destination-hp-flight').send_keys('HYD') driver.find_element(By.ID,"flight-departing-single-hp-flight").click() time.sleep(2) driver.find_element(By.XPATH,"/html/body/meso-native-marquee/section/div/div/div[1]/section/div/div[2]/div[2]/section[1]/form/fieldset[2]/div/div[1]/div/div/div[2]/div[2]/table/tbody/tr[3]/td[5]/button").click() driver.find_element(By.XPATH,'/html/body/meso-native-marquee/section/div/div/div[1]/section/div/div[2]/div[2]/section[1]/form/div[8]/label/button').click() #explict wait line wait=WebDriverWait(driver,10) wait.until(EC.element_to_be_clickable.By.XPATH("//*[@id='tab-flight-tab-hp']")).click() time.sleep(3) driver.quit()<file_sep>/action_chains.py #performed action chain by mouse hover action #seems like firefox and safari having issues to perform actionchain so opted for chrome #contains mouse hover acttion from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver import ActionChains import time driver=webdriver.Chrome(executable_path="/usr/local/bin/chromedriver") driver.maximize_window() #following code for mouse hover actions ''' driver.get("https://opensource-demo.orangehrmlive.com") driver.find_element(By.ID,"txtUsername").send_keys("Admin")#enter login details and click login button driver.find_element(By.ID,"txtPassword").send_keys("<PASSWORD>") driver.find_element(By.ID,"btnLogin").click() admin=driver.find_element(By.XPATH,"//*[@id='menu_admin_viewAdminModule']/b")#storing the menu in variables user_mag=driver.find_element(By.XPATH,"//*[@id='menu_admin_UserManagement']") users=driver.find_element(By.XPATH,"//*[@id='menu_admin_viewSystemUsers']") actions=ActionChains(driver) actions.move_to_element(admin).move_to_element(user_mag).move_to_element(users).click().perform()#performing action chains *will not work unless there is perform() at the end ''' #following code consists to double click '''driver.get("http://testautomationpractice.blogspot.com") element=driver.find_element(By.XPATH,"//*[@id='HTML10']/div[1]/button") action=ActionChains(driver) action.double_click(element).perform()''' #following script is for double click() driver.get("http://demo.guru99.com/test/simple_context_menu.html") element=driver.find_element(By.XPATH,"//*[@id='authentication']/span") actions=ActionChains(driver) actions.context_click(element).perform() time.sleep(5) driver.quit()<file_sep>/shopping.py #automation of web from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver=webdriver.Firefox(executable_path='/usr/local/bin/geckodriver') driver.maximize_window() #get webpage driver.get('https://www.saucedemo.com') #enter login details and click driver.find_element_by_id('user-name').send_keys('<PASSWORD>') driver.find_element_by_id('password').send_keys('<PASSWORD>') driver.find_element_by_class_name('btn_action').click() #add item driver.find_element_by_xpath('//*[@id="inventory_container"]/div/div[1]/div[3]/button').click() #click cart button driver.find_element_by_css_selector('.svg-inline--fa > path:nth-child(1)').click() time.sleep(3) #check weather the item is added to cart or not check_item_add=driver.find_element_by_css_selector('button.btn_secondary').is_displayed() if check_item_add==True: driver.find_element_by_css_selector('.btn_action').click() time.sleep(2) #entering details driver.find_element_by_id('first-name').send_keys('Naveen') driver.find_element_by_id('last-name').send_keys('kota') driver.find_element_by_id('postal-code').send_keys('B3j2k9') #click continue driver.find_element_by_css_selector('.btn_primary').click() time.sleep(2) #final confi driver.find_element_by_css_selector('.btn_action').click() #showing the order placed successfully if (driver.find_element_by_css_selector('html body.main-body div#page_wrapper.page_wrapper div#contents_wrapper div#checkout_complete_container.checkout_complete_container h2.complete-header').is_displayed())==True: print('order_placed successfully') print('test_completed_successfully') time.sleep(3) driver.quit() <file_sep>/alerts.py #contains code to accept and dismiss the alert by using sithch to alert from selenium import webdriver import time driver=webdriver.Firefox(executable_path="/usr/local/bin/geckodriver") driver.get("http://testautomationpractice.blogspot.com") driver.find_element_by_xpath("//*[@id='HTML9']/div[1]/button").click() time.sleep(2) #driver.switch_to_alert().accept() #to accept driver.switch_to_alert().dismiss() #to dismiss time.sleep(2)<file_sep>/testsuite/package2/TC_Payment.py import unittest class Payment(unittest.TestCase): def test_cash(self): print("Transation through cash") self.assertTrue(True) def test_card_credit(self): print("Transation through credit card") self.assertTrue(True) def test_card_Debit(self): print("Transaction through Debit") self.assertTrue(True) if __name__=="__main__": unittest.main()<file_sep>/logging_test.py #following script to enable logging from selenium import webdriver import logging #module for logging logging.basicConfig(filename="/Users/naveenkota/Documents/selenium/logtest.log", level=logging.DEBUG) #set location and level of log logging.debug("this is debug message") logging.info("this is info") logging.warning("this is warning") logging.error("this is error message") logging.critical("this is critical")<file_sep>/week_1.py #this script contains importing modules requirerd for keys , by ,select, expected conditions #importing modules from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support.select import Select from selenium.webdriver.support import expected_conditions as EC import time #using firefox module driver=webdriver.Firefox(executable_path="/usr/local/bin/geckodriver") driver.maximize_window() driver.get("https://fs2.formsite.com/meherpavan/form2/index.html?1537702596407") #get webpage total_txt_field=driver.find_elements(By.CLASS_NAME,"text_field") #for text field print("total_text_fields_in_webpages=",len(total_txt_field)) total_links=driver.find_elements(By.TAG_NAME,"a") #for links with anchor print("totel links present in webpage:",len(total_links)) element_1=driver.find_elements(By.ID,"RESULT_RadioButton-9") #for dropdown element=driver.find_element(By.ID,"RESULT_RadioButton-9") drp=Select(element) drp_options=drp.options print ("totel number of dropdowns:",len(element_1)) print("options available in dropdown::",len(drp_options)) #to view dropdown options status=driver.find_element(By.ID,"RESULT_RadioButton-7_0").is_selected() #to check status of checkboxes and radios status_1=driver.find_element(By.ID,"RESULT_CheckBox-8_1").is_selected() driver.find_element(By.ID,"RESULT_TextField-1").send_keys("Naveen") #enter values driver.find_element(By.ID,"RESULT_TextField-2").send_keys("kota") driver.find_element(By.ID,"RESULT_TextField-3").send_keys("9012222222") driver.find_element(By.ID,"RESULT_TextField-4").send_keys("Canada") driver.find_element(By.ID,"RESULT_TextField-5").send_keys("Halifax") driver.find_element(By.ID,"RESULT_TextField-6").send_keys("@<PASSWORD>") if status==False & status_1==False: #to change only certain conditions meet driver.find_element(By.ID,"RESULT_CheckBox-8_1").click() driver.find_element(By.ID,"RESULT_RadioButton-7_0").click() else : pass for option in drp_options: #to view options in drop down in text print(option.text) drp.select_by_visible_text("Morning") #to select option driver.find_element(By.PARTIAL_LINK_TEXT,"Software").click() #to click the link by partial text time.sleep(3) #wait before quit driver.quit() #to close firefox automation driver<file_sep>/find_elements.py #trying to find elements in webpages can be helpful incase if we want to see totel number of common elements from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait import time driver=webdriver.Firefox(executable_path="/usr/local/bin/geckodriver") driver.maximize_window() driver.get("https://fs2.formsite.com/meherpavan/form2/index.html?1537702596407") #using class as commomn attribute input_boxes=driver.find_elements(By.CLASS_NAME,"text_field") print(len(input_boxes)) #to find number of input boxes print(driver.find_element(By.XPATH,"//*[@id='q26']/table/tbody/tr[1]/td/label").is_enabled()) driver.quit()<file_sep>/downlod_path.py from selenium import webdriver from selenium.webdriver.chrome.options import Options chromeoptions=Options() chromeoptions.add_experimental_option("prefs",{"download.default_directory":"/usr/local/bin/"}) driver=webdriver.Chrome(executable_path="/usr/local/bin/chromedriver",chrome_options=chromeoptions) <file_sep>/links_test.py #working on links from selenium import webdriver from selenium.webdriver.common.by import By import time driver=webdriver.Firefox(executable_path="/usr/local/bin/geckodriver") driver.get("https://www.edureka.co/blog/keyboard-mouse-events-actions-class") all_links=driver.find_elements(By.TAG_NAME,"a") #to get totel number of links print(len(all_links)) #to print links in text '''for links in all_links: print (links.text)''' #to click links by full name driver.find_element(By.LINK_TEXT,"Selenium").click() time.sleep(2) driver.quit()
abb0363e867cf9b5783d27f096ff6310ea6645e4
[ "Python" ]
28
Python
Naveenkota55/selenium_testsuite
e144eb4ad0036e021beabf37fba869814326ba8a
e00b263e5db6d7da4b1e319a82e73d4e619f84f9
refs/heads/master
<repo_name>KevinOlvera/ARP_Scan<file_sep>/ARP_Scan.c #include "comnet.c" int main(int argc, char const *argv[]) { int packet_socket = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL)); BD_MySQL_Connect(); BD_MySQL_Reset_Data(); if(packet_socket == -1) { perror("Error al abrir el socket."); exit(1); } else { perror("Exito al abrir el socket."); int index = getData(packet_socket); printf("El indice es %d\n", index); for(int i = 1; i < 255; i++) { getDestinationIP(i); ARPframe(frame_s, my_MAC, my_IP, dest_MAC, dest_IP); //printFrame(frame_s, 42); sendFrame(packet_socket, index, frame_s, 42); receiveFrame(packet_socket, frame_r); } } BD_MySQL_Show_Data(); BD_MySQL_Close(); close(packet_socket); return 0; }<file_sep>/ARP_Scan_BD.sql CREATE DATABASE ARP_Scan; USE ARP_Scan; CREATE TABLE PC ( ID int NOT NULL AUTO_INCREMENT PRIMARY KEY, IP_Address VARCHAR(15) NOT NULL, MAC_Address VARCHAR(17) NOT NULL ); <file_sep>/comnet.c #include "comnet.h" int getData(int sd) { struct ifreq nic; int index, i; char select, interface_name[10]; printf("Elije la interfaz de red a utilizar\n 1.-enp2s0\n 2.-wlp3s0\n 3.-Salir\n ->"); scanf("%c", &select); switch (select) { case '1': strcpy(interface_name, "enp2s0"); break; case '2': strcpy(interface_name, "wlp3s0"); break; default: printf("Error al seleccionar la interfaz de red.\n"); exit(1); break; } strcpy(nic.ifr_name, interface_name); /* obtener el indice de la interfaz de red */ if(ioctl(sd, SIOCGIFINDEX, &nic) == -1) { perror("Error al obtener el indice\n"); exit(1); } else { index = nic.ifr_ifindex; } /* obtener mi direccion MAC */ if(ioctl(sd, SIOCGIFHWADDR, &nic ) == -1) { perror("Error al obtener la MAC\n"); exit(1); } else { memcpy(my_MAC, nic.ifr_hwaddr.sa_data+0, 6); printf("Mi direccion MAC es: "); for( i = 0 ; i < 6 ; i++ ) { if(i == 5) printf("%.2X\n", my_MAC[i]); else printf("%.2X:", my_MAC[i]); } } /* obtener mi direccion IP */ if(ioctl(sd, SIOCGIFADDR, &nic) == -1) { perror("Error al obtener la dirección IP\n"); exit(1); } else { memcpy(my_IP, nic.ifr_addr.sa_data+2, 4); printf("Mi direccion IP es: "); for( i = 0 ; i < 4 ; i++ ){ if( i == 3 ) printf("%d\n", my_IP[i]); else printf("%d.", my_IP[i]); } } /* obtener mi mascara de subred */ if(ioctl(sd, SIOCGIFNETMASK, &nic) == -1) { perror("Error al obtener la mascara de subred\n"); exit(1); } else { memcpy(NETMASK, nic.ifr_netmask.sa_data+2, 4); printf("Mi mascara de subred es: "); for( i = 0 ; i < 4 ; i++ ){ if( i == 3 ) printf("%d\n", NETMASK[i]); else printf("%d.", NETMASK[i]); } } /* obtener la metrica */ if(ioctl(sd, SIOCGIFMETRIC, &nic) == -1) { perror("Error al obtener la metrica\n"); exit(1); } else { Metric = nic.ifr_metric; printf("Mi metrica es: %d\n", Metric); } /* obtener el MTU */ if(ioctl(sd, SIOCGIFMTU, &nic) == -1) { perror("Error al obtener el MTU\n"); exit(1); } else { MTU = nic.ifr_mtu; printf("Mi MTU es: %d\n", MTU); } printf("\n"); return index; } void ARPframe(unsigned char *frame, unsigned char *s_MAC, unsigned char *s_IP, unsigned char *d_MAC, unsigned char *d_IP) { memcpy(frame+0, bro_MAC, 6); memcpy(frame+6, s_MAC, 6); memcpy(frame+12, ethertype_ARP, 2); memcpy(frame+14, HW, 2); memcpy(frame+16, PR, 2); memcpy(frame+18, LDH, 1); memcpy(frame+19, LDP, 1); memcpy(frame+20, epcode_ARP_request, 2); memcpy(frame+22, s_MAC, 6); memcpy(frame+28, s_IP, 4); memcpy(frame+32, d_MAC, 6); memcpy(frame+38, d_IP, 4); } void frame(unsigned char *frame) { memcpy(frame+0, alameda_MAC_WLAN, 6); memcpy(frame+6, my_MAC, 6); memcpy(frame+12, ethertype_ethernet, 2); memcpy(frame+14, "Quintanilla Network", 40); } void sendFrame(int sd, int index, unsigned char *frame, int frame_size) { int size; struct sockaddr_ll interface; memset(&interface, 0x00, sizeof(interface)); interface.sll_family = AF_PACKET; interface.sll_protocol = htons(ETH_P_ALL); interface.sll_ifindex = index; size = sendto(sd, frame, frame_size, 0, (struct sockaddr *)&interface, sizeof(interface)); if(size == -1) { perror("Error al enviar"); exit(1); } else { //printf("Exito al enviar\n"); } } void printFrame(unsigned char *frame, int size) { int i; for( i = 0 ; i < size ; i++ ) { if( i%16 == 0 ) printf("\n"); printf("%.2x ", frame[i]); } printf("\n"); } void printARPinfo(unsigned char *frame, int size) { int i; printf("\nDireccion MAC: "); for( i = 22 ; i < 28 ; i++ ) { if(i == 27) printf("%.2X\n", frame[i]); else printf("%.2X:", frame[i]); } printf("Direccion IP: "); for( i = 28 ; i < 32 ; i++ ) { if( i == 31 ) printf("%d\n", frame[i]); else printf("%d.", frame[i]); } } void receiveFrame(int sd, unsigned char *frame) { int size, flag = 0; gettimeofday(&start, NULL); mtime = 0; while(mtime < 200){ size = recvfrom(sd, frame, 1514, MSG_DONTWAIT, NULL, 0); if( size == -1 ) { //perror("Error al recibir"); } else { if( !memcmp(frame+0, my_MAC, 6) && !memcmp(frame+12, ethertype_ARP, 2) && !memcmp(frame+20, epcode_ARP_replay, 2) && !memcmp(frame+28, dest_IP, 4) ) { //printFrame(frame, size); //printARPinfo(frame, size); BD_MySQL_Save_Data(frame); flag = 1; } } gettimeofday(&end, NULL); seconds = end.tv_sec - start.tv_sec; useconds = end.tv_usec - start.tv_usec; mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5; if( flag == 1 ) { //printf("\nElapsed time: %ld milliseconds\n", mtime); break; } } if( flag == 0 ){ //perror("Error al recibir"); //printf("Elapsed time: %ld milliseconds\n", mtime); } } void stringToIP(char *ip_s) { inet_aton(ip_s, (struct in_addr *)IP); } void getDestinationIP(int index) { dest_IP[0] = my_IP[0]; dest_IP[1] = my_IP[1]; dest_IP[2] = my_IP[2]; int i; char ip[14] = ""; char aux[14] = ""; for( i = 0 ; i < 3 ; i++ ){ sprintf(aux, "%d.", dest_IP[i]); strcat(ip, aux); } sprintf(aux, "%d", index); strcat(ip, aux); inet_aton(ip, (struct in_addr *)dest_IP); } void BD_MySQL_Connect() { char *server = "localhost"; char *user = "root"; char *password = "<PASSWORD>"; char *database = "ARP_Scan"; connection = mysql_init(NULL); /* Connect to database */ if (!mysql_real_connect(connection, server, user, password, database, 0, NULL, 0)) { fprintf(stderr, "%s\n", mysql_error(connection)); exit(1); } else { perror("Exito al conectar con la base de datos"); } } void BD_MySQL_Close() { mysql_free_result(result); mysql_close(connection); } void BD_MySQL_Save_Data(unsigned char *frame) { char ip[15] = ""; char aux_ip[15] = ""; char mac[17] = ""; char aux_mac[17] = ""; int i; for(i = 6;i < 12;i++) { if(i != 11) sprintf(aux_mac, "%.2X:", frame[i]); else sprintf(aux_mac, "%.2X", frame[i]); strcat(mac, aux_mac); } for(i = 28;i < 32;i++) { if(i != 31) sprintf(aux_ip, "%d.", frame[i]); else sprintf(aux_ip, "%d", frame[i]); strcat(ip, aux_ip); } sprintf(consult, "insert into PC values(NULL, '%s', '%s');", ip, mac); if (mysql_query(connection, consult)) { fprintf(stderr, "%s\n", mysql_error(connection)); exit(1); } //else //printf("\nSe agrego a %s - %s", mac, ip); } void BD_MySQL_Show_Data() { sprintf(consult, "select * from PC;"); if((mysql_query(connection, consult) == 0)) { result = mysql_use_result(connection); printf("\n+-------+---------------+-------------------+\n"); printf("| PC_ID | IP_Address\t| MAC_Address |\n"); printf("+-------+---------------+-------------------+\n"); while(row = mysql_fetch_row(result)) printf("| %s\t| %s\t| %s |\n", row[0], row[1], row[2]); printf("+-------+---------------+-------------------+\n"); } if(!mysql_eof(result)) printf("Error de lectura %s\n", mysql_error(connection)); } void BD_MySQL_Reset_Data() { sprintf(consult, "truncate PC;"); mysql_query(connection, consult); if((mysql_query(connection, consult) == 0)) { result = mysql_use_result(connection); } }
de273e85819a49e1a7d03b7cf051391ff29ce2ce
[ "C", "SQL" ]
3
C
KevinOlvera/ARP_Scan
4f8d9f32ad7dc7fad75338a977219ba624aa0a41
2fc9dbaac5a8ed7765f36817699235006afc2fbd
refs/heads/master
<file_sep>const nameCampus = require('./information.js'); let cowsay = require("cowsay") console.log(cowsay.say({ text : `My name is ${nameCampus.name} and I'm in ${nameCampus.campus}`, e : "oO", T : "U" }))<file_sep>let nameCampus = { name : "Malo", campus : "Biarritz", } module.exports = nameCampus ;
4ef595443633bd62bd445748a3d5abbda472eeb6
[ "JavaScript" ]
2
JavaScript
00FuNkY/Node01
e0131b7c9a22534534257f9572f31544adee1afb
731e761fd7b888d63d51a408f407bcd7bbffdd3e
refs/heads/master
<repo_name>jackylee1/InfoCountries<file_sep>/app/presentationLogic.py from app.businessLogic import * from app.wikidataInterface import * from app.inferences import * # Get all the metrics and values of one country # Returned in the format: ({"uri": uri of predicate, "url": url of predicate, "label": name of predicate}, value of predicate in country) def getParsedMetricsOfCountry(country): metrics = getMetricsOfCountry(BASE_URL+"/country/"+country) pred = getAllPredicateNames() parsedMetrics = [] for metric in metrics: for value in metrics[metric]: for p in pred: if metric==p: metric_name = value pred_nameof = "" url="" if len(value.split("/"))>1: # Check if URI is not from a country metric_name = getNameOfSubject(value) if len(metric_name)>0: metric_name = metric_name[0] pred_nameof="foaf:name" else: # URI is from a contry metric_name = getNameCountryByURI(value) url = value.split("/")[-1] if len(metric_name)>0: metric_name = metric_name[0] pred_nameof = "countries:countryPredicate/1" parsedMetrics += [({"uri":p ,"url":p.split("/")[-1],"label":pred[p]}, {"url":url, "uri": value,"value": metric_name, "pred_nameof":pred_nameof})] continue return parsedMetrics # Return list (URI, url, label) of all countries def getListOfCountries(): countries = getAllCountries() listCountries = [{"uri":uri.split("/", 7)[-1], "url":uri.split("/")[-1], "label":countries[uri]} for uri in countries] return listCountries # Returns list with all countries that have a metric, and its value # In the form {uri of country, label of country, url of country}, label) def getParsedAllCountriesByMetric(metric_uri): parsedMetrics = [] countries = getAllCountriesByMetric(metric_uri) allCountries = getAllCountries() for country in countries: label = country if(country in allCountries): label = allCountries[country] for value in countries[country]: pred_nameof = "" url = "" if len(value.split("/")) > 1: # Check if URI is not from a country names = getNameOfSubject(value) if len(names) > 0: names = names[0] pred_nameof="foaf:name" else: # URI is from a contry names = getNameCountryByURI(value) url = value.split("/")[-1] if len(names) > 0: names = names[0] pred_nameof="countries:countryPredicate/1" else: names = value parsedMetrics += [({"uri":country, "label":label, "url": country.split("/")[-1]}, {"url":url, "uri": value,"value": names, "pred_nameof":pred_nameof})] return parsedMetrics # Returns the name of a country given an URI, if it exists def getCountryName(country_id): names = getNameCountryByURI(BASE_URL+"/country/"+country_id) if len(names)>0: return names[0] else: return None # Returns the name of one metric given an URI def getMetricName(metric_id): metrics = getAllPredicateNames() name = [metrics[elem] for elem in metrics if elem==metric_id] if len(name)>0: return name[0] else: return None # Return list of predicates def getListOfPredicates(): predicates = getAllPredicateNames() listPredicates = [{"name": predicates[elem], "id": elem.split("/")[-1]} for elem in predicates] return listPredicates # Parse the reflexive inferences to get the label and url of each entity def getParsedReflexiveInferences(): relations = getReflexiveInferences() parsedRelations = {} for rel in relations: sub = getNameOfSubject(rel) if len(sub)>0: sub = sub[0] parsedRelations[rel] = {"label":sub, "url": rel.split("/")[-1], "content":{}} for entity1 in relations[rel]: name = getNameCountryByURI(entity1) if len(name)>0: name = name[0] parsedRelations[rel]["content"].update({entity1:{}}) parsedRelations[rel]["content"][entity1].update({"label":name, "url": entity1.split("/")[-1], "content":{}}) for entity2 in relations[rel][entity1]: name = getNameCountryByURI(entity2) if len(name)>0: name = name[0] parsedRelations[rel]["content"][entity1]["content"].update({entity2:{}}) parsedRelations[rel]["content"][entity1]["content"][entity2].update({"label":name, "url": entity2.split("/")[-1]}) return parsedRelations # Returns the favorite countries of one user def getParsedFavoriteCountries(user_id): favos = getFavoriteCountries(str(user_id)) parsedFavos = [] for favo in favos: name = getNameCountryByURI(favo)[0] url = favo.split("/")[-1] uri = favo.split("/", 7)[-1] parsedFavos += [{"uri": uri, "url": url, "label": name}] return parsedFavos def getParsedCountriesMoreInternetTraffic(): netTraffic = getCountriesWithMoreInternetTraffic() parsednetTraffic = [] for idx, country in enumerate(netTraffic): name = getNameCountryByURI(country)[0] url = country.split("/")[-1] uri = country.split("/", 7)[-1] parsednetTraffic += [{"uri": uri, "url": url, "label": name, "predURI": "rankMoreInternetTraffic", "value": str(idx+1)}] return parsednetTraffic def getParsedCountriesToInvest(): invest = getBestCountriesToInvest() parsedInvest = [] for idx, country in enumerate(invest): name = getNameCountryByURI(country)[0] url = country.split("/")[-1] uri = country.split("/", 7)[-1] parsedInvest += [{"uri": uri, "url": url, "label": name, "predURI": "rankBestCountriesToInvest", "value": str(idx+1)}] return parsedInvest def getParsedCountriesToLive(): tolive = getBestCountriesToLive() parsedToLive = [] for idx, country in enumerate(tolive): name = getNameCountryByURI(country)[0] url = country.split("/")[-1] uri = country.split("/", 7)[-1] parsedToLive += [{"uri": uri, "url": url, "label": name, "predURI": "rankBestCountriesToLive", "value": str(idx+1)}] return parsedToLive def checkIfFavorite(user_id, country): favo = getFavoriteCountries(str(user_id)) if BASE_URL+"/country/"+country in favo: return True return False <file_sep>/Projeto2/urls.py """Projeto2 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url import django.contrib.auth.views from datetime import datetime import app.forms import app.views from django.contrib import admin urlpatterns = [ url(r'^$', app.views.home, name="home"), url(r'^predicates/', app.views.predicates, name="pred"), url(r'^admin/', admin.site.urls, name="admin"), url(r'^registar/$', app.views.registar, name="registar"), url(r'^country/(?P<country>[0-9]+)/favo$', app.views.changeFavorite, name="changeFavorite"), url(r'^country/(?P<country>[0-9]+)$', app.views.country, name="country"), url(r'^country/(?P<country>[0-9]+)/reload$', app.views.reload, name="reload"), url(r'^country/(?P<country>[0-9]+)/relations', app.views.relations, name="relations"), url(r'^metric/(?P<metric>[A-Z]?[0-9]+)$', app.views.metric, name="metric"), url(r'^inferences/(?P<success>success)?$', app.views.inferences, name="inferences"), url(r'^inferences/save$', app.views.saveinferences, name="saveinferences"), url(r'^favorites/$', app.views.favorites, name="favorites"), url(r'^statistics/$', app.views.statistics, name="statistics"), url(r'^login/$', django.contrib.auth.views.login, { 'template_name': 'app/login.html', 'extra_context': { 'title': 'Sign in with your account', 'year': datetime.now().year, } }, name='login'), url(r'^logout$', django.contrib.auth.views.logout, { 'next_page': '/', }, name='logout'), ] <file_sep>/app/views.py from datetime import datetime from django.contrib.auth import login, authenticate from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render, redirect from app.presentationLogic import * from app.wikidataInterface import * from app.inferences import * ''' Home page of InfoCountries ''' @login_required(login_url='/login/') def home(request): countries = getListOfCountries() return render( request, 'app/home.html', { 'title': 'Countries', 'year': datetime.now().year, 'countries': countries } ) @login_required(login_url='/login/') def predicates(request): predicates = getListOfPredicates() return render( request, 'app/predicates.html', { 'title': 'Predicates', 'year': datetime.now().year, 'predicates': predicates } ) # Tries to create new predicates with data from wikidata @login_required(login_url='/login/') def reload(request, country): country_name = getCountryName(country) wikiCountry = getWikidataCountryEntity(country_name) try: createCountryNewPredicates(country, wikiCountry) except Exception as e: print(e) print("Could not gather data from country "+str(country)) return redirect('country', country=country) # Tries to create new relations between countries with data from wikidata @login_required(login_url='/login/') def relations(request, country): country_name = getCountryName(country) wikiCountry = getWikidataCountryEntity(country_name) try: createCountriesRelations(country, wikiCountry) except Exception as e: print(e) print("Could not gather data from country " + str(country)) return redirect('country', country=country) @login_required(login_url='/login/') def country(request, country): hasWiki = checkCountryHasWikidata(country) hasRelations = checkCountryHasWikidataRelations(country) metrics = getParsedMetricsOfCountry(country) # Tries to get the image URL from wikidata try: country_name = getCountryName(country) wikiCountry = getWikidataCountryEntity(country_name) image_URL = getWikidataImageURL(wikiCountry) except Exception as e: image_URL = "" print(e) print("Could not gather data from country "+str(country)) favo = checkIfFavorite(request.user.id, country) return render( request, 'app/country.html', { 'title': country_name, 'year': datetime.now().year, 'country_id': country, 'metrics': metrics, 'image': image_URL, 'has_wiki': hasWiki, 'has_relations': hasRelations, 'favorite': favo } ) @login_required(login_url='/login/') def metric(request, metric): try: # If first element is int, is local metric test = int(metric[0]) url = BASE_URL+"/countryProperty/"+metric # Otherwise, it is wikidata metric except Exception as e: url = WIKIDATA_BASEURL+metric countries = getParsedAllCountriesByMetric(url) metric_name = getMetricName(url) if metric_name==None: metric_name="Metric" return render( request, 'app/metrics.html', { 'title': metric_name, 'metric': url, 'year': datetime.now().year, 'countries': countries } ) @login_required(login_url='/login/') def inferences(request, success): refInferences = getParsedReflexiveInferences() return render( request, 'app/inferences.html', { 'title': "Inferences", 'year': datetime.now().year, 'inferences': refInferences, 'success': True if success=="success" else False } ) @login_required(login_url='/login/') def statistics(request): tolive = getParsedCountriesToLive() nettraffic = getParsedCountriesMoreInternetTraffic() toinvest = getParsedCountriesToInvest() return render( request, 'app/statistics.html', { 'title': "Statistics", 'tolive': tolive, 'toinvest': toinvest, 'nettraffic': nettraffic, 'year': datetime.now().year, } ) @login_required(login_url='/login/') def saveinferences(request): addRelations(getReflexiveInferences()) return redirect('inferences', success="success") @login_required(login_url='/login/') def favorites(request): favorites = getParsedFavoriteCountries(request.user.id) return render( request, 'app/favorites.html', { 'title': "Favorites", 'year': datetime.now().year, 'favorites': favorites } ) @login_required(login_url='/login/') def changeFavorite(request, country): favo = checkIfFavorite(str(request.user.id), country) if favo: removeFromFavorites(str(request.user.id), country) else: addToFavorites(str(request.user.id), country) return redirect('country', country=country) ''' Register page ''' def registar(request): # If form is valid, register new user if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('<PASSWORD>') user = authenticate(username=username, password=<PASSWORD>) login(request, user) return redirect('home') else: form = UserCreationForm() return render(request, 'app/registar.html', { 'title': 'Register', 'form': form, 'year': datetime.now().year })<file_sep>/README.md # InfoCountries The project was presented in the Data & Knowledge Engineering (Universidade de Aveiro), 2017. The main goal is to compare world countries based on several metrics, like child mortality rate, birth rate and others. The application is made using semantic web standards, to ease the machine-to-machine interaction. Technologies like SPARQL, GraphDB or RDFa were used. <NAME> <NAME> <NAME> <file_sep>/app/dbInterface.py """ Create and insert dataset into the graphdb database """ import requests import json from s4api.graphdb_api import GraphDBApi from s4api.swagger import ApiClient from lxml import etree from django.conf import settings # Graphdb settings ENDPOINT = "http://localhost:7200" REPO_NAME = "countries" # URI of known entities BASE_URL = "http://www.ua.pt/ensino/uc/2380/projeto2" WIKIDATA_BASEURL = "http://www.wikidata.org/wiki/" nameof = "http://xmlns.com/foaf/0.1/name" # Metrics used on the local data and his labels METRICS = [ ("Country", "<"+BASE_URL+"/countryProperty/1>"), ("Area(sq km)", "<"+BASE_URL+"/countryProperty/2>"), ("Birth rate(births/1000 population)", "<"+BASE_URL+"/countryProperty/3>"), ("Current account balance", "<"+BASE_URL+"/countryProperty/4>"), ("Death rate(deaths/1000 population)", "<"+BASE_URL+"/countryProperty/5>"), ("Debt - external", "<"+BASE_URL+"/countryProperty/6>"), ("Electricity - consumption(kWh)", "<"+BASE_URL+"/countryProperty/7>"), ("Electricity - production(kWh)", "<"+BASE_URL+"/countryProperty/8>"), ("Exports", "<"+BASE_URL+"/countryProperty/9>"), ("GDP", "<"+BASE_URL+"/countryProperty/10>"), ("GDP - per capita", "<"+BASE_URL+"/countryProperty/11>"), ("GDP - real growth rate(%)", "<"+BASE_URL+"/countryProperty/12>"), ("HIV/AIDS - adult prevalence rate(%)", "<"+BASE_URL+"/countryProperty/13>"), ("HIV/AIDS - deaths", "<"+BASE_URL+"/countryProperty/14>"), ("HIV/AIDS - people living with HIV/AIDS", "<"+BASE_URL+"/countryProperty/15>"), ("Highways(km)", "<"+BASE_URL+"/countryProperty/16>"), ("Imports", "<"+BASE_URL+"/countryProperty/17>"), ("Industrial production growth rate(%)", "<"+BASE_URL+"/countryProperty/18>"), ("Infant mortality rate(deaths/1000 live births)", "<"+BASE_URL+"/countryProperty/19>"), ("Inflation rate (consumer prices)(%)", "<"+BASE_URL+"/countryProperty/20>"), ("Internet hosts", "<"+BASE_URL+"/countryProperty/21>"), ("Internet users", "<"+BASE_URL+"/countryProperty/22>"), ("Investment (gross fixed)(% of GDP)", "<"+BASE_URL+"/countryProperty/23>"), ("Labor force", "<"+BASE_URL+"/countryProperty/24>"), ("Life expectancy at birth(years)", "<"+BASE_URL+"/countryProperty/25>"), ("Military expenditures - dollar figure", "<"+BASE_URL+"/countryProperty/26>"), ("Military expenditures - percent of GDP(%)", "<"+BASE_URL+"/countryProperty/27>"), ("Natural gas - consumption(cu m)", "<"+BASE_URL+"/countryProperty/28>"), ("Natural gas - exports(cu m)", "<"+BASE_URL+"/countryProperty/29>"), ("Natural gas - imports(cu m)", "<"+BASE_URL+"/countryProperty/30>"), ("Natural gas - production(cu m)", "<"+BASE_URL+"/countryProperty/31>"), ("Natural gas - proved reserves(cu m)", "<"+BASE_URL+"/countryProperty/32>"), ("Oil - consumption(bbl/day)", "<"+BASE_URL+"/countryProperty/33>"), ("Oil - exports(bbl/day)", "<"+BASE_URL+"/countryProperty/34>"), ("Oil - imports(bbl/day)", "<"+BASE_URL+"/countryProperty/35>"), ("Oil - production(bbl/day)", "<"+BASE_URL+"/countryProperty/36>"), ("Oil - proved reserves(bbl)", "<"+BASE_URL+"/countryProperty/37>"), ("Population", "<"+BASE_URL+"/countryProperty/38>"), ("Public debt(% of GDP)", "<"+BASE_URL+"/countryProperty/39>"), ("Railways(km)", "<"+BASE_URL+"/countryProperty/40>"), ("Reserves of foreign exchange & gold", "<"+BASE_URL+"/countryProperty/41>"), ("Telephones - main lines in use", "<"+BASE_URL+"/countryProperty/42>"), ("Telephones - mobile cellular", "<"+BASE_URL+"/countryProperty/43>"), ("Total fertility rate(children born/woman)", "<"+BASE_URL+"/countryProperty/44>"), ("Unemployment rate(%)", "<"+BASE_URL+"/countryProperty/45>") ] # Predicates gathered from wikidata WIKIDATA_PREDICATES = [ ('Head of government', 'P6'), ('Officcial language', 'P37'), ('Anthem', 'P85'), ('Continent','P30'), ('Capital', 'P36'), ('Highest Point', 'P610'), ('Head of State', 'P35'), ('Head of Government', 'P6'), ('Member of', 'P463'), ('Currency', 'P38'), ('Top level internet domain', 'P78') ] # Relations between countries gathered from wikidata WIKIDATA_COUNTRY_RELATIONS = [ ('Shares border', 'P47'), ('Diplomatic Relation', 'P530') ] # Execute query def executeQuery(query): client = ApiClient(endpoint=ENDPOINT) accessor = GraphDBApi(client) payload_query = {"query": query} res = accessor.sparql_select(body=payload_query, repo_name=REPO_NAME) try: return json.loads(res) except Exception as e: print(res) return None # Insert data on the database def executeInsert(update): client = ApiClient(endpoint=ENDPOINT) accessor = GraphDBApi(client) payload_update = {"update": update} res = accessor.sparql_update(body=payload_update, repo_name=REPO_NAME) return res # Inserts the predicates used for graphdb in the database, with its name # Insert also the predicates gathered on wikidata def createPredicates(): data = "" for metric in METRICS: data += metric[1]+" <"+nameof+"> \""+metric[0]+"\" .\n" for metric in WIKIDATA_PREDICATES+WIKIDATA_COUNTRY_RELATIONS: data += "<"+WIKIDATA_BASEURL+metric[1]+"> <"+nameof+">"+"\""+metric[0]+"\" .\n" update = """INSERT DATA{""" + data + """}""" ins = executeInsert(update) if len(ins) != 0: print(ins) # Creates a countries repository if it does not exist and populates it with countries' RDF data def setupRepository(): print("Setting up the repository") # Check if repository exists # if it already exists do nothing if repoExists(): return False # Create repository createRepository() # Transform xml into RDF # and store in 'countries.nt' parseXMLtoRDF() # Populate newly created repository with RDF data importRDF() # Create predicates createPredicates() return True # Check if the countries repository already exists def repoExists(): headers = { 'Accept': 'application/json', } response = requests.get('http://localhost:7200/rest/repositories', headers=headers) repositories = json.loads(response.text) for repo in repositories: if 'countries' == repo['id']: return True return False # Creates the countries repository def createRepository(): files = { 'config': ('countries-config.ttl', open('app/helper_files/countries-config.ttl', 'rb')), } params = { 'type': 'form-data' } res = requests.post('http://localhost:7200/rest/repositories', files=files, params=params) # Convert XML countries data to RDF NT def parseXMLtoRDF(): # Get xslt transform and xml file try: xslt_file = etree.parse(settings.XML_FILES + 'countries_transform.xslt') except: raise FileNotFoundError('Could not find the countries tranform') # Create transform transform = etree.XSLT(xslt_file) # Get countries xml countries_tree = etree.parse(settings.XML_FILES + 'countries_data.xml') # Apply transform res = transform(countries_tree) res.write_output("app/nt_files/countries.nt") # Import new countries RDF data into the countries repository def importRDF(): data = "" with open('app/nt_files/countries.nt') as countries_nt: triples = countries_nt.readlines() for triple in triples: data += triple # Perform the insertion update = """INSERT DATA{"""+data+"""}""" ins = executeInsert(update) # If insert returns anything, there is an error if len(ins)>0: print(ins) print("Setup Repository: " + str(setupRepository()))<file_sep>/app/businessLogic.py from app.dbInterface import * # Get the URI's and labels of all countries def getAllCountries(): query = """ PREFIX countries: <"""+BASE_URL+"""/countryProperty/> select ?country ?country_name WHERE{ ?country countries:1 ?country_name } """ results = executeQuery(query) countries = {} for result in results["results"]["bindings"]: countries[result["country"]["value"]] = result["country_name"]["value"] return countries # Get the metrics of all countries def getAllCountryMetrics(): query = """ PREFIX countries: <"""+BASE_URL+"""/countryProperty/> PREFIX foaf: <http://xmlns.com/foaf/0.1/> select distinct ?predicate ?predicate_name WHERE{ ?country countries:1 ?country_name . ?country ?predicate ?value . ?predicate foaf:name ?predicate_name . } """ results = executeQuery(query) predicates = {} for result in results["results"]["bindings"]: predicates[result["predicate"]["value"]] = result["predicate_name"]["value"] return predicates # Get the metrics URI and label all metrics of one country def getMetricsOfCountry(country_uri): query = """ PREFIX countries: <"""+BASE_URL+"""/countryProperty/> PREFIX foaf: <http://xmlns.com/foaf/0.1/> select ?predicate ?value WHERE{ ?country ?predicate ?value . filter(?country=<"""+country_uri+""">) . } """ results = executeQuery(query) predicates = {} for result in results["results"]["bindings"]: if(result["predicate"]["value"] not in predicates): predicates[result["predicate"]["value"]] = [result["value"]["value"]] else: predicates[result["predicate"]["value"]] += [result["value"]["value"]] return predicates # Get the name and URI of all the predicates def getAllPredicateNames(): query = """ PREFIX foaf: <http://xmlns.com/foaf/0.1/> select distinct ?predicate ?predicate_name WHERE{ ?subject ?predicate ?value . ?predicate foaf:name ?predicate_name . } """ results = executeQuery(query) predicates = {} for result in results["results"]["bindings"]: predicates[result["predicate"]["value"]] = result["predicate_name"]["value"] return predicates # Get all countries that have one metric def getAllCountriesByMetric(metric_uri): query = """ PREFIX countries: <""" + BASE_URL + """/countryProperty/> PREFIX foaf: <http://xmlns.com/foaf/0.1/> select distinct ?country ?value WHERE{ ?country ?metric ?value . filter(?metric=<"""+metric_uri+""">) . } """ results = executeQuery(query) countries = {} for result in results["results"]["bindings"]: if (result["country"]["value"] not in countries): countries[result["country"]["value"]] = [result["value"]["value"]] else: countries[result["country"]["value"]] += [result["value"]["value"]] return countries # Get name of subject(URI) def getNameOfSubject(subject): query = """ PREFIX foaf: <http://xmlns.com/foaf/0.1/> select distinct ?name WHERE{ ?subject foaf:name ?name . filter(?subject=<"""+subject+""">) . } """ results = executeQuery(query) predicates = [] for result in results["results"]["bindings"]: predicates += [result["name"]["value"]] return predicates # Get country URI by its name def getCountryURIByName(name): query = """ PREFIX countries: <"""+BASE_URL+"""/countryProperty/> select ?countryURI WHERE{ ?countryURI countries:1 ?name . filter(?name=\"""" + name + """\") . } """ results = executeQuery(query) predicates = [] for result in results["results"]["bindings"]: predicates += [result["countryURI"]["value"]] return predicates # Get country name by its URI def getNameCountryByURI(uri): query = """ PREFIX countries: <""" + BASE_URL + """/countryProperty/> select ?name WHERE{ ?countryURI countries:1 ?name . filter(?countryURI=<""" + uri + """>) . } """ results = executeQuery(query) predicates = [] for result in results["results"]["bindings"]: predicates += [result["name"]["value"]] return predicates def getFavoriteCountries(user_id): query = """ PREFIX base: <""" + BASE_URL + """/> select distinct ?country WHERE{ ?user base:favorite ?country . filter(?user=<""" + BASE_URL+"/user/"+user_id + """>) . } """ results = executeQuery(query) predicates = [] for result in results["results"]["bindings"]: predicates += [result["country"]["value"]] return predicates def addToFavorites(user_id, countryURI): data = "<"+BASE_URL+"/user/"+user_id+"> <"+BASE_URL+"/favorite"+"> <"+BASE_URL+"/country/"+countryURI+"> .\n" update = """INSERT DATA{""" + data + """}""" ins = executeInsert(update) if len(ins) != 0: print(ins) def removeFromFavorites(user_id, countryURI): data = "<" + BASE_URL + "/user/" + user_id + "> <" + BASE_URL + "/favorite" + "> <" + BASE_URL + "/country/" + countryURI + "> .\n" update = """DELETE DATA{""" + data + """}""" ins = executeInsert(update) if len(ins) != 0: print(ins)<file_sep>/app/inferences.py from app.businessLogic import * # Add inferences to database def addRelations(relations): data = "" for relation in relations: for subject in relations[relation]: for obj in relations[relation][subject]: data += "<"+subject+"> <"+relation+"> <"+obj+"> . \n" print(data) query = """ PREFIX countries: <""" + BASE_URL + """/countryProperty/> INSERT DATA {"""+data+"""} """ ins = executeInsert(query) if len(ins) != 0: print(ins) # Returns the reflexice inferences def getReflexiveInferences(): relations = {} newRelations = {} for relation in WIKIDATA_COUNTRY_RELATIONS: relations[WIKIDATA_BASEURL+relation[1]] = getAllCountriesByMetric(WIKIDATA_BASEURL+relation[1]) for relation in relations: if relation not in newRelations: newRelations[relation] = {} for country1 in relations[relation]: for country2 in relations[relation][country1]: if country2 not in newRelations[relation]: newRelations[relation][country2] = [] newRelations[relation][country2] += [country1] return newRelations # Query to get the best countries to invest def getBestCountriesToInvest(): query = """ PREFIX countries: <""" + BASE_URL + """/countryProperty/> select ?countryURI WHERE{ ?countryURI countries:45 ?unemploymentRate . ?countryURI countries:26 ?laborForce . ?countryURI countries:23 ?investment . ?countryURI countries:39 ?publicDebt . ?countryURI countries:20 ?inflationRate . ?countryURI countries:25 ?lifeExpectancy . ?countryURI countries:9 ?exports . filter(?unemploymentRate<10.0) filter(?laborForce>100000) filter(?investment>15.0) filter(?publicDebt<175.0) filter(?inflationRate<10.0) filter(?lifeExpectancy>75.0) } ORDER BY DESC(?exports) """ results = executeQuery(query) predicates = [] for result in results["results"]["bindings"]: predicates += [result["countryURI"]["value"]] return predicates # Query to get the countries with more internet traffic def getCountriesWithMoreInternetTraffic(): query = """ PREFIX countries: <""" + BASE_URL + """/countryProperty/> select ?countryURI WHERE{ ?countryURI countries:43 ?mobileCelularUsers . ?countryURI countries:42 ?mainLinesInUse . ?countryURI countries:21 ?internetHosts . filter(?mobileCelularUsers>10000000) filter(?mainLinesInUse>10000000) filter(?internetHosts>1056950) } ORDER BY DESC(?internetHosts) """ results = executeQuery(query) predicates = [] for result in results["results"]["bindings"]: predicates += [result["countryURI"]["value"]] return predicates # Query to get the best countries to live def getBestCountriesToLive(): query = """ PREFIX countries: <""" + BASE_URL + """/countryProperty/> select ?countryURI WHERE{ ?countryURI countries:45 ?unemploymentRate . ?countryURI countries:23 ?investment . ?countryURI countries:39 ?publicDebt . ?countryURI countries:20 ?inflationRate . ?countryURI countries:25 ?lifeExpectancy . ?countryURI countries:13 ?hiv_adult . ?countryURI countries:5 ?death_rate . filter(?unemploymentRate<10.0) filter(?investment>=15.0) filter(?publicDebt<=175.0) filter(?inflationRate<=10.0) filter(?lifeExpectancy>=75.0) filter(?hiv_adult<=0.40) filter(?death_rate<=11) } ORDER BY DESC(?lifeExpectancy) """ results = executeQuery(query) predicates = [] for result in results["results"]["bindings"]: predicates += [result["countryURI"]["value"]] return predicates<file_sep>/app/templates/app/country.html {% extends "app/layout.html" %} {% block menuNavbar %} <li class="active"><a href="{% url 'home' %}">Countries</a></li> <li><a href="{% url 'pred' %}">Predicates</a></li> <li><a href="{% url 'inferences' %}">Inferences</a></li> <li><a href="{% url 'favorites' %}">Favorites</a></li> <li><a href="{% url 'statistics' %}">Statistics</a></li> {% endblock %} {% block content %} {% load staticfiles %} <div class="row"> <div class="col-md-12"> <div class="page-header"> <h1 id="{{ title }}">{{ title }}</h1> <p class="lead">Choose one metric to compare it with other countries</p> <hr /> </div> <div class="jumbotron"> <h3>Country information</h3> <hr /> <div class="row"> <ul> {% for predicate, metric in metrics %} <li> <a href="/metric/{{ predicate.url }}"> <span about="{{ predicate.uri }}" property="foaf:name">{{ predicate.label }}</span> </a> - {% ifequal metric.uri metric.value %} <span about="countries:country/{{ country_id }}" property="{{ predicate.uri }}">{{ metric.value }}</span> {% else %} {% ifnotequal metric.url "" %} <a href="/country/{{ metric.url }}"> <span about="countries:country/{{ country_id }}" rel="{{ predicate.uri }}"> <span about="{{ metric.uri }}" property="{{ metric.pred_nameof }}">{{ metric.value }}</span> </span> </a> {% else %} <span about="countries:country/{{ country_id }}" rel="{{ predicate.uri }}"> <span about="{{ metric.uri }}" property="{{ metric.pred_nameof }}">{{ metric.value }}</span> </span> {% endifnotequal %} {% endifequal %} </li> {% endfor %} </ul> <br> <img style="max-height: 300px; max-width: 300px; display: block; margin: auto;" about="countries:country/{{ country_id }}" rel="countries:countryProperty/flag" src="{{ image }}"> <br> {% if favorite %} <p>Country is on favorites</p> <button type="button" onclick="location.href = '/country/{{ country_id }}/favo';" class="btn btn-primary">Remove from favorites</button> {% else %} <p>Country is not on favorites</p> <button type="button" onclick="location.href = '/country/{{ country_id }}/favo';" class="btn btn-primary">Add to favorites</button> {% endif %} <br> <br> {% if has_wiki %} <p>Wikidata data is already on this country!</p> <button type="button" onclick="location.href = '/country/{{ country_id }}/reload';" class="btn btn-primary">Reload the data from wikidata!</button> {% else %} <button type="button" onclick="location.href = '/country/{{ country_id }}/reload';" class="btn btn-primary">Gather data from Wikidata!</button> {% endif %} <br> <br> {% if has_relations %} <p>Wikidata relations are already updated on this country!</p> <button type="button" onclick="location.href = '/country/{{ country_id }}/relations';" class="btn btn-primary">Reload the relations with other countries!</button> {% else %} <button type="button" onclick="location.href = '/country/{{ country_id }}/relations';" class="btn btn-primary">Try to get relations with other countries!</button> {% endif %} </div> </div> <br> </div> </div> {% endblock %} <file_sep>/app/wikidataInterface.py from wikidata.client import Client import requests from lxml import etree from app.dbInterface import * from app.businessLogic import getCountryURIByName # Queries the wikidata with the REST API with sparql query def queryWiki(query): response = requests.get("https://query.wikidata.org/bigdata/namespace/wdq/sparql?query=" + query) response.encoding = 'utf-8' content = response.text parser = etree.XMLParser(encoding='utf-8') root = etree.fromstring(content.encode('utf-8'), parser=parser) results = root.findall('.//{http://www.w3.org/2005/sparql-results#}result') dict_results = [] for result in results: res = result.findall('{http://www.w3.org/2005/sparql-results#}binding') binding = [] for bind in res: if (bind.find('{http://www.w3.org/2005/sparql-results#}uri') != None): binding += [{bind.get('name'): bind.find('{http://www.w3.org/2005/sparql-results#}uri').text}] elif (bind.find('{http://www.w3.org/2005/sparql-results#}literal') != None): binding += [{bind.get('name'): bind.find('{http://www.w3.org/2005/sparql-results#}literal').text}] dict_results += [binding] return dict_results # Splits the path from the wikidata entity def getWikidataEntity(path): return path.split("http://www.wikidata.org/entity/")[1] # Return all countries on wikidata, with it's name and URI, in form (country, countryLabel) def getAllWikidataCountries(): query = """ SELECT ?country ?countryLabel WHERE { ?country wdt:P31 wd:Q3624078 . SERVICE wikibase:label { bd:serviceParam wikibase:language "en" } } """ return queryWiki(query) # Returns the data in form (country, countryLabel) of one country in wikidata def getWikidataCountry(country_name): query=""" SELECT ?country ?countryLabel WHERE { ?country wdt:P31 wd:Q3624078 . ?country rdfs:label ?countryLabel . FILTER (lang(?countryLabel) = "en") filter(regex(?countryLabel,"^"""+country_name+"""$", "i")) } """ result = queryWiki(query) if len(result)>0: return result[0] return None # Get the country entity, given a label of the country def getWikidataCountryEntity(label): try: wikidataCountry = getWikidataCountry(label)[0]["country"] except: return None client = Client() entity = client.get(getWikidataEntity(wikidataCountry)) return entity # Returns the url of the image of an entity def getWikidataImageURL(entity): client = Client() flag_img_prop = client.get('P41') flag_file = entity[flag_img_prop] return flag_file.image_url # Creates new predicates given a country URI and a country wikidata entity def createCountryNewPredicates(country, countryEntity): client = Client() newRelations = [] newValues = [] for predicate in WIKIDATA_PREDICATES: pred = client.get(predicate[1]) print() print(predicate[0]) print(pred) if pred in countryEntity: for element in countryEntity.getlist(pred): predid = pred.id elementid = element.id elementlabel = element.label print(country, predid, element) newRelations += [(country, predid, elementid)] print(element.id, nameof, elementlabel) newValues += [(elementid, nameof, elementlabel)] else: print("No data was found") data = "" for metric in newRelations: data += "<"+BASE_URL+"/country/"+metric[0] + "> <" + WIKIDATA_BASEURL+metric[1] + "> <" + WIKIDATA_BASEURL+metric[2] + "> .\n" for metric in newValues: data += "<" + WIKIDATA_BASEURL + metric[0] + "> <" + nameof + "> \"" + str(metric[2]) + "\" .\n" data += "<"+BASE_URL+"/country/"+country + "> <"+BASE_URL+"/hasWikidata>"+" \"True\" .\n" update = """INSERT DATA{""" + data + """}""" ins = executeInsert(update) if len(ins) != 0: print(ins) return newRelations # Checks if the country has results updated with wikidata data def checkCountryHasWikidata(country_id): query = """ PREFIX foaf: <http://xmlns.com/foaf/0.1/> select ?name WHERE{ ?subject <"""+BASE_URL+"""/hasWikidata> "True" . filter(?subject=<""" + BASE_URL+"/country/"+country_id + """>) . } """ results = executeQuery(query) if len(results["results"]["bindings"])>0: return True return False # Creates new relations between countries def createCountriesRelations(countryURI, countryEntity): client = Client() newData = "" for rel in WIKIDATA_COUNTRY_RELATIONS: pred = client.get(rel[1]) if pred in countryEntity: for element in countryEntity.getlist(pred): elementlabel = element.label print(elementlabel) countriesURI = getCountryURIByName(str(elementlabel)) if(len(countriesURI)==0): print("Could not find country "+str(elementlabel)+" in local database") else: country2URI = countriesURI[0] print(country2URI) newData += "<"+BASE_URL+"/country/"+countryURI+"> <" + WIKIDATA_BASEURL+rel[1] +"> <"+country2URI+"> . \n" newData += "<" + BASE_URL + "/country/" + countryURI + "> <" + BASE_URL + "/hasRelations>" + " \"True\" .\n" print(newData) update = """INSERT DATA{""" + newData + """}""" ins = executeInsert(update) if len(ins) != 0: print(ins) # Checks if the country has relations with other countries updated with wikidata data def checkCountryHasWikidataRelations(country_id): query = """ PREFIX foaf: <http://xmlns.com/foaf/0.1/> select ?subject WHERE{ ?subject <"""+BASE_URL+"""/hasRelations> "True" . filter(?subject=<""" + BASE_URL+"/country/"+country_id + """>) . } """ results = executeQuery(query) if len(results["results"]["bindings"])>0: return True return False<file_sep>/app/templates/app/home.html {% extends "app/layout.html" %} {% block menuNavbar %} <li class="active"><a href="{% url 'home' %}">Countries</a></li> <li><a href="{% url 'pred' %}">Predicates</a></li> <li><a href="{% url 'inferences' %}">Inferences</a></li> <li><a href="{% url 'favorites' %}">Favorites</a></li> <li><a href="{% url 'statistics' %}">Statistics</a></li> {% endblock %} {% block content %} {% load staticfiles %} <div class="row"> <div class="col-md-12"> <div class="page-header"> <h1 id="{{ title }}">{{ title }}</h1> <p class="lead">Choose one country and see its metrics!</p> <hr /> </div> <div class="jumbotron"> <h3>Countries</h3> <hr /> <div class="row"> <ul> {% for country in countries %} <li><a about="countries:{{ country.uri }}" href="country/{{ country.url }}"><span property="countries:countryProperty/1">{{ country.label }}</span></a></li> {% endfor %} </ul> </div> </div> <br> </div> </div> {% endblock %}
e671e9bfb6f27c284829d8310479990862008bf8
[ "Markdown", "Python", "HTML" ]
10
Python
jackylee1/InfoCountries
57c04cec80e174ae62d5be71ebaf387898ffdbb5
0ff583714c6b3e7c84c42a6290df4721e4878d91
refs/heads/master
<file_sep>import time import sys import csv import aerospike def test_db(): config = { 'hosts': [ ('127.0.0.1', 3000) ] } client = aerospike.client(config).connect() t0 = time.time() global rec rec = {} with open('skunkworks.csv', 'r') as f: reader = csv.reader(f) rownum = 0 for row in reader: # Save First Row with headers if rownum == 0: header = row else: colnum = 0 for col in row: rec[header[colnum]] = col colnum += 1 rownum += 1 if rec: client.put(('test', 'demo', str(rownum)), rec) rec = {} t1 = time.time() load_time = t1 - t0 client.close() return load_time <file_sep>import time import sys import csv import aerospike import pandas as pd def test_db(): config = { 'hosts': [ ('127.0.0.1', 3000) ] } client = aerospike.client(config).connect() t0 = time.time() data = pd.read_csv('skunkworks.csv') columns = data.columns count = 0 for index, row in data.iterrows(): temp_value = {} for column in columns: temp_value[column] = row[column] client.put(('test', 'demo', str(index)), temp_value) # global rec # rec = {} # # # with open('skunkworks.csv', 'r') as f: # reader = csv.reader(f) # rownum = 0 # for row in reader: # # # Save First Row with headers # if rownum == 0: # header = row # else: # colnum = 0 # for col in row: # rec[header[colnum]] = col # colnum += 1 # rownum += 1 # if rec: # client.put(('test', 'demo', str(rownum)), rec) # rec = {} t1 = time.time() load_time = t1 - t0 client.close() return load_time <file_sep>import time import sys import csv import aerospike def test_db(): t2 = time.time() config = { 'hosts': [ ('127.0.0.1', 3000) ] } client = aerospike.client(config).connect() for i in range(2,500002): (key, metadata, record) = client.get(('test', 'demo', str(i))) # print(record) t3 = time.time() read_time = t3 - t2 return read_time
16d149b448452ad0432bd5982812226165a2a50f
[ "Python" ]
3
Python
benjcabalona1029/Skunkworks
4b4882ad78ce2c065ba400a9beca22ecdb787ca6
4105b3837858f1c9e9d8a5ffa4ab90e5071f491a
refs/heads/master
<repo_name>RadamHussein/CS362-004-SP17<file_sep>/projects/smithada/dominion/cardtest3.c #include "dominion.h" #include "dominion_helpers.h" #include <stdio.h> #include <string.h> #include <stdlib.h> void buildHand(struct gameState *G){ G->hand[0][0] = estate; G->hand[0][1] = copper; G->hand[0][2] = smithy; G->hand[0][3] = gold; G->hand[0][4] = duchy; } void checkReturnValue(int ret, int choice){ if (ret == -1){ printf("mineFunction(): PASS choice %d not a valid card\n", choice); } else{ printf("mineFunction(): FAIL choice %d not a valid card\n", choice); } } int main(){ int i; int failDiscard = 0; int passGainCard = 0; int ret; int players = 2; struct gameState G; //int testCards[10] = {mine, adventurer, estate, gold, duchy, gardens, silver, copper, estate, smithy}; int gameCards[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse, sea_hag, great_hall, smithy}; ret = initializeGame(players, gameCards, 10, &G); if (ret != 0){ printf("adventurerFunction(): FAILED to initialize game\n"); } //test choice 1 < copper ret = mineFunction(0, 0, 1, &G, 0); checkReturnValue(ret, 1); //test choice 1 > gold ret = mineFunction(0, 2, 1, &G, 2); checkReturnValue(ret, 1); //test valid choice 1, invalid choice 2 ret = mineFunction(0, 1, estate, &G, 1); checkReturnValue(ret, 2); ret = mineFunction(0, 1, copper, &G, 1); checkReturnValue(ret, 2); //test passing choice 1 + 3 > choice 2 ret = mineFunction(0, 2, gold, &G, 1); if (ret == -1){ printf("mineFunction(): FAIL value of choice1 + 3 > choice2\n"); } else{ printf("mineFunction(): PASS value of choice1 + 3 > choice2\n"); } //test passing choice 1 + 3 < choice 2 ret = mineFunction(0, 0, gold, &G, 1); if (ret == -1){ printf("mineFunction(): PASS value of choice1 + 3 < choice2\n"); } else{ printf("mineFunction(): FAIL value of choice1 + 3 < choice2\n"); } //test ret = mineFunction(0, 2, gold, &G, 0); for (i = 0; i < 5; i++){ if (G.hand[0][i] == smithy){ failDiscard = 1; } if (G.hand[0][i] == gold){ passGainCard = 1; } } if (failDiscard == 0 && passGainCard == 1){ printf("mineFunction(): PASS trashing card from hand and receiving selected treasure card\n"); } else{ printf("mineFunction(): FAIL trashing card from hand and receiving selected treasure card\n"); } return 0; }<file_sep>/projects/smithada/dominion/randomtestcard1.c #include "dominion.h" #include "dominion_helpers.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> const char* getCardName(int cardType){ switch(cardType){ case estate: return "estate"; case duchy: return "duchy"; case province: return "province"; case copper: return "copper"; case silver: return "silver"; case gold: return "gold"; case adventurer: return "adventurer"; case council_room: return "council room"; case feast: return "feast"; case gardens: return "gardens"; case mine: return "mine"; case remodel: return "remodel"; case smithy: return "smithy"; case village: return "village"; case baron: return "baron"; case great_hall: return "great_hall"; case minion: return "minion"; case steward: return "steward"; case tribute: return "tribute"; case ambassador: return "ambassador"; case cutpurse: return "cutpurse"; case embargo: return "embargo"; case outpost: return "outpost"; case salvager: return "salvager"; case sea_hag: return "sea hag"; case treasure_map: return "treasure_map"; } return "unknown_value"; } void displayDeck(int player, struct gameState *G, int numCards){ int i; printf("Player %d's deck:\n", player); for (i = 0; i < numCards; i++){ printf("%s\n", getCardName(G->deck[player][i])); } printf("\n"); } void displayHand(int player, struct gameState *G, int numCards){ int i; printf("Player %d's hand: \n", player); for (i = 0; i < numCards; i++){ printf("%s\n", getCardName(G->hand[player][i])); } printf("\n"); } void displayDiscard(int player, struct gameState *G, int numCards){ int i; printf("Player %d's discard: \n", player); for (i = 0; i < numCards; i++){ printf("%s\n", getCardName(G->discard[player][i])); } printf("\n"); } int main(){ int i; int v; int ret; int players = 4; int chosenCard; int currentPlayer; int currentHandPos; int originalDeckCount; int originalHandCount; int passCount = 0; int failCount = 0; struct gameState G; struct gameState G2; int k[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse, sea_hag, great_hall, smithy}; int J[16] = {adventurer, gardens, embargo, village, minion, mine, cutpurse, sea_hag, great_hall, smithy, copper, gold, silver, duchy, province, estate}; srand(time(NULL)); ret = initializeGame(players, k, 10, &G); if (ret != 0){ printf("FAILED to initialize game\n"); } //make a copy of the initial struct memcpy(&G2, &G, sizeof(struct gameState)); for (i = 0; i < 2000; i++){ currentPlayer = rand() % 4; //get a random handCount number originalHandCount = rand() % 500; G.handCount[currentPlayer] = originalHandCount; //fill player's hand with random cards. Keep track of the first two treasure_map cards. for(v = 0; v < originalHandCount; v++){ chosenCard = J[rand() % 16]; G.hand[currentPlayer][v] = chosenCard; if(chosenCard == smithy){ currentHandPos = v; } } //get a random handCount number originalDeckCount = rand() % 500; G.deckCount[currentPlayer] = originalDeckCount; //fill player's hand with random cards. Keep track of the first two treasure_map cards. for(v = 0; v < originalDeckCount; v++){ chosenCard = J[rand() % 16]; G.hand[currentPlayer][v] = chosenCard; } //play smithy smithyFunction(currentPlayer, currentHandPos, &G); if (G.handCount[currentPlayer] == (originalHandCount + 2)){ if(G.hand[currentPlayer][currentHandPos] == smithy){ failCount++; } else{ passCount++; } } else{ failCount++; } //copy initial struct back into G memcpy(&G, &G2, sizeof(struct gameState)); G.deckCount[currentPlayer] = originalDeckCount; G.handCount[currentPlayer] = originalHandCount; } printf("Test completed:\n"); printf("PASSED.... %d\n", passCount); printf("FAILED.... %d\n", failCount); return 0; }<file_sep>/projects/smithada/dominion/cardtest1.c #include "dominion.h" #include "dominion_helpers.h" #include <stdio.h> #include <string.h> #include <stdlib.h> const char* getCardName(int cardType){ switch(cardType){ case estate: return "estate"; case duchy: return "duchy"; case province: return "province"; case copper: return "copper"; case silver: return "silver"; case gold: return "gold"; case adventurer: return "adventurer"; case council_room: return "council room"; case feast: return "feast"; case gardens: return "gardens"; case mine: return "mine"; case remodel: return "remodel"; case smithy: return "smithy"; case village: return "village"; case baron: return "baron"; case great_hall: return "great_hall"; case minion: return "minion"; case steward: return "steward"; case tribute: return "tribute"; case ambassador: return "ambassador"; case cutpurse: return "cutpurse"; case embargo: return "embargo"; case outpost: return "outpost"; case salvager: return "salvager"; case sea_hag: return "sea hag"; case treasure_map: return "treasure_map"; } return "unknown_value"; } void printDeck(int player, struct gameState *G){ int i; printf("Player 1's deck:\n"); for (i = 0; i < 9; i++){ printf("%s\n", getCardName(G->deck[0][i])); } printf("\n"); printf("Player 1's hand: \n"); for (i = 0; i < 9; i++){ printf("%s\n", getCardName(G->hand[0][i])); } printf("Player 1's discard: \n"); for (i = 0; i < 9; i++){ printf("%s\n", getCardName(G->discard[0][i])); } } int main(){ int i; int ret; int drawntreasure = 0; int players = 2; struct gameState G; struct gameState G2; int k[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse, sea_hag, great_hall, smithy}; ret = initializeGame(players, k, 10, &G); if (ret != 0){ printf("adventurerFunction(): FAILED to initialize game\n"); } G.deck[0][0] = smithy; G.deck[0][1] = estate; G.deck[0][2] = silver; G.deck[0][3] = embargo; G.deck[0][4] = mine; G.deck[0][5] = duchy; G.deck[0][6] = gold; G.deck[0][7] = mine; G.deck[0][8] = estate; memcpy (&G2, &G, sizeof(struct gameState)); adventurerFunction(0, &G, drawntreasure); for (i = 0; i < 9; i++){ if (G.deck[0][i] != G2.deck[0][i]){ drawntreasure++; } } if(drawntreasure < 2){ printf("adventurerFunction(): FAIL drawing treasure from deck\n"); printf("adventurerFunction(): TEST FAILED\n"); } else{ printf("adventurerFunction(): PASS drawing treasure from deck\n"); } return 0; }<file_sep>/projects/smithada/dominion/randomcardtest1.c #include "dominion.h" #include "dominion_helpers.h" #include <stdio.h> #include <string.h> #include <stdlib.h> const char* getCardName(int cardType){ switch(cardType){ case estate: return "estate"; case duchy: return "duchy"; case province: return "province"; case copper: return "copper"; case silver: return "silver"; case gold: return "gold"; case adventurer: return "adventurer"; case council_room: return "council room"; case feast: return "feast"; case gardens: return "gardens"; case mine: return "mine"; case remodel: return "remodel"; case smithy: return "smithy"; case village: return "village"; case baron: return "baron"; case great_hall: return "great_hall"; case minion: return "minion"; case steward: return "steward"; case tribute: return "tribute"; case ambassador: return "ambassador"; case cutpurse: return "cutpurse"; case embargo: return "embargo"; case outpost: return "outpost"; case salvager: return "salvager"; case sea_hag: return "sea hag"; case treasure_map: return "treasure_map"; } return "unknown_value"; } int main(){ int i; int ret; int players = 4; int currentPlayer; int currentHandPos; int originalDeckCount; int originalHandCount; struct gameState G; struct gameState G2; int k[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse, sea_hag, great_hall, smithy}; ret = initializeGame(players, k, 10, &G); if (ret != 0){ printf("adventurerFunction(): FAILED to initialize game\n"); } //make a copy of the initial struct memcpy(&G2, &G, sizeof(struct gameState)); originalDeckCount = G.deckCount[0]; originalHandCount = G.handCount[0]; for (i = 0; i < 5; i++){ currentPlayer = rand() % 4; currentHandPos = rand() % 5; G.hand[currentPlayer][currentHandPos] = smithy; //play smithy smithyFunction(0, 0, &G); printf("\n"); printf("Playing smithy from hand position %d...\n", i+1); if (G.deckCount[currentPlayer] == (originalDeckCount - 3) && G.handCount[currentPlayer] == (originalHandCount + 2)){ printf("smithyFunction(): PASS correctly gaining 3 cards and removing smithy from hand\n"); } else{ printf("smithyFunction(): FAIL correctly gaining 3 cards and removing smithy from hand\n"); } //copy initial struct back into G memcpy(&G, &G2, sizeof(struct gameState)); G.deckCount[0] = originalDeckCount; G.handCount[0] = originalHandCount; } return 0; }<file_sep>/projects/smithada/Quiz2/randomstring.c Random Testing Quiz 2 <NAME> CS 362 - Spring 2017 Development: I first started off by probably overcomplicating things. I wanted to know if there were any limits on how the randomization should work for both inputChar() and inputString(). inputChar() was the easiest to settle on as far as the implementation goes. It simply generates a random number which corresponds to an index in an array of characters. I chose to fill that array with the lowercase alphabet and all the special characters which would also be needed to eventually make the error message appear. I then tested the program with inputString() returning the string literal 'reset\0'. This caused the error to occur at around 200 iterations. inputString() took some more thought as to what would be appropriate for the randomization. My first thought was to simply use the random characters returned from inputChar() to build a random string in inputString(). I attempted this first and have actually left that code in inputString() with comments. It is a very good example of how random testing is not ideal for uncovering edge cases. I let the program run through 200 million iterations and finally shut it down. In this case, had I not had the source code for the testme() function, I would have likely settled on this implementation and passed the test without ever finding the error and without letting it run through nearly that many iterations. However, this may also have been fine in a real world application depending on how it is being used. If this were something like a simple program to generate randomized passwords, and such a program could be run at least 200 million times without an error, this could be completely acceptable. Next, in an attempt to actually reach the error message with a random string, I made 2 other alterations to inputString(). First, I tried constructing a random string using only the lowercase alphabet. In this situation also I ran the program until I reached 200 million iterations, then stopped. I still was not able to reach the error message. So I made a final alteration which you will see is what is currently imlemented. I assigned a char array with only the characters that make up the 'reset\0' string and still use rand() to get randomly get indices from the char array to build the string. Finally I was able to reach the error with this pseudorandom string at around 2000 iterations.<file_sep>/projects/smithada/dominion/unittest1.c #include "dominion.h" #include <stdio.h> #include <assert.h> #include <string.h> #include <stdlib.h> int checkTheDecks(struct gameState *G){ int copperCount = 0; int estateCount = 0; int wrongCard = 0; int i; for (i = 0; i < 10; i++){ if (G->deck[0][i] == copper){ copperCount++; } else if (G->deck[0][i] == estate){ estateCount++; } else{ wrongCard++; } } if (copperCount == 7 && estateCount == 3 && wrongCard == 0){ return 0; } else{ return -1; } } int main () { struct gameState G; struct gameState G2; int i; int j; int numPlayers = 2; int ret; // Initialize G. //////Test1: Passing invalid deckCount//////// G.deckCount[0] = 0; ret = shuffle(0, &G); printf("shuffle(): "); if (ret == -1){ printf("PASS"); } else{ printf("FAIL"); } printf(" when passing invalid deckCount\n"); //set player decks for (i = 0; i < numPlayers; i++) { G.deckCount[i] = 0; for (j = 0; j < 3; j++) { G.deck[i][j] = estate; G.deckCount[i]++; } for (j = 3; j < 10; j++) { G.deck[i][j] = copper; G.deckCount[i]++; } } memcpy (&G2, &G, sizeof(struct gameState)); ///////Test2: Decks are the same before shuffling//////// printf("shuffle(): "); if (memcmp(&G, &G2, sizeof(struct gameState)) == 0){ printf("PASS"); } else{ printf("FAIL"); } printf(" when comparing un-shuffled decks\n"); ret = shuffle(0,&G); ///////Test3: Expected return value/////// printf("shuffle(): "); if (ret == 0){ printf("PASS"); } else{ printf("FAIL"); } printf(" return value check\n"); ///////Test4: Decks are different after shuffling/////// printf("shuffle(): "); if (memcmp(&G, &G2, sizeof(struct gameState)) == 0){ printf("FAIL"); } else{ printf("PASS"); } printf(" when comparing shuffled decks (decks are different)\n"); ///////Test5: Decks are same after shuffle and sort/////// i = checkTheDecks(&G); j = checkTheDecks(&G2); printf("shuffle(): "); if (i == 0 && j == 0){ printf("PASS"); } else{ printf("FAIL"); } printf(" when comparing original and shuffled decks\n"); return 0; } <file_sep>/projects/smithada/dominion/randomtestadventurer.c #include "dominion.h" #include "dominion_helpers.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> const char* getCardName(int cardType){ switch(cardType){ case estate: return "estate"; case duchy: return "duchy"; case province: return "province"; case copper: return "copper"; case silver: return "silver"; case gold: return "gold"; case adventurer: return "adventurer"; case council_room: return "council room"; case feast: return "feast"; case gardens: return "gardens"; case mine: return "mine"; case remodel: return "remodel"; case smithy: return "smithy"; case village: return "village"; case baron: return "baron"; case great_hall: return "great_hall"; case minion: return "minion"; case steward: return "steward"; case tribute: return "tribute"; case ambassador: return "ambassador"; case cutpurse: return "cutpurse"; case embargo: return "embargo"; case outpost: return "outpost"; case salvager: return "salvager"; case sea_hag: return "sea hag"; case treasure_map: return "treasure_map"; } return "unknown_value"; } void displayDeck(int player, struct gameState *G, int numCards){ int i; printf("Player %d's deck:\n", player); for (i = 0; i < numCards; i++){ printf("%s\n", getCardName(G->deck[player][i])); } printf("\n"); } int main(){ int i; int v; int ret; int drawntreasure = 0; int players = 4; int currentPlayer; int chosenCard; int treasureCount; int originalHandCount; int originalDeckCount; int numberOfCardsDrawn; int passCount = 0; int failCount = 0; struct gameState G; struct gameState G2; int k[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse, sea_hag, great_hall, smithy}; int J[16] = {adventurer, gardens, embargo, village, minion, mine, cutpurse, sea_hag, great_hall, smithy, copper, gold, silver, duchy, province, estate}; //array holds the location where the first two treasure cards are placed in the initial deck int treasureLocation[2] = {0, 0}; srand(time(NULL)); ret = initializeGame(players, k, 10, &G); if (ret != 0){ printf("FAILED to initialize game\n"); } memcpy (&G2, &G, sizeof(struct gameState)); for (i = 0; i < 2000; i++){ treasureCount = 0; currentPlayer = rand() % 4; //get a random handCount number originalHandCount = rand() % 498; G.handCount[currentPlayer] = originalHandCount; //fill player's hand with random cards. for(v = 0; v < originalHandCount; v++){ chosenCard = J[rand() % 16]; G.hand[currentPlayer][v] = chosenCard; } //get a random handCount number originalDeckCount = rand() % 500; G.deckCount[currentPlayer] = originalDeckCount; //fill player's deck with random cards. Keep track of the first two treasure cards. for(v = 0; v < originalDeckCount; v++){ chosenCard = J[rand() % 16]; G.deck[currentPlayer][v] = chosenCard; if (chosenCard == copper || chosenCard == gold || chosenCard == silver){ if (treasureCount < 2){ treasureLocation[treasureCount] = v; treasureCount++; } } } //printf("Deck after initialization: \n"); //printf("treasureCount: %d\n", treasureCount); //printf("Card locations: %d, %d\n", treasureLocation[0], treasureLocation[1]); numberOfCardsDrawn = treasureLocation[1] + 1; //don't call function if no treasure in deck. Will cause infinite loop. if (treasureCount > 0){ adventurerFunction(currentPlayer, &G, drawntreasure); } if (treasureCount == 2){ if(G.handCount[currentPlayer] == originalHandCount + 1 && G.discardCount[currentPlayer] == numberOfCardsDrawn - 2){ passCount++; } else{ failCount++; } } else if(treasureCount == 1){ if (G.handCount[currentPlayer] == originalHandCount && G.discardCount[currentPlayer] == numberOfCardsDrawn - 1){ passCount++; } else{ failCount++; } } memcpy (&G, &G2, sizeof(struct gameState)); } printf("Test complete: \n"); printf("PASS.... %d\n", passCount); printf("FAIL.... %d\n", failCount); return 0; }<file_sep>/projects/smithada/dominion/cardtest4.c #include "dominion.h" #include "dominion_helpers.h" #include <stdio.h> #include <string.h> #include <stdlib.h> void buildHand(struct gameState *G){ G->hand[0][0] = treasure_map; G->hand[0][1] = copper; G->hand[0][2] = smithy; G->hand[0][3] = gold; G->hand[0][4] = duchy; } int main(){ int foundTreasureMap = 0; int treasureAdded = 0; int i; int ret; struct gameState G; int players = 2; int gameCards[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse, sea_hag, great_hall, smithy}; ret = initializeGame(players, gameCards, 10, &G); if (ret != 0){ printf("adventurerFunction(): FAILED to initialize game\n"); } //test hand with only 1 treasure map ret = treasuremapFunction(0, &G, 0); if (ret == -1){ printf("treasuremapFunction(): PASS hand with only 1 treasure map\n"); } else{ printf("treasuremapFunction(): FAIL hand with only 1 treasure map\n"); } //test that 1 treasure map was removed from hand for (i = 0; i < 5; i++){ if (G.hand[0][i] == treasure_map){ foundTreasureMap = 1; } } if (foundTreasureMap == 1){ printf("treasuremapFunction(): FAIL removing single treasure_map from hand\n"); foundTreasureMap = 0; } else{ printf("treasuremapFunction(): PASS removing single treasure_map from hand\n"); } //Now add a second treasure map to the hand G.hand[0][2] = treasure_map; //test with 2 treasure maps ret = treasuremapFunction(0, &G, 0); for (i = 0; i < 5; i++){ if (G.hand[0][i] == treasure_map){ foundTreasureMap = 1; } } //does the function return 1 for success and find no more treasure maps in the hand if (ret == 1 && foundTreasureMap == 0){ printf("treasuremapFunction(): PASS hand with 2 treasure maps\n"); } else{ printf("treasuremapFunction(): FAIL hand with 2 treasure maps\n"); } for (i = 0; i < 11; i++){ if (G.deck[0][i] == gold){ treasureAdded = 1; } } if (treasureAdded == 1){ printf("treasuremapFunction(): PASS gold added to deck\n"); } else{ printf("treasuremapFunction(): FAIL gold added to deck\n"); } return 0; }<file_sep>/projects/smithada/dominion/unittest4.c #include "dominion.h" #include "dominion_helpers.h" #include <stdio.h> #include <string.h> #include <stdlib.h> int main(){ int i; struct gameState G; struct gameState G2; int k[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse, sea_hag, great_hall, smithy}; int cardsNotInGame[10] = {council_room, feast, remodel, baron, steward, tribute, ambassador, outpost, salvager, treasure_map}; char *cardsChanged[3] = {"discard", "deck", "hand"}; int players = 2; int ret; ret = initializeGame(players, k, 10, &G); if (ret !=0){ printf("INITIALIZATION FAILED\n"); return 0; } ///////Test1: Check all cards not in game/////// for (i = 0; i < sizeof(cardsNotInGame)/sizeof(cardsNotInGame[0]); i++){ ret = gainCard(cardsNotInGame[i], &G, 1, 1); if (ret == -1){ printf("gainCard(): PASS passing card not in game\n"); } else{ printf("gainCard(): FAIL passing card not in game\n"); } } ///////Test2: Check that changes have been made to hands, deck and discard for players/////// memcpy (&G2, &G, sizeof(struct gameState)); for (i = 0; i < 3; i++){ ret = gainCard(adventurer, &G, i, 1); if (ret != 0){ printf("gainCard(): FAIL passing valid game card to %s\n", cardsChanged[i]); } else{ if (memcmp(&G, &G2, sizeof(struct gameState)) == 0){ printf("gainCard(): FAIL passing valid game card to %s\n", cardsChanged[i]); } else{ printf("gainCard(): PASS passing valid game card to %s\n", cardsChanged[i]); memcpy (&G, &G2, sizeof(struct gameState)); //copy G2 back to G } } } return 0; } <file_sep>/projects/smithada/dominion/unittest2.c #include "dominion.h" #include <stdio.h> #include <assert.h> #include <string.h> #include <stdlib.h> void assertNotZero(value){ if (value != 0){ printf("PASS"); } else{ printf("FAIL"); } } void assertZero(value){ if (value != 0){ printf("FAIL"); } else{ printf("PASS"); } } void comp(variable, value){ if (variable == value){ printf("PASS"); } else{ printf("FAIL"); } } const char* getCardName(int cardType){ switch(cardType){ case adventurer: return "adventurer"; case council_room: return "council room"; case feast: return "feast"; case gardens: return "gardens"; case mine: return "mine"; case remodel: return "remodel"; case smithy: return "smithy"; case village: return "village"; case baron: return "baron"; case great_hall: return "great_hall"; case minion: return "minion"; case steward: return "steward"; case tribute: return "tribute"; case ambassador: return "ambassador"; case cutpurse: return "cutpurse"; case embargo: return "embargo"; case outpost: return "outpost"; case salvager: return "salvager"; case sea_hag: return "sea hag"; case treasure_map: return "treasure_map"; } return "unknown_value"; } void verifyInitialDecks(int players, struct gameState *state){ int copperCount = 0; int estateCount = 0; int i; int j; for (i = 0; i < players; i++){ for (j = 0; j < 10; j++){ if (state->deck[i][j] == copper){ copperCount++; } else{ estateCount++; } } } if (copperCount == (7 * players) && estateCount == (3 * players)){ printf("initializeGame(): PASS initial player deck configuration\n"); //printf("copperCount = %d, estateCount = %d\n", copperCount, estateCount); } else{ printf("initializeGame(): FAIL initial player deck configuration\n"); //printf("copperCount = %d, estateCount = %d\n", copperCount, estateCount); } } void verifyShuffle(struct gameState *G, int numPlayers){ int i; int j; int estateCount = 0; int copperCount = 0; for (i = 0; i < numPlayers; i++){ for (j = 0; j < 3; j++){ if (G->deck[i][j] == estate){ estateCount++; } } for (j = 3; j < 10; j++){ if (G->deck[i][j] == copper){ copperCount++; } } if (copperCount == 7 || estateCount == 3){ printf("initializeGame(): FAIL shuffle player %d deck\n", i+1); } else{ printf("initializeGame(): PASS shuffle player %d deck\n", i+1); } estateCount = 0; copperCount = 0; } } void verifyPlayerHands(struct gameState *G, int numPlayers){ int i; int j; int count = 0; for (i = 0; i < numPlayers; i++){ for (j = 0; j < 5; j++){ if (G->hand[i][j] == estate || G->hand[i][j] == copper){ count++; } } if (count == 5){ printf("initializeGame(): PASS player %d has 5 cards in hand\n", i+1); } else{ printf("initializeGame(): FAIL player %d has 5 cards in hand\n", i+1); } count = 0; } } void verifyEmbargoTokens(struct gameState *G){ int i; int count = 0; for (i = 0; i <= treasure_map; i++) { if (G->embargoTokens[i] == 0){ count++; } } if (count == i){ printf("initializeGame(): PASS setting embargoTokens\n"); } else{ printf("initializeGame(): FAIL setting embargoTokens\n"); } } void verifyFirstPlayersTurn(struct gameState *G){ if(G->outpostPlayed != 0){ printf("initializeGame(): FAIL initialize first player's turn\n"); } else if(G->phase != 0){ printf("initializeGame(): FAIL initialize first player's turn\n"); } else if(G->numActions != 1){ printf("initializeGame(): FAIL initialize first player's turn\n"); } else if(G->numBuys != 1){ printf("initializeGame(): FAIL initialize first player's turn\n"); } else if(G->playedCardCount != 0){ printf("initializeGame(): FAIL initialize first player's turn\n"); } else{ printf("initializeGame(): PASS initialize first player's turn\n"); } } void verifyKingdomCardCount(struct gameState *G, int kingdomCards[], int numPlayers){ int i; int j; int fail = 0; for (i = adventurer; i <= treasure_map; i++){ //loop all cards for (j = 0; j < 10; j++) //loop chosen cards { if (kingdomCards[j] == i) { //check if card is a 'Victory' Kingdom card if (kingdomCards[j] == great_hall || kingdomCards[j] == gardens) { if (numPlayers == 2){ if(G->supplyCount[i] != 8){ fail = 1; } } else{ if(G->supplyCount[i] != 12){ fail = 1; } } } else { if(G->supplyCount[i] != 10){ fail = 1; } } break; } else //card is not in the set choosen for the game { if(G->supplyCount[i] != -1){ fail = 1; } } } } if (fail == 0){ printf("initializeGame(): PASS set number of kingdom cards\n"); } else{ printf("initializeGame(): FAIL set number of kingdom cards\n"); } } int main(){ struct gameState G; struct gameState G2; int k[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse, sea_hag, great_hall, smithy}; int players; int ret; ///////Test1: Invlaid number of players/////// players = 1; //too few players ret = initializeGame(players, k, 10, &G); printf("initializeGame(): "); assertNotZero(ret); printf(" when invalid number of players....not enough players\n"); players = MAX_PLAYERS + 1; //too many players ret = initializeGame(players, k, 10, &G); printf("initializeGame(): "); assertNotZero(ret); printf(" when invalid number of players....too many players\n"); ///////Test2: Duplicate kingdom cards/////// k[6] = adventurer; players = 2; ret = initializeGame(players, k, 10, &G); printf("initializeGame(): "); assertNotZero(ret); printf(" when passing array with duplicate kingdom cards\n"); ///////Test3: /////// k[6] = cutpurse; players = 2; memcpy(&G2, &G, sizeof(struct gameState)); while (players < 5){ ret = initializeGame(players, k, 10, &G); printf("initializeGame(): "); assertZero(ret); printf(" return value with %d players\n", players); if (players == 2){ printf("\n"); printf("********** numPlayers: 2 **********\n"); ///Curse cards/// printf("initializeGame(): "); comp(G.supplyCount[curse], 10); printf(" curse cards with 2 players\n"); ///victory cards/// printf("initializeGame(): "); comp(G.supplyCount[estate], 8); printf(" estate cards with 2 players\n"); printf("initializeGame(): "); comp(G.supplyCount[duchy], 8); printf(" duchy cards with 2 players\n"); printf("initializeGame(): "); comp(G.supplyCount[province], 8); printf(" province cards with 2 players\n"); ///Treasure Cards/// printf("initializeGame(): "); comp(G.supplyCount[copper], 46); printf(" coppers with 2 players\n"); printf("initializeGame(): "); comp(G.supplyCount[silver], 40); printf(" silver with 2 players\n"); printf("initializeGame(): "); comp(G.supplyCount[gold], 30); printf(" gold with 2 players\n"); //verify set number of kingdom cards verifyKingdomCardCount(&G, k, players); //Loaded decks verifyInitialDecks(players, &G); //is deck shuffled verifyShuffle(&G, players); //do players have correct five cards in hand verifyPlayerHands(&G, players); //were embargoTokens set to 0 verifyEmbargoTokens(&G); //verify initialize first player's turn verifyFirstPlayersTurn(&G); } else if (players == 3){ printf("\n"); printf("********** numPlayers: 3 **********\n"); ///Curse cards/// printf("initializeGame(): "); comp(G.supplyCount[curse], 20); printf(" curse cards with 3 players\n"); ///victory cards/// printf("initializeGame(): "); comp(G.supplyCount[estate], 12); printf(" estate cards with 3 players\n"); printf("initializeGame(): "); comp(G.supplyCount[duchy], 12); printf(" duchy cards with 3 players\n"); printf("initializeGame(): "); comp(G.supplyCount[province], 12); printf(" province cards with 3 players\n"); ///Treasure Cards/// printf("initializeGame(): "); comp(G.supplyCount[copper], 39); printf(" coppers with 3 players\n"); printf("initializeGame(): "); comp(G.supplyCount[silver], 40); printf(" silver with 3 players\n"); printf("initializeGame(): "); comp(G.supplyCount[gold], 30); printf(" gold with 3 players\n"); //verify set number of kingdom cards verifyKingdomCardCount(&G, k, players); //Loaded decks verifyInitialDecks(players, &G); //is deck shuffled verifyShuffle(&G, players); //do players have correct five cards in hand verifyPlayerHands(&G, players); //were embargoTokens set to 0 verifyEmbargoTokens(&G); //verify initialize first player's turn verifyFirstPlayersTurn(&G); } else{ printf("\n"); printf("********** numPlayers: 4 **********\n"); ///Curse cards printf("initializeGame(): "); comp(G.supplyCount[curse], 30); printf(" curse cards with 4 players\n"); ///victory cards/// printf("initializeGame(): "); comp(G.supplyCount[estate], 12); printf(" estate cards with 4 players\n"); printf("initializeGame(): "); comp(G.supplyCount[duchy], 12); printf(" duchy cards with 4 players\n"); printf("initializeGame(): "); comp(G.supplyCount[province], 12); printf(" province cards with 4 players\n"); ///Treasure Cards/// printf("initializeGame(): "); comp(G.supplyCount[copper], 32); printf(" coppers with 3 players\n"); printf("initializeGame(): "); comp(G.supplyCount[silver], 40); printf(" silver with 3 players\n"); printf("initializeGame(): "); comp(G.supplyCount[gold], 30); printf(" gold with 3 players\n"); //verify set number of kingdom cards verifyKingdomCardCount(&G, k, players); //Loaded decks verifyInitialDecks(players, &G); //is deck shuffled verifyShuffle(&G, players); //do players have correct five cards in hand verifyPlayerHands(&G, players); //were embargoTokens set to 0 verifyEmbargoTokens(&G); //verify initialize first player's turn verifyFirstPlayersTurn(&G); } players++; memcpy(&G, &G2, sizeof(struct gameState)); } return 0; }<file_sep>/projects/smithada/dominion/unittest3.c #include "dominion.h" #include <stdio.h> #include <assert.h> #include <string.h> #include <stdlib.h> #include <time.h> int main(){ struct gameState G; int ret; int i; int x; int randNum; int zeroCount; time_t t; ///////Test1: Depleted province cards. Game should end/////// //set province cards to 0 G.supplyCount[province] = 0; ret = isGameOver(&G); if (ret == 1){ printf("isGameOver(): PASS depleted province cards\n"); } else{ printf("isGameOver(): FAIL depleted province cards\n"); } ///////Test2: Refill province cards and randomly deplete stacks of supply cards/////// //set province count higher than 0 G.supplyCount[province] = 8; /* Intializes random number generator */ srand((unsigned) time(&t)); for (x = 0; x < 5; x++){ zeroCount = 0; for (i = 0; i < 25; i++){ randNum = rand() % 9; if (randNum == 0){ zeroCount++; } G.supplyCount[i] = randNum; } ret = isGameOver(&G); if(zeroCount < 3){ if (ret == 0){ printf("isGameOver(): PASS less than 3 supply piles depleted\n"); } else{ printf("isGameOver(): FAIL less than 3 supply piles depleted\n"); } } else{ if (ret == 1){ printf("isGameOver(): PASS 3 supply piles depleted\n"); } else{ printf("isGameOver(): FAIL 3 supply piles depleted\n"); } } } return 0; }<file_sep>/projects/smithada/dominion/randomtestcard2.c #include "dominion.h" #include "dominion_helpers.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> const char* getCardName(int cardType){ switch(cardType){ case estate: return "estate"; case duchy: return "duchy"; case province: return "province"; case copper: return "copper"; case silver: return "silver"; case gold: return "gold"; case adventurer: return "adventurer"; case council_room: return "council room"; case feast: return "feast"; case gardens: return "gardens"; case mine: return "mine"; case remodel: return "remodel"; case smithy: return "smithy"; case village: return "village"; case baron: return "baron"; case great_hall: return "great_hall"; case minion: return "minion"; case steward: return "steward"; case tribute: return "tribute"; case ambassador: return "ambassador"; case cutpurse: return "cutpurse"; case embargo: return "embargo"; case outpost: return "outpost"; case salvager: return "salvager"; case sea_hag: return "sea hag"; case treasure_map: return "treasure_map"; } return "unknown_value"; } void displayDeck(int player, struct gameState *G, int numCards){ int i; printf("Player %d's deck:\n", player); for (i = 0; i < numCards; i++){ printf("%s\n", getCardName(G->deck[player][i])); } printf("\n"); } void displayHand(int player, struct gameState *G, int numCards){ int i; printf("Player %d's hand: \n", player); for (i = 0; i < numCards; i++){ printf("%s\n", getCardName(G->hand[player][i])); } printf("\n"); } void displayDiscard(int player, struct gameState *G, int numCards){ int i; printf("Player %d's discard: \n", player); for (i = 0; i < numCards; i++){ printf("%s\n", getCardName(G->discard[player][i])); } printf("\n"); } int main(){ int i; int v; int ret; int players = 4; int currentPlayer; int numCards; int chosenCard; int treasureCount; int handCount; int passCount = 0; int failCount = 0; int goldCount = 0; struct gameState G; struct gameState G2; int k[10] = {adventurer, gardens, embargo, village, minion, mine, treasure_map, sea_hag, great_hall, smithy}; int J[16] = {adventurer, gardens, embargo, village, minion, mine, treasure_map, sea_hag, great_hall, smithy, copper, gold, silver, duchy, province, estate}; //array holds the location where the first two treasure_map cards are placed in the initial deck int treasureLocation[2] = {0, 0}; srand(time(NULL)); ret = initializeGame(players, k, 10, &G); if (ret != 0){ printf("FAILED to initialize game\n"); } memcpy (&G2, &G, sizeof(struct gameState)); for (v = 0; v < 2000; v++){ treasureCount = 0; //get a random player number currentPlayer = rand() % 4; //get a random handCount number numCards = rand() % 500; //set current number of cards in chosen player's hand G.handCount[currentPlayer] = numCards; //fill player's hand with random cards. Keep track of the first two treasure_map cards. for(i = 0; i < numCards; i++){ chosenCard = J[rand() % 16]; G.hand[currentPlayer][i] = chosenCard; if (chosenCard == treasure_map){ if (treasureCount < 2){ treasureLocation[treasureCount] = i; treasureCount++; } } } //store the handcount before the call to treasuremapFuntion() handCount = G.handCount[currentPlayer]; ret = treasuremapFunction(currentPlayer, &G, treasureLocation[0]); if (treasureCount == 0){ if (ret == -1){ goldCount = 0; //check that the deck does not contain gold cards for (i = 0; i < G.deckCount[currentPlayer]; i++){ if (G.deck[currentPlayer][i] == gold){ goldCount++; } } if(goldCount == 0){ passCount++; } else{ failCount++; } } else{ failCount++; } } else if(treasureCount == 1){ if (ret == 1 && handCount - 1 == G.handCount[currentPlayer]){ goldCount = 0; //check that the deck does not contain gold cards for (i = 0; i < G.deckCount[currentPlayer]; i++){ if (G.deck[currentPlayer][i] == gold){ goldCount++; } } if(goldCount == 0){ passCount++; } else{ failCount++; } } else{ failCount++; } } else { //check return value. Check that two treasure cards were removed from hand. if (ret == 1 && handCount - 2 == G.handCount[currentPlayer] ){ goldCount = 0; //check that the deck contains 4 gold cards for (i = 0; i < G.deckCount[currentPlayer]; i++){ if (G.deck[currentPlayer][i] == gold){ goldCount++; } } if (goldCount == 4){ passCount++; } else{ failCount++; } //displayDeck(currentPlayer, &G, G.deckCount[currentPlayer]); //displayDiscard(currentPlayer, &G, G.discardCount[currentPlayer]); //printf("hand count: %d\n", G.handCount[currentPlayer]); } else{ failCount++; printf("Test FAIL: \n"); printf("treasureCount: %d\n", treasureCount); } } memcpy (&G, &G2, sizeof(struct gameState)); } printf("Test complete: \n"); printf("PASS.... %d\n", passCount); printf("FAIL.... %d\n", failCount); return 0; }
0bf1a9cc11ed964dedb78782309f161592d78dd8
[ "C" ]
12
C
RadamHussein/CS362-004-SP17
67f9882f01a387f34fd9bb2f41386cf72b838366
513772b92c8f3f071baff6913ba67055600f4ce1
refs/heads/main
<repo_name>steveoh/logo-lightroom<file_sep>/vite.config.js import { defineConfig } from 'vite' import reactRefresh from '@vitejs/plugin-react-refresh' export default defineConfig({ plugins: [reactRefresh()], server: { port: 1337 }, base: 'https://steveoh.github.io/logo-lightroom/' }) <file_sep>/src/App.jsx import * as React from 'react' import { SketchPicker } from 'react-color'; import './App.css' function App() { const [tree, setTree] = React.useState('#7fdbff'); const [base, setBase] = React.useState('#f1f1f1'); const [diamondLeft, setDiamondLeft] = React.useState('#16697a'); const [diamondRight, setDiamondRight] = React.useState('#0d3f49'); const [halo, setHalo] = React.useState('#db6400'); const [haloOutline, setHaloOutline] = React.useState('ffa62b'); return ( <div className="App"> <div style={{ display: 'flex', justifyContent: 'center' }}> <svg className="App-logo" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 195.09 195.09"> <g id="Layer_2" data-name="Layer 2"> <g id="Layer_1-2" data-name="Layer 1"> <rect style={{ fill: 'none' }} width="195.09" height="195.09" /> <path style={{ fill: halo }} d="M98.51,114.63l71.24,29.1a74.53,74.53,0,1,0-144.41,0l71.24-29.1A2.58,2.58,0,0,1,98.51,114.63Z" /> <path style={{ fill: haloOutline }} d="M98.42,115l64.44,26.32a67.41,67.41,0,1,0-130.62,0L96.67,115A2.31,2.31,0,0,1,98.42,115Z" /> <path style={{ fill: base }} d="M188,142.46,98.71,178.94a3.13,3.13,0,0,1-2.33,0L7.09,142.46a3.08,3.08,0,0,1,0-5.7l89.29-36.47a3,3,0,0,1,2.33,0L188,136.76A3.08,3.08,0,0,1,188,142.46Z" /> <path style={{ fill: tree }} d="M151.36,143.45,99.49,178.11a1.74,1.74,0,0,1-2.64-.93l-13-41.5a1.72,1.72,0,0,1,.08-1.26l39-84.47a1.76,1.76,0,0,1,3.27.21l27.37,87.07A5.48,5.48,0,0,1,151.36,143.45Z" /> <path style={{ fill: tree }} d="M43.74,143.46,95.58,178.1a1.77,1.77,0,0,0,2.68-.94l13-41.47a1.75,1.75,0,0,0-.09-1.27L72.2,50a1.77,1.77,0,0,0-3.3.21l-27.36,87A5.52,5.52,0,0,0,43.74,143.46Z" /> <path style={{ fill: diamondLeft }} d="M132.05,137.44,99.29,177.3a2.26,2.26,0,0,1-3.48,0L62,136.12a2.25,2.25,0,0,1-.42-2.06L95.38,17.55a2.26,2.26,0,0,1,4.33,0l33.37,114.87A5.48,5.48,0,0,1,132.05,137.44Z" /> <path style={{ fill: diamondRight }} d="M133.52,135.66,99.52,177a1.11,1.11,0,0,1-2-.71V17.92a1.11,1.11,0,0,1,2.18-.31l34,117A1.11,1.11,0,0,1,133.52,135.66Z" /> </g> </g> </svg> <pre> {JSON.stringify({ base: base, trees: tree, diamondLeft: diamondLeft, diamondRight: diamondRight, halo: halo, haloOutline: haloOutline }, null, 2)} </pre> </div> <div style={{ display: 'grid', textAlign: 'center', gridTemplateColumns: 'repeat(4, minmax(0, 1fr))' }}> <div> <p>base color</p> <SketchPicker color={base} onChange={(color) => setBase(color.hex)} ></SketchPicker> </div> <div> <p>background color</p> <SketchPicker color={tree} onChange={(color) => setTree(color.hex)} ></SketchPicker> </div> <div> <p>diamond left</p> <SketchPicker color={diamondLeft} onChange={(color) => setDiamondLeft(color.hex)} ></SketchPicker> </div> <div> <p>diamond left</p> <SketchPicker color={diamondRight} onChange={(color) => setDiamondRight(color.hex)} ></SketchPicker> </div> <div> <p>halo color</p> <SketchPicker color={halo} onChange={(color) => setHalo(color.hex)} ></SketchPicker> </div> <div> <p>halo outline color</p> <SketchPicker color={haloOutline} onChange={(color) => setHaloOutline(color.hex)} ></SketchPicker> </div> </div> </div> ) } export default App
47c7b06cb653e66749f89e5c5b8663b7a8a01f33
[ "JavaScript" ]
2
JavaScript
steveoh/logo-lightroom
e231c02ed6e209f9bda0ae2cad359d0a7a3ab30e
add6c8b8f44b04863d01bc6bb7197aebf8750536
refs/heads/master
<repo_name>gobiiv/A3csci3130<file_sep>/app/src/androidTest/java/com/acme/a3csci3130/CRUDEspressoTest.java /* This is the espresso UI test for the CRUD methods. */ package com.acme.a3csci3130; public class CRUDEspressoTest { }
aeebe6953c8a0064c8d42837b56f9686c93cd36b
[ "Java" ]
1
Java
gobiiv/A3csci3130
192b8e8e33601fa8daaf14ce60b99c4357e88293
4de74b82296845298ed8cee54419e0e66ed28238
refs/heads/master
<file_sep># encoding: utf-8 require 'em-http-request' require 'when' require 'logger' require './http-handler' class TwitchAdaptor include HttpHandler class StreamInfo def initialize(raw_data) @raw_data = raw_data end def live? !@raw_data['stream'].nil? && !@raw_data['stream']['is_playlist'] end def game_name return nil unless live? @raw_data['stream']['channel']['game'] end def stream_name return nil unless live? @raw_data['stream']['channel']['status'] end def username return nil unless live? @raw_data['stream']['channel']['name'] end def id return nil unless live? @raw_data['stream']['_id'] end def preview_url return nil unless live? @raw_data['stream']['preview']['medium'] end def hash username.hash end def eql?(other) username == other.username end end def initialize @logger = Logger.new("log/twitch.log") end def streams⏲(usernames) promises = usernames.map do |username| deferred = When.defer #puts "https://api.twitch.tv/kraken/streams/#{username}" req = EventMachine::HttpRequest.new("https://api.twitch.tv/kraken/streams/#{username}").get :head => {"Client-ID" => "reoery9uj6vb5g7wlzebfemopona2h8"} req.callback do logging_non_ok_responses(req, deferred) do data = JSON.parse(req.response) stream_info = StreamInfo.new(data) #puts "fetched #{username}" deferred.resolver.resolve([username, stream_info]) end end deferred.promise end deferred = When.defer When.all(promises).then do |values| streams = values.select do |value| value[1].live? end.map {|pair| pair[1]} deferred.resolver.resolve(streams) end return deferred.promise end end <file_sep>module HttpHandler def logging_non_ok_responses(req, deferred) if req.response_header.status != 200 @logger.error("Received status #{req.response_header.status}:") @logger.error(req.response) deferred.reject(req) return end yield end end <file_sep># encoding: utf-8 require 'em-http-request' require 'when' require 'json' require 'logger' require './http-handler' class SlackAdaptor include HttpHandler def initialize(options, mode) # @read_token = options.fetch('read-token') @webhook_url = options.fetch(mode == :prod ? 'webhook-url-prod' : 'webhook-url-testing') @logger = Logger.new("log/slack.log") end # def users⏲ # deferred = When.defer # req = EventMachine::HttpRequest.new('https://slack.com/api/users.list').get(query: {token: @read_token}) # req.callback do # logging_non_ok_responses(req, deferred) do # data = JSON.parse(req.response) # deferred.resolver.resolve(data['members']) # end # end # return deferred.promise # end def notify⏲(params) deferred = When.defer payload = {'payload' => JSON.generate(params)} req = EventMachine::HttpRequest.new(@webhook_url).post(body: payload) req.callback do logging_non_ok_responses(req, deferred) do deferred.resolver.resolve(req.response) end end return deferred.promise end end <file_sep># encoding: utf-8 require './slack-adaptor' require './twitch-adaptor' require 'eventmachine' require 'when' require 'circular_queue' require 'set' require 'optparse' class Bot def initialize(announced: [], mode: :testing) @announced_stream_ids = Set.new(announced) @mode = mode end def setup settings = JSON.parse(File.read("settings.json")) @slacks = Hash[settings.collect { |v| [v.fetch('name'), SlackAdaptor.new(v, @mode)]}] @ta = TwitchAdaptor.new @streams = [] # A simple set of all Twitch usernames we track @twitch_usernames = Set.new settings.each { |slack| @twitch_usernames.merge(slack.fetch('twitch-usernames')) } # A mapping from a given Twitch username to the a list of Slacks on which to announce it. @twitches_to_slacks = Hash.new {|h,k| h[k] = [] } settings.each do |slack| slack.fetch('twitch-usernames').each do |twitch| @twitches_to_slacks[twitch.downcase] << slack.fetch('name') end end @twitches_last_announce = Hash.new(Time.new(0)) end def go EventMachine.run do setup #refresh_twitch_usernames⏲.then do #refresh_online_streams⏲ #end #EventMachine::PeriodicTimer.new(3600) do # refresh_twitch_usernames⏲ #end refresh_online_streams⏲.then do notify_of_new_streams end EventMachine::PeriodicTimer.new(60) do refresh_online_streams⏲.then do notify_of_new_streams end end end end def notify_of_new_streams @streams.each do |stream| id_announced_already = @announced_stream_ids.include?(stream.id) username_last_announced_at = @twitches_last_announce[stream.username] puts "considering announcing '#{stream.username}' id #{stream.id} -- '#{stream.stream_name}'" puts " id_announced_already: #{id_announced_already}" puts " username last announced at: #{username_last_announced_at}" if !(id_announced_already) && (Time.now - username_last_announced_at > 3600) @twitches_to_slacks[stream.username].each do |slackname| puts "announcing #{stream.username} to #{slackname}" @slacks[slackname].notify⏲({text: ("<http://twitch.tv/#{stream.username}|twitch.tv/#{stream.username}> has gone live — #{stream.game_name} — \"#{stream.stream_name}\" <#{stream.preview_url}| >")}) end @announced_stream_ids << stream.id @twitches_last_announce[stream.username] = Time.now end end ann_str = @streams.map(&:id).join(',') puts "can restart with: #{@mode == :prod ? "-p" : ""} #{ann_str.empty? ? "" : "-a #{ann_str}"}" puts end # def refresh_twitch_usernames⏲ # deferred = When.defer # promise = @sa.users⏲ # promise.then do |users| # @twitch_usernames = users.map do |user| # next nil if user['profile']['title'].nil? # result = user['profile']['title'].match(/twitch\.tv\/(.*)/) # next nil if result.nil? # result[1] # end # @twitch_usernames.compact! # puts "Refreshed twitch usernames: #{@twitch_usernames.inspect}" # deferred.resolver.resolve # end # return deferred.promise # end def refresh_online_streams⏲ deferred = When.defer puts Time.now.iso8601 puts "Querying twitch usernames: #{@twitch_usernames.inspect}" @streams = [] promise = @ta.streams⏲(@twitch_usernames.to_a) promise.then do |streams| @streams = streams #puts "#{@streams.inspect}" puts "Refreshed online twitch streams: #{streams.map(&:username)}" deferred.resolver.resolve end return deferred.promise end end if $0 == __FILE__ options = {:mode => :testing} OptionParser.new do |opts| opts.banner = "Usage: main.rb [options]" # TODO instead of this being IDs it should just be usernames, and we initialize their # announced time to be the current time. opts.on("-a", "--announced a,b,c", Array, "List of already announced stream ids") do |ann| options[:announced] = ann.map {|v| v.to_i} end opts.on("-p", "--prod", "Run as production (default testing)") do |p| options[:mode] = p ? :prod : :testing end end.parse! puts options Bot.new(announced: options[:announced], mode: options[:mode]).go end <file_sep>source 'https://rubygems.org' gem 'eventmachine' gem 'em-http-request' gem 'when' gem 'json' gem 'slack-notify' gem 'rest-client' gem 'circular_queue' <file_sep>require './slack-adaptor' require './twitch-adaptor' require 'eventmachine' require 'when' require 'circular_queue' def go EventMachine.run do settings = JSON.parse(File.read("settings.json")) puts settings.inspect sa = SlackAdapator.new(settings) promise = sa.notify⏲({text: "Hello, I am notifying you of something", channel: "@justinf"}) promise.then do EventMachine.stop end end end if __FILE__ == $0 go end
fc744453a109eee6306b86358ed1c783614de507
[ "Ruby" ]
6
Ruby
cdanis/kumite-twitch
e7ee1ab0f4b184df86f7592c1023c3e77a7fb3f2
f118820d36bf1d628bfe5958dbcd90ed341ab43e
refs/heads/main
<repo_name>adrianchan94/Movie-Browser<file_sep>/src/components/AboutView.js import React from 'react' import Hero from './Hero' const AboutView = () => { return ( <> <Hero text="About Us"/> <div className="container"> <div className="row"> <div className="col-lg-8 offset-lg-2 my-5"> <p className="lead"> Movie Browser is a very simple application that allows you to browse, search, watch movie trailers, read synopsis, and see rating for your favorite movies. <br /><br/> Built with React, Bootstrap & TMDb API. </p> </div> </div> </div> </> ) } export default AboutView<file_sep>/src/components/MovieCard.js import React from 'react' import { Link } from 'react-router-dom' const MovieCard = ({ movie}) => { const posterURL = `https://image.tmdb.org/t/p/w500/${movie.poster_path}` const detailURL = `/movies/${movie.id}` const unavailablePoster = "https://images.unsplash.com/photo-1604975701397-6365ccbd028a?ixid=MXwxMjA3fDB8MHxzZWFyY2h8OHx8Y2luZW1hfGVufDB8fDB8&ixlib=rb-1.2.1&w=1000&q=80" return ( <div className="col-lg-3 col-md-6 col-sm-12 my-4"> <div className="card" style={{ width: "18rem" }}> {movie.poster_path ? <img className="card-img-top" src={posterURL} alt={movie.original_title} /> : <img className="card-img-top" src={unavailablePoster} alt={movie.original_title} /> } <div className="card-body"> <h5 className="card-title pb-2">{movie.original_title}</h5> <Link to={detailURL} className="btn btn-warning w-100">Show Details</Link> </div> </div> </div> ) } export default MovieCard<file_sep>/src/components/MovieView.js import { useState , useEffect, React} from 'react' import Hero from './Hero' import { useParams } from 'react-router-dom' import ReactPlayer from "react-player" const MovieView = () => { const { id } = useParams() console.log(id) const [movieDetails, setMovieDetails] = useState({}) const [ isLoading, setIsLoading ] = useState(true) const [ trailerURL, setTrailerURL ] = useState({}) useEffect(() => { console.log('make an api request', id) fetch(`https://api.themoviedb.org/3/movie/${id}?api_key=17d4a2274a993dc278559c3122a5c7b1&language=en-US`) .then(response => response.json()) .then(data => { console.log(data) setMovieDetails(data) setIsLoading(false) }) fetch(`https://api.themoviedb.org/3/movie/${id}/videos?api_key=17d4a2274a993dc278559c3122a5c7b1&language=en-US`) .then(response => response.json()) .then(data => { setTrailerURL(data.results[0]) }) }, [id]) function renderMovieDetails(){ let movieTrailerURL; if(trailerURL){ movieTrailerURL = `https://www.youtube.com/watch?v=${trailerURL.key}` } if(isLoading){ return <Hero text="Loading..."/> } if(movieDetails){ let posterPath; let backdropURL; if(movieDetails.poster_path) { posterPath = `http://image.tmdb.org/t/p/w500${movieDetails.poster_path}` backdropURL = `http://image.tmdb.org/t/p/original${movieDetails.backdrop_path}` } else { posterPath = "https://images.unsplash.com/photo-1604975701397-6365ccbd028a?ixid=MXwxMjA3fDB8MHxzZWFyY2h8OHx8Y2luZW1hfGVufDB8fDB8&ixlib=rb-1.2.1&w=1000&q=80" } return( <> <Hero movieView={true} text={movieDetails.original_title} backdrop={backdropURL}/> <div className="container my-5"> <div className="row"> <div className="col-md-3 bg-dark py-2"> <img src={posterPath} alt="..." className="img-fluid shadow rounded"/> </div> <div className="col-md-9"> <div className="container"> <h2>{movieDetails.original_title}</h2> <p className="lead py-2"><i>{movieDetails.overview}</i></p> <p>Release Date: {movieDetails.release_date}</p> <p>Vote Average: {movieDetails.vote_average}</p> <p>No. of Votes: {movieDetails.vote_count}</p> { movieTrailerURL && <ReactPlayer url={movieTrailerURL}/> } </div> </div> </div> </div> </> ) } } return renderMovieDetails() } export default MovieView<file_sep>/src/components/Home.js import { useEffect, useState, React} from 'react' import Hero from './Hero' import MovieCard from './MovieCard' const TrendingMovies = () => { const [trendingMovies, setTrendingMovies] = useState([]) const [ isLoading, setIsLoading ] = useState(true) useEffect(() => { fetch('https://api.themoviedb.org/3/trending/movie/day?api_key=17d4a2274a993dc278559c3122a5c7b1') .then(response => response.json()) .then(data => { setTrendingMovies(data.results) setIsLoading(false) console.log(trendingMovies) }) }, [trendingMovies]) const resultsHTML = trendingMovies.map((obj, i) => { return <MovieCard movie={obj} key={i} /> }) return ( <> <div className="container"> <div className="row"> { isLoading ? <p className="lead my-5">Loading...</p> : resultsHTML } </div> </div> </> ) } const Home = () => { return( <> <Hero text="Trending Movies"/> <TrendingMovies /> </> ) } export default Home;<file_sep>/README.md # Movie-Browser Movie Browser App with React <file_sep>/src/components/UpcomingMovies.js import { useState, useEffect, React} from 'react' import Hero from './Hero' import MovieCard from './MovieCard' const GetUpcomingMovies = () => { const [upcomingMovies, setUpcomingMovies] = useState([]); const [isLoading, setIsLoading] = useState(true) useEffect(() => { fetch('https://api.themoviedb.org/3/movie/upcoming?api_key=17d4a2274a993dc278559c3122a5c7b1&language=en-US&page=1') .then(response => response.json()) .then(data => { setUpcomingMovies(data.results) setIsLoading(false) }) }, [upcomingMovies]) const resultsHTML = upcomingMovies.map((obj, i) => { return <MovieCard movie={obj} key={i} /> }) return ( <> <div className="container"> <div className="row"> { isLoading ? <p className="lead my-5">Loading...</p> : resultsHTML } </div> </div> </> ) } const UpcomingMovies = () => { return( <> <Hero text="Coming Soon"/> <GetUpcomingMovies /> </> ) } export default UpcomingMovies; <file_sep>/src/components/Navbar.js import React from 'react' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faFilm } from '@fortawesome/free-solid-svg-icons' import { Link, useHistory } from 'react-router-dom'; const NavBar = ({searchText, setSearchText}) => { const history = useHistory() const updateSearchText = (e) => { history.push("/search") setSearchText(e.target.value) } const formSubmit = (event) => { event.preventDefault(); let searchQuery = event.target.elements[0].value history.push("/search") setSearchText(searchQuery) } return ( <nav className="navbar navbar-expand-lg navbar-light bg-warning px-4"> <div className="container-fluid"> <Link className="navbar-brand" to="/"><b>Movie Browser</b> <FontAwesomeIcon className="ml-5" icon={faFilm}/></Link> <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span className="navbar-toggler-icon"></span> </button> <div className="collapse navbar-collapse" id="navbarSupportedContent"> <ul className="navbar-nav me-auto mb-2 mb-lg-0"> <li className="nav-item"> <Link className="nav-link" aria-current="page" to="/">Home</Link> </li> <li className="nav-item"> <Link className="nav-link" to="/about">About</Link> </li> <li className="nav-item"> <Link className="nav-link" to="/upcoming">Coming Soon</Link> </li> </ul> <form onSubmit={formSubmit} className="d-flex"> <input className="form-control me-2" type="text" placeholder="Search" value={searchText} onChange={updateSearchText} /> <button className="btn btn-outline-success" type="submit">Search</button> </form> </div> </div> </nav> ) } export default NavBar;
540d63384dcb33d2f438bd188e3be9b3e8031873
[ "JavaScript", "Markdown" ]
7
JavaScript
adrianchan94/Movie-Browser
2b75929507f19c8bc2ad82110255a8a8ffa97843
2c9d8adcb25b89879e22c3b103bcd5c083911a72
refs/heads/master
<file_sep>import asyncRoutes from "@/router/asyncRoutes"; import curlToParams from "curl-to-params"; const reg = /\/:[A-Za-z]*/g; export const matchRoutes = role => { let len = role.length; if (len <= 0) { return []; } const ROUTE_MODE = process.env.VUE_APP_ROUTE; let accessRoutes = []; console.log(role, ROUTE_MODE); switch (ROUTE_MODE) { case "NONE": accessRoutes = diffRoute(role, asyncRoutes); break; case "LOCAL": accessRoutes = diffRouteLocal(role, asyncRoutes); break; } return accessRoutes; }; const diffRoute = (source, target) => { let _target = matchRoutePath(target); let result = source.map(item => { try { let { children, url, title } = item; if (url) { let matched = _target ? _target.filter(item => { return url.match(item.reg); }) : []; if (matched.length > 0) { let _matched = {}; if (matched.length > 1) { matched.forEach(match => { if (match.path === url) { _matched = match; } }); } else { _matched = matched[0]; } if (Array.isArray(children) && children.length > 0) { return { ..._matched, path: url, meta: { title: title }, children: diffRoute(children, _matched.children || null) }; } else { return { ..._matched, meta: { title: title }, path: url, children: null }; } } else { return null; } } else { return null; } } catch (e) { console.error(e); } }); if (result.length > 0) { result = result.filter(item => { return item && item.name !== undefined; }); } return result; }; const diffRouteLocal = (source, target) => { let common = [ ...source .filter(item => (item.name ? true : false)) .map(item => { item.local = true; return item; }), ...target ]; let routes = {}; common.forEach(item => { const { name, local } = item; console.log(item); if (!routes[name]) { if (local) { routes[name] = item; } } else { let children = routes[name]["children"]; item.children = diffRouteLocal(children, item.children); routes[name] = item; } }); return Object.values(routes); }; const matchRoutePath = routes => { if (!Array.isArray(routes)) { return []; } return routes.map(item => { let matchResult = item.path.match(reg); if (matchResult && Array.isArray(matchResult) && matchResult.length > 0) { let regStr = item.path; matchResult.forEach(str => { regStr = regStr.replace(str, "\\/[A-Za-z0-9]*"); }); item.reg = new RegExp(regStr, "g"); } else { item.reg = item.path; } return item; }); }; export const matchMenu = role => { return role .filter(item => { return item.hide === "NO"; }) .map(item => { item.children = item.children.length > 0 ? item.children .filter(child => { return child.hide === "NO"; }) .map(child => { return { name: child.name, pageRoute: curlProtocol(child.pageRoute), role: child.role }; }) : []; return item; }); }; const curlProtocol = path => { if (path.startsWith("route://")) { path = path.replace("route://", "curl "); let params = curlToParams(path); if (params.static) { return "/" + params.url; } else if (params.dynamic) { return "/generate/page/" + params.url; } else { return params.url; } } else { return ""; } }; <file_sep>import { getToken, clearToken, setToken } from "../../util/auth"; import { login, getRole } from "@/api/user"; const state = { token: getToken(), roles: [] }; const mutations = { SET_TOKEN: (state, token) => { state.token = token; }, REMOVE_TOKEN: state => { state.token = null; }, SET_ROLE: (state, role) => { state.roles = role; }, REMOVE_ROLE: state => { state.roles = []; } }; const actions = { login({ commit }, loginData) { const { username, password } = loginData; return new Promise((resolve, reject) => { login({ username, password }) .then(res => { if (res.code === 200) { commit("SET_TOKEN", res.data.token); setToken(res.data.token); resolve(res); } else { reject(res); } }) .catch(err => { reject(err); }); }); }, logout({ commit }) { commit("REMOVE_TOKEN"); commit("REMOVE_ROLE"); clearToken(); }, getRole({ commit }) { return new Promise((resolve, reject) => { getRole() .then(res => { if (res.code === 200) { commit("SET_ROLE", res.data); resolve(res); } else { reject(res); } }) .catch(err => { reject(err); }); }); } }; export default { namespaced: true, state, mutations, actions }; <file_sep>import Request from "../util/request"; import { jsonToFormData } from "../util/operation"; export const getMenuList = () => { return Request({ url: "/admin/access/v1/cms-menu/list", method: "GET" }); }; export const addMenu = data => { return Request({ url: "/admin/access/v1/cms-menu/add", method: "POST", data: jsonToFormData(data) }); }; export const editMenu = (id, data) => { return Request({ url: "/admin/access/v1/cms-menu/update/" + id, method: "POST", data: jsonToFormData(data) }); }; export const deleteMenu = id => { return Request({ url: "/admin/access/v1/cms-menu/del/" + id, method: "DELETE" }); }; export const addSubMenu = data => { return Request({ url: "/admin/access/v1/cms-menu-sub/add", method: "POST", data: jsonToFormData(data) }); }; export const editSubMenu = (id, data) => { return Request({ url: "/admin/access/v1/cms-menu-sub/update/" + id, method: "POST", data: jsonToFormData(data) }); }; export const deleteSubMenu = id => { return Request({ url: "/admin/access/v1/cms-menu-sub/del/" + id, method: "DELETE" }); }; export const addAction = data => { return Request({ url: "/admin/access/v1/cms-menu-fun/add", method: "POST", data: jsonToFormData(data) }); }; export const editAction = (id, data) => { return Request({ url: "/admin/access/v1/cms-menu-fun/update/" + id, method: "POST", data: jsonToFormData(data) }); }; export const deleteAction = id => { return Request({ url: "/admin/access/v1/cms-menu-fun/del/" + id, method: "DELETE" }); }; export const getPageList = () => { return Request({ url: "/admin/access/v1/cms-page-group/list", method: "GET" }); }; export const addPageGroup = data => { return Request({ url: "/admin/access/v1/cms-page-group/add", method: "POST", data: jsonToFormData(data) }); }; export const editPageGroup = (id, data) => { return Request({ url: "/admin/access/v1/cms-page-group/update/" + id, method: "POST", data: jsonToFormData(data) }); }; export const deletePageGroup = id => { return Request({ url: "/admin/access/v1/cms-page-group/del/" + id, method: "DELETE" }); }; export const addPage = data => { return Request({ url: "/admin/access/v1/cms-page/add", method: "POST", data: jsonToFormData(data) }); }; export const editPage = (id, data) => { return Request({ url: "/admin/access/v1/cms-page/update/" + id, method: "POST", data: jsonToFormData(data) }); }; export const deletePage = id => { return Request({ url: "/admin/access/v1/cms-page/del/" + id, method: "DELETE" }); }; export const importPageConfig = () => { return Request({ url: "http://localhost:8080/mockApi/importConfig", method: "POST" }); }; export const savePageConfig = data => { return Request({ url: "http://localhost:8080/mockApi/saveConfig", method: "POST", data: jsonToFormData(data) }); }; export const getPageHistory = id => { return Request({ url: "/admin/access/v1/cms-page-version/list/" + id, method: "GET" }); }; export const addPageHistory = data => { return Request({ url: "/admin/access/v1/cms-page-version/add", method: "POST", data: jsonToFormData(data) }); }; export const pageHistoryDetail = id => { return Request({ url: "/admin/access/v1/cms-page-version/details/" + id, method: "GET" }); }; export const deleteHistory = id => { return Request({ url: "/admin/access/v1/cms-page-version/del/" + id, method: "DELETE" }); }; export const getPageInfo = type => { return Request({ url: "/admin/access/v1/cms-page/details/route-name/" + type, method: "GET" }); }; <file_sep>import Request from "../util/request"; import { jsonToFormData } from "../util/operation"; export const login = data => { return Request({ url: "/admin/v1/login", method: "POST", data: jsonToFormData(data) }); }; export const getRole = () => { return Request({ url: "/admin/access/v1/function/role", method: "GET" }); }; export const getRoleList = params => { return Request({ url: "/admin/access/v1/sys-role/list", method: "GET", params: params }); }; export const deleteRole = id => { return Request({ url: `/admin/access/v1/sys-role`, method: "DELETE", params: { ids: id } }); }; export const addRole = data => { return Request({ url: "/admin/access/v1/sys-role", method: "PUT", data: jsonToFormData(data) }); }; //获取后台用户信息 export const getUserInfo = () => { return Request({ url: `/admin/access/v1/user/info`, method: "GET" }); }; export const editRole = (id, data) => { return Request({ url: `/admin/access/v1/sys-role/${id}`, method: "POST", data: jsonToFormData(data) }); }; export const getRoleData = id => { return Request({ url: `/admin/access/v1/sys-role/${id}`, method: "GET" }); }; export const getAllPermission = () => { return Request({ url: "/admin/v1/all-role", method: "GET" }); }; export const getUserList = params => { return Request({ url: "/admin/access/v1/sys-user/list", method: "GET", params: params }); }; export const addUser = data => { return Request({ url: "/admin/access/v1/sys-user", method: "PUT", data: jsonToFormData(data) }); }; export const editUser = (id, data) => { return Request({ url: "/admin/access/v1/sys-user/" + id, method: "POST", data: jsonToFormData(data) }); }; export const getUserData = id => { return Request({ url: `/admin/access/v1/sys-user/${id}`, method: "GET" }); }; export const deleteUser = params => { return Request({ url: `/admin/access/v1/sys-user`, method: "DELETE", params }); }; export const editUserPassword = (id, data) => { return Request({ url: `/admin/access/v1/sys-user/${id}/password`, method: "POST", data: jsonToFormData(data) }); }; //获取工作台信息 export const getTool = params => { return Request({ url: `/admin/access/v1/tool-table/info`, method: "GET", params }); }; //app用户管理 // 添加 export const addApp = data => { return Request({ url: "/admin/access/v1/user/member/add", method: "PUT", data: jsonToFormData(data) }); }; //获取app用户列表 export const appList = params => { return Request({ url: "/admin/access/v1/user/member/page", method: "GET", params }); }; //获取所有角色 和对应的账号 /admin/access/v1/selector/select/{optionsMappingContext}/{key} export const getUser = data => { return Request({ url: `/admin/access/v1/selector/select/${data.type}/${data.key}`, method: "GET" }); }; //禁用app用户 export const disableApp = id => { return Request({ url: `/admin/access/v1/user/member/disable/${id}`, method: "DELETE" }); }; //删除app用户 export const deleteApp = params => { return Request({ url: `/admin/access/v1/user/member/delete`, method: "DELETE", params }); }; //解禁app用户 export const enableApp = id => { return Request({ url: `/admin/access/v1/user/member/enable/${id}`, method: "POST" }); }; <file_sep>import OSS from "ali-oss"; import { getAliUploadSts, serverUpload } from "@/api/upload"; export const _aliUpload = file => { return new Promise((resolve, reject) => { getAliUploadSts().then(res => { if (res.code === 200) { const name = res.data.prefix + "/" + file.name; const client = new OSS({ accessKeyId: res.data.sts.accessKeyId, accessKeySecret: res.data.sts.accessKeySecret, stsToken: res.data.sts.securityToken, region: "oss-cn-hangzhou", bucket: res.data.bucket }); client .put(name, file) .then(response => { resolve({ ...response }); }) .catch(error => { reject(error); }); } }); }); }; export const _serverUpload = file => { const formData = new FormData(); formData.append("file", file); return serverUpload(formData).then(res => { return res.data; }); }; <file_sep>import axios from "axios"; import { Loading } from "element-ui"; const local = localStorage.getItem("local"); let request = null; if (local === "true") { request = axios.create({ // baseURL: "https://dev.api.beiru168.com/framework" baseURL: "http://localhost:8080" }); } else { request = axios.create({ baseURL: "https://dev.api.beiru168.com/graves" // baseURL: "http://192.168.2.15:8080" }); } // request.defaults.baseURL = _domain; let loading; request.interceptors.request.use( function(response) { if (sessionStorage.getItem("TOKEN")) { response.headers["Authorization"] = sessionStorage.getItem("TOKEN"); } if (!response.config) { loading = Loading.service({ background: "rgba(255,255,255,0.3)" }); } return response; }, function(error) { return Promise.reject(error); } ); request.interceptors.response.use( function(response) { if (loading) { loading.close && loading.close(); } return response.data; }, function(error) { if (loading) { loading.close && loading.close(); } // loading.close && loading.close(); return Promise.reject(error); } ); export const POST = request.post; export const GET = request.get; export const PUT = request.put; export const DELETE = request.delete; export default request; <file_sep>import Vue from "vue"; import VueRouter from "vue-router"; import login from "../layout/login.vue"; import setting from "@/views/setting"; import layout from "../layout/index"; import store from "../store/index"; const VueRouterPush = VueRouter.prototype.push; VueRouter.prototype.push = function push(location) { store.dispatch("routeTab/push", location); return VueRouterPush.call(this, location).catch(err => console.warn(err)); }; Vue.use(VueRouter); export const baseRoutes = [ { path: "/login", name: "Login", component: login, hidden: true }, { path: "/setting", name: "Setting", component: setting, hidden: true }, { path: "/", component: layout, redirect: "/dashboard", hidden: true, children: [ { path: "dashboard", component: () => import("@/views/dashboard"), name: "Dashboard", meta: { title: "工作台", icon: "dashboard", affix: true } } ] }, { path: "/404", name: "404", component: () => import("@/layout/404.vue"), hidden: true }, { path: "/generate", component: layout, children: [ { path: "page/:routeName", component: () => import("@/views/generator.vue"), name: "Generator" } ] } ]; const router = new VueRouter({ routes: baseRoutes }); export default router; <file_sep>const getters = { token: state => state.user.token, roles: state => state.user.roles, routes: state => state.permission.routes, menu: state => state.permission.menu }; export default getters; <file_sep>import Vue from "vue"; import App from "./App.vue"; import router from "./router"; import store from "./store"; import Generator from "admin-page-generator"; import elementUI from "element-ui"; import MlTabs from "element-tabs"; import KeepActive from "vue-keep-active"; import "./router/permission"; import "./element.scss"; import { _page, _request, _route, _http } from "@/util/util.js"; import { _serverUpload } from "@/util/upload.js"; Vue.config.productionTip = false; Vue.use(elementUI, { size: "small" }); Vue.use(MlTabs); Vue.use(KeepActive); Vue.use(Generator, { navigator: { page: _page, route: _route, request: _request, http: _http }, upload: _serverUpload, custom: { upload: () => {} } }); // import "./api/mock"; new Vue({ router, store, render: h => h(App) }).$mount("#app"); <file_sep>import Request from "../util/request"; export const getUuid = () => { return Request({ url: "/oss/v1/uuid", method: "GET" }); }; export const getAliUploadSts = () => { return Request({ url: "/admin/access/v1/sts", method: "GET" }); }; export const serverUpload = data => { return Request({ url: "/fs/upload", method: "POST", data: data }); }; <file_sep>import { queryToString } from "@/util/operation"; const state = { activeRoute: {}, visitedRoutes: [], excludeRoutes: [], tabRoutes: {} }; const mutations = { INIT_TAB_ROUTES: (state, routes) => { state.visitedRoutes = routes; }, ADD_TAB_ROUTE: (state, route) => { state.visitedRoutes.push(route); }, SET_ACTIVE_ROUTE: (state, route) => { state.activeRoute = route; }, DELETE_TAB_ROUTE: (state, routeIndex) => { return new Promise(resolve => { state.visitedRoutes.splice(routeIndex, 1); resolve(); }); }, ADD_EXCLUDE_ROUTE: (state, route) => { state.excludeRoutes.push(route); }, DELETE_EXCLUDE_ROUTE: (state, routeIndex) => { state.excludeRoutes.splice(routeIndex, 1); }, PUSH_ROUTE: (state, location) => { let { path, fullPath, query } = location; console.log(location); let _path = ""; if (fullPath) { _path = fullPath; } else { _path = path + queryToString(query); } if (!state.tabRoutes[_path]) { state.tabRoutes[_path] = location; } }, DELETE_ROUTE: (state, path) => { delete state.tabRoutes[path]; } }; const actions = { initTabRoutes: ({ commit }, routes) => { commit("INIT_TAB_ROUTES", routes); commit("SET_ACTIVE_ROUTE", routes[0]); }, addTabRoute: ({ state, commit, dispatch }, route) => { if (!state.visitedRoutes.some(v => v.fullPath === route.fullPath)) { commit("ADD_TAB_ROUTE", { fullPath: route.fullPath, path: route.path, name: route.name, meta: { ...route.meta }, query: { ...route.query }, params: { ...route.params } }); dispatch("addExcludeRoute", route.fullPath); } commit("SET_ACTIVE_ROUTE", route); }, setActiveRoute: ({ commit }, tabName) => { return new Promise((resolve, reject) => { let matchedRoute = state.visitedRoutes.filter( route => route.fullPath === tabName ); if (matchedRoute.length > 0) { commit("SET_ACTIVE_ROUTE", matchedRoute[0]); resolve(matchedRoute[0]); } else { reject(); } }); }, deleteRoute: ({ state, commit, dispatch }, tabName) => { return new Promise(resolve => { let matchedRouteIndex = -1; state.visitedRoutes.forEach((route, index) => { if (route.fullPath === tabName) { matchedRouteIndex = index; } }); if (matchedRouteIndex < 0) { return; } commit("DELETE_ROUTE", tabName); dispatch("deleteExcludeRoute", tabName); if (tabName !== state.activeRoute.fullPath) { commit("DELETE_TAB_ROUTE", matchedRouteIndex); return; } let _activeRoute; if (state.visitedRoutes[matchedRouteIndex - 1]) { _activeRoute = state.visitedRoutes[matchedRouteIndex - 1]; } else if (state.visitedRoutes[matchedRouteIndex + 1]) { _activeRoute = state.visitedRoutes[matchedRouteIndex + 1]; } else { _activeRoute = null; } commit("DELETE_TAB_ROUTE", matchedRouteIndex); if (_activeRoute !== null) { commit("SET_ACTIVE_ROUTE", _activeRoute); } else { resolve(); } }); }, addExcludeRoute: ({ commit }, route) => { commit("ADD_EXCLUDE_ROUTE", route); }, deleteExcludeRoute: ({ state, commit }, tabName) => { let matchedRouteIndex = -1; state.excludeRoutes.forEach((route, index) => { if (route === tabName) { matchedRouteIndex = index; } }); if (matchedRouteIndex > -1) { commit("DELETE_EXCLUDE_ROUTE", matchedRouteIndex); } }, push: ({ commit }, location) => { if (typeof location === "string") { commit("PUSH_ROUTE", { path: location }); } else { commit("PUSH_ROUTE", location); } } }; export default { namespaced: true, state, mutations, actions };
6a6ef72ed883bc48fb682f4164a64d7183a564e0
[ "JavaScript" ]
11
JavaScript
kaitochen/vue-admin-next
9d9401e27ad864385e90cf74730fc7c610a941f3
a78d155aec4753656622509e537aff6031ccbee6
refs/heads/master
<file_sep><?php namespace App\Models; use PDO; class Post extends \Core\Model { public static function getAll() { $db = static::getDB(); $stmt = $db->query('SELECT id, title, body, photo FROM posts'); return $stmt->fetchAll(PDO::FETCH_ASSOC); } } <file_sep><?php namespace App\Controllers; use \Core\View; use App\Models\Post; use App\Models\Menu; class Posts extends \Core\Controller { public function indexAction() { $menus = Menu::getall(); $root = $_SERVER['SERVER_NAME']; View::renderTemplate('Posts/index.html', [ 'menus' => $menus, 'root' => $root ]); } public function addNew() { echo "Hello from posts addNew"; } public function edit() { echo "Hello from the edit action in the Posts controller!"; echo "<p>Route parameters: <pre>" . htmlspecialchars(print_r($this->route_params, true)) . '</pre></p>'; } } <file_sep>{% extends "base.html" %} {% block title %}Users{% endblock %} {% block body %} <h1>Welcome</h1> <p1>Hello from the Users view!</p1> <ul> {% for menu in menus %} <li><a href="{{ menu.slug }}">{{ menu.name }}</a></li> {% endfor %} </ul> {% endblock %} <file_sep><?php namespace App\Controllers\Admin; use \Core\View; use App\Models\Menu; class Users extends \Core\Controller { protected function before() { echo 'before <br />'; } public function indexAction() { echo 'Welcome to ADMIN area!'; $menus = Menu::getall(); $root = $_SERVER['SERVER_NAME']; view::renderTemplate('Home/index.html', [ 'menus' => $menus, 'root' => $root ]); } protected function after() { echo ' <br />after'; } } <file_sep># basic-mvc Very basic bootstrap CMS MVC platform written in PHP. Not supposed to be used in production. <file_sep><?php namespace App\Models; use PDO; class Menu extends \Core\Model { public static function getAll() { $db = static::getDB(); $stmt = $db->query('SELECT id, name, slug FROM menus'); return $stmt->fetchAll(PDO::FETCH_ASSOC); } }
2a1cd88e4e2ccbaf471adc0d4c1af66a7c9b85a8
[ "Markdown", "HTML", "PHP" ]
6
PHP
warleyerocha/basic-mvc
1abb9fa597c1e791afa52da63f7f893e7b67b283
af052826cd235ab6481a3f0c69d4a93b79584f27
refs/heads/master
<file_sep>package com.soupcan.aquapulse.model.entity; import org.newdawn.slick.geom.Rectangle; import org.newdawn.slick.geom.Vector2f; public class Entity { public Vector2f position; public Rectangle bounds; public Entity(Vector2f position, float width, float height) { this.position = position; this.bounds = new Rectangle(position.x, position.y, width, height); } public Entity(float width, float height) { this.position = new Vector2f(0, 0); this.bounds = new Rectangle(position.x, position.y, width, height); } public void update() { bounds.setX(position.x); bounds.setY(position.y); } } <file_sep>package com.soupcan.aquapulse.model.engine; import org.newdawn.slick.SlickException; import org.newdawn.slick.geom.Rectangle; import org.newdawn.slick.geom.Vector2f; import org.newdawn.slick.tiled.TiledMap; import java.util.ArrayList; import java.util.List; public class Level { public Vector2f position; public List<Rectangle> bounds; private TiledMap map; public Level(String mapLocation) throws SlickException { map = new TiledMap(mapLocation); position = new Vector2f(); bounds = new ArrayList<Rectangle>(); for(int x = 0; x < map.getWidth(); x++) { for(int y = 0; y < map.getHeight(); y++) { int tileId = map.getTileId(x, y, 0); if(tileId == 7) { bounds.add(new Rectangle(x * 32, y * 32, 32, 32)); } } } } public Level(String mapLocation, Vector2f position) throws SlickException { map = new TiledMap(mapLocation); this.position = position; } public void render() { map.render((int) position.x, (int) position.y); } public void render(int layer) { map.render((int) position.x, (int) position.y, layer); } public void render(int[] layer) { for (int index = 0; index < layer.length; index++) { map.render((int) position.x, (int) position.y, layer[index]); } } public int getWidth() { return map.getWidth() * map.getTileWidth(); } public int getHeight() { return map.getHeight() * map.getHeight(); } public int getHorizontalTiles() { return map.getWidth(); } public int getVerticalTiles() { return map.getHeight(); } public int getTileId(int x, int y, int layer) { return map.getTileId(x, y, layer); } } <file_sep>package com.soupcan.aquapulse.controller; import com.soupcan.aquapulse.AquapulseGame; import com.soupcan.aquapulse.model.engine.LevelGroup; import com.soupcan.aquapulse.model.entity.Player; import org.newdawn.slick.Input; import org.newdawn.slick.SlickException; import org.newdawn.slick.Sound; import org.newdawn.slick.geom.Shape; import org.newdawn.slick.state.StateBasedGame; public class MovementController { public static float BPM_TO_ADD_IF_PLAYER_MOVED = 30; public static float BPM_TO_SUBTRACT_IF_PLAYER_DID_NOT_MOVE = 20; public static float MOVEMENT_COEFFICIENT = 0.1f; private Player player; private LevelGroup levels; private Sound collide; public MovementController(Player player, LevelGroup levels) throws SlickException { collide = new Sound("res/sound/collision.wav"); this.player = player; this.levels = levels; } public void processInput(Input input, float delta, StateBasedGame stateBasedGame) { boolean playerMoved = false; if(input.isKeyDown(Input.KEY_W) || input.isKeyDown(Input.KEY_UP)) { boolean collided = false; for(int i = 0; i < levels.size(); i++) { for(int j = 0; j < levels.get(i).bounds.size(); j++) { Shape tileBlock = levels.get(i).bounds.get(j); if(player.bounds.intersects(tileBlock) && player.bounds.getMinY() <= tileBlock.getMaxY()) { collide.play(); stateBasedGame.enterState(AquapulseGame.GAME_OVER_STATE); } } } if (!collided) player.position.y -= MOVEMENT_COEFFICIENT * delta; playerMoved = true; } if(input.isKeyDown(Input.KEY_A) || input.isKeyDown(Input.KEY_LEFT)) { boolean collided = false; for(int i = 0; i < levels.size(); i++) { for(int j = 0; j < levels.get(i).bounds.size(); j++) { Shape tileBlock = levels.get(i).bounds.get(j); if(player.bounds.intersects(tileBlock) && player.bounds.getMinX() <= tileBlock.getMaxX()) { collide.play(); stateBasedGame.enterState(AquapulseGame.GAME_OVER_STATE); } } } if (!collided) player.position.x -= MOVEMENT_COEFFICIENT * delta; playerMoved = true; } if(input.isKeyDown(Input.KEY_S) || input.isKeyDown(Input.KEY_DOWN)) { boolean collided = false; for(int i = 0; i < levels.size(); i++) { for(int j = 0; j < levels.get(i).bounds.size(); j++) { Shape tileBlock = levels.get(i).bounds.get(j); if(player.bounds.intersects(tileBlock) && player.bounds.getMinY() <= tileBlock.getMaxY()) { collide.play(); stateBasedGame.enterState(AquapulseGame.GAME_OVER_STATE); } } } if (!collided) player.position.y += MOVEMENT_COEFFICIENT * delta; playerMoved = true; } if(input.isKeyDown(Input.KEY_D) || input.isKeyDown(Input.KEY_RIGHT)) { boolean collided = false; for(int i = 0; i < levels.size(); i++) { for(int j = 0; j < levels.get(i).bounds.size(); j++) { Shape tileBlock = levels.get(i).bounds.get(j); if(player.bounds.intersects(tileBlock) && player.bounds.getMaxX() >= tileBlock.getMinX()) { collide.play(); stateBasedGame.enterState(AquapulseGame.GAME_OVER_STATE); } } } if (!collided) player.position.x += MOVEMENT_COEFFICIENT * delta; playerMoved = true; } player.heartRate += (playerMoved ? BPM_TO_ADD_IF_PLAYER_MOVED : -BPM_TO_SUBTRACT_IF_PLAYER_DID_NOT_MOVE) * delta/1000.0f; } } <file_sep>package com.soupcan.aquapulse.state; import com.soupcan.aquapulse.AquapulseGame; import org.newdawn.slick.*; import org.newdawn.slick.geom.Vector2f; import org.newdawn.slick.state.BasicGameState; import org.newdawn.slick.state.StateBasedGame; public class MainMenuState extends BasicGameState { private int stateId; private Image background; private Image startButtonDown; private Image startButtonUp; private Vector2f startButtonPosition; private Sound hover; private Sound select; private Music music; boolean insideStart; public MainMenuState(int stateId) { this.stateId = stateId; } @Override public int getID() { return stateId; } @Override public void enter(GameContainer gameContainer, StateBasedGame stateBasedGame) throws SlickException { music.loop(); } @Override public void init(GameContainer container, StateBasedGame stateBasedGame) throws SlickException { background = new Image("res/img/ui/mainmenu.png"); startButtonDown = new Image("res/img/ui/startbutton_down.png"); startButtonUp = new Image("res/img/ui/startbutton_up.png"); startButtonPosition = new Vector2f(325, 400); hover = new Sound("res/sound/ui/hover.wav"); select = new Sound("res/sound/ui/select.wav"); music = new Music("res/sound/menu_music.ogg"); insideStart = false; } @Override public void render(GameContainer container, StateBasedGame stateBasedGame, Graphics graphics) throws SlickException { background.draw(0, 0, 800, 600); if(insideStart) { startButtonDown.draw(startButtonPosition.x, startButtonPosition.y); } else { startButtonUp.draw(startButtonPosition.x, startButtonPosition.y); } } @Override public void update(GameContainer container, StateBasedGame stateBasedGame, int i) throws SlickException { Input input = container.getInput(); int mouseX = input.getMouseX(); int mouseY = input.getMouseY(); if((mouseX >= startButtonPosition.x && mouseX <= startButtonPosition.x + startButtonDown.getWidth()) && (mouseY >= startButtonPosition.y && mouseY <= startButtonPosition.y + startButtonDown.getHeight())) { if(!insideStart) { hover.play(); } insideStart = true; if(input.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON)) { select.play(); music.stop(); stateBasedGame.enterState(AquapulseGame.GAMEPLAY_STATE); } } else { insideStart = false; } } } <file_sep>package com.soupcan.aquapulse.state; import com.soupcan.aquapulse.AquapulseGame; import org.newdawn.slick.*; import org.newdawn.slick.geom.Vector2f; import org.newdawn.slick.state.BasicGameState; import org.newdawn.slick.state.StateBasedGame; public class GameOverState extends BasicGameState { private int stateId; private Image background; private Image startButtonDown; private Image startButtonUp; private Vector2f restartButtonPosition; private Sound hover; private Sound select; private Music music; private Sound death1, death2, death3, death4; boolean insideRestart; public GameOverState(int stateId) { this.stateId = stateId; } @Override public int getID() { return stateId; } @Override public void enter(GameContainer gameContainer, StateBasedGame stateBasedGame) throws SlickException { switch((int)(Math.random() * ((4 -1)) + 1)) { case 1: death1.play(); break; case 2: death2.play(); break; case 3: death3.play(); break; case 4: death4.play(); break; } music.loop(); } @Override public void init(GameContainer container, StateBasedGame stateBasedGame) throws SlickException { background = new Image("res/img/ui/gameover.png"); startButtonDown = new Image("res/img/ui/restartbutton_down.png"); startButtonUp = new Image("res/img/ui/restartbutton_up.png"); restartButtonPosition = new Vector2f(325, 400); hover = new Sound("res/sound/ui/hover.wav"); select = new Sound("res/sound/ui/select.wav"); music = new Music("res/sound/menu_music.ogg"); death1 = new Sound("res/sound/death_01.wav"); death2 = new Sound("res/sound/death_02.wav"); death3 = new Sound("res/sound/death_03.wav"); death4 = new Sound("res/sound/death_04.wav"); insideRestart = false; } @Override public void render(GameContainer container, StateBasedGame stateBasedGame, Graphics graphics) throws SlickException { background.draw(0, 0, 800, 600); if(insideRestart) { startButtonDown.draw(restartButtonPosition.x, restartButtonPosition.y); } else { startButtonUp.draw(restartButtonPosition.x, restartButtonPosition.y); } } @Override public void update(GameContainer container, StateBasedGame stateBasedGame, int i) throws SlickException { Input input = container.getInput(); int mouseX = input.getMouseX(); int mouseY = input.getMouseY(); if((mouseX >= restartButtonPosition.x && mouseX <= restartButtonPosition.x + startButtonDown.getWidth()) && (mouseY >= restartButtonPosition.y && mouseY <= restartButtonPosition.y + startButtonDown.getHeight())) { if(!insideRestart) { hover.play(); } insideRestart = true; if(input.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON)) { select.play(); music.stop(); stateBasedGame.enterState(AquapulseGame.GAMEPLAY_STATE); } } else { insideRestart = false; } } }
8a3fc42e034dccbdd2d9d7f30f3af6a603c0d0aa
[ "Java" ]
5
Java
soup-can/aquapulse
632a55451d120c8de5336e808506c23501c9ab11
7d9f0ab5ee5c89f9a749c8dd1bac36d9019c9ff5
refs/heads/master
<file_sep># screenshot-paste-and-upload-django Sample Application that uploads the screenshot copied in the clipboard to the server. ![alt tag](https://github.com/jithin-c/screenshot-paste-and-upload-django/blob/master/files/media/preview.png) ####How to ? copy screenshot to clipboard using Ctrl-V in Windows or Cmd-Ctrl-Shift-3 in Mac OS X and paste in the 'Paste Screenshots' Div ####Support: Works only on Google Chrome and Mozilla FireFox. ####Requires: 1. Django 1.7 2. Bootstrap 3 3. Jquery ###License This project is licensed under the MIT License. <file_sep>from django.db import models # Create your models here. class Screenshot(models.Model): attachment = models.FileField(upload_to='/screenshots/')<file_sep># screenshot-paste-and-upload-django Folder where the screenshots gets uploaded :)<file_sep>from django.conf.urls import patterns, include, url from . import views urlpatterns = patterns('', url(r'^$', views.list_screenshots, name='list_screenshots' ), url(r'^upload_screenshot$', views.upload_screenshot, name='upload_screenshot' ), ) <file_sep>import os import uuid from django.conf import settings from django.http.response import JsonResponse from django.shortcuts import render_to_response from django.template.context import RequestContext from django.views.decorators.http import require_POST from file_upload.models import Screenshot def list_screenshots(request): screenshots = Screenshot.objects.all() return render_to_response('landing_page.html',{'screenshots':screenshots},context_instance=RequestContext(request)) @require_POST def upload_screenshot(request): unique_filename = 'screenshot_' + str(uuid.uuid4()) + '.png' file_upload_path = os.path.join('screenshots', unique_filename) try: content = request.POST.get('data').replace('data:image/png;base64,', '') fh = open(os.path.join(settings.MEDIA_ROOT,file_upload_path), "wb") fh.write(content.decode('base64')) fh.close() file = Screenshot.objects.create(attachment = file_upload_path) return JsonResponse({ 'status': 'success', # 'delete_url': reverse('delete_file', kwargs={'pk':file.id}), 'fileName': unique_filename, 'url': file.attachment.url }) except Exception,e: print e return JsonResponse({'status': 'error'})
d70d4cf3b7023e524fe178e91ba1079e28ce3333
[ "Markdown", "Python" ]
5
Markdown
jithin-c/screenshot-paste-upload-django
5984945bb8fa1670f1a5084b45354c1b3ab3c110
2cbdcaa3e40b267dad64e4a60f756da9b13cba3c
refs/heads/master
<repo_name>igelbox/thermostat<file_sep>/timer.cpp #include "timer.hpp" namespace timer { Time::Time(uint8_t hour, uint8_t minute) :value(hour) { value = value * 60 + minute; } Time::Time(uint16_t total_minutes) :value(total_minutes) { } uint8_t Time::hour() const { return value / 60; } uint8_t Time::minute() const { return value % 60; } uint16_t Time::total_minutes() const { return value; } } <file_sep>/timer-rtc.cpp #include "timer.hpp" #include <RTClib.h> RTC_DS1307 tm; namespace timer { bool initialize() { tm.begin(); return tm.isrunning(); } Time now() { DateTime now = tm.now(); return Time(now.hour(), now.minute()); } void adjust(const Time &time) { tm.adjust(DateTime(0, 0, 0, time.hour(), time.minute())); } } <file_sep>/config.hpp #define LCD_RS 2 #define LCD_EE 3 #define LCD_D4 4 #define LCD_D5 5 #define LCD_D6 6 #define LCD_D7 7 #define ENC_DEC A1 #define ENC_INC A2 #define ENC_BTN A3 #define RLY_LIGHT 8 #define RLY_HEAT 9 <file_sep>/display.hpp #pragma once namespace display { void initialize(); void clear(); void reset(); void print(const char *message); void print(char character); void print(float value, int digits); void println(); } <file_sep>/buttons.hpp #pragma once namespace buttons { void init(uint8_t pin); bool read(uint8_t pin, void (*long_click)() = nullptr); } <file_sep>/main.ino #include "display.hpp" #include "config.hpp" #include "buttons.hpp" #include "menu.hpp" #include "timer.hpp" #include <Wire.h> #include <RotaryEncoder.h> #include <EEPROM.h> using namespace display; using namespace menu; void Printer::print(const char *message) { display::print(message); } void Printer::print(char character) { display::print(character); } void Printer::print(int value) { display::print(value, 0); } void Printer::print(float value, int digits) { display::print(value, digits); } void Printer::println() { print(" "); display::println(); } menu::Printer out; typedef ValueIncDecLimiter<uint16_t>::Repeat<0, 24 * 60 - 1> LimitTime; class Time: public ValueTimeHHMM<uint16_t&, LimitTime> { typedef ValueTimeHHMM<uint16_t&, LimitTime> super; public: using super::value; using super::ValueTimeHHMM; }; #pragma pack(1) struct NVMem_TimeSpan { uint16_t on, off; bool is_active(uint16_t time) const { return (time >= on) && (time < off); } }; #pragma pack(1) struct NVMem { NVMem_TimeSpan light; NVMem_TimeSpan heat[2]; } nvmem; Time miLight0_On(nvmem.light.on), miLight0_Off(nvmem.light.off); List::Item miiLight0[2] = { { "Вкл: ", miLight0_On }, { "Откл: ", miLight0_Off }, }; auto miLight0 = List::from(miiLight0); Time miHeat0_On(nvmem.heat[0].on), miHeat0_Off(nvmem.heat[0].off); List::Item miiHeat0[2] = { { "Вкл: ", miHeat0_On }, { "Откл: ", miHeat0_Off }, }; auto miHeat0 = List::from(miiHeat0); Time miHeat1_On(nvmem.heat[1].on), miHeat1_Off(nvmem.heat[1].off); List::Item miiHeat1[2] = { { "Вкл: ", miHeat1_On }, { "Откл: ", miHeat1_Off }, }; auto miHeat1 = List::from(miiHeat1); List::Item miiHeat[] = { { "Утро> ", miHeat0 }, { "Вечер> ", miHeat1 }, }; auto miHeat = List::from(miiHeat); uint16_t time; Time miTime(time); List::Item miiMain[] = { { "Время: ", miTime }, { "Свет> ", miLight0 }, { "Грев> ", miHeat }, }; auto miMain = List::from(miiMain); void pciSetup(uint8_t pin) { *digitalPinToPCMSK(pin) |= bit (digitalPinToPCMSKbit(pin)); // enable pin PCIFR |= bit (digitalPinToPCICRbit(pin)); // clear any outstanding interrupt PCICR |= bit (digitalPinToPCICRbit(pin)); // enable interrupt for the group } uint16_t clampHHMM(uint16_t value) { return value >= 24 * 60 ? 24 * 60 - 1 : value; } bool run = false; void setup() { Serial.begin(9600); display::initialize(); print("Init..."); println(); List::BACK_TEXT = "Назад"; pciSetup(ENC_INC); pciSetup(ENC_DEC); pciSetup(ENC_BTN); pinMode(RLY_LIGHT, OUTPUT); pinMode(RLY_HEAT, OUTPUT); Wire.begin(); if (!timer::initialize()) { print("Error: timer"); return; }; EEPROM.get(0, nvmem); menu::focused = &miMain; print("OK"); run = true; } RotaryEncoder enc(ENC_INC, ENC_DEC); ISR(PCINT1_vect) { enc.tick(); } unsigned long last_action_time; AbstractItem *cleared = nullptr; int prev_pos = 0; void loop() { if (!run) { return; } unsigned long ms = millis(); time = clampHHMM(timer::now().total_minutes()); NVMem prev_mem = nvmem; uint16_t prev_time = time; auto pos = -enc.getPosition(); auto delta = pos - prev_pos; if (delta) { prev_pos = pos; for (; delta < 0; ++delta) { focused->exec('-'); last_action_time = ms; } for (; delta > 0; --delta) { focused->exec('+'); last_action_time = ms; } } if (buttons::read(ENC_BTN)) { focused->exec('>'); last_action_time = ms; } if (time != prev_time) { timer::adjust(timer::Time(time)); } if (memcmp(&nvmem, &prev_mem, sizeof(nvmem))) { Serial.println('w'); EEPROM.put(0, nvmem); } auto last_action_timeout = ms - last_action_time; out.blink = (last_action_timeout / 500) % 2; if (cleared != focused) { cleared = focused; display::clear(); } else { display::reset(); } focused->draw_screen(out, 2); bool light = nvmem.light.is_active(time); digitalWrite(RLY_LIGHT, light ? HIGH : LOW); bool heat = nvmem.heat[0].is_active(time) || nvmem.heat[1].is_active(time); digitalWrite(RLY_HEAT, heat ? HIGH : LOW); } <file_sep>/menu.hpp #pragma once namespace menu { typedef unsigned char uchar; struct Printer { bool blink; void print(const char *message); void print(char character); void print(int value); void print(float value, int digits); void println(); }; class AbstractItem { public: virtual void draw_value(Printer &out) const; virtual void draw_screen(Printer &out, uchar lines_count) const; virtual void exec(char command); protected: virtual void draw_simple_value(Printer &out) const; }; extern AbstractItem *focused; class FocusableItem: public AbstractItem { typedef AbstractItem super; public: void draw_screen(Printer &out, uchar lines_count) const; void exec(char command); protected: AbstractItem *previous; }; class List: public FocusableItem { typedef FocusableItem super; public: static const char *BACK_TEXT; struct Item { const char* label; AbstractItem &item; }; template<uchar count> static List from(Item(&items)[count]) { return List(items, count); } explicit List(Item *items, uchar count); void draw_screen(Printer &out, uchar lines_count) const; void exec(char command); public: Item *items; uchar count, max_index; uchar cursor, offset; }; template<typename T> struct remove_reference { typedef T type; }; template<typename T> struct remove_reference<T&> { typedef T type; }; template <typename Ty> struct ValueIncDecLimiter { typedef typename remove_reference<Ty>::type T; struct Native { static T limit_max(const T &value, const T &prev) { return value; } static T limit_min(const T &value, const T &prev) { return value; } }; template <T vmin, T vmax> struct Clamp { static T limit_max(const T &value, const T &prev) { return prev == vmax ? vmax : value; } static T limit_min(const T &value, const T &prev) { return prev == vmin ? vmin : value; } }; template <T vmin, T vmax> struct Repeat { static T limit_max(const T &value, const T &prev) { return prev == vmax ? vmin : value; } static T limit_min(const T &value, const T &prev) { return prev == vmin ? vmax : value; } }; }; template < typename T, typename Limiter = typename ValueIncDecLimiter<T>::Native > class BaseValueIncDec: public FocusableItem { typedef FocusableItem super; typedef typename remove_reference<T>::type I; public: explicit BaseValueIncDec(const T &value, const I &increment) : value(value), increment(increment) { } void exec(char command) { switch (command) { case '+': value = Limiter::limit_max(value + increment, value); break; case '-': value = Limiter::limit_min(value - increment, value); break; default: super::exec(command); break; } } protected: T value; I increment; }; template < typename T, typename Limiter = typename ValueIncDecLimiter<T>::Native > class ValueIncDec: public BaseValueIncDec<T, Limiter> { typedef BaseValueIncDec<T, Limiter> super; public: using super::BaseValueIncDec; protected: void draw_simple_value(Printer &out) const { out.print(this->value); } }; template <class T> class WithLeadingPlusSign: public T { typedef T super; public: using T::T; protected: void draw_simple_value(Printer &out) const { if (this->value > 0) { out.print('+'); } super::draw_simple_value(out); } }; template <class T, char chr> class WithTrailingChar: public T { typedef T super; public: using T::T; protected: void draw_simple_value(Printer &out) const { super::draw_simple_value(out); out.print(chr); } }; class BaseValueTimeHHMM { protected: void draw_time(Printer &out, bool minutes, unsigned short time) const; }; template < typename T, typename Limiter = typename ValueIncDecLimiter<T>::Native > class ValueTimeHHMM: public BaseValueIncDec<T, Limiter>, BaseValueTimeHHMM { typedef BaseValueIncDec<T, Limiter> super; public: explicit ValueTimeHHMM(const T &value) : super(value, 60) { } void draw_value(Printer &out) const { draw_time(out, this->increment == 1, this->value); } void exec(char command) { switch(command) { case '>': if (this->increment == 1) { super::exec(command); } else { this->increment = 1; } break; case '.': this->increment = 60; // fall through default: super::exec(command); break; } } }; } <file_sep>/timer.hpp #pragma once #include <stdint.h> namespace timer { class Time { uint16_t value; public: Time(uint8_t hour, uint8_t minute); explicit Time(uint16_t total_minutes); uint8_t hour() const; uint8_t minute() const; uint16_t total_minutes() const; }; bool initialize(); Time now(); void adjust(const Time &time); } <file_sep>/display-lcd.cpp #include "display.hpp" #include "config.hpp" #include <LiquidCrystal_1602_RUS.h> LiquidCrystal_1602_RUS lcd(LCD_RS, LCD_EE, LCD_D4, LCD_D5, LCD_D6, LCD_D7); int row; namespace display { void initialize() { lcd.begin(16, 2); } void clear() { lcd.clear(); } void reset() { lcd.setCursor(0, row = 0); } void print(const char *message) { lcd.print(message); } void print(char character) { lcd.print(character); } void print(float value, int digits) { lcd.print(value, digits); } void println() { lcd.setCursor(0, ++row); } } <file_sep>/buttons.cpp #include "buttons.hpp" namespace buttons { void init(uint8_t pin) { pinMode(pin, INPUT_PULLUP); } bool read(uint8_t pin, void (*long_click)() = nullptr) { if (digitalRead(pin) != LOW) { return false; } unsigned long ms = millis(); boolean result = true; do { delay(150); unsigned long dt = millis() - ms; if (long_click && (dt > 1000)) { long_click(); result = false; } } while (digitalRead(pin) == LOW); return result; } } <file_sep>/menu.cpp #include "menu.hpp" namespace menu { AbstractItem *focused = nullptr; void AbstractItem::draw_value(Printer &out) const { if (!out.blink) { draw_simple_value(out); } } void AbstractItem::draw_screen(Printer &out, uchar lines_count) const {} void AbstractItem::exec(char command) {} void AbstractItem::draw_simple_value(Printer &out) const {} void FocusableItem::draw_screen(Printer &out, uchar lines_count) const { previous->draw_screen(out, lines_count); } void FocusableItem::exec(char command) { switch (command) { case '>': focused = previous; break; case '.': previous = focused; focused = this; break; default: super::exec(command); break; } } const char *List::BACK_TEXT = "Back"; List::List(List::Item *items, uchar count) : items(items), count(count), max_index(count - 1), cursor(0), offset(0) { } void List::draw_screen(Printer &out, uchar lines_count) const { bool blink = out.blink; for (auto i = 0; i < lines_count; ++i) { auto index = i + offset; char pointer = ' '; if ((index == cursor) && (focused == this)) { pointer = index == count ? '<' : '>'; } out.print(pointer); if (index == count) { out.print(BACK_TEXT); } else { auto &item = items[index]; out.print(item.label); out.blink = blink && (focused == &item.item); item.item.draw_value(out); } out.println(); } } void List::exec(char command) { switch (command) { case '-': if (cursor != 0) { offset = --cursor; } break; case '+': if (cursor != max_index) { offset = cursor++; } break; case '>': if (cursor != count) { items[cursor].item.exec('.'); break; } case '.': max_index = count; // fall through default: super::exec(command); break; } } void print_lz2(struct Printer &out, uchar v) { if (v < 10) { out.print('0'); } out.print(v); } void BaseValueTimeHHMM::draw_time(Printer &out, bool minutes, unsigned short value) const { auto blink = out.blink; if (blink && !minutes) { out.print(" "); } else { print_lz2(out, value / 60); } out.print(':'); if (blink && minutes) { out.print(" "); } else { print_lz2(out, value % 60); } } }
6d8732c3acf98516215508465ad1f8fc9c294133
[ "C++" ]
11
C++
igelbox/thermostat
67c3a1a80777ce63e95c0e7a450fa67ec783661e
dc46f6cb046a8ebacc4f2c98fa152f0e275df2b8
refs/heads/main
<file_sep>#include <stdio.h> #include <stdlib.h> #include <locale.h> int main(void) { setlocale(LC_ALL,""); float raio,area; printf("qual é o raio da circurferência?"); scanf("%f",&raio); area=2*3.14*raio; printf("com o raio de %f a circurferência terá:%.2f de area",raio,area); return 0; }
0f12a47b37cf4dda1953a5d5695582e0d390835b
[ "C" ]
1
C
albertoneto03/TED-05-c
6d0353c7af5291c3e29e671e008790aaa80860fb
afa062efee7399f55ea8e12139b3bab98aeb60f3
refs/heads/master
<repo_name>alginokursoy/test-repo<file_sep>/hello_world.py import os import sys import requests def say_something(sentences): for i in sentences.split(" "): os.system("say %s" % i) r = requests.get("https://coreyms.com") print(r.status_code) name = input("Your Name? ") say_something("merhaba %s" % name) print(sys.executable)
3103c67aa33bcdd279baf8bbfc558cea8b4961e6
[ "Python" ]
1
Python
alginokursoy/test-repo
ec810d3a3ca6f1a81f5b65bf79da0e78bd080d48
398777fa0477fd0ddddcc222491d6348087fe176
refs/heads/master
<file_sep>const express = require('express'); const bodyParser = require('body-parser'); const mongoose = require('mongoose'); const cors = require('./cors') const Favorites = require('../models/favorites'); const favoriteRouter = express.Router(); favoriteRouter.use(bodyParser.json()); var authenticate = require('../authenticate'); favoriteRouter.route('/') .options(cors.corsWithOptions, (req, res) => { res.sendStatus(200); }) .get(cors.corsWithOptions, (req,res,next) => { Favorites.findOne({user: req.user._id}) .populate('user') .populate('dishes') .then((fav) => { res.json(fav); }, (err) => next(err)) .catch((err) => next(err)); }) .post(cors.corsWithOptions, authenticate.verifyUser, (req, res, next) => { Favorites.findOne({user: req.user._id}) .then((favorite) => { if (favorite) { favorite.save() .then((favorite) => { Favorites.findById(favorite._id) .populate('user') .populate('dishes') .then((favorite) => { res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.json(favorite); }) }) .catch((err) => { return next(err); }); } else { for (i = 0; i < req.body.length; i++ ) if (favorite.dishes.indexOf(req.body[i]._id) < 0) favorite.dishes.push(req.body[i]); favorite.save() .then((favorite) => { Favorites.findById(favorite._id) .populate('user') .populate('dishes') .then((favorite) => { res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.json(favorite); }) }) .catch((err) => { return next(err); }); } }) }) .put(cors.corsWithOptions, authenticate.verifyUser, (req, res, next) => { res.statusCode = 403; res.end('PUT operation not supported on /dishes'); }) .delete(cors.corsWithOptions, authenticate.verifyUser, (req, res, next) => { Favorites.remove({}) .then((resp) => { res.json(resp); resp.save() .then((favorite) => { Favorites.findById(favorite._id) .populate('user') .populate('dishes') .then((favorite) => { res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.json(favorite); }) }) }, (err) => next(err)) .catch((err) => next(err)); }); favoriteRouter.route('/:favId') .options(cors.corsWithOptions, (req, res) => { res.sendStatus(200); }) .get(cors.cors, authenticate.verifyUser, (req,res,next) => { Favorites.findOne({user: req.user._id}) .then((favorites) => { if (!favorites) { res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); return res.json({"exists": false, "favorites": favorites}); } else { if (favorites.dishes.indexOf(req.params.dishId) < 0) { res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); return res.json({"exists": false, "favorites": favorites}); } else { res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); return res.json({"exists": true, "favorites": favorites}); } } }, (err) => next(err)) .catch((err) => next(err)) }) .post(cors.corsWithOptions, authenticate.verifyUser, (req, res, next) => { res.statusCode = 403; res.end('POST operation not supported on /dishes/'+ req.params.dishId); }) .put(cors.corsWithOptions, authenticate.verifyUser, (req, res, next) => { Favorites.findByIdAndUpdate(req.params.favId, { $set: req.body }, { new: true }) .then((dish) => { res.json(dish); }, (err) => next(err)) .catch((err) => next(err)); }) .delete(cors.corsWithOptions, authenticate.verifyUser, (req, res, next) => { Favorites.findByIdAndRemove(req.params.favId) .then((resp) => { res.json(resp); }, (err) => next(err)) .catch((err) => next(err)); }); module.exports = favoriteRouter;
5b45f1959b9e5330d8112c3e471fe2f537b6459e
[ "JavaScript" ]
1
JavaScript
KorsakovSemen/rest-API
f01e36e0e035f8f85734449f0e0c184c78aa48d7
7fd9424da657ca065a1f9ee69b528598fdce306c
refs/heads/master
<repo_name>JosefWalls/CarzSeller<file_sep>/server/routes/Users.js const cars = require("../models/Cars"); const Router = require("express").Router(); const User = require("../models/User"); Router.route("/SaveCar/:carId").post((req, res) => { const userId = (req.session.user.userId); const carId = req.params.carId; User.update({"_id": userId}, {$push: {"savedCars": carId}}) .then(savedCars => { res.json(savedCars) }) .catch(err => { res.json(err) }) }) module.exports = Router;<file_sep>/src/routes.js import React from "react"; import {Route, Switch} from "react-router-dom"; import Login from "./components/Auth/Login"; import Landing from "./components/LandingSearch/Landing"; import ViewCars from "./components/Search/ViewCars"; import Profile from "./components/Profile/Profile"; import AddCar from "./components/Profile/AddCar"; import ViewCar from "./components/Search/ViewCar"; import ManageCar from "./components/Profile/ManageCar"; export default ( <Switch> <Route component={AddCar} path="/Profile/AddCar" /> <Route component={Login} path="/Login" /> <Route component={Landing} exact path="/" /> <Route component={ViewCar} path="/Search/:car_id" /> <Route component={ViewCars} path="/Search" /> <Route component={Profile} exact path="/Profile/:userId" /> <Route component={ManageCar} path="/Profile/ManageCar/:carId"/> </Switch> )<file_sep>/src/quakers/store.js import {combineReducers, createStore, applyMiddleware} from "redux"; import promise from "redux-promise-middleware" import AuthReducer from "./reducers/AuthReducer"; import CarReducer from "./reducers/CarReducer"; import UserCarReducer from "./reducers/UserCarReducer"; const root = combineReducers({ AuthReducer, CarReducer, UserCarReducer }) export default createStore(root, applyMiddleware(promise))<file_sep>/src/components/Search/ViewCars.js import React from "react"; import {connect} from "react-redux"; import {getCars, getCarsOnlyMake} from "../../quakers/reducers/CarReducer"; import "./ViewCars.css"; import {Link} from "react-router-dom"; class ViewCar extends React.Component { constructor(){ super() } componentDidMount = async () => { const make = this.props.make; const model = this.props.model; if(model.length === 0){ this.props.getCarsOnlyMake(make) } else { this.props.getCars(make, model) } } render() { const mappedCars = this.props.cars.map((val, i) => { return ( <Link to={`/Search/${val._id}`}> <div className="carSearchCard"> <img src={val.header} alt="Car image"></img> <div className="carInfo"> <h1>{val.year} {val.make} {val.model}</h1> <p>Miles: {val.miles} || {val.highway} highway / {val.city} city || Transmission: {val.transmission}</p> <h3>${val.price}</h3> </div> </div> </Link> ) }) return ( <div className="mappedCars"> {mappedCars} </div> ) } } const mapStateToProps = reduxState => { return { cars: reduxState.CarReducer.cars, make: reduxState.CarReducer.make, model: reduxState.CarReducer.model } } export default connect(mapStateToProps, {getCars, getCarsOnlyMake})(ViewCar);<file_sep>/src/components/Search/ViewCar.js import React from "react"; import {carDetails, getCarOwner} from "../../quakers/reducers/CarReducer"; import {updateState, addView} from "../../quakers/reducers/UserCarReducer"; import {connect} from "react-redux"; import "./ViewCar.css" class ViewCar extends React.Component { constructor(){ super() } componentDidMount = async () => { await this.props.carDetails(this.props.match.params.car_id) const posterId = this.props.car[0].posterId; this.props.getCarOwner(posterId) const originalViews = +this.props.car[0].views++ this.props.updateState({views: originalViews}) console.log(originalViews) this.props.addView(this.props.views, this.props.match.params.car_id) } render() { const mappedCarHeader = this.props.car.map((val, i) => { return ( <div className="carHeader"> <h1>{val.condition} {val.year} {val.make} {val.model}</h1> <img src={val.header}></img> </div> ) }) const mappedCarDetails = this.props.car.map((val, i) => { return ( <div className="carInformation"> <p>Mileage: {val.miles} miles</p> <p>Highway: {val.highway}</p> <p>City: {val.city}</p> <p>Transmission: {val.transmission}</p> <p>Engine: {val.engine}</p> </div> ) }) const mappedPrice = this.props.car.map((val, i) => { return ( <div className="carPriceCard"> <h3>${val.price}</h3> </div> ) }) const mappedOwner = this.props.owner.map((val, i) => { return ( <div className="mappedOwner"> <h1>{val.email}</h1> <img src={val.profileImg}></img> <p>Address: </p> </div> ) }) const mappedDescription = this.props.car.map((val, i) => { return ( <div className="carDescription"> <p>{val.description}</p> </div> ) }) return ( <div className="carDetails"> {mappedCarHeader} {mappedPrice} {mappedCarDetails} {mappedOwner} {mappedDescription} </div> ) } } const mapStateToProps = reduxState => { return { car: reduxState.CarReducer.car, owner: reduxState.CarReducer.owner, views: reduxState.UserCarReducer.views } } export default connect(mapStateToProps, {carDetails, getCarOwner, updateState, addView})(ViewCar);<file_sep>/src/components/Profile/AddCar.js import React from "react"; import {connect} from "react-redux"; import {updateState, addcar} from "../../quakers/reducers/UserCarReducer"; import {storage} from "../../../firebase-config"; import "./Addcar.css"; import {Link} from "react-router-dom"; class AddCar extends React.Component { constructor(){ super() } handleDetails = (e) => { this.props.updateState({[e.target.name]: e.target.value}) } handleMake = async (e) => { await this.props.updateState({make: e.target.value}) } uploadHeader = (e) => { if(e.target.files[0]){ const image = (e.target.files[0]); const uploadTask = storage.ref(`/cars/${image.name}`).put(image) uploadTask.on("state_changed", () => { storage.ref('cars').child(image.name).getDownloadURL() .then(url => { console.log(url) this.props.updateState({header: url}) }) } ) } } submitCar = async (e) => { e.preventDefault(); const {year, make, model, description, price, miles, highway, city, transmission, engine, header, vin, stockNumber, exterior, interior} = this.props; if(!header){ this.props.updateState({header: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAA1BMVEUAAP+KeNJXAAAASElEQVR4nO3BgQAAAADDoPlTX+AIVQEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADwDcaiAAFXD1ujAAAAAElFTkSuQmCC"}) } await this.props.addcar(year, make, model, description, price, miles, highway, city, transmission, engine, header, vin, stockNumber, exterior, interior) .then(() => { this.props.history.push(`/Profile/${this.props.user.userId}`) }) .catch(err => { console.log(err) }) } render() { const mappedMakes = this.props.makes.map((val, i) => { return ( <option value={val}>{val}</option> ) }) return ( <section className="addCarMain"> <div className="addCarForm"> <input name="year" placeholder="Year" onChange={this.handleDetails}></input> <select onChange={this.handleMake}> <option>--Select Make--</option> {mappedMakes} </select> <input name="model" placeholder="Model" onChange={this.handleDetails}></input> <input name="description" placeholder="Description" onChange={this.handleDetails}></input> <input name="miles" placeholder="Miles" onChange={this.handleDetails}></input> <input name="highway" placeholder="Highway" onChange={this.handleDetails}></input> <input name="city" placeholder="City" onChange={this.handleDetails}></input> <input name="transmission" placeholder="Transmission" onChange={this.handleDetails}></input> <input name="engine" placeholder="Engine" onChange={this.handleDetails}></input> <input name="header" type="file" onChange={this.uploadHeader}></input> <input name="vin" placeholder="Vin" onChange={this.handleDetails}></input> <input name="stockNumber" placeholder="Stock Number" onChange={this.handleDetails}></input> <input name="exterior" placeholder="Exterior Color" onChange={this.handleDetails}></input> <input name="interior" placeholder="Interior Color" onChange={this.handleDetails}></input> <input name="price" placeholder="Price" onChange={this.handleDetails}></input> <button onClick={this.submitCar} className="cancelButton">Add Vehicle</button> <Link to={`/Profile/${this.props.user.userId}`}> <button className="cancelButton">Cancel</button> </Link> </div> </section> ) } } const mapStateToProps = reduxState => { return { makes: reduxState.UserCarReducer.makes, year: reduxState.UserCarReducer.year, make: reduxState.UserCarReducer.make, model: reduxState.UserCarReducer.model, description: reduxState.UserCarReducer.description, price: reduxState.UserCarReducer.price, miles: reduxState.UserCarReducer.miles, highway: reduxState.UserCarReducer.highway, city: reduxState.UserCarReducer.city, transmission: reduxState.UserCarReducer.transmission, engine: reduxState.UserCarReducer.engine, header: reduxState.UserCarReducer.header, vin: reduxState.UserCarReducer.vin, stockNumber: reduxState.UserCarReducer.stockNumber, exterior: reduxState.UserCarReducer.exterior, interior: reduxState.UserCarReducer.interior, user: reduxState.AuthReducer.user } } export default connect(mapStateToProps, {updateState, addcar})(AddCar);<file_sep>/server/models/Cars.js const mongoose = require("mongoose"); const CarSchema = new mongoose.Schema({ year: { type: Number, default: 2020 }, make: { type: String, default: "" }, model: { type: String, default: "" }, description: { type: String, default: "" }, posterId: { type: String, default: 0 }, price: { type: String, default: 0 }, miles: { type: String, default: 0 }, highway: { type: String, default: 0 }, city: { type: String, default: 0 }, transmission: { type: String, default: "Automatic" }, engine : { type: String, default: "" }, header: { type: String, default: "" }, views: { type: Number, default: 0 }, vin: { type: Number, default: 0 }, stockNumber: { type: Number, default: 0 }, exterior: { type: String, default: "" }, interior: { type: String, default: "" } }) module.exports = mongoose.model("Car", CarSchema);<file_sep>/server/routes/Cars.js const cars = require("../models/Cars"); const Router = require("express").Router(); const User = require("../models/User"); Router.route("/Add").post((req, res) => { console.log("added hit") const {year, make, model, description, images, price, miles, highway, city, transmission, engine, condition, header, vin, stockNumber, exterior, interior} = req.body; const userId = req.session.user.userId; const newCar = new cars(); newCar.year = year; newCar.make = make; newCar.model = model; newCar.description = description; newCar.images = images; newCar.posterId = userId; newCar.price = price; newCar.miles = miles; newCar.highway = highway; newCar.city = city; newCar.transmission = transmission; newCar.engine = engine; newCar.condition = condition; newCar.header = header; newCar.vin = vin; newCar.stockNumber = stockNumber; newCar.exterior = exterior; newCar.interior = interior; newCar.save((err, car) => { if(err){ res.status(403).json(err) } else { res.status(200).json(car) } res.end("Car added") }) }); Router.route("/Sort/AllMakes").get((req, res) => { cars.distinct("make") .then(cars => res.json(cars)) .catch(err => res.json(err)) }) Router.route("/Sort/Model/:make").get((req, res) => { const make = req.params.make; cars.distinct("model", {make}) .then(cars => res.json(cars)) .catch(error => res.json(error)) }) //if user doesnt enter any params Router.route("/Search").get((req, res) => { cars.find() .then(cars => res.json(cars)) .catch(err => res.json(err)) }) //if user only enters make Router.route("/Search/:make").get((req, res) => { const make = req.params.make; console.log(make) cars.find({make}) .then(cars => res.json(cars)) .catch(err => res.json(err)) }) //searches make and model Router.route("/Search/:make/:model").get((req, res) => { const make = req.params.make; const model = req.params.model; cars.find({make, model}) .then(cars => res.json(cars)) .catch(err => res.json(err)) }) Router.route("/ViewCar/:car_id").get((req, res) => { console.log("hit added") const carId = req.params.car_id; cars.find({_id: carId}) .then(cars => res.json(cars)) .catch(err => res.json(err)) }) Router.route("/User/Cars").get((req, res) => { const posterId = req.session.user.userId; cars.find({posterId}) .then(cars => res.json(cars)) .catch(err => res.json(err)) }) Router.route("/ViewCar/Owner/:posterId").get((req, res) => { const userId = req.params.posterId; User.find({_id: userId}) .then((profile => res.json(profile))) .catch(err => res.json(err)) }) Router.route("/Edit/:carId").put((req, res) => { const carId = req.params.carId const {year, make, model, description, price, miles, highway, city, transmission, engine, header, vin, stockNumber, exterior, interior} = req.body; cars.updateOne({_id: carId}, {$set: {year: year, make: make, model: model, description: description, price: price, miles: miles, highway: highway, city: city, transmission: transmission, engine: engine, header: header, vin: vin, stockNumber: stockNumber, exterior: exterior, interior: interior}}) .then(() => res.json("Car updated")) .catch(err => res.json(err)) }) Router.route("/Delete/:carId").delete((req, res) => { const carId = req.params.carId; cars.deleteOne({_id: carId}) .then(() => { res.json("Car deleted") }) .catch(err => { res.json(err) }) }) Router.route("/AddView/:carId").put((req, res)=> { const carId = req.params.carId; const {views} = req.body; cars.updateOne({_id: carId}, {$set: {views: views}}) .then(() => res.json("Views added")) .catch(err => res.json(err)) }) module.exports = Router;<file_sep>/src/quakers/reducers/AuthReducer.js import axios from "axios"; const initalState = { loading: false, email: "", password: "", loggedIn: false, user: [] } const UPDATE_STATE = "UPDATE_STATE"; const LOGGED_IN = "LOGGGED_IN"; export const updateState = (e) => { return { type: UPDATE_STATE, payload: e } } export const logIn = (email, password) => { return { type: LOGGED_IN, payload: axios.post("/autoClone/account/signin", { email: email, password: <PASSWORD> }) } } export default function reducer (state = initalState, action){ const {type, payload} = action; switch(type){ case UPDATE_STATE: return {...state, ...payload} case `${LOGGED_IN}_PENDING`: return {...state, loading: true} case `${LOGGED_IN}_FULFILLED`: return {...state, loading: false, loggedIn: true, user: payload.data} default: return state } }<file_sep>/src/firebase-config.js import firebase from "firebase/app" import "firebase/storage" const config = { apiKey: "<KEY>", authDomain: "autoclone-3dac1.firebaseapp.com", databaseURL: "https://autoclone-3dac1.firebaseio.com", projectId: "autoclone-3dac1", storageBucket: "autoclone-3dac1.appspot.com", messagingSenderId: "1083804532195", appId: "1:1083804532195:web:7872f30330f429f8c274d6", measurementId: "G-3NVF6HTDES" } firebase.initializeApp(config) const storage = firebase.storage(); export { storage, firebase as default }<file_sep>/src/components/Profile/ManageCar.js import React from "react"; import {carDetails, updateState} from "./../../quakers/reducers/CarReducer"; import {updateCar, unlistCar} from "../../quakers/reducers/UserCarReducer"; import {connect} from "react-redux"; import "./ManageCar.css"; class ManageCar extends React.Component { constructor(){ super() this.state = { editMenuHeader: "editMenuClosed", editMenuPrice: "editPriceClosed", editMenuDetails: "editDetailsClosed", editMenuDescription: "editDescriptionClosed" } } componentDidMount = async () => { await this.props.carDetails(this.props.match.params.carId); this.props.updateState({year: this.props.car[0].year}); this.props.updateState({make: this.props.car[0].make}); this.props.updateState({model: this.props.car[0].model}); this.props.updateState({price: this.props.car[0].price}) this.props.updateState({highway: this.props.car[0].highway}) this.props.updateState({city: this.props.car[0].city}) this.props.updateState({stockNumber: this.props.car[0].stockNumber}) this.props.updateState({transmission: this.props.car[0].transmission}) this.props.updateState({vin: this.props.car[0].vin}) this.props.updateState({exterior: this.props.car[0].exterior}) this.props.updateState({interior: this.props.car[0].interior}) } changeHeaderMenu = (e) => { if(this.state.editMenuHeader === "editMenuClosed"){ this.setState({editMenuHeader: "editMenuOpen"}) } else { this.setState({editMenuHeader: "editMenuClosed"}) } } changePriceMenu = (e) => { if(this.state.editMenuPrice === "editPriceClosed"){ this.setState({editMenuPrice: "editPriceOpen"}) } else { this.setState({editMenuPrice: "editPriceClosed"}) } } changeDetailMenu = (e) => { if(this.state.editMenuDetails === "editDetailsClosed"){ this.setState({editMenuDetails: "editDetailsOpen"}) } else { this.setState({editMenuDetails: "editDetailsClosed"}) } } changeDescriptionMenu = (e) => { if(this.state.editMenuDescription ==="editDescriptionClosed"){ this.setState({editMenuDescription: "editDescriptionOpen"}) } else { this.setState({editMenuDescription: "editDescriptionClosed"}) } } handleUpdate = async (e) => { await this.props.updateState({[e.target.name]: e.target.value}) } updateCar = async (e) => { const carId = this.props.match.params.carId; const {year, make, model, description, price, miles, highway, city, transmission, engine, header, vin, stockNumber, exterior, interior} = this.props; console.log(description) await this.props.updateCar(carId, year, make, model, description, price, miles, highway, city, transmission, engine, header, vin, stockNumber, exterior, interior) .then(() => { alert("car edited") }) .catch(err => { console.log(err) }) } handleUnlist = async (e) => { await this.props.unlistCar(this.props.match.params.carId) .then(() => { this.props.history.push(`/Profile/${this.props.user.userId}`) }) } render() { const mappedMakes = this.props.makes.map((val, i) => { return ( <option value={val}>{val}</option> ) }) const mappedCarHeader = this.props.car.map((val, i) => { return ( <div className="manageCarHeader"> <h1>{val.condition} {val.year} {val.make} {val.model}</h1> <img src={val.header}></img> <button onClick={this.changeHeaderMenu}>Edit Header</button> </div> ) }) const mappedCarDetails = this.props.car.map((val, i) => { return ( <div className="manageCarDetails"> <p>Mileage: {val.miles} miles</p> <p>Highway: {val.highway}</p> <p>City: {val.city}</p> <p>Transmission: {val.transmission}</p> <p>Engine: {val.engine}</p> <p>Vin: {val.vin}</p> <p>Stock Number: {val.stockNumber}</p> <p>Exterior: {val.exterior}</p> <p>Interior: {val.interior}</p> <button onClick={this.changeDetailMenu}>Edit Details</button> </div> ) }) const mappedPrice = this.props.car.map((val, i) => { return ( <div className="manageCarPrice"> <h3>${val.price}</h3> <button onClick={this.changePriceMenu}>Edit Price</button> </div> ) }) const mappedDescription = this.props.car.map((val, i) => { return ( <div className="manageCarDescription"> <p>{val.description}</p> <button onClick={this.changeDescriptionMenu}>Edit Description</button> </div> ) }) return ( <div> {mappedCarHeader} {mappedCarDetails} {mappedPrice} {mappedDescription} {/* Header menu */} <div className={this.state.editMenuHeader}> <input placeholder="Edit Car Year" onChange={this.handleUpdate} name="year"></input> <select onChange={this.handleUpdate} name="make"> <option>--Select Make--</option> {mappedMakes} </select> <input placeholder="Edit Car Model" onChange={this.handleUpdate} name="model"></input> <h5>Edit Header Image:</h5> <input type="file"></input> <button onClick={this.changeHeaderMenu}>Cancel</button> <button onClick={this.updateCar}>Update Header Section</button> </div> {/* Price menu */} <div className={this.state.editMenuPrice}> <input placeholder="Edit Car Price" onChange={this.handleUpdate} name="price"></input> <button onClick={this.changePriceMenu}>Cancel</button> <button onClick={this.updateCar}>Update Price Section</button> </div> {/* Details menu */} <div className={this.state.editMenuDetails}> <input placeholder="Edit Car Mileage" onChange={this.handleUpdate} name="miles"></input> <input placeholder="Edit Car Highway MPG" onChange={this.handleUpdate} name="highway"></input> <input placeholder="Edit Car City MPG" onChange={this.handleUpdate} name="city"></input> <input placeholder="Edit Car Transmission" onChange={this.handleUpdate} name="transmission"></input> <input placeholder="Edit Car Engine" onChange={this.handleUpdate} name="engine"></input> <input placeholder="Edit Car Vin" onChange={this.handleUpdate} name="vin"></input> <input placeholder="Edit Car Stock Number" onChange={this.handleUpdate} name="stockNumber"></input> <input placeholder="Edit Car Exterior Color" onChange={this.handleUpdate} name="exterior"></input> <input placeholder="Edit Car Interior Color" onChange={this.handleUpdate} name="interior"></input> <button onClick={this.changeDetailMenu}>Cancel</button> <button onClick={this.updateCar}>Update Details Section</button> </div> {/* Description menu */} <div className={this.state.editMenuDescription}> <input placeholder="Edit Car Description" name="description" onChange={this.handleUpdate}></input> <button onClick={this.changeDescriptionMenu}>Cancel</button> <button onClick={this.updateCar}>Update Description Section</button> </div> <div> <h5>Need To Unlist This Vehicle?</h5> <button onClick={this.handleUnlist}>Remove Vehicle</button> </div> <button onClick={this.updateCar}>Submit Updates</button> </div> ) } } const mapStateToProps = reduxState => { return { makes: reduxState.UserCarReducer.makes, year: reduxState.UserCarReducer.year, make: reduxState.UserCarReducer.make, model: reduxState.UserCarReducer.model, description: reduxState.UserCarReducer.description, price: reduxState.UserCarReducer.price, miles: reduxState.UserCarReducer.miles, highway: reduxState.UserCarReducer.highway, city: reduxState.UserCarReducer.city, transmission: reduxState.UserCarReducer.transmission, engine: reduxState.UserCarReducer.engine, header: reduxState.UserCarReducer.header, vin: reduxState.UserCarReducer.vin, stockNumber: reduxState.UserCarReducer.stockNumber, exterior: reduxState.UserCarReducer.exterior, interior: reduxState.UserCarReducer.interior, car: reduxState.CarReducer.car, makes: reduxState.UserCarReducer.makes, user: reduxState.AuthReducer.user } } export default connect(mapStateToProps, {carDetails, updateState, updateCar, unlistCar})(ManageCar);<file_sep>/server/index.js require("dotenv").config(); const express = require("express"); const session = require("express-session"); const massive = require("massive"); const app = express(); const mongoose = require("mongoose"); const cors = require("cors") app.use(express.json()); app.use(cors()); const uri = process.env.AUTH_URI; mongoose.connect(uri, {useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); const connection = mongoose.connection; connection.once("open", () => { console.log("MongoDB connected") }) app.use(session({ secret: "Autoclone", saveUninitialized: true, resave: false })) const authRouter = require("./routes/auth"); const CarRouter = require("./routes/Cars"); const userRouter = require("./routes/Users"); app.use("/autoClone", authRouter); app.use("/autoClone/Car", CarRouter); app.use("/autoClone/User", userRouter); app.listen(4020, () => console.log("Port 4020"))<file_sep>/src/components/Profile/Profile.js import React from "react"; import {Link} from "react-router-dom"; import {connect} from "react-redux"; import {getProfileCars} from "../../quakers/reducers/UserCarReducer"; import "./Profile.css"; class Profile extends React.Component { constructor(){ super() } componentDidMount(){ this.props.getProfileCars() } render() { const mappedCars = this.props.cars.map((val, i) => { return ( <div className="ProfileCarCard"> <h3>{val.year} {val.make} {val.model}</h3> <img src={val.header}></img> <Link to={`/Profile/ManageCar/${val._id}`}> <button>Manage Vehicle</button> </Link> </div> ) }) return ( <section className="profileSection"> <div className="profileCard"> {mappedCars} <Link to="/Profile/AddCar"> <button className="submitButton">Add Car</button> </Link> </div> </section> ) } } const mapStateToProps = reduxState => { return { cars: reduxState.UserCarReducer.cars } } export default connect(mapStateToProps, {getProfileCars})(Profile);<file_sep>/src/components/LandingSearch/Landing.js import React from "react"; import "./Landing.css"; import {connect} from "react-redux"; import {filterMakes, filterModels, updateState} from "../../quakers/reducers/CarReducer"; import {Link} from "react-router-dom"; class Landing extends React.Component { constructor(){ super() this.state = { make: "", model: "" } } componentDidMount(){ this.props.filterMakes(); } handleMake = async (e) => { this.props.updateState({make: e.target.value}) await this.props.filterModels(e.target.value) } handleModel = async (e) => { this.props.updateState({model: e.target.value}) await this.setState({model: e.target.value}) } render() { const mappedMakes = this.props.makes.map((val, i) => { return ( <option value={val}>{val}</option> ) }) const mappedModels = this.props.models.map((val, i) => { return ( <option value={val}>{val}</option> ) }) return ( <div className="landingSort"> <img src="https://drop.ndtv.com/albums/AUTO/porsche-taycan-turbo/6401200x900_1_640x480.jpg"></img> <div className="landingSortCard"> <h4>Search Carz!</h4> <select onChange={this.handleMake}> <option>--Select Make--</option> {mappedMakes} </select> <select onChange={this.handleModel}> <option>--Select Model--</option> {mappedModels} </select> <Link to={`/Search/`}> <button>Search</button> </Link> </div> </div> ) } } const mapStateToProps = reduxState => { return { make: reduxState.CarReducer.make, model: reduxState.CarReducer.model, makes: reduxState.CarReducer.makes, models: reduxState.CarReducer.models } } export default connect(mapStateToProps, {filterMakes, filterModels, updateState})(Landing);
296d6c5782b63dfd6293abac8e68e5388470901a
[ "JavaScript" ]
14
JavaScript
JosefWalls/CarzSeller
9a22bd44d9497f3d43ad8669fbe3af707ce0522f
787c89b335cc7755839edf42e99e4b88aade01f8
refs/heads/master
<file_sep>import React, {useState, useEffect} from 'react'; import logo from './logo.svg'; import './App.css'; import Saludar from './components/Saludar'; import { Button, Accordion, Card } from 'react-bootstrap'; import { ReactComponent as ReactIcon } from './logo.svg'; import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom'; import Contacto from './pages/Contacto'; import QuienSoy from './pages/QuienSoy'; function App() { const user = { nombre: "<NAME>", edad: 37 } const saludarFn = name => { // alert("Hola " + name); // Usando template strings alert(`Hola ${name}`); }; const [stateCar, setStateCar] = useState(false); const [contar, setContar] = useState(0); useEffect(() => { console.log("Total " + contar); }, [contar]); const encenderApagar = () => { console.log('Encender | Apagar'); // se le manda el valor contrario que tenga stateCar a setStateCar con el signo de admiración // setStateCar(!stateCar); // obteniendo el valor previo del state: setStateCar(prevValue => !prevValue); setContar(contar + 1); } return ( <div className="App"> <header className="App-header"> <Router> <div> <Link to = "/"> <button variant="primary">Home</button> </Link> <Link to = "/contacto"> <button variant="primary">Contacto</button> </Link> <Link to = "/quien-soy"> <button variant="primary">Quien soy</button> </Link> </div> <Switch> <Route path="/contacto"> <Contacto /> </Route> <Route path="/quien-soy"> <QuienSoy /> </Route> </Switch> </Router> <h2>El coche está: {stateCar === true ? 'Encendido' : 'Apagado'}</h2> <Button variant="primary" onClick={encenderApagar}>Encender | Apagar</Button> <img src={logo} className="App-logo" alt="logo" /> <p> Edit <code>src/App.js</code> and save to reload. </p> <Saludar userInfo = {user} saludarFn = {saludarFn}/> <h1>React Bootstrap</h1> <Button variant="primary">Primary</Button> <h1>Acordion</h1> <Accordion defaultActiveKey="0"> <Card> <Card.Header> <Accordion.Toggle as={Button} variant="link" eventKey="0"> Click me! </Accordion.Toggle> </Card.Header> <Accordion.Collapse eventKey="0"> <Card.Body>Hello! I'm the body</Card.Body> </Accordion.Collapse> </Card> <Card> <Card.Header> <Accordion.Toggle as={Button} variant="link" eventKey="1"> Click me! </Accordion.Toggle> </Card.Header> <Accordion.Collapse eventKey="1"> <Card.Body>Hello! I'm another body</Card.Body> </Accordion.Collapse> </Card> </Accordion> <ReactIcon></ReactIcon> </header> </div> ); } export default App; <file_sep>import React from 'react'; function Saludar(props){ const {userInfo, saludarFn} = props; const {nombre = "Anonimo"} = userInfo; return ( <div> <h1>Hola {userInfo.nombre} tiene {userInfo.edad} años</h1> <button onClick={() => saludarFn(nombre)}>Saludar</button> </div> ); } export default Saludar;
5497432380ea046501c4d417fccece334d4f0a9a
[ "JavaScript" ]
2
JavaScript
LuigisDev/mi-primera-app-react
ab752ee8f2b84798bab8d3023c753e5037aaef94
48e520b97d9017cc7cad042c92f9d9a703867f99
refs/heads/master
<file_sep>算法 时间复杂度: <file_sep>package com.latico.algorithm.sort; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class BubbleSortUtilsTest { @Test public void sort() { int[] arr = new int[]{2,1,3,5,7,2,7,0,8,4}; BubbleSortUtils.sortArr(arr); System.out.println(Arrays.toString(arr)); } @Test public void sort2() { int[] arr = new int[]{2,1,3,5,7,2,7,0,8,4}; BubbleSortUtils.sortArr2(arr); System.out.println(Arrays.toString(arr)); } @Test public void sortComparable(){ List<ComparableBean> list = new ArrayList<>(); list.add(new ComparableBean(2)); list.add(new ComparableBean(1)); list.add(new ComparableBean(3)); list.add(new ComparableBean(5)); list.add(new ComparableBean(7)); list.add(new ComparableBean(2)); list.add(new ComparableBean(7)); list.add(new ComparableBean(0)); list.add(new ComparableBean(8)); list.add(new ComparableBean(4)); BubbleSortUtils.sortComparable(list); System.out.println(list); } }<file_sep>package com.latico.algorithm.sort; import org.junit.Test; import java.util.Arrays; public class InsertionSortUtilsTest { @Test public void sort() { int[] arr = new int[]{2,1,3,5,7,2,7,0,8,4}; InsertionSortUtils.sort(arr); System.out.println(Arrays.toString(arr)); } @Test public void sort2() { int[] arr = new int[]{2,1,3,5,7,2,7,0,8,4}; InsertionSortUtils.sort2(arr); System.out.println(Arrays.toString(arr)); } }<file_sep>package com.latico.algorithm; import org.junit.Test; public class Test3 { public static void test(boolean flag) { if (flag) { System.out.println("flag true"); throw new RuntimeException(); } System.out.println("end"); } /** * */ @Test public void test(){ String str1 = "abc"; String str2 = new String("abc"); String str3 = "abc"; String str4 = "abc" + "d"; String str5 = "abcd"; System.out.println(str2 == str1); System.out.println(str3 == str1); System.out.println(str4 == str5); System.out.println(str2.intern() == str1); System.out.println(str2 == str1); } /** * */ @Test public void test2(){ String str1 = new StringBuilder("计算机").append("软件").toString(); System.out.println(str1.intern() == str1); String str2 = new StringBuilder("计算机").append("软件").toString(); System.out.println(str2.intern() == str2); System.out.println(str2.intern() == str1); System.out.println(str2.intern() == str1.intern()); } }<file_sep>package com.latico.algorithm.sort; import java.util.Random; /** * <PRE> * * </PRE> * * @Author: latico * @Date: 2019-07-16 23:39 * @Version: 1.0 */ public class XiPai { public static int[] random(int[] arr) { Random random =new Random(); for (int i = arr.length - 1; i >= 1; i--) { int index = random.nextInt(i + 1); // 把随机结果的数据交换到i int tmp = arr[index]; arr[index] = arr[i]; arr[i] = tmp; } return arr; } } <file_sep>package com.latico.algorithm.string; import org.junit.Test; public class StrToIntTest { @Test public void convert() { String str = "12357"; StrToInt.convert(str); } }<file_sep>package com.latico.algorithm.sort; /** * <PRE> * 快速排序 * 1、选取一个元素作为分区中心元素; * 2、排序时,一个下标从左边开始,一个从右边开始,互相交换数据,根据中心元素分成左右两个区域,左边的都比中心元素小,右边的都比中心元素大; * 3、对中心元素左边区域(不包括中心元素)执行步骤1和2,对右边区域(不包括中心元素)也执行步骤1和2; * 4、不断重复步骤3; * <p> * ①以第一个关键字 K 1 为控制字,将 [K 1 ,K 2 ,…,K n ] 分成两个子区,使左区所有关键字小于等于 K 1 * ,右区所有关键字大于等于 K 1 ,最后控制字居两个子区中间的适当位置。在子区内数据尚处于无序状态。 * ②把左区作为一个整体,用①的步骤进行处理,右区进行相同的处理。(即递归) ③重复第①、②步,直到左区处理完毕。 * <p> * 【示例】: * <p> * 初始关键字 [49 38 65 97 76 13 27 49] 一趟排序之后 [27 38 13] 49 [76 97 65 49] 二趟排序之后 * [13] 27 [38] 49 [49 65]76 [97] 三趟排序之后 13 27 38 49 49 [65]76 97 最后的排序结果 13 * 27 38 49 49 65 76 97 各趟排序之后的状态 * </PRE> * * @Author: latico * @Date: 2019-03-26 11:12 * @Version: 1.0 */ public class QuickSortUtils { /** * 对指定的数组中索引从start到end之间的元素进行快速排序 * 快速排序 * <p> * ①以第一个关键字 K 1 为控制字,将 [K 1 ,K 2 ,…,K n ] 分成两个子区,使左区所有关键字小于等于 K 1 * ,右区所有关键字大于等于 K 1 ,最后控制字居两个子区中间的适当位置。在子区内数据尚处于无序状态。 * ②把左区作为一个整体,用①的步骤进行处理,右区进行相同的处理。(即递归) ③重复第①、②步,直到左区处理完毕。 * <p> * 【示例】: * <p> * 初始关键字 [49 38 65 97 76 13 27 49] 一趟排序之后 [27 38 13] 49 [76 97 65 49] 二趟排序之后 * [13] 27 [38] 49 [49 65]76 [97] 三趟排序之后 13 27 38 49 49 [65]76 97 最后的排序结果 13 * 27 38 49 49 65 76 97 各趟排序之后的状态 * * @param array 指定的数组 * @param start 需要快速排序的数组索引起点 * @param end 需要快速排序的数组索引终点 */ public static final void sort(int[] array, final int start, final int end) { // 终止条件 if (start >= end) { return; } // i相当于助手1的位置,j相当于助手2的位置 int left = start; int right = end; // 取第1个元素为基准分区中心元素pivot final int pivot = array[left]; // 表示空位的位置索引,默认为被取出的基准元素的位置 int emptyIndex = left; // 如果需要排序的元素个数不止1个,就进入快速排序(只要left // 和right不同,就表明至少有2个数组元素需要排序) while (left < right) { // 助手2开始从右向左一个个地查找小于基准元素的元素 while (left < right && array[right] >= pivot) { right--; } // 找到了,如果助手2在遇到助手1之前就找到了对应的元素,就将该元素给助手1的"空位",right成了空位 if (left < right) { array[emptyIndex] = array[right]; emptyIndex = right; } // 助手1开始从左向右一个个地查找大于基准元素的元素 while (left < right && array[left] <= pivot) { left++; } // 如果助手1在遇到助手2之前就找到了对应的元素,就将该元素给助手2的"空位",left成了空位 if (left < right) { array[emptyIndex] = array[left]; emptyIndex = left; } } // 助手1和助手2相遇后会停止循环,将最初取出的基准值给最后的空位,一轮排序完毕,该位置有序 array[emptyIndex] = pivot; // =====本轮快速排序完成,下面开始对左右分区进行排序,一直递归===== // 对左边的区域排序 sort(array, start, emptyIndex - 1); // 对右边的区域排序 sort(array, emptyIndex + 1, end); } public static void quickSort(int[] array, int left, int right) { int pivotIndex; if (left < right) { pivotIndex = partition(array, left, right); quickSort(array, left, pivotIndex - 1); quickSort(array, pivotIndex + 1, right); } } /** * 快速排序的分区排序 * * @param array * @param left * @param right * @return 中间基准数的数组下标 */ private static int partition(int[] array, int left, int right) { int pivot = array[left]; // 记住基准数 while (left < right) { while (left < right && array[right] >= pivot) right--; if (left < right) array[left++] = array[right]; // 把右小存进左 while (left < right && array[left] <= pivot) left++; if (left < right) array[right--] = array[left]; // 把左大存进右 } array[left] = pivot; return left; } } <file_sep>/** * <PRE> * 字符串算法 * * 详情参看书籍:编程之法-面试和算法心得 * </PRE> * * @Author: latico * @Date: 2019-04-01 17:17 * @Version: 1.0 */ package com.latico.algorithm.string;<file_sep>package com.latico.algorithm.string; import java.util.LinkedHashSet; import java.util.Set; /** * <PRE> * 字符的所有组合 * 比如给定字符串 abc * 输出结果为:[a, ab, abc, ac, b, bc, c] * </PRE> * * @Author: latico * @Date: 2019-03-30 21:23 * @Version: 1.0 */ public class CharTotalGroup { /** * 时间复杂度 */ public static int time = 0; public static void order(String str){ Set<String> set = new LinkedHashSet<>(); recursion("", str, set); System.out.println(set); System.out.println("时间复杂度次数:" + time); } private static void recursion(String result, String str, Set<String> set){ if (!"".endsWith(result)) { set.add(result); } char[] chars = str.toCharArray(); for (int i = 0; i < chars.length; i++) { char a = chars[i]; time++; recursion(result + a, str.substring(i + 1), set); } } } <file_sep>package com.latico.algorithm.sort; /** * <PRE> * 插入排序 * 每次比较后最多移掉一个逆序,因此与冒泡排序的效率相同.但它在速度 * 上还是要高点,这是因为在冒泡排序下是进行值交换,而在插入排序下是值移动, * 所以直接插入排序将要优于冒泡排序.直接插入法也是一种对数据的有序性非常敏感的一种算法. * 在有序情况下只需要经过n-1次比较,在最坏情况下,将需要n(n-1)/2次比较 * * </PRE> * * @Author: latico * @Date: 2019-03-26 9:44 * @Version: 1.0 */ public class InsertionSortUtils { /** * 从数组第二个数开始,每轮都把该数从该数据为起点,从后往前判断,如果前面的数据大于自己,就把后面的数后移一位 * * @param array */ public static void sort(int[] array) { // i是每轮要比较的数据索引,从第二个元素开始 for (int i = 1; i < array.length; i++) { // 先临时保存当前要比较的数据 int currentValue = array[i]; // j是i前面的数据,从后往前逐个跟i比较 int j = i - 1; while (j >= 0) { // 找不到比当前值大的了,退出循环 if (array[j] <= currentValue) { break; } // 把数据后移一位 array[j + 1] = array[j]; //向前一位 j--; } // 因为上面for循环中的j--,最后减多了一个1,假如是因为找不到了,退出循环,那么由于j = i - 1,也是减多了一次1,所以在这里要加上, array[j + 1] = currentValue; } } /** * 利用后面的数i逐个跟前面的数j比较,直到找到一个比i大的,就交换,一直跟前面的所有数据比较完 * * @param array */ public static void sort2(int[] array) { // i是后面的数 for (int i = 1; i < array.length; i++) { // j是前面的数据,逐个跟i比较 for (int j = 0; j < i; j++) { if (array[j] > array[i]) { swap(array, i, j); } } } } private static void swap(int[] array, int i, int j) { int tmp = array[i]; array[i] = array[j]; array[j] = tmp; } } <file_sep>package com.latico.algorithm.string; import org.junit.Test; public class CharTotalGroupTest { @Test public void order() { String str = "abc"; CharTotalGroup.order(str); } }<file_sep>package com.latico.algorithm.string; import java.util.LinkedHashSet; import java.util.Set; /** * <PRE> * 指定长度的随机任意全排序 * 比如给定字符串 abc, 指定随意长度2 * 输出结果为:[aa, ab, ac, ba, bb, bc, ca, cb, cc] * </PRE> * * @Author: latico * @Date: 2019-03-30 21:23 * @Version: 1.0 */ public class CharRandom { /** * 时间复杂度 */ public static int time = 0; public static void order(String str, int maxLen){ Set<String> set = new LinkedHashSet<>(); recursion("", str, set, maxLen); System.out.println(set); System.out.println("时间复杂度次数:" + time); } private static void recursion(String result, String str, Set<String> set, int maxLen){ if (result.length() == maxLen) { set.add(result); return; } char[] chars = str.toCharArray(); for (char a : chars) { time++; recursion(result + a, str, set, maxLen); } } } <file_sep>package com.latico.algorithm.sort; import java.util.List; /** * <PRE> 冒泡排序 时间 冒泡排序(Bubble Sort,台湾译为:泡沫排序或气泡排序)是一种简单的排序算法。它重复地走访过要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来 。走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。这个算法的名字由来是因为越小的元素会经由交换慢慢“浮”到数列的顶端。 冒泡排序算法的运作如下: 比较相邻的元素,如果第一个比第二个大,就交换他们两个。 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对,在这一点,最后的元素应该会是最大的数。 针对所有的元素重复以上的步骤,除了最后一个。 持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。 时间复杂度:n(n-1)/2次比较。所以一般情况下,特别是在逆序时,它很不理想。 </PRE> * * @Author: latico * @Date: 2019-03-25 23:34 * @Version: 1.0 */ public class BubbleSortUtils { /** * 排序一个数组,从小到大 冒泡排序法思路 1:外层循环:控制它要走几次。 假设你有5个数,那就要走4次,最后一次不用走,最后那个数已经在它位置了所以就要length-1次。 2:内层循环:控制逐一比较,如果发现前一个数比后一个数大,则交换。 注意!因为越比较长度就越小了,所以长度要length-1-i。 * @param arr * @return */ public static void sortArr(int[] arr) { //最大的循环次数 final int maxCyclicCount = arr.length - 1; for (int i = 0; i < maxCyclicCount; i++) { //因为每轮都选出了最大值放到后面,最大判断值每次都减少1一个,通过减i实现 for (int j = 0; j < maxCyclicCount - i; j++) { //判断是否大于自己后面一位 if (arr[j] > arr[j + 1]) { swap(arr, j, j + 1); } } } } /** * 交换AZ位置 * @param arr * @param a * @param z */ private static void swap(int[] arr, int a, int z) { int tmp = arr[a]; arr[a] = arr[z]; arr[z] = tmp; } /** * 从小到大 * @param list * @param <T> */ public static <T extends Comparable> void sortComparable(List<T> list) { //最大的循环次数 final int maxCyclicCount = list.size() - 1; for (int i = 0; i < maxCyclicCount; i++) { for (int j = 0; j < maxCyclicCount - i; j++) { T a; if (list.get(j).compareTo(list.get(j + 1)) > 0) { a = list.get(j); list.set((j), list.get(j + 1)); list.set(j + 1, a); } } } } public static void sortArr2(int[] arr) { final int maxCyclicCount = arr.length - 1; for (int i = 0; i < maxCyclicCount; i++) { for (int j = 0; j < maxCyclicCount - i; j++) { if (arr[j] > arr[j + 1]) { int tmp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = tmp; } } } } } <file_sep>package com.latico.algorithm.sort; /** * <PRE> * 选择排序 * a) 原理:每一趟从待排序的记录中选出最小的元素,顺序放在已排好序的序列最后,直到全部记录排序完毕。也就是:每一趟在n-i+1(i=1,2,…n-1)个记录中选取关键字最小的记录作为有序序列中第i个记录。基于此思想的算法主要有简单选择排序、树型选择排序和堆排序。(这里只介绍常用的简单选择排序) b) 简单选择排序的基本思想:给定数组:int[] arr={里面n个数据};第1趟排序,在待排序数据arr[1]~arr[n]中选出最小的数据,将它与arrr[1]交换;第2趟,在待排序数据arr[2]~arr[n]中选出最小的数据,将它与r[2]交换;以此类推,第i趟在待排序数据arr[i]~arr[n]中选出最小的数据,将它与r[i]交换,直到全部排序完成。 c) 举例:数组 int[] arr={5,2,8,4,9,1}; ------------------------------------------------------- 第一趟排序: 原始数据:5 2 8 4 9 1 最小数据1,把1放在首位,也就是1和5互换位置, 排序结果:1 2 8 4 9 5 ------------------------------------------------------- 第二趟排序: 第1以外的数据{2 8 4 9 5}进行比较,2最小, 排序结果:1 2 8 4 9 5 ------------------------------------------------------- 第三趟排序: 除1、2以外的数据{8 4 9 5}进行比较,4最小,8和4交换 排序结果:1 2 4 8 9 5 ------------------------------------------------------- 第四趟排序: 除第1、2、4以外的其他数据{8 9 5}进行比较,5最小,8和5交换 排序结果:1 2 4 5 9 8 ------------------------------------------------------- 第五趟排序: 除第1、2、4、5以外的其他数据{9 8}进行比较,8最小,8和9交换 排序结果:1 2 4 5 8 9 ------------------------------------------------------- 注:每一趟排序获得最小数的方法:for循环进行比较,定义一个第三个变量temp,首先前两个数比较,把较小的数放在temp中,然后用temp再去跟剩下的数据比较,如果出现比temp小的数据,就用它代替temp中原有的数据。具体参照后面的代码示例,相信你在学排序之前已经学过for循环语句了,这样的话,这里理解起来就特别容易了。 * </PRE> * * @Author: latico * @Date: 2019-03-26 0:19 * @Version: 1.0 */ public class SelectionSortUtils { public static void sort(int[] arr) { for (int i = 0; i < arr.length - 1; i++) { // 记录本轮最小数据的索引 int miniIndex = i; // 循环找出混乱区域的最小数的索引 for (int j = i + 1; j < arr.length; j++) { if (arr[miniIndex] > arr[j]) { miniIndex = j; } } // 如果本轮最小数的索引不是第一个,那么就交换 if (miniIndex != i) { swap(arr, i, miniIndex); } } } private static void swap(int[] arr, int a, int z) { int tmp = arr[a]; arr[a] = arr[z]; arr[z] = tmp; } } <file_sep>package com.latico.algorithm.sort; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Sorts { /** * <pre> * 冒泡排序 * 在最优情况下只需要经过n-1次比较即可得出结果(这个最优情况那就是序列己是正序, * 从100K的正序结果可以看出结果正是如此),但在最坏情况下,即倒序(或一个较小值在最后), * 下沉算法将需要n(n-1)/2次比较。所以一般情况下,特别是在逆序时,它很不理想。 * 它是对数据有序性非常敏感的排序算法。 * 默认为升序 * </pre> * * @param list * 集合 */ @SuppressWarnings("rawtypes") public static void bubbleSort(List<Comparable> list) { bubbleSort(list, true); } /** * <pre> * 冒泡排序 * 在最优情况下只需要经过n-1次比较即可得出结果(这个最优情况那就是序列己是正序, * 从100K的正序结果可以看出结果正是如此),但在最坏情况下,即倒序(或一个较小值在最后), * 下沉算法将需要n(n-1)/2次比较。所以一般情况下,特别是在逆序时,它很不理想。 * 它是对数据有序性非常敏感的排序算法。 * </pre> * * @param list * 集合 * @param asc * 是否升序排列,true升序,false降序 */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static void bubbleSort(List<Comparable> list, boolean asc) { for (int i = 0; i < list.size() - 1; i++) { for (int j = 0; j < list.size() - i - 1; j++) { Comparable a; if (asc && list.get(j).compareTo(list.get(j + 1)) > 0) { // 升序 a = list.get(j); list.set((j), list.get(j + 1)); list.set(j + 1, a); } else if (!asc & list.get(j).compareTo(list.get(j + 1)) < 0) { // 降序 a = list.get(j); list.set((j), list.get(j + 1)); list.set(j + 1, a); } } } } /** * <pre> * 选择排序 * 它的比较次数一定:n(n-1)/2。也因此无论在序列何种情况下, * 它都不会有优秀的表现(从上100K的正序和反序数据可以发现它耗时相差不多, * 相差的只是数据移动时间),可见对数据的有序性不敏感。它虽然比较次数多, * 但它的数据交换量却很少。所以我们将发现它在一般情况下将快于冒泡排序。 * </pre> * * @param list * 集合 * @param asc * 是否升序排列 */ public static void selectionSort(List<Comparable> list, boolean asc) { for (int i = 0; i < list.size() - 1; i++) { for (int j = i + 1; j < list.size(); j++) { if (asc && (list.get(i).compareTo(list.get(j)) > 0)) { Comparable temp = list.get(i); list.set((i), list.get(j)); list.set(j, temp); } else if (!asc && list.get(i).compareTo(list.get(j)) < 0) { Comparable temp = list.get(i); list.set((i), list.get(j)); list.set(j, temp); } } } } /** * <pre> * 选择排序 * 它的比较次数一定:n(n-1)/2。也因此无论在序列何种情况下, * 它都不会有优秀的表现(从上100K的正序和反序数据可以发现它耗时相差不多, * 相差的只是数据移动时间),可见对数据的有序性不敏感。它虽然比较次数多, * 但它的数据交换量却很少。所以我们将发现它在一般情况下将快于冒泡排序。 * 默认是升序 * </pre> * * @param list * 集合 */ @SuppressWarnings("rawtypes") public static void selectionSort(List<Comparable> list) { selectionSort(list, true); } /** * <pre> * 插入排序 * 每次比较后最多移掉一个逆序,因此与冒泡排序的效率相同.但它在速度 * 上还是要高点,这是因为在冒泡排序下是进行值交换,而在插入排序下是值移动, * 所以直接插入排序将要优于冒泡排序.直接插入法也是一种对数据的有序性非常敏感的一种算法. * 在有序情况下只需要经过n-1次比较,在最坏情况下,将需要n(n-1)/2次比较 * </pre> * * @param list * 集合 * @param asc * 是否升序排列 */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static void insertSort(List<Comparable> list, boolean asc) { int i; int j; Comparable temp; for (i = 1; i < list.size(); i++) { temp = list.get(i); if (asc) { for (j = i - 1; j >= 0 && temp.compareTo(list.get(j)) < 0; j--) { list.set((j + 1), list.get(j)); } list.set((j + 1), temp); } else { for (j = i - 1; j >= 0 && temp.compareTo(list.get(j)) > 0; j--) { list.set((j + 1), list.get(j)); } list.set((j + 1), temp); } } } /** * <pre> * 插入排序 * 每次比较后最多移掉一个逆序,因此与冒泡排序的效率相同.但它在速度 * 上还是要高点,这是因为在冒泡排序下是进行值交换,而在插入排序下是值移动, * 所以直接插入排序将要优于冒泡排序.直接插入法也是一种对数据的有序性非常敏感的一种算法. * 在有序情况下只需要经过n-1次比较,在最坏情况下,将需要n(n-1)/2次比较 * 默认为升序 * </pre> * * @param list * 集合 */ @SuppressWarnings("rawtypes") public static void insertSort(List<Comparable> list) { insertSort(list, true); } /** * <pre> * 快速排序 * 它同样是冒泡排序的改进,它通过一次交换能消除多个逆序,这样可以减少逆序时所消耗的扫描和数据交换次数. * 在最优情况下,它的排序时间复杂度为O(nlog2n).即每次划分序列时,能均匀分成两个子串. * 但最差情况下它的时间复杂度将是O(n&circ;2).即每次划分子串时,一串为空,另一串为m-1 * (程序中的100K正序和逆序就正是这样,如果程序中采用每次取序列中部数据作为划分点,那将在正序和逆时达到最优). * 从100K中正序的结果上看“快速排序”会比“冒泡排序”更慢,这主要是“冒泡排序”中采用了提前结束排序的方法. * 有的书上这解释“快速排序”,在理论上讲,如果每次能均匀划分序列,它将是最快的排序算法,因此称它作快速排序. * 虽然很难均匀划分序列,但就平均性能而言,它仍是基于关键字比较的内部排序算法中速度最快者。 * 默认为升序 * </pre> * * @param obj * 集合 */ @SuppressWarnings("rawtypes") public static void quickSort(List<Comparable> obj) { quickSort(obj, 0, obj.size(), true); } /** * <pre> * 快速排序 * 它同样是冒泡排序的改进,它通过一次交换能消除多个逆序,这样可以减少逆序时所消耗的扫描和数据交换次数. * 在最优情况下,它的排序时间复杂度为O(nlog2n).即每次划分序列时,能均匀分成两个子串. * 但最差情况下它的时间复杂度将是O(n&circ;2).即每次划分子串时,一串为空,另一串为m-1 * (程序中的100K正序和逆序就正是这样,如果程序中采用每次取序列中部数据作为划分点,那将在正序和逆时达到最优). * 从100K中正序的结果上看“快速排序”会比“冒泡排序”更慢,这主要是“冒泡排序”中采用了提前结束排序的方法. * 有的书上这解释“快速排序”,在理论上讲,如果每次能均匀划分序列,它将是最快的排序算法,因此称它作快速排序. * 虽然很难均匀划分序列,但就平均性能而言,它仍是基于关键字比较的内部排序算法中速度最快者。 * </pre> * * @param obj * 集合 * @param asc * 是否升序排列 */ @SuppressWarnings("rawtypes") public static void quickSort(List<Comparable> obj, boolean asc) { quickSort(obj, 0, obj.size(), asc); } @SuppressWarnings({ "rawtypes", "unchecked" }) private static void quickSort(List<Comparable> obj, final int left, final int right, boolean asc) { int i, j; Comparable middle, temp; i = left; j = right; middle = obj.get(left); while (true) { if (asc) { while ((++i) < right - 1 && obj.get(i).compareTo(middle) < 0) ; while ((--j) > left && obj.get(j).compareTo(middle) > 0) ; if (i >= j) break; temp = obj.get(i); obj.set(i, obj.get(j)); obj.set(j, temp); } else { while ((++i) < right - 1 && obj.get(i).compareTo(middle) > 0) ; while ((--j) > left && obj.get(j).compareTo(middle) < 0) ; if (i >= j) break; temp = obj.get(i); obj.set(i, obj.get(j)); obj.set(j, temp); } } obj.set(left, obj.get(j)); obj.set(j, middle); if (left < j) quickSort(obj, left, j, asc); if (right > i) quickSort(obj, i, right, asc); } /** * <pre> * 归并排序 * 归并排序是一种非就地排序,将需要与待排序序列一样多的辅助空间.在使用它对两个己有序的序列归并, * 将有无比的优势.其时间复杂度无论是在最好情况下还是在最坏情况下均是O(nlog2n). * 对数据的有序性不敏感.若数据节点数据量大,那将不适合.但可改造成索引操作,效果将非常出色. * 默认为升序 * </pre> * * @param obj * 集合 */ @SuppressWarnings("rawtypes") public static void mergeSort(List<Comparable> obj) { List<Comparable> bridge = new ArrayList<Comparable>(obj); // 初始化中间数组 mergeSort(obj, 0, obj.size() - 1, true, bridge); // 归并排序 bridge = null; } /** * <pre> * 归并排序 * 归并排序是一种非就地排序,将需要与待排序序列一样多的辅助空间.在使用它对两个己有序的序列归并, * 将有无比的优势.其时间复杂度无论是在最好情况下还是在最坏情况下均是O(nlog2n). * 对数据的有序性不敏感.若数据节点数据量大,那将不适合.但可改造成索引操作,效果将非常出色. * </pre> * * @param obj * 集合 * @param asc * 是否升序排列 */ @SuppressWarnings("rawtypes") public static void mergeSort(List<Comparable> obj, boolean asc) { List<Comparable> bridge = new ArrayList<Comparable>(obj); // 初始化中间数组 mergeSort(obj, 0, obj.size() - 1, asc, bridge); // 归并排序 bridge = null; } @SuppressWarnings("rawtypes") private static void mergeSort(List<Comparable> obj, int left, int right, boolean asc, List<Comparable> bridge) { if (left < right) { int center = (left + right) / 2; mergeSort(obj, left, center, asc, bridge); mergeSort(obj, center + 1, right, asc, bridge); merge(obj, left, center, right, asc, bridge); } } @SuppressWarnings({ "rawtypes", "unchecked" }) private static void merge(List<Comparable> obj, int left, int center, int right, boolean asc, List<Comparable> bridge) { int mid = center + 1; int third = left; int tmp = left; while (left <= center && mid <= right) { // 从两个数组中取出小的放入中间数组 if (asc) { if (obj.get(left).compareTo(obj.get(mid)) <= 0) { bridge.set(third++, obj.get(left++)); } else { bridge.set(third++, obj.get(mid++)); } } else { if (obj.get(left).compareTo(obj.get(mid)) > 0) { bridge.set(third++, obj.get(left++)); } else { bridge.set(third++, obj.get(mid++)); } } } // 剩余部分依次置入中间数组 while (mid <= right) { bridge.set(third++, obj.get(mid++)); } while (left <= center) { bridge.set(third++, obj.get(left++)); } // 将中间数组的内容拷贝回原数组 copy(obj, tmp, right, bridge); } @SuppressWarnings("rawtypes") private static void copy(List<Comparable> obj, int left, int right, List<Comparable> bridge) { while (left <= right) { obj.set(left, bridge.get(left)); left++; } } /** * <pre> * 对排序后的队列进行快速合并,使合并后的队列有序(归并排序算法). * 默认为升序 * * 使用实例: * List list1 = new ArrayList(); * list1.add(&quot;dsd&quot;); * list1.add(&quot;tsest&quot;); * list1.add(&quot;ga&quot;); * list1.add(&quot;aaaa&quot;); * list1.add(&quot;bb&quot;); * CollectionUtils.quickSort(list1); * * List list2 = new ArrayList(); * list2.add(&quot;cc&quot;); * list2.add(&quot;dd&quot;); * list2.add(&quot;zz&quot;); * CollectionUtils.quickSort(list2); * * List listAll = new ArrayList(); * listAll.add(list1); * listAll.add(list2); * * List sortList = CollectionUtils.listMerge(listAll); * System.out.println(sortList); * </pre> * * @param objs * 集合的集合 * @return 排序后的集合 */ @SuppressWarnings("rawtypes") public static List listMerge(List<List<Comparable>> objs) { return listMerge(objs, true); } /** * <pre> * 对排序后的队列进行快速合并,使合并后的队列有序(归并排序算法). * List list1 = new ArrayList(); * list1.add(&quot;dsd&quot;); * list1.add(&quot;tsest&quot;); * list1.add(&quot;ga&quot;); * list1.add(&quot;aaaa&quot;); * list1.add(&quot;bb&quot;); * CollectionUtils.quickSort(list1); * * List list2 = new ArrayList(); * list2.add(&quot;cc&quot;); * list2.add(&quot;dd&quot;); * list2.add(&quot;zz&quot;); * CollectionUtils.quickSort(list2); * * List listAll = new ArrayList(); * listAll.add(list1); * listAll.add(list2); * * List sortList = CollectionUtils.listMerge(listAll,false); * System.out.println(sortList); * </pre> * * @param objs * 集合的集合 * @param asc * 是否升序排列 * @return 排序后的集合 */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static List listMerge(List<List<Comparable>> objs, boolean asc) { List list = new ArrayList(); for (List<Comparable> obj : objs) { list.addAll(obj); mergeSort(list, asc); } return list; } /** * <pre> * 二分查找法 * 在进行此调用之前,必须根据列表元素的自然顺序对列表进行升序排序(通过 sort1(List) 方法). * 如果没有对列表进行排序,则结果是不确定的。如果列表包含多个等于指定对象的元素,则无法保证找到的是哪一个。 * </pre> * * @param obj * 集合 * @param key * 查找内容 * @return 关键字在集合中的位置 */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static int binarySearch(List obj, Object key) { int index = Collections.binarySearch(obj, key); return index; } /** * 根据下标找到相对应的对象 * * @param obj * 集合 * @param key * 查找内容 * @return 对应的对象值 */ @SuppressWarnings("rawtypes") public static Object getObject(List obj, int key) { return obj.get(key); } }
e4918213ec6e60216b73df74bbc78bd1442c5e60
[ "Markdown", "Java" ]
15
Markdown
latico/latico-algorithm
ca836d97de629b7d4b2fd6a9d5cca5881294c455
8c65f76911edcd67f75bad3d3b8ddbebb21f0b93
refs/heads/master
<file_sep>module.exports = { 'Cintas US SSL Homepage' : function(browser){ browser .url('http://www.cintas.com') browser.waitForElementVisible('body', 3000, false); browser.verify.urlEquals('https://www.cintas.com/', 'SSL Test1 Homepage'); }, 'Verify US SSL Uniform Work Apparel' : function (browser) { browser .url('http://cintas.com/uniform-work-apparel') browser.waitForElementVisible('body', 3000, false); browser.verify.urlContains('https://www.cintas.com/uniform-work-apparel', 'SSL Test2 Uniform-Work-Apparel') }, 'Cintas CA SSL' : function(browser){ browser .url('http://www.cintas.ca') browser.waitForElementVisible('body', 3000, false); browser.verify.urlEquals('https://www.cintas.ca/','SSL Test3 CA Homepage') browser.end(); } }; <file_sep>module.exports = function (browser){ this.staging = function(logincountry){ browser .windowMaximize() if(logincountry === 'us'){ browser.url('https://cintas-stage.willin.gs') browser.pause(2000) } else if(logincountry === "canada"){ browser.url('https://cintas-stage-ca.willin.gs') browser.pause(2000) } else if(logincountry === "frenchca"){ browser.url('https://cintas-stage-ca.willin.gs/fr') browser.pause(2000) } else if(logincountry === "devus"){ browser.url('https://cintas-stage.willin.gs') browser.pause(5000) } else if(logincountry === "devcafr"){ browser.url('https://cintas-stage-ca.willin.gs/fr') browser.pause(5000) } else{ console.log("We got problems man") } browser.waitForElementVisible('body', 1000) return browser; }; this.loginstaging = function(){ browser var useelements = browser.page.elements(); useelements.setValue('@loginname', 'julius.jackson') useelements.setValue('@loginpassword', <PASSWORD>') useelements.click('@loginbutton') return browser; }; this.checkuserlogin = function(){ browser .element('css selector', '.sfForm'.unavailable, function (result){ if(result.value) { browser.click('.sfLinkBtn.sfPrimary') browser.waitForElementVisible('.sfSubmitBtn', 2000) // browser.click('.sfSubmitBtn') .pause(1000) browser.acceptAlert() .pause(5000) console.log('Logged User Out') } else { console.log('Did nothing as user was not loggged in') } }) return browser; }; }; <file_sep>module.exports = function(browser){ this.findlocationlink = function(country){ var useelements = browser.page.elements(); browser.pause(1000) useelements.click('@findlocation') browser.pause(1000) if(country === "us"){ browser.verify.containsText(".lf-ZipSearchContainer", "Find a Location", "Verified US Location Form Available") } else if(country === "frenchca"){ browser.verify.containsText(".lf-ZipSearchContainer", "Trouver un établissement", "Verified French Location Form Available") } useelements.setValue('@locationinput', '45402') useelements.setValue('@locationinput', browser.Keys.ENTER) browser.waitForElementVisible('#map', 2000) browser.click('.lf-lb-filterContainer') browser.verify.visible('.serviceFilterOptions', "Service Options Showing Properly") browser.verify.visible('.lf-lb-locationsContainer', 'Filtered Options Showing Properly') return browser; }; this.invalidresults = function(country){ var useelements = browser.page.elements(); browser.pause(1000) useelements.click('@findlocation') browser.waitForElementVisible('#map', 2500) browser.pause(1000) useelements.setValue('@locationinput', 'invalidsearch') useelements.setValue('@locationinput', browser.Keys.ENTER) browser.pause(5000) if(country === "devus"){ browser.verify.containsText(".lf-lb-noResults", "WE DID NOT FIND ANY LOCATIONS FOR", "US No Results Found") } else if(country === "devcafr"){ browser.verify.containsText(".lf-lb-noResults", "NOUS N’AVONS TROUVÉ AUCUN EMPLACEMENT POUR", "French No Results Found") } return browser; }; } <file_sep>module.exports = { 'Cintas Open Website' : function (browser) { browser .windowMaximize() .url('https://cintas.com') .waitForElementVisible('body', 1000); // return browser; }, 'Open Contact Form' : function(browser) { browser .click('#headerContactLink') .pause(3000) //create function to clear all fields //create function to insert all fields //create function to select checkboxes //create function to submit //create function to verify submission entered }, 'Set Required Fields' : function(browser){ browser // .clearValue('#HeaderPlaceHolder_T981C7CEC019_firstName') .setValue('#HeaderPlaceHolder_T981C7CEC019_firstName', 'RealartTestFirst') // .clearValue('#HeaderPlaceHolder_T981C7CEC019_lastName') .setValue('#HeaderPlaceHolder_T981C7CEC019_lastName', 'RealartTestLast') .setValue('#HeaderPlaceHolder_T981C7CEC019_company', 'Real Art Test Company') .setValue('#HeaderPlaceHolder_T981C7CEC019_postalCode', '45324') .setValue('#HeaderPlaceHolder_T981C7CEC019_phone', '1234567890') .setValue('#HeaderPlaceHolder_T981C7CEC019_email', '<EMAIL>') .click('#HeaderPlaceHolder_T981C7CEC019_chklUserInterests1_0') .click('#HeaderPlaceHolder_T981C7CEC019_chklUserInterests1_1') .click('#HeaderPlaceHolder_T981C7CEC019_chklUserInterests1_2') .click('#HeaderPlaceHolder_T981C7CEC019_chklUserInterests1_3') .click('#HeaderPlaceHolder_T981C7CEC019_chklUserInterests1_4') .click('#HeaderPlaceHolder_T981C7CEC019_chklUserInterests1_5') .click('#HeaderPlaceHolder_T981C7CEC019_chklUserInterests1_6') .click('#HeaderPlaceHolder_T981C7CEC019_chklUserInterests1_7') .pause(3000) .end(); return browser; } }; <file_sep>module.exports = { elements: { loginname: '#wrap_name', loginpassword: <PASSWORD>', loginbutton: '.sfSave', maincontactform: '.contact_box.contactNavClick', firstname: '#InputFirstName', lastname: '#InputLastName', company: '#InputCompany', address: '#InputAddress', postalcode: '#InputPostalCode', phone: '#InputPhone', comments: '#InputComments', email: '#InputEmail', checkbox1: '#ContactInterestOptions_0', checkbox2: '#ContactInterestOptions_1', checkbox3: '#ContactInterestOptions_2', checkbox4: '#ContactInterestOptions_3', checkbox5: '#ContactInterestOptions_4', checkbox6: '#ContactInterestOptions_5', checkbox7: '#ContactInterestOptions_6', checkbox8: '#ContactInterestOptions_7', submit:'#InputSubmitButton', modalconfirm: '#modal-confirm', submitoriginal: '#modal-deny', servicegrid: '#service_grid-mobile', careerslink: '#CareersLink', findlocation: '#MobileHeaderPlaceHolder_T981C7CEC020_LocationFinderLink', contactus: '#ContactUsLink', findlocation: '#HeaderNavLocationFinder', locationinput: '#locationFinderFindALocationInputSearch', locationinput2: '#lf-lb-searchInput' }, url: function(){ return this.api.launch_url; } } <file_sep>module.exports = { 'Login Staging Environment' : function(browser){ var homepage = browser.page.login(); homepage.navigate(); homepage .windowMaximize() .setValue('#wrap_name', 'julius.jackson') .setValue('#wrap_password','+-<PASSWORD>') .pause(3000) .click('.sfSave') .pause(5000) }, 'Check if User Already Logged In' : function(browser){ browser .waitForElementVisible('.sfForm', defaultMaximumWaitTime, false, function (result){ if(result.value){ browser.click('.sfLinkBtn.sfPrimary') browser.waitForElementVisible('.sfSubmitBtn', 2000) // browser.click('.sfSubmitBtn') .pause(1000) browser.acceptAlert() .pause(5000) console.log('Made it here') } else { console.log('User was already logged in.') } }) }, /* 'Staging Cintas Open Website' : function (browser) { browser .windowMaximize() .url('https://stage.cintas.com') .waitForElementVisible('body', 1000); // return browser; }, */ 'Open Contact Form' : function(browser) { browser .click('#HeaderContactUs') .pause(3000) }, 'Set Required Fields' : function(browser){ browser //Clear Values .clearValue('#InputFirstName') .clearValue('#InputLastName') .clearValue('#InputCompany') .clearValue('#InputAddress') .clearValue('#InputPostalCode') .clearValue('#InputPhone') .clearValue('#InputComments') .clearValue('#InputEmail') // .setValue('#InputFirstName', 'RealartAutomatedFirst') .setValue('#InputLastName', 'RealartTestAutomatedLast') .setValue('#InputCompany', 'Real Art Test Automated Company') .setValue('#InputAddress', 'Real Art Test Automated Address') .setValue('#InputPostalCode', '45324') .setValue('#InputPhone', '1234567890') .setValue('#InputEmail', '<EMAIL>') .click('#ContactInterestOptions_0') .click('#ContactInterestOptions_1') .click('#ContactInterestOptions_2') .click('#ContactInterestOptions_3') .click('#ContactInterestOptions_4') .click('#ContactInterestOptions_5') .click('#ContactInterestOptions_6') .click('#ContactInterestOptions_7') .click('#InputSubmitButton') .waitForElementVisible('.modalWindow', 2000) .click('#modal-deny') }, 'Check Contact Form Sent' : function(browser){ browser browser.verify.visible('#ThankYouContainer','Thank you message should be visible'); browser.pause(5000) }, 'Save Screenshot' : function(browser){ browser .saveScreenshot('./reports/cintastesting/FirefoxDesktop.png') .pause(5000) .end(); } };
e7ce89cc2e9c5c301a79918858e3b0b1e965f6d8
[ "JavaScript" ]
6
JavaScript
julius2427/Nightwatchtest
3b98ebc65c1b0ac58b3dfbd96a8750a93dd111c4
8abea57894b933998381d8e88db6c9a3cb06947e
refs/heads/master
<file_sep># import base64 # import json import datetime import os from google.cloud import bigquery from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail def process_storage_event(data, context): # data_buffer = base64.b64decode(data['data']) # event_entry = json.loads(data_buffer)['protoPayload'] # Troubleshooting Storage Events print(data) print(context) # bucket = json.loads(data_buffer)['resource']['labels']['bucket_name'] # bucket_file = json.loads(data_buffer)['resource']['labels']['bucket_name'] bucket = data['bucket'] bucket_file = data['name'] print("Triggered Bucket: {}".format(bucket)) print("Triggered File in Bucket: {}".format(bucket_file)) query_bq(bucket_file) def query_bq(gs_csv_file): file_basefile = gs_csv_file.split('.')[-2] print(file_basefile) current_date = datetime.datetime.strptime(file_basefile, '%m-%d-%Y') # Construct a BigQuery client object. client = bigquery.Client() query = """ SELECT SUM(Confirmed) AS SUM_CONFIRMED, SUM(Deaths) AS SUM_DEATHS, SUM(Recovered) AS SUM_RECOVERED, SUM(Active) AS SUM_ACTIVE FROM covid.march_results WHERE DATE(Last_Update) = @current_date """ job_config = bigquery.QueryJobConfig( query_parameters=[ bigquery.ScalarQueryParameter("current_date", "DATE", current_date.date()), ] ) query_job = client.query(query, job_config=job_config, project=os.environ.get('PROJECT_ID')) # Make an API request. # query_job = client.query(query, job_config=job_config, project=project) # Make an API request. # print("The query data:") # for row in query_job: # print("") # for data in row: # print(data, "\t", end='') rows = query_job.result() # print without html formatting # # format_string = "{!s:<16} " * len(rows.schema) # field_names = [field.name for field in rows.schema] # print(format_string.format(*field_names)) # Prints column headers. # for row in rows: # print(format_string.format(*row)) # Prints row data. # format for email table = "<table>\n" # Create the table's column headers header = [field.name for field in rows.schema] table += " <tr>\n" for column in header: # table += " <th>{0}</th>\n".format(column.strip()) table += " <th>{0}</th>\n".format(column) table += " </tr>\n" # Create the table's row data for row in rows: table += " <tr>\n" for column in row: # table += " <td>{0}</td>\n".format(column.strip()) table += " <td>{0}</td>\n".format(column) table += " </tr>\n" table += "</table>" # print(table) subject = "{}-{}-{}".format("Google","COVID",current_date.strftime("%Y%m%d")) send_mail(table,subject) def send_mail(msg_body, msg_subject): message = Mail( from_email=os.environ.get('SENDER'), # to_emails=recipients, to_emails=os.environ.get('RECIPIENT'), subject=msg_subject, html_content=msg_body) try: sg_client = SendGridAPIClient(os.environ.get('SG_API_KEY')) # sg_client = SendGridAPIClient(sg_api) response = sg_client.send(message) # Uncomment for extra debug info # print(response.status_code) # print(response.body) # print(response.headers) print('Email Successfully sent with status code: {}.'.format(response.status_code)) except Exception as e: print(e.message) # when launching for testing :) # if __name__ == '__main__': # query_bq("03-31-2020.csv")<file_sep>sendgrid google-cloud-bigquery <file_sep># bq-cf-demo
c4be7fe1cf3bc0a36040c1ac0825370a51c3d327
[ "Markdown", "Python", "Text" ]
3
Python
elatovg/bq-cf-demo
048fe130910904d5ad65e69d647443e6791460ac
3332b5313debaca3a6935491620c9333873b1be2
refs/heads/main
<file_sep>import changeTheme from "./js/changeTheme"; import template from "./js/template"; import "./styles.css"
29659be3b3799eb1c94a6fbe90410ab78ad94df3
[ "JavaScript" ]
1
JavaScript
Anastasia-A-2020/goit-js-hw-10-food-service
19e2d4d2ee536ba7e437de4c13b5b18f6320e4f9
001d818f9897178d99d1eac962d2a1f2a9cf04be
refs/heads/master
<repo_name>Akilimali003/Traffic-light<file_sep>/Feu_Rouge/Feu_Rouge.ino //Creation of variables //and put each variables to his pinBreach int const led_vert1 = 2; int const led_jaune1 = 3; int const led_rouge1 = 4; int const led_vert2 = 5; int const led_jaune2 = 6; int const led_rouge2 = 7; void setup() { // Initialisation of variables pinMode(led_vert1, OUTPUT); pinMode(led_jaune1, OUTPUT); pinMode(led_rouge1, OUTPUT); pinMode(led_vert2, OUTPUT); pinMode(led_jaune2, OUTPUT); pinMode(led_rouge2, OUTPUT); } void loop() { //---------****** MAIN CODE ******------------------// // All the code for the first lamps are written here... //Then we manage all the first lamps here before the second digitalWrite(led_vert1, HIGH); digitalWrite(led_rouge2, HIGH); digitalWrite(led_rouge1, LOW); digitalWrite(led_jaune2, LOW); // wait until 5000 millisecond (5 seconds) // before start an other process delay(5000); digitalWrite(led_jaune1, HIGH); digitalWrite(led_rouge2, HIGH); digitalWrite(led_vert1, LOW); delay(4000); //-----------****** THE SECOND PART OF THE CODE ******------// // A RED LED for the first process is ON and let place for the second process to start // The GREEN LED of the second process is ON... it's a new task digitalWrite(led_rouge1, HIGH); digitalWrite(led_vert2, HIGH); digitalWrite(led_vert1, LOW); digitalWrite(led_jaune1, LOW); digitalWrite(led_rouge2, LOW); delay(5000); digitalWrite(led_vert1, LOW); digitalWrite(led_rouge1, HIGH); digitalWrite(led_jaune2, HIGH); digitalWrite(led_vert2, LOW); digitalWrite(led_jaune1, LOW); delay(4000); } <file_sep>/sketch_aug30a/sketch_aug30a.ino const int yellowLed = 5; const int blueLed = 4; const int redLed = 3; //variable for the switch const int switchPin = 2; void setup() { // put your setup code here, to run once: pinMode(yellowLed, OUTPUT); pinMode(blueLed, OUTPUT); pinMode(redLed, OUTPUT); //declare the switch pin as an input pinMode(switchPin, INPUT); } void loop() { // put your main code here, to run repeatedly: int switchState; switchState = digitalRead(switchPin); if(switchState == LOW){ digitalWrite(redLed, LOW); digitalWrite(yellowLed, HIGH); digitalWrite(blueLed, LOW); delay(5000); digitalWrite(yellowLed, LOW); digitalWrite(blueLed, HIGH); delay(5000); }else{ digitalWrite(yellowLed, LOW); digitalWrite(blueLed, LOW); digitalWrite(redLed, HIGH); } }
598e8cfd98e5a832b42b4cc79a7d49f1f88384b2
[ "C++" ]
2
C++
Akilimali003/Traffic-light
b658a2aafe0b57ff707d38ab66e63efac6a848e0
3cb7b9d0a46b4d84372b448fa22de2343c3b4e33
refs/heads/master
<file_sep>const doctorsData = require('../../../data/doctor-data.js') const createDoctor = (knex, doctor) => { return knex('doctors').insert({ name: doctor.name, specialization: doctor.specialization, phone: doctor.phone }, 'id') .then(doctorId => { let patientPromises = []; doctor.patients.forEach(patient => { patientPromises.push( createPatient(knex, { name: patient.name, phone: patient.phone, gender: patient.gender, doctor_id: doctorId[0] }) ) }); return Promise.all(patientPromises); }) }; const createPatient = (knex, patient) => { return knex('patients').insert(patient); }; exports.seed = (knex) => { return knex('patients').del() // delete patients first .then(() => knex('doctors').del()) // delete all doctors .then(() => { let doctorPromises = []; doctorsData.forEach(doctor => { doctorPromises.push(createDoctor(knex, doctor)); }); return Promise.all(doctorPromises); }) .catch(error => console.log(`Error seeding data: ${error}`)); }; // const createDoctor = (knex, doctor) => { // return knex('doctors').insert({ // name: doctor.name, // specialization: doctor.specialization, // phone: doctor.phone // }) // }; // exports.seed = (knex) => { // return knex('doctors').del() // .then(() => { // let doctorPromises = []; // doctorsData.forEach(doctor => { // doctorPromises.push(createDoctor(knex, doctor)); // }); // return Promise.all(doctorPromises); // }) // .catch(error => console.log(`Error seeding data: ${error}`)) // } <file_sep># CLINIQUE API This API consists of data on doctors and their patients in a clinic. New doctors can be added, as well as new patients of a doctor can be added. *Each doctor can have several patients, but the each patient will only have one doctor.* Doctors and patients can be removed from the database. API access is through HTTP. Data is sent and received as JSON. ### URL: https://byob-clinique.herokuapp.com ## DOCTOR DATA ENDPOINTS #### GET all the doctors: ```/clinique/doctors``` *Example request* ```GET '/clinique/doctors'``` *Example response* ``` [ { id: 1, name: "<NAME>", specialization: "general medicine", phone: "303-000-0000", created_at: "2019-08-16T16:08:26.976Z", updated_at: "2019-08-16T16:08:26.976Z" }, { id: 2, name: "<NAME>", specialization: "dermatology", phone: "303-000-0001", created_at: "2019-08-16T16:08:26.984Z", updated_at: "2019-08-16T16:08:26.984Z" }, { id: 3, name: "<NAME>", specialization: "neurology", phone: "303-000-0002", created_at: "2019-08-16T16:08:26.990Z", updated_at: "2019-08-16T16:08:26.990Z" } ] ``` #### GET a specific doctor: ```/clinique/doctors/<doctor id>``` *Example request* ```GET '/clinique/doctors/1'``` *Example response* ``` { id: 1, name: "<NAME>", specialization: "general medicine", phone: "303-000-0000", created_at: "2019-08-16T16:08:26.976Z", updated_at: "2019-08-16T16:08:26.976Z", patients: [ { id: 1, name: "<NAME>", phone: "303-111-1112", gender: "male", doctor_id: 1, created_at: "2019-08-16T16:08:27.054Z", updated_at: "2019-08-16T16:08:27.054Z" }, { id: 7, name: "<NAME>", phone: "303-111-1111", gender: "female", doctor_id: 1, created_at: "2019-08-16T16:08:27.052Z", updated_at: "2019-08-16T16:08:27.052Z" } ] } ``` #### POST a new doctor: ```/clinique/doctors``` *Example request* ```POST '/clinique/doctors'``` *Required parameters* ``` Headers: "Content-Type": "application/json" Body: { "name": <String>, "specialization" : <String>, "phone": <String> } ``` *Example response* ``` [ { "id": 414, "name": "<NAME>", "specialization": "general medicine", "phone": "303-000-7777", "created_at": "2019-08-18T06:18:36.193Z", "updated_at": "2019-08-18T06:18:36.193Z" } ] ``` #### DELETE a doctor: ```/clinique/doctors/<doctor id>``` *Example request* ```DELETE '/clinique/doctors/414'``` *Example response* ``` { "success": "You have successfully deleted doctor with the id of 414" } ``` ## PATIENT DATA ENDPOINTS #### GET all the patients of a certain doctor: ```/clinique/doctors/<doctor id>/patients``` *Example request* ```GET '/clinique/doctors/1/patients'``` *Example response* ``` [ { id: 1, name: "<NAME>", phone: "303-111-1112", gender: "male", doctor_id: 1, created_at: "2019-08-16T16:08:27.054Z", updated_at: "2019-08-16T16:08:27.054Z" }, { id: 7, name: "<NAME>", phone: "303-111-1111", gender: "female", doctor_id: 1, created_at: "2019-08-16T16:08:27.052Z", updated_at: "2019-08-16T16:08:27.052Z" } ] ``` #### GET a specific patient of a certain doctor: ```/clinique/doctors/<doctor id>/patients/<patient id>``` *Example request* ```GET '/clinique/doctors/1/patients/1'``` *Example response* ``` [ { id: 1, name: "<NAME>", phone: "303-111-1112", gender: "male", doctor_id: 1, created_at: "2019-08-16T16:08:27.054Z", updated_at: "2019-08-16T16:08:27.054Z" } ] ``` #### POST a new patient of an existing doctor: ```/clinique/doctors/<doctor id>/patients``` *Example request* ```POST '/clinique/doctors/1/patients'``` *Required parameters* ``` Headers: "Content-Type": "application/json" Body: { "name": <String>, "phone": <String>, "gender": <String>, "doctor_id": <Integer> } ``` *Example response* ``` [ { "id": 1, "name": "<NAME>", "phone": "303-111-1111", "gender": "female", "doctor_id": 1, "created_at": "2019-08-18T06:28:43.957Z", "updated_at": "2019-08-18T06:28:43.957Z" } ] ``` #### DELETE a patient of a certain doctor: ```/clinique/doctors/<doctor id>/patients/<patient id>``` *Example request* ```DELETE '/clinique/doctors/1/patients/1'``` *Example response* ``` { "success": "You have successfully deleted patient with the id of 1" } ``` <file_sep>const doctorsData1 = [ { name: '<NAME>', specialization: 'general medicine', phone: '303-000-0000', patients: [ { name: '<NAME>', phone: '303-111-1111', gender: 'female', }, { name: '<NAME>', phone: '303-111-1112', gender: 'male', } ] }, { name: '<NAME>', specialization: 'dermatology', phone: '303-000-0001', patients: [ { name: '<NAME>', phone: '303-111-1113', gender: 'female', }, { name: '<NAME>', phone: '303-111-1114', gender: 'female', } ] }, { name: '<NAME>', specialization: 'neurology', phone: '303-000-0002', patients: [ { name: '<NAME>', phone: '303-111-1115', gender: 'male', }, { name: '<NAME>', phone: '303-111-7777', gender: 'non-binary', }, { name: '<NAME>', phone: '303-111-4375', gender: 'male', }, ] }, { name: '<NAME>', specialization: 'plastic surgery', phone: '303-000-0003', patients: [ { name: '<NAME>', phone: '303-111-1116', gender: 'female', }, { name: '<NAME>', phone: '303-111-5938', gender: 'female', }, { name: '<NAME>', phone: '303-111-4353', gender: 'female', }, ] }, { name: '<NAME>', specialization: 'cardiology', phone: '303-000-0004', patients: [ { name: '<NAME>', phone: '303-111-1117', gender: 'female', }, { name: '<NAME>', phone: '303-111-2435', gender: 'female', }, { name: '<NAME>', phone: '303-111-1640', gender: 'female', } ] }, { name: '<NAME>', specialization: 'gynecology', phone: '303-000-0005', patients: [ { name: '<NAME>', phone: '303-111-1118', gender: 'female', }, ] }, { name: '<NAME>', specialization: 'podiatry', phone: '303-000-0066', patients: [ { name: '<NAME>', phone: '303-111-1120', gender: 'female', }, ] }, { name: '<NAME>', specialization: 'stomatology', phone: '303-000-0007', patients: [ { name: '<NAME>', phone: '303-111-1119', gender: 'male', }, ] }, { name: '<NAME>', specialization: 'allergy & immunology', phone: '303-000-0008', patients: [ { name: '<NAME>', phone: '303-111-1122', gender: 'male', }, ] }, { name: '<NAME>', specialization: 'anesthesiology', phone: '303-000-0009', patients: [ { name: '<NAME>', phone: '303-111-1121', gender: 'female', }, ] }, { name: '<NAME>', specialization: 'diagnostic radiology', phone: '303-000-0010', patients: [ { name: '<NAME>', phone: '303-111-1123', gender: 'male', }, ] }, { name: '<NAME>', specialization: 'medical genetics', phone: '303-000-0011', patients: [ { name: '<NAME>', phone: '303-111-1987', gender: 'female', }, ] }, { name: '<NAME>', specialization: 'thoracic surgery', phone: '303-000-0012', patients: [ { name: '<NAME>', phone: '303-111-1124', gender: 'non-binary', }, ] }, { name: '<NAME>', specialization: 'ophthalmology', phone: '303-000-0013', patients: [ { name: '<NAME>', phone: '303-111-1125', gender: 'male', }, ] }, { name: '<NAME>', specialization: 'gastroenterology ', phone: '303-000-0016', patients: [ { name: '<NAME>', phone: '303-111-1126', gender: 'male', }, ] }, { name: '<NAME>', specialization: 'hematology', phone: '303-000-0017', patients: [ { name: '<NAME>', phone: '303-111-1127', gender: 'female', }, ] }, { name: '<NAME>', specialization: 'infectious disease', phone: '303-000-0018', patients: [ { name: '<NAME>', phone: '303-111-1128', gender: 'male', }, ] }, { name: '<NAME>', specialization: 'medical microbiology', phone: '303-000-0019', patients: [ { name: '<NAME>', phone: '303-111-1129', gender: 'female', }, ] }, { name: '<NAME>', specialization: 'general medicine', phone: '404-000-0000', patients: [ { name: '<NAME>', phone: '303-111-1130', gender: 'female', }, ] }, { name: '<NAME>', specialization: 'dermatology', phone: '404-000-0001', patients: [ { name: '<NAME>', phone: '303-111-1131', gender: 'male', }, ] }, { name: '<NAME>', specialization: 'neurology', phone: '404-000-0002', patients: [ { name: '<NAME>', phone: '303-111-1132', gender: 'female', }, ] }, { name: '<NAME>', specialization: 'plastic surgery', phone: '404-000-0003', patients: [ { name: '<NAME>', phone: '303-111-2693', gender: 'male', }, { name: '<NAME>', phone: '303-111-2322', gender: 'female', }, ] }, { name: '<NAME>', specialization: 'cardiology', phone: '404-000-0004', patients: [ { name: '<NAME>', phone: '303-111-1133', gender: 'female', }, ] }, { name: '<NAME>', specialization: 'gynecology', phone: '404-000-0005', patients: [ { name: '<NAME>', phone: '303-111-1134', gender: 'male', }, ] }, { name: '<NAME>', specialization: 'podiatry', phone: '404-000-0066', patients: [ { name: '<NAME>', phone: '303-111-1135', gender: 'male', }, ] }, { name: '<NAME>', specialization: 'stomatology', phone: '404-000-0007', patients: [ { name: '<NAME>', phone: '303-111-1136', gender: 'male', }, ] }, { name: '<NAME>', specialization: 'allergy & immunology', phone: '404-000-0008', patients: [ { name: '<NAME>', phone: '303-111-1137', gender: 'female', }, ] }, { name: '<NAME>', specialization: 'anesthesiology', phone: '404-000-0009', patients: [ { name: '<NAME>', phone: '303-111-1138', gender: 'male', }, ] }, { name: '<NAME>', specialization: 'diagnostic radiology', phone: '404-000-0010', patients: [ { name: '<NAME>', phone: '303-111-1139', gender: 'female', }, ] }, { name: '<NAME>', specialization: 'medical genetics', phone: '404-000-0011', patients: [ { name: '<NAME>', phone: '303-111-1140', gender: 'female', }, ] }, { name: '<NAME>', specialization: 'thoracic surgery', phone: '304-000-0012', patients: [ { name: '<NAME>', phone: '303-111-1177', gender: 'female', }, { name: '<NAME>', phone: '303-111-1183', gender: 'female', }, ] } ] module.exports = doctorsData1;<file_sep> exports.up = function(knex) { return Promise.all([ knex.schema.table('doctors', (table) => table.string('patients')) ]) }; exports.down = function(knex) { return Promise.all([ knex.schema.table('doctors', (table) => table.dropColumn('patients')) ]) }; <file_sep> exports.up = function(knex) { return Promise.all([ knex.schema.createTable('doctors', (table) => { table.increments('id').primary(); table.string('name'); table.string('specialization'); table.string('phone'); table.timestamps(true, true) }), knex.schema.createTable('patients', (table) => { table.increments('id').primary(); table.string('name'); table.string('phone'); table.string('gender'); table.integer('doctor_id').unsigned() table.foreign('doctor_id') .references('doctors.id'); table.timestamps(true, true); }) ]) }; exports.down = function(knex) { return Promise.all([ knex.schema.dropTable('patients'), knex.schema.dropTable('doctors') ]) }; <file_sep>const express = require('express'); const app = express(); const environment = process.env.NODE_ENV || 'development'; const configuration = require('./knexfile')[environment]; const database = require('knex')(configuration); const bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.set('port', process.env.PORT || 3000); app.locals.title = "Clinique"; app.listen(app.get('port'), () => { console.log(`${app.locals.title} is running on http://localhost:${app.get('port')}.`); }) //GET ALL DOCTORS ('/clinique/doctors') app.get('/clinique/doctors', (request, response) => { database('doctors').select() .then((doctors) => { doctors.forEach(doctor => { delete doctor.patients }) response.status(200).json(doctors); }) .catch((error) => { response.status(500).json({ error }); }) }) //GET ONE DOCTOR ('/clinique/doctors/:id') app.get('/clinique/doctors/:id', (request, response) => { database('doctors').where('id', request.params.id).select() .then(doctor => { if(doctor.length) { database('patients').where('doctor_id', request.params.id).select() .then(patients => { doctor[0].patients = patients response.status(200).json(doctor[0]); }) } else { response.status(404).json({ error: `Could not find doctor with id ${request.params.id}` }) } }) .catch(error => { response.status(500).json({ error }); }) }) //GET ALL PATIENTS OF A CERTAIN DOCTOR???('/clinique/doctors/:id/patients') app.get('/clinique/doctors/:id/patients', (request, response) => { database('patients').where('doctor_id', request.params.id).select() .then(patients => { if(patients.length) { response.status(200).json(patients) } else { response.status(404).json({ error: 'Couldn\'t find patients for this doctor' }) } }) .catch((error) => { response.status(500).json({ error }) }) }) //get certain doctor //then, get all patients //then, get patients with doctors id //GET ONE CERTAIN PATIENT OF A CERTAIN DOCTOR('/clinique/doctors/:id/patients/:id) app.get('/clinique/doctors/:id/patients/:id', (request, response) => { database('patients').where('id', request.params.id).select() .then(patient => { if(patient.length) { response.status(200).json(patient) } else { response.status(404).json({ error: `Could not find patient with id ${request.params.id}` }) } }) .catch((error) => { response.status(500).json({ error }) }) }) //POST DOCTOR('/clinique/doctors) app.post('/clinique/doctors', (request, response) => { let data = request.body for(let requiredParameter of ['name', 'phone', 'specialization']) { if(!data[requiredParameter]) { return response.status(422).json({ error: `Expected format: { name: <String>, specialization: <String>, phone: <String> }. You're missing a ${requiredParameter} property.` }) } } database.insert(request.body).returning('*').into('doctors') .then((data) => { response.status(201).json(data); }) .catch((error) => { response.status(500).json({ error }) }) }) //POST PATIENT('/clinique/doctors/:id/patients') app.post('/clinique/doctors/:id/patients', (request, response) => { let data = request.body; for(let requiredParameter of ['name', 'phone', 'gender', 'doctor_id']) { if(!data[requiredParameter]) { return response.status(422).json({ error: `Expected format: { name: <String>, phone: <String>, gender: <String>, doctor_id: <Integer> }. You're missing a ${requiredParameter} property.` }) } } database.insert(request.body).returning('*').into('patients') .then((data) => { response.status(201).json(data); }) .catch((error) => { response.status(500).json({ error }) }) }) //DELETE PATIENT ('/clinique/doctors/:id/patiens/1004') app.delete('/clinique/doctors/:id/patients/:id', (request, response) => { const { id } = request.params database('patients').where('id', id).del() .then((patient) => { if(patient) { response.status(200).json({ success: `You have successfully deleted patient with the id of ${id}`}); } else { response.status(404).json({ error: `Could not find patient with the id of ${id}` }) } }) .catch((error) => { response.status(500).json({ error }) }) }); //DELETE DOCTOR('/clinique/doctors/:id') app.delete('/clinique/doctors/:id', (request, response) => { const { id } = request.params const deleteDocsAndPatients = [ database('patients').where('doctor_id', id).del(), database('doctors').where('id', id).del()] Promise.all(deleteDocsAndPatients) .then(() => { response.json({ success: `You have successfully deleted doctor with the id of ${id}`}); }) .catch((error) => { response.status(500).json({ error }) }) });
014b2eada4cea37dcb742245e51a0c0fb8129f58
[ "JavaScript", "Markdown" ]
6
JavaScript
andreeahanson/byob
c17b513f8dc3e32ed520e3af9ca3766e5ffbb360
8153ace67b9a0610e39ba66ba423fc081d45ecc0
refs/heads/master
<file_sep>class AppDelegate def application(application, didFinishLaunchingWithOptions:launchOptions) @window = UIWindow.alloc.initWithFrame(UIScreen.mainScreen.bounds) @window.rootViewController = TableViewController.new @window.makeKeyAndVisible end end class TableViewController < UITableViewController stylesheet :main def viewDidLoad self.view.registerClass(CustomCell, forCellReuseIdentifier:'cell id') end def tableView(tableView, numberOfSectionsInTableView:section) 1 end def tableView(tableView, numberOfRowsInSection:section) 3 end def tableView(tableView, heightForRowAtIndexPath:index_path) 100 end def tableView(tableView, cellForRowAtIndexPath:indexPath) cell = tableView.dequeueReusableCellWithIdentifier('cell id') cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton layout(cell.contentView, :root) do subview(UIView, :padding) do cell.title_label = subview(UILabel, :cell_title_label, :text => "title #{indexPath.row}") cell.details_label = subview(UILabel, :cell_details_label, :text => "details #{indexPath.row}") cell.attendees_label = subview(UILabel, :cell_attendees_label, :text => "attendees #{indexPath.row}") end end cell.contentView.apply_constraints cell end end class CustomCell < UITableViewCell attr_accessor :title_label, :details_label, :attendees_label end Teacup::Stylesheet.new :main do style :root, backgroundColor: UIColor.colorWithRed(247.0 / 256.0, green:221.0 / 256.0, blue:186.0 / 256.0, alpha:1) style :padding, backgroundColor: UIColor.greenColor, constraints: [ constrain(:width).equals(:superview, :width).times(0.96), constrain(:height).equals(:superview, :height).times(0.96), constrain(:center_x).equals(:superview, :center_x), constrain(:center_y).equals(:superview, :center_y) ] style :cell_title_label, font: UIFont.boldSystemFontOfSize(17), constraints: [ constrain_height(20), constrain(:top).equals(:superview, :top), constrain(:width).equals(:superview, :width), constrain(:center_x).equals(:superview, :center_x) ] style :cell_details_label, font: UIFont.systemFontOfSize(14), color: UIColor.grayColor, constraints: [ constrain_height(17), constrain_below(:cell_title_label, 5), constrain(:width).equals(:superview, :width), constrain(:center_x).equals(:superview, :center_x) ] style :cell_attendees_label, font: UIFont.systemFontOfSize(14), color: UIColor.grayColor, constraints: [ constrain_height(17), constrain_below(:cell_details_label, 5), constrain(:width).equals(:superview, :width), constrain(:center_x).equals(:superview, :center_x) ] end
925230fb7034267c5a19ee82fb4de4f4908ec32e
[ "Ruby" ]
1
Ruby
sxross/constraint_based_table_cell
75d1ad1d70b1f5daf63afa2497af63c6b0edfed2
ce1a05d9fe1dffef4483592b061f39de7dbb5e42
refs/heads/master
<file_sep>using System; namespace Serpis.Ed { public class MyArray { public static void Main (string[] args) { //int[] v = new int[]{5, 15, 12, 7, 3, 9}; //SelectionSort<int>(v); //show<int>(v); Persona[] personas = new Persona[] { new Persona("Dani", new DateTime(1969, 2, 25)), new Persona("David", new DateTime(1999, 3, 1)), new Persona("Blanca", new DateTime(1988, 2, 25)), new Persona("Ana", new DateTime(1990, 2, 25)), new Persona("Adam", new DateTime(1970, 2, 25)), new Persona("Belén", new DateTime(1983, 2, 25)) }; // SelectionSort<Persona>(personas); // show<Persona>(personas); // int x = 33; // int y = 77; // Swap(ref x, ref y); } private static void show<T>(T[] v) { for (int index = 0; index < v.Length; index++) Console.WriteLine("v[{0}]={1}", index, v[index]); } public static int IndexOfMin<T>(T[] v, int startIndex) where T : IComparable<T> { int indexOfMin = startIndex; for (int index = startIndex + 1; index < v.Length; index++) if (v[index].CompareTo(v[indexOfMin]) < 0) indexOfMin = index; return indexOfMin; } // public static void Swap(ref int a, ref int b) { // int temp = a; // a = b; // b = temp; // } public static void Swap<T>(ref T a, ref T b) { T temp = a; a = b; b = temp; } private static void selectionSortV2<T>(T[] v) where T : IComparable<T>{ for (int selectedIndex = 0; selectedIndex < v.Length - 1; selectedIndex++) { int indexOfMin = IndexOfMin<T>(v, selectedIndex); Swap<T>(ref v[selectedIndex], ref v[indexOfMin]); } } public static void SelectionSort<T>(T[] v) where T : IComparable<T> { selectionSortV2<T>(v); } private static void selectionSortV1<T>(T[] v) where T : IComparable<T> { int count = v.Length; for (int selectedIndex = 0; selectedIndex < count - 1; selectedIndex++) { int indexOfMin = selectedIndex; for (int index = selectedIndex + 1; index < count; index++) if (v[index].CompareTo(v[indexOfMin]) < 0) indexOfMin = index; T temp = v[selectedIndex]; v[selectedIndex] = v[indexOfMin]; v[indexOfMin] = temp; } } public static void SelectionSort<T>(T[] v, Comparison<T> } } <file_sep> // This file has been generated by the GUI designer. Do not modify. public partial class MainWindow { private global::Gtk.VBox vbox1; private global::Gtk.HBox hbox1; private global::Gtk.Label label1; private global::Gtk.Entry entryNombre; private global::Gtk.HBox hbox3; private global::Gtk.Button button; private global::Gtk.Label labelSaludo; private global::Gtk.HBox hbox2; protected virtual void Build () { global::Stetic.Gui.Initialize (this); // Widget MainWindow this.Name = "MainWindow"; this.Title = global::Mono.Unix.Catalog.GetString ("MainWindow"); this.WindowPosition = ((global::Gtk.WindowPosition)(4)); // Container child MainWindow.Gtk.Container+ContainerChild this.vbox1 = new global::Gtk.VBox (); this.vbox1.Spacing = 6; // Container child vbox1.Gtk.Box+BoxChild this.hbox1 = new global::Gtk.HBox (); this.hbox1.Name = "hbox1"; this.hbox1.Spacing = 6; // Container child hbox1.Gtk.Box+BoxChild this.label1 = new global::Gtk.Label (); this.label1.Name = "label1"; this.label1.LabelProp = global::Mono.Unix.Catalog.GetString ("Introduce tu nombre"); this.hbox1.Add (this.label1); global::Gtk.Box.BoxChild w1 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.label1])); w1.Position = 0; w1.Expand = false; w1.Fill = false; // Container child hbox1.Gtk.Box+BoxChild this.entryNombre = new global::Gtk.Entry (); this.entryNombre.CanFocus = true; this.entryNombre.Name = "entryNombre"; this.entryNombre.IsEditable = true; this.entryNombre.InvisibleChar = '•'; this.hbox1.Add (this.entryNombre); global::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.entryNombre])); w2.Position = 1; this.vbox1.Add (this.hbox1); global::Gtk.Box.BoxChild w3 = ((global::Gtk.Box.BoxChild)(this.vbox1 [this.hbox1])); w3.Position = 0; w3.Expand = false; w3.Fill = false; // Container child vbox1.Gtk.Box+BoxChild this.hbox3 = new global::Gtk.HBox (); this.hbox3.Name = "hbox3"; this.hbox3.Spacing = 6; // Container child hbox3.Gtk.Box+BoxChild this.button = new global::Gtk.Button (); this.button.CanFocus = true; this.button.Name = "button"; this.button.UseUnderline = true; this.button.Label = global::Mono.Unix.Catalog.GetString ("Pulsa aqui para entrar"); this.hbox3.Add (this.button); global::Gtk.Box.BoxChild w4 = ((global::Gtk.Box.BoxChild)(this.hbox3 [this.button])); w4.Position = 0; this.vbox1.Add (this.hbox3); global::Gtk.Box.BoxChild w5 = ((global::Gtk.Box.BoxChild)(this.vbox1 [this.hbox3])); w5.Position = 1; w5.Expand = false; w5.Fill = false; // Container child vbox1.Gtk.Box+BoxChild this.labelSaludo = new global::Gtk.Label (); this.labelSaludo.Name = "labelSaludo"; this.vbox1.Add (this.labelSaludo); global::Gtk.Box.BoxChild w6 = ((global::Gtk.Box.BoxChild)(this.vbox1 [this.labelSaludo])); w6.Position = 2; w6.Expand = false; w6.Fill = false; // Container child vbox1.Gtk.Box+BoxChild this.hbox2 = new global::Gtk.HBox (); this.hbox2.Name = "hbox2"; this.hbox2.Spacing = 6; this.vbox1.Add (this.hbox2); global::Gtk.Box.BoxChild w7 = ((global::Gtk.Box.BoxChild)(this.vbox1 [this.hbox2])); w7.Position = 4; this.Add (this.vbox1); if ((this.Child != null)) { this.Child.ShowAll (); } this.DefaultWidth = 609; this.DefaultHeight = 566; this.Show (); this.DeleteEvent += new global::Gtk.DeleteEventHandler (this.OnDeleteEvent); this.button.Clicked += new global::System.EventHandler (this.OnButtonClicked); } } <file_sep>using System; using Gtk; using Serpis.EDcs; public partial class MainWindow: Gtk.Window { private Bingo bingo = new Bingo(); public MainWindow (): base (Gtk.WindowType.Toplevel) { Build(); //bingo.NumeroInicialBolas = 43; bingo.Iniciar(); // uint rowCount = (uint) bingo.NumeroInicialBolas / 10; // for (uint row = 0; row < rowCount; row++){ // for (uint col = 0; col <= 9; col++) { // Button button = new Button(); // button.Label = "" + (col + 1 + (row * 10)); // button.Visible = true; // //table.Add (button); // table.Attach (button, col, 1 + col, row, row + 1, // AttachOptions.Fill , // AttachOptions.Fill, // 1,1); // } for (uint index = 0; index < bingo.NumeroInicialBolas; index ++){ Button button = new Button(); button.Label = "" + (index + 1); button.Visible = true; uint row = index / 10; uint col = index % 10; //mod table.Attach (button, col, 1 + col, row, row + 1, AttachOptions.Fill , AttachOptions.Fill, 1,1); } } protected void OnDeleteEvent (object sender, DeleteEventArgs a) { Application.Quit (); a.RetVal = true; } protected void OnButtonNextClicked (object sender, System.EventArgs e) { int bola = bingo.ExtraeBola(); Console.WriteLine("bola={0}", bola); //string path = "C:\\ProgramFiles\\Serpis\\Format.exe"; //string path = @"C:\ProgramFiles\Serpis\Format.exe"; // estas formas no son correctas porque no sirven para todos los S.O. // ver clase System.IO.Path //Process.Start("nautilus", "--browser"); Bingo.Cantar(bola); } } <file_sep> // This file has been generated by the GUI designer. Do not modify. public partial class MainWindow { private global::Gtk.VBox vbox2; private global::Gtk.HBox hbox3; private global::Gtk.Button buttonNext; private global::Gtk.Table table; protected virtual void Build () { global::Stetic.Gui.Initialize (this); // Widget MainWindow this.Name = "MainWindow"; this.Title = global::Mono.Unix.Catalog.GetString ("MainWindow"); this.WindowPosition = ((global::Gtk.WindowPosition)(4)); // Container child MainWindow.Gtk.Container+ContainerChild this.vbox2 = new global::Gtk.VBox (); this.vbox2.Name = "vbox2"; this.vbox2.Spacing = 6; // Container child vbox2.Gtk.Box+BoxChild this.hbox3 = new global::Gtk.HBox (); this.hbox3.Name = "hbox3"; this.hbox3.Spacing = 6; // Container child hbox3.Gtk.Box+BoxChild this.buttonNext = new global::Gtk.Button (); this.buttonNext.CanFocus = true; this.buttonNext.Name = "buttonNext"; this.buttonNext.UseUnderline = true; this.buttonNext.Label = global::Mono.Unix.Catalog.GetString ("Añadir"); this.hbox3.Add (this.buttonNext); global::Gtk.Box.BoxChild w1 = ((global::Gtk.Box.BoxChild)(this.hbox3 [this.buttonNext])); w1.Position = 0; w1.Expand = false; w1.Fill = false; this.vbox2.Add (this.hbox3); global::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.vbox2 [this.hbox3])); w2.Position = 0; w2.Expand = false; w2.Fill = false; // Container child vbox2.Gtk.Box+BoxChild this.table = new global::Gtk.Table (((uint)(3)), ((uint)(4)), false); this.table.Name = "table"; this.table.RowSpacing = ((uint)(6)); this.table.ColumnSpacing = ((uint)(6)); this.vbox2.Add (this.table); global::Gtk.Box.BoxChild w3 = ((global::Gtk.Box.BoxChild)(this.vbox2 [this.table])); w3.Position = 1; this.Add (this.vbox2); if ((this.Child != null)) { this.Child.ShowAll (); } this.DefaultWidth = 485; this.DefaultHeight = 412; this.Show (); this.DeleteEvent += new global::Gtk.DeleteEventHandler (this.OnDeleteEvent); this.buttonNext.Clicked += new global::System.EventHandler (this.OnButtonNextClicked); } } <file_sep>using System; using Gtk; public partial class MainWindow: Gtk.Window { public MainWindow (): base (Gtk.WindowType.Toplevel) { Build (); // button.Clicked += delegate { // labelSaludo.LabelProp = "Hola " + entryNombre.Text; // }; } protected void OnDeleteEvent (object sender, DeleteEventArgs a) { Application.Quit (); a.RetVal = true; } protected void OnButtonClicked (object sender, System.EventArgs e) { labelSaludo.LabelProp =string.Format("Hola {0} ({1})", entryNombre.Text, DateTime.Now); } } <file_sep>EDcs ==== Almacen para Entornos de Desarrollo con c#<file_sep>using System; using System.Collections.Generic; using System.Diagnostics; namespace Serpis.EDcs { public class Bingo { private List<int> bolas = new List<int>(); private int numeroInicialBolas = 90; //se podrá cambiar public int NumeroInicialBolas { get { return numeroInicialBolas;} set { if (value <= 0) return; numeroInicialBolas = value; } } /// <summary> /// Llena el bombo con las bolas. /// </summary> public void Iniciar(){ bolas.Clear(); for (int numero = 1; numero <= numeroInicialBolas; numero ++) bolas.Add (numero); } public int ExtraeBola() { int numeroAleatorio = new Random().Next(bolas.Count); int bola = bolas[numeroAleatorio]; bolas.Remove(bola); return bola; } public static void Cantar(int bola){ // TODO resolver implementacion string fileName = "espeak"; string arguments = "-v es \"14 1 4\""; Process.Start(fileName, arguments); } } }<file_sep>using System; namespace PDelegate { public delegate int MiFuncAB(int a, int b); class MainClass { public static void Main (string[] args) { Console.WriteLine ("Hello World!"); int aleatorio = new Random().Next(4); //0..3 MiFuncAB[] miFunABs = new MiFuncAB[]{suma, resta, producto, division}; MiFuncAB miFunAB = miFunABs[aleatorio]; // switch (aleatorio){ // case 0: miFunAB = suma; // break; // case 1:miFunAB = resta; // break; Console.WriteLine("aleatorio = {0} valor = {1}", aleatorio, miFunAB(5, 2)); } private static int suma(int a, int b){ return a + b; } private static int resta(int a, int b){ return a - b; } private static int producto(int a, int b){ return a * b; } private static int division(int a, int b){ return a / b; } } }
2f1893affb9ab6fad8bb098e6919d67ece689b5b
[ "Markdown", "C#" ]
8
C#
ivives/EDcs
bc4822a0c55d92a10a8c2d19cb984325b025de06
af5b0be30821cb958b9979c99496c09480568b72
refs/heads/master
<repo_name>andreyyv/grin-pool<file_sep>/scripts/build-docker-images.sh #!/bin/bash # Build containers docker build -t localhost:32000/splunk splunk -f ./splunk/Dockerfile.splunk docker build -t localhost:32000/universalforwarder splunk -f ./splunk/Dockerfile.universalforwarder docker build -t localhost:32000/rmq rmq -f ./rmq/Dockerfile docker build -t localhost:32000/stratum stratum -f ./stratum/Dockerfile docker build -t localhost:32000/bitgrin bitgrin -f ./bitgrin/Dockerfile docker build -t localhost:32000/grin grin -f ./grin/Dockerfile docker build -t localhost:32000/logstash logstash -f ./logstash/Dockerfile docker build -t localhost:32000/nginx nginx -f ./nginx/Dockerfile docker build -t localhost:32000/letsencrypt letsencrypt -f ./letsencrypt/Dockerfile docker build -t localhost:32000/keybase keybase -f ./keybase/Dockerfile docker build -t localhost:32000/webui-js grin-py/webui-js -f ./grin-py/webui-js/Dockerfile docker build -t localhost:32000/mwdockerbase grin-py/mwdockerbase -f ./grin-py/mwdockerbase/Dockerfile docker build -t localhost:32000/services grin-py -f ./grin-py/Dockerfile
96f486d01a5cd7a2d98fdbc81eb91319448a36c8
[ "Shell" ]
1
Shell
andreyyv/grin-pool
a2b916969e76d9a19654d7e954c1b28e739d3c5a
359b0cd35fe44205abac90fc8e942c2b7902491b
refs/heads/main
<file_sep>package com.mycompany.server; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.CacheControl; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController() @RequestMapping("employees") public class EmployeeRestController { private final EmployeeRepository repository; private final Logger logger = LoggerFactory.getLogger(EmployeeRestController.class); @Autowired EmployeeRestController(EmployeeRepository repository) { this.repository = repository; } @RequestMapping(method = RequestMethod.GET) public ResponseEntity<List<Employee>> all(@RequestParam(value = "text", required = false) String containingText) { final List<Employee> employees = repository.findAll(); return ResponseEntity.ok().cacheControl(CacheControl.noCache()).body(employees); } @RequestMapping(method = RequestMethod.PUT) ResponseEntity<String> addEmployee(@RequestBody Employee newEmployee) { repository.save(newEmployee); logger.info("employee saved:" + newEmployee.toString()); return new ResponseEntity<>(HttpStatus.OK); } @RequestMapping(method = RequestMethod.DELETE) public ResponseEntity<String> deleteEmployee(@RequestBody Employee employee) { repository.delete(employee); logger.info("employee deleted:" + employee.toString()); return new ResponseEntity<>(HttpStatus.OK); } } <file_sep>logging.level.org.springframework=ERROR logging.level.com.mycompany=info spring.main.banner-mode=off spring.jpa.hibernate.ddl-auto=none spring.datasource.initialization-mode=always spring.datasource.platform=postgres spring.datasource.url=jdbc:postgresql://localhost:5433/springTestDb spring.datasource.username=root spring.datasource.password=<PASSWORD> spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true <file_sep>spring-boot-gwt.scheduled-database-reset=false<file_sep>buildscript { repositories { mavenCentral() } dependencies { classpath 'org.wisepersist:gwt-gradle-plugin:1.0.6' } } plugins { id 'java' id 'idea' id 'org.springframework.boot' version '2.0.1.RELEASE' id 'com.github.ben-manes.versions' version '0.17.0' } apply plugin: 'gwt' apply plugin: 'io.spring.dependency-management' sourceCompatibility = 1.8 targetCompatibility = 1.8 def GWT_VERSION = '2.8.2' ext['spock.version'] = '1.1' repositories { jcenter() } sourceSets { main.java.srcDir "src/main/java" main.resources.srcDir "src/main/resources" test.java.srcDir "src/test/java" // test.groovy.srcDir "src/test/groovy" test.resources.srcDir "src/test/resources" } dependencies { compileOnly("com.google.gwt:gwt-user:${GWT_VERSION}") compileOnly("com.google.gwt:gwt-dev:${GWT_VERSION}") compileOnly('org.fusesource.restygwt:restygwt:2.2.3') // compile group: 'org.springframework.hateoas', name: 'spring-hateoas', version: '1.2.0' compile group: 'org.postgresql', name: 'postgresql', version: '42.1.4' compile('javax.ws.rs:javax.ws.rs-api:2.1') compile('org.springframework.boot:spring-boot-starter-data-jpa') compile('org.springframework.boot:spring-boot-starter-jetty') { exclude group: 'ch.qos.logback', module: 'logback-classic' } compile('org.springframework.boot:spring-boot-starter-web') { exclude module: 'spring-boot-starter-tomcat' } // runtime (group: 'com.h2database', name: 'h2', version: '1.4.200') testCompile('org.springframework.boot:spring-boot-starter-test') annotationProcessor('org.springframework.boot:spring-boot-configuration-processor') } wrapper { gradleVersion = '5.6' } gwt { gwtVersion = GWT_VERSION modules 'com.mycompany.SpringBootGwt' maxHeapSize = "1024M" } compileJava.dependsOn(processResources) bootJar.dependsOn compileGwt bootJar { baseName = 'spring-boot-gwt' version = '1.0.0' into('BOOT-INF/classes/static') { from compileGwt.outputs } }<file_sep># IDEA Settings To run both the frontend and backend in IntelliJ, make sure the following settings are set: #### Project Structure... ![GWT project structure web](gwt-project-structure-web.jpg) ![GWT project structure gwt](gwt-project-structure-gwt.jpg) #### Run configs ![GWT run config](gwt-run-config.jpg) ![Spring run config](spring-run-config.jpg)<file_sep>DROP TABLE IF EXISTS emp; CREATE TABLE emp(id serial PRIMARY KEY, name VARCHAR(255), role VARCHAR(255));
4aac74c01119471decf3c28d9f18791e1336d481
[ "SQL", "Markdown", "INI", "Gradle", "Java" ]
6
Java
MacLin123/EmployeeGwtSpring
3426c999bdf501d5aed2f850a80f0a7790ee30f3
07250b9a135f22ae85efb2ea54081da3accfe108
refs/heads/master
<repo_name>lazynessmind/srt2vtt<file_sep>/README.md # srt2vtt *.srt converter to *.vtt written in python <file_sep>/index.py import sys import re from pathlib import Path def convertType(srtFile): subtitlefile = open(srtFile, "r", encoding='utf8') convertedFile = open(Path(srtFile).stem + '.vtt', "w", encoding='utf8') lineArray = subtitlefile.read().splitlines() convertedFile.write('WEBVTT\n\n') i = 1 while i < len(lineArray): if not lineArray[i].isdigit(): convline = re.sub(',(?! )', '.', lineArray[i]) convertedFile.write(convline + '\n') i += 1 convertedFile.close() if __name__ == '__main__': convertType(sys.argv[1])
648b31721e438fd9f24621c53ba9bc708607a8f9
[ "Markdown", "Python" ]
2
Markdown
lazynessmind/srt2vtt
4205e820b71a7e362c933744ad69dfae81768fee
f4f2036e7bc46e77b6447df5222b5d220bc3a81c
refs/heads/master
<repo_name>sebakocz/Little_Amy-Discord_Bot<file_sep>/bot.py ####IDEAS############## # DONE randomize every action - 1/4 chance that Amy ignores you or goes "Grrrrr" -> random_cat_behaviour # DONE >friends - show cat photos # DONE >futter - daily check in # DONE list of commands # kotz_behaviour -> -> try to kotz in a random channel -> prevent it by typing >scream/take her away/push her -> goes back into main channel -> /clean # activities -> add long sleeping inbetween # goes to scratch pad -> cat emotional release # change bot avatar picture -> loop # hunting game -> throw an item to another channel -> cat tries to catch it / show where with #channel # somehow represent her strawberry obsession # randomly starts meowing, sometimes holding mouse in her mouth ####IDEAS############## import os import re import requests from discord.ext import commands, tasks import discord import random from itertools import cycle rulesFile = open("rules.txt", encoding="UTF-8") rules = rulesFile.readlines() current_prefix = 'Amy ' current_channel = {} def get_prefix(client, message): return commands.when_mentioned_or(current_prefix)(client, message) client = commands.Bot(command_prefix=get_prefix) cat_activities = cycle( ['with your underwear', 'the laserpointer game', 'with her mice', 'hide no seek', 'sleep world record', 'kitchen climbing simulator', 'shadow hunters', 'singstar - meow at a corner edition']) @client.event async def on_ready(): print("discord version: " + discord.__version__) change_activity.start() walk_around.start() print("Amy wakes up") global current_channel current_channel = client.get_channel(734552235131797590) # 'the-amish-people' ######################## # Random Cat Behaviour # ######################## # you could use checks instead : https://www.youtube.com/watch?v=9KOJgfaUPmQ class CatInterrupt(Exception): pass @client.before_invoke async def random_cat_behaviour(ctx): possibleMessages = ["Grrr...", "Meow.", "Meow?", "*Turns and walks away.*", '*Sleeping.*'] chance = 0 if random.randrange(1, 100) <= chance: possible_behaviour = [1, 2] behaviour = random.choice(possible_behaviour) # 1 : do nothing # 2 : random message if behaviour == 2: await ctx.send(random.choice(possibleMessages)) raise CatInterrupt else: return @client.event async def on_command_error(ctx, error): if isinstance(error, CatInterrupt): print("cat error3") return # Ignore Cat Related Errors else: print(error) ######################## # Random Cat Behaviour # ######################## @client.check async def is_amy_here(ctx): return ctx.channel == current_channel @tasks.loop(seconds=10) async def change_activity(): await client.change_presence(activity=discord.Game(next(cat_activities))) @client.command(aliases=['meow', 'greetings', 'hello']) async def hey(ctx): """Greet the cat and hope she greets you back""" await ctx.send(f'*Meows at you, {ctx.author.name}.*') @client.command() @commands.cooldown(1, 60 * 60 * 24, commands.BucketType.user) async def food(ctx): """Feed the cat once per day""" await ctx.send('*nom, nom, nom*') @food.error async def food_error(ctx, error): if isinstance(error, commands.CommandOnCooldown): seconds = int(error.retry_after) % (24 * 3600) hours = seconds // 3600 seconds %= 3600 minutes = seconds // 60 seconds %= 60 await ctx.send(f"That's too much! Please wait {hours} hours, {minutes} minutes and {seconds} seconds.") @client.command() async def rule(ctx, *, number): """Show cat rule number X""" await ctx.send(rules[int(number) - 1]) @client.command() async def friends(ctx): """Show a random cat image from https://random.cat""" await ctx.send(random_cat_image()) def random_cat_image(): r = requests.get('https://random.cat') img = re.search('(?<=<meta property="og:image" content=")(.*?)(?=" />)', r.text) return img.group() @client.command() async def goto(ctx, channel: discord.TextChannel): """Tell Amy to go to another channel""" change_channel(channel) await ctx.send('*Walks to ' + channel.mention + '.*') def change_channel(channel): global current_channel current_channel = channel @client.command() async def prefix(ctx, prefix): """Change prefix""" global current_prefix current_prefix = prefix await ctx.send('prefix changed to ' + prefix) @client.command() async def true_name(ctx): """You can only control a demon if you know their true name""" await ctx.send('Aimée') @tasks.loop(minutes=30) async def walk_around(): global current_channel for guild in client.guilds: channel = random.choice(guild.text_channels) await current_channel.send(f'*Wanders to {channel.mention}.*') change_channel(channel) client.load_extension('cogs.testcog') client.load_extension('cogs.debugger') client.run(os.environ['TOKEN']) <file_sep>/cogs/debugger.py from discord.ext import commands class Debugger(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async def channel(self, ctx): """Shows in which channel you are""" await ctx.send(ctx.channel) def setup(bot): bot.add_cog(Debugger(bot))<file_sep>/cogs/random_behaviour.py from discord.ext import commands import random class random_behaviour(commands.Cog): def __init__(self, bot): self.bot = bot def setup(bot): bot.add_cog(random_behaviour(bot))<file_sep>/README.md # Little_Amy-Discord_Bot Personal companion - a discord cat bot <file_sep>/cogs/testcog.py from discord.ext import commands class Testcog(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async def testing(self, ctx): await ctx.send(ctx.channel.id) def setup(bot): bot.add_cog(Testcog(bot))
d95ce3731d7b80d8cf007fd398b6f81349a73af3
[ "Markdown", "Python" ]
5
Python
sebakocz/Little_Amy-Discord_Bot
bfbfefe31613feefcfbd57b508f1005fa44de7a6
e84078048cd75c94e970284e6d1faa08f3aecee3
refs/heads/master
<file_sep>Git Sample on Create Project App.# git-sample <file_sep><?php echo "example on vscode connected."; ?>
3d7e55eddcdc5bb2decc4a1e561dbb72b1a58238
[ "Markdown", "PHP" ]
2
Markdown
jay-supakorn/git-sample
fbc912429723dcdf500c6f50c9481a21b80f97d4
b9a73c5ade05a077e4759eb653af8dfc1e0eef70
refs/heads/master
<file_sep>package drtetris; import java.io.FileNotFoundException; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.Input; import org.newdawn.slick.Music; import org.newdawn.slick.SlickException; import org.newdawn.slick.state.GameState; import org.newdawn.slick.state.StateBasedGame; public class MainMenu implements GameState { private final int id; //Declares the background image and music along with the buttons private Image background; private Button tutorialbutton; private Button challengebutton; private Button infinitebutton; private Button optionsbutton; private Button exitbutton; private Button savebutton; private Music backgroundMusic; private SaveHandler saveHandler; public MainMenu(int id) { this.id = id; } @Override public int getID() { return id; } public SaveHandler getSaveHandler() { return saveHandler; } public void save(StateBasedGame sbg) throws FileNotFoundException { saveHandler.save(((ChallengeMode) sbg.getState(DrTetris.CHALLENGE_MODE)).getHighestLevel(), ((InfiniteMode) sbg.getState(DrTetris.INFINITE_MODE)).getHighestLevel(), ((Options) sbg.getState(DrTetris.OPTIONS)).getDifficulty(), (int) (((Options) sbg.getState(DrTetris.OPTIONS)).getVolume() * 100)); } @Override public void init(GameContainer gc, StateBasedGame sbg) throws SlickException { //Initializes the background image and music along with the buttons' positions try { backgroundMusic = new Music(Config.MAINMENUBACKGROUNDMUSIC); background = new Image(Config.MAINMENU); tutorialbutton = new Button(Config.TUTORIALBUTTON, 5, 200, 300, 60); challengebutton = new Button(Config.CHALLENGEBUTTON, 5, 265, 300, 60); infinitebutton = new Button(Config.INFINITEBUTTON, 5, 330, 300, 60); optionsbutton = new Button(Config.OPTIONSBUTTON, 5, 395, 300, 60); savebutton = new Button(Config.SAVEBUTTON, 5, 460, 300, 60); exitbutton = new Button(Config.EXITBUTTON, 5, 525, 300, 60); saveHandler = new SaveHandler(Config.SAVEFILE); saveHandler.load(); } catch (Exception e) { sbg.addState(new ErrorReport(DrTetris.ERR_REPORT, e)); sbg.enterState(DrTetris.ERR_REPORT); } } @Override public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException { //Draws all of the buttons and the background try { background.draw(); tutorialbutton.draw(); challengebutton.draw(); infinitebutton.draw(); optionsbutton.draw(); savebutton.draw(); exitbutton.draw(); } catch (Exception e) { sbg.addState(new ErrorReport(DrTetris.ERR_REPORT, e)); sbg.enterState(DrTetris.ERR_REPORT); } } @Override public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException { try { //Gives the buttons their purposes and sets the volume backgroundMusic.setVolume(((Options) sbg.getState(DrTetris.OPTIONS)).getVolume()); if (tutorialbutton.getClicked()) { sbg.enterState(DrTetris.TUTORIAL); tutorialbutton.setClicked(false); } if (infinitebutton.getClicked()) { sbg.enterState(DrTetris.INFINITE_MODE); infinitebutton.setClicked(false); } if (challengebutton.getClicked()) { sbg.enterState(DrTetris.LEVEL_SELECTION); challengebutton.setClicked(false); } if (optionsbutton.getClicked()) { ((Options) sbg.getState(DrTetris.OPTIONS)).setBackgroundState(sbg.getCurrentStateID()); sbg.enterState(DrTetris.OPTIONS); optionsbutton.setClicked(false); } if (savebutton.getClicked()) { save(sbg); savebutton.setClicked(false); } if (exitbutton.getClicked()) { save(sbg); gc.exit(); } } catch (Exception e) { sbg.addState(new ErrorReport(DrTetris.ERR_REPORT, e)); sbg.enterState(DrTetris.ERR_REPORT); } } @Override public void enter(GameContainer gc, StateBasedGame sbg) throws SlickException { try { //Loops the music if (!backgroundMusic.playing()) { backgroundMusic.loop(1F, ((Options) sbg.getState(DrTetris.OPTIONS)).getVolume()); } } catch (Exception e) { sbg.addState(new ErrorReport(DrTetris.ERR_REPORT, e)); sbg.enterState(DrTetris.ERR_REPORT); } } @Override public void leave(GameContainer gc, StateBasedGame sbg) throws SlickException { } @Override public void mouseWheelMoved(int i) { } @Override public void mouseClicked(int button, int x, int y, int clickCount) { } //The next four methods tell the buttons what to do depending on what the mouse does in relation to them @Override public void mousePressed(int button, int x, int y) { tutorialbutton.mousePressed(button, x, y); challengebutton.mousePressed(button, x, y); infinitebutton.mousePressed(button, x, y); optionsbutton.mousePressed(button, x, y); savebutton.mousePressed(button, x, y); exitbutton.mousePressed(button, x, y); } @Override public void mouseReleased(int button, int x, int y) { tutorialbutton.mouseReleased(button, x, y); challengebutton.mouseReleased(button, x, y); infinitebutton.mouseReleased(button, x, y); optionsbutton.mouseReleased(button, x, y); savebutton.mouseReleased(button, x, y); exitbutton.mouseReleased(button, x, y); } @Override public void mouseMoved(int oldX, int oldY, int newX, int newY) { tutorialbutton.mouseMoved(oldX, oldY, newX, newY); challengebutton.mouseMoved(oldX, oldY, newX, newY); infinitebutton.mouseMoved(oldX, oldY, newX, newY); optionsbutton.mouseMoved(oldX, oldY, newX, newY); savebutton.mouseMoved(oldX, oldY, newX, newY); exitbutton.mouseMoved(oldX, oldY, newX, newY); } @Override public void mouseDragged(int oldX, int oldY, int newX, int newY) { tutorialbutton.mouseDragged(oldX, oldY, newX, newY); challengebutton.mouseDragged(oldX, oldY, newX, newY); infinitebutton.mouseDragged(oldX, oldY, newX, newY); optionsbutton.mouseDragged(oldX, oldY, newX, newY); savebutton.mouseDragged(oldX, oldY, newX, newY); exitbutton.mouseDragged(oldX, oldY, newX, newY); } @Override public void setInput(Input input) { } @Override public boolean isAcceptingInput() { return true; } @Override public void inputEnded() { } @Override public void inputStarted() { } @Override public void keyPressed(int i, char c) { } @Override public void keyReleased(int i, char c) { } @Override public void controllerLeftPressed(int i) { } @Override public void controllerLeftReleased(int i) { } @Override public void controllerRightPressed(int i) { } @Override public void controllerRightReleased(int i) { } @Override public void controllerUpPressed(int i) { } @Override public void controllerUpReleased(int i) { } @Override public void controllerDownPressed(int i) { } @Override public void controllerDownReleased(int i) { } @Override public void controllerButtonPressed(int i, int i1) { } @Override public void controllerButtonReleased(int i, int i1) { } } <file_sep>package drtetris; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.concurrent.CopyOnWriteArrayList; import org.newdawn.slick.SlickException; public class Field extends TileMap { public static final int END = 0, CONTINUE = 1, NORMAL = 2, ANIMATE = 3; private static final int UP = 0, DOWN = 1, LEFT = 2, RIGHT = 3; private int state; private List<MovingBlock> fallingBlocks; private boolean checkBlocks; public Field(Tile[][] map) { super(map); state = NORMAL; fallingBlocks = new CopyOnWriteArrayList<MovingBlock>(); checkBlocks = true; lockBlocks(); } private void lockBlocks() { for (Tile[] tiles : map) { for (Tile tile : tiles) { if (tile != null && tile.getId() != 6) { tile.setLocked(true); } } } } @Override public void draw(int x, int y) { super.draw(x, y, true); for (MovingBlock block : fallingBlocks) { block.draw(Config.FIELDX, Config.FIELDY); } } public void update(int delta) { for (MovingBlock block : fallingBlocks) { if (block != null) { if (!isRoom(block, Config.STACKTOLERANCE, true)) { addMap(block, false, false); checkBlocks = true; fallingBlocks.remove(block); } else { block.modY(delta * Config.FALLINGBLOCKSPEED); yLimit(block, Config.STACKTOLERANCE); } } } if (checkBlocks && fallingBlocks.size() <= 0) { breakBlocks(); findFallingBlocks(); checkBlocks = false; } updateState(); } public void reset(Tile[][] map) throws IOException, NumberFormatException { this.map = map; state = NORMAL; fallingBlocks = new CopyOnWriteArrayList<MovingBlock>(); checkBlocks = true; lockBlocks(); } public void addMap(MovingBlock block, boolean breakBlocks, boolean findFallingBlocks) { addMap(block.getMap(), block.getX(), block.getY(), breakBlocks, findFallingBlocks); } public void addMap(MovingBlock block) { addMap(block.getMap(), block.getX(), block.getY(), true, true); } public void addMap(TileMap map, int rotation, int x, double y) { addMap(map.getMap(rotation), x, y, true, true); } public void addMap(Tile[][] map, int x, double y, boolean breakBlocks, boolean findFallingBlocks) { int yPos = (int) (y + Config.FIELDOFFSET) / Config.BLOCKSIZE; String blockId = UUID.randomUUID().toString(); for (int i = 0; i < map.length; i++) { for (int j = 0; j < map[i].length; j++) { if (map[i][j] != null) { if (yPos + i >= 0) { if (map[i][j] instanceof Tunnel || map[i][j] instanceof LinkedTile) { this.map[yPos + i][x + j] = map[i][j]; } else { try { this.map[yPos + i][x + j] = new LinkedTile(map[i][j].getId(), blockId); } catch (SlickException ex) { } catch (ArrayIndexOutOfBoundsException ex) { } } } } } } if (breakBlocks) { breakBlocks(); } if (findFallingBlocks) { findFallingBlocks(); } } //Finds tiles that are floating and groups of linked tiles thats are floating private void findFallingBlocks() { int lastSize; do { lastSize = fallingBlocks.size(); List<LinkedTile> antiFallingBlocks = new ArrayList<LinkedTile>(); for (int i = 0; i < map.length; i++) { for (int j = 0; j < map[i].length; j++) { if (map[i][j] instanceof LinkedTile) { if (i < map.length - 1 && map[i][j] != null && !map[i][j].isLocked() && (map[i + 1][j] == null || (map[i + 1][j] instanceof LinkedTile && ((LinkedTile) map[i][j]).getBlockId().equals(((LinkedTile) map[i + 1][j]).getBlockId())))) { fallingBlocks.add(new MovingBlock(new Tile[][]{{map[i][j]}}, TileMap.ROTATENONE, j, i * Config.BLOCKSIZE)); } else { antiFallingBlocks.add(((LinkedTile) map[i][j])); } } else if (i < map.length - 1) { if (map[i][j] != null && !map[i][j].isLocked() && map[i + 1][j] == null) { fallingBlocks.add(new MovingBlock(new Tile[][]{{map[i][j]}}, TileMap.ROTATENONE, j, i * Config.BLOCKSIZE)); } } } } for (LinkedTile antiFallingBlock : antiFallingBlocks) { for (MovingBlock block : fallingBlocks) { if (block.getMap()[0][0] instanceof LinkedTile && ((!block.getMap()[0][0].hasGravity() && !antiFallingBlock.hasGravity()) || (block.getMap()[0][0].getId() == 6 && antiFallingBlock.getId() == 6)) && ((LinkedTile) block.getMap()[0][0]).getBlockId().equals(antiFallingBlock.getBlockId())) { fallingBlocks.remove(block); } } } for (MovingBlock block : fallingBlocks) { map[(int) block.getY() / Config.BLOCKSIZE][block.getX()] = null; } } while ((lastSize != fallingBlocks.size())); } private void breakBlocks() { boolean[][] breakMap = new boolean[map.length][map[0].length]; for (int i = 0; i < map.length; i++) { for (int j = 0; j < map[i].length; j++) { if (map[i][j] != null && map[i][j].getId() != 10) { for (int k = (j > map[i].length - 4 ? 3 - map[i].length + j : j); k >= j - 3 && k >= 0; k--) { if (map[i][k] != null && (map[i][k].equals(map[i][k + 1]) && map[i][k].equals(map[i][k + 2]) && map[i][k].equals(map[i][k + 3]))) { breakMap[i][k] = true; breakMap[i][k + 1] = true; breakMap[i][k + 2] = true; breakMap[i][k + 3] = true; } } for (int k = (i > map.length - 4 ? 3 - map.length + i : i); k >= i - 3 && k >= 0; k--) { if (map[k][j] != null && (map[k][j].equals(map[k + 1][j]) && map[k][j].equals(map[k + 2][j]) && map[k][j].equals(map[k + 3][j]))) { breakMap[k][j] = true; breakMap[k + 1][j] = true; breakMap[k + 2][j] = true; breakMap[k + 3][j] = true; } } } } } for (int i = 0; i < breakMap.length; i++) { for (int j = 0; j < breakMap[i].length; j++) { if (breakMap[i][j]) { map[i][j] = null; } } } } public boolean isRoom(MovingBlock block, double tolerance, boolean falling) { return isRoom(block.getMap(), block.getX(), block.getY(), tolerance, falling); } public boolean isRoom(Tile[][] map, int x, double y, double tolerance, boolean falling) { int lowCheck = (int) ((y + tolerance) / Config.BLOCKSIZE), highCheck = (int) ((y - tolerance) / Config.BLOCKSIZE + 1), lowY = (int) (y / Config.BLOCKSIZE), highY = (int) (y / Config.BLOCKSIZE + 1); if (x < 0 || x + map[0].length > 12 || (lowY + map.length >= 12 && falling)) { return false; } for (int i = 0; i < map.length; i++) { for (int j = 0; j < map[i].length; j++) { if (map[i][j] != null) { if (lowCheck < 0 || lowCheck + map.length > this.map.length || this.map[i + lowCheck][j + x] != null) { return false; } else if (highCheck < 0 || highCheck + map.length > this.map.length || this.map[i + (falling ? highY : highCheck)][j + x] != null) { return false; } } } } return true; } public void yLimit(MovingBlock block, double tolerance) { if (!isRoom(block, tolerance, true) && block.getY() > ((int) block.getY() / Config.BLOCKSIZE) * Config.BLOCKSIZE) { block.setY(((int) block.getY() / Config.BLOCKSIZE) * Config.BLOCKSIZE); } } //Decides whether the blocks are falling, the next level is continued to, //there is a game over, or if the game is continuing as normal public void updateState() { if (fallingBlocks.size() > 0) { state = ANIMATE; } else if (isTunnel()) { state = CONTINUE; } else if (isFull()) { state = END; } else { state = NORMAL; } } public int getState() { return state; } //Checks to see if the there is a block above the limit private boolean isFull() { for (Tile tile : map[0]) { if (tile != null) { return true; } } return false; } //The isTunnel methods are used to check if a tunnel is connected from the bottom to the top private boolean isTunnel() { boolean isTunnel = false; for (int i = 0; i < map[map.length - 1].length && !isTunnel; i++) { if (map[map.length - 1][i] instanceof Tunnel) { isTunnel = isTunnel || isTunnel(i, map.length - 1, UP); } } return isTunnel; } private boolean isTunnel(int x, int y, int direction) { boolean isTunnel = false; if (y < 2) { isTunnel = true; } else { if (y > 0 && map[y - 1][x] instanceof Tunnel && !isTunnel) { isTunnel = isTunnel || isTunnel(x, y - 1, UP); } if (direction != RIGHT && x > 0 && map[y][x - 1] instanceof Tunnel && !isTunnel) { isTunnel = isTunnel || isTunnel(x - 1, y, LEFT); } if (direction != LEFT && x < map[y].length - 1 && map[y][x + 1] instanceof Tunnel && !isTunnel) { isTunnel = isTunnel || isTunnel(x + 1, y, RIGHT); } } return isTunnel; } } <file_sep>package drtetris; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.Input; import org.newdawn.slick.Music; import org.newdawn.slick.SlickException; import org.newdawn.slick.state.GameState; import org.newdawn.slick.state.StateBasedGame; public class Credits implements GameState { private final int id; private Image credits; private Music backgroundMusic; private int y = 0; private boolean clicked = false; public Credits(int id) { this.id = id; } @Override public int getID() { return id; } @Override public void init(GameContainer gc, StateBasedGame sbg) throws SlickException { try { //Initializes the background music and the credits image backgroundMusic = new Music(Config.MAINMENUBACKGROUNDMUSIC); credits = new Image(Config.CREDITSIMAGE); } catch (Exception e) { sbg.addState(new ErrorReport(DrTetris.ERR_REPORT, e)); sbg.enterState(DrTetris.ERR_REPORT); } } @Override public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException { try { //Makes the credits appear credits.draw(0, y); } catch (Exception e) { sbg.addState(new ErrorReport(DrTetris.ERR_REPORT, e)); sbg.enterState(DrTetris.ERR_REPORT); } } @Override public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException { try { //Allows the credits image to be any length backgroundMusic.setVolume(((Options) sbg.getState(DrTetris.OPTIONS)).getVolume()); if (clicked) { sbg.enterState(DrTetris.MAIN_MENU); } if (y <= 600 - credits.getHeight()) { y = 600 - credits.getHeight(); } else { y -= delta * Config.CREDITSSPEED; } } catch (Exception e) { sbg.addState(new ErrorReport(DrTetris.ERR_REPORT, e)); sbg.enterState(DrTetris.ERR_REPORT); } } @Override public void enter(GameContainer gc, StateBasedGame sbg) throws SlickException { try { backgroundMusic.loop(1F, ((Options) sbg.getState(DrTetris.OPTIONS)).getVolume()); } catch (Exception e) { sbg.addState(new ErrorReport(DrTetris.ERR_REPORT, e)); sbg.enterState(DrTetris.ERR_REPORT); } } @Override public void leave(GameContainer gc, StateBasedGame sbg) throws SlickException { } @Override public void mouseWheelMoved(int i) { } @Override public void mouseClicked(int i, int i1, int i2, int i3) { clicked = true; } @Override public void mousePressed(int i, int i1, int i2) { } @Override public void mouseReleased(int i, int i1, int i2) { } @Override public void mouseMoved(int i, int i1, int i2, int i3) { } @Override public void mouseDragged(int i, int i1, int i2, int i3) { } @Override public void setInput(Input input) { } @Override public boolean isAcceptingInput() { return true; } @Override public void inputEnded() { } @Override public void inputStarted() { } @Override public void keyPressed(int i, char c) { } @Override public void keyReleased(int i, char c) { clicked = true; } @Override public void controllerLeftPressed(int i) { } @Override public void controllerLeftReleased(int i) { } @Override public void controllerRightPressed(int i) { } @Override public void controllerRightReleased(int i) { } @Override public void controllerUpPressed(int i) { } @Override public void controllerUpReleased(int i) { } @Override public void controllerDownPressed(int i) { } @Override public void controllerDownReleased(int i) { } @Override public void controllerButtonPressed(int i, int i1) { } @Override public void controllerButtonReleased(int i, int i1) { } } <file_sep>package drtetris; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.Input; import org.newdawn.slick.SlickException; import org.newdawn.slick.SpriteSheet; import org.newdawn.slick.state.GameState; import org.newdawn.slick.state.StateBasedGame; //This class is used to make a slideshow of the spritesheet for a tutorial public class Tutorial implements GameState { private final int id; private SpriteSheet tutorialSlides; private int slide = 0; public Tutorial(int id) { this.id = id; } @Override public int getID() { return id; } @Override public void init(GameContainer gc, StateBasedGame sbg) throws SlickException { tutorialSlides = new SpriteSheet(new Image(Config.TUTORIALSLIDES), 800, 600); } @Override public void render(GameContainer gc, StateBasedGame sbg, Graphics grphcs) throws SlickException { tutorialSlides.getSprite(slide, 0).draw(); } @Override public void update(GameContainer gc, StateBasedGame sbg, int i) throws SlickException { if (slide > tutorialSlides.getWidth() / 800 - 1) { sbg.enterState(DrTetris.MAIN_MENU); slide = 0; } } @Override public void enter(GameContainer gc, StateBasedGame sbg) throws SlickException { } @Override public void leave(GameContainer gc, StateBasedGame sbg) throws SlickException { } @Override public void mouseWheelMoved(int i) { } @Override public void mouseClicked(int i, int i1, int i2, int i3) { slide++; } @Override public void mousePressed(int i, int i1, int i2) { } @Override public void mouseReleased(int i, int i1, int i2) { } @Override public void mouseMoved(int i, int i1, int i2, int i3) { } @Override public void mouseDragged(int i, int i1, int i2, int i3) { } @Override public void setInput(Input input) { } @Override public boolean isAcceptingInput() { return true; } @Override public void inputEnded() { } @Override public void inputStarted() { } @Override public void keyPressed(int i, char c) { } @Override public void keyReleased(int i, char c) { slide++; } @Override public void controllerLeftPressed(int i) { } @Override public void controllerLeftReleased(int i) { } @Override public void controllerRightPressed(int i) { } @Override public void controllerRightReleased(int i) { } @Override public void controllerUpPressed(int i) { } @Override public void controllerUpReleased(int i) { } @Override public void controllerDownPressed(int i) { } @Override public void controllerDownReleased(int i) { } @Override public void controllerButtonPressed(int i, int i1) { } @Override public void controllerButtonReleased(int i, int i1) { } } <file_sep>package drtetris; import org.newdawn.slick.SlickException; //This class creates linkage between blocks so that linked blocks do not break when there is overhang by assigning a falling block an ID. //Blocks with the same ID will not break apart. public class LinkedTile extends Tile { public static final int STRAIGHT = 0, ALL = 1, CORNER = 2, T = 3, LEG = 4, NONE = 5; public static final TileConstruct[][][][] TUNNELCONSTRUCTS = new TileConstruct[][][][]{ //DONE {//0 False {//1 False {//2 False new TileConstruct(STRAIGHT, 90F),//3 False DONE new TileConstruct(STRAIGHT, 0F)//3 True DONE }, {//2 True new TileConstruct(STRAIGHT, 0F),//3 False DONE new TileConstruct(STRAIGHT, 0F)//3 True DONE } }, {// 1 True {//2 False new TileConstruct(STRAIGHT, 90F),//3 False DONE new TileConstruct(CORNER, -90F)//3 True DONE }, {//2 True new TileConstruct(CORNER, 0F),//3 False DONE new TileConstruct(T, 0F)//3 True DONE } } }, {//0 True {//1 False {//2 False new TileConstruct(STRAIGHT, 90F),//3 False DONE new TileConstruct(CORNER, 180F)//3 True DONE }, {//2 True new TileConstruct(CORNER, 90F),//3 False DONE new TileConstruct(T, 180F)//3 True DONE } }, {//1 True {//2 False new TileConstruct(STRAIGHT, 90F),//3 False DONE new TileConstruct(T, -90F)//3 True DONE }, {//2 True new TileConstruct(T, 90F),//3 False DONE new TileConstruct(ALL, 0F)//3 True DONE } } } }; public static final TileConstruct[][][][] CONSTRUCTS = new TileConstruct[][][][]{//DONE {//0 False {//1 False {//2 False new TileConstruct(NONE, 0F),//3 False DONE new TileConstruct(LEG, 180F)//3 True DONE }, {//2 True new TileConstruct(LEG, 0F),//3 False DONE new TileConstruct(STRAIGHT, 0F)//3 True DONE } }, {// 1 True {//2 False new TileConstruct(LEG, -90F),//3 False DONE new TileConstruct(CORNER, -90F)//3 True DONE }, {//2 True new TileConstruct(CORNER, 0F),//3 False DONE new TileConstruct(T, 0F)//3 True DONE } } }, {//0 True {//1 False {//2 False new TileConstruct(LEG, 90F),//3 False DONE new TileConstruct(CORNER, 180F)//3 True DONE }, {//2 True new TileConstruct(CORNER, 90F),//3 False DONE new TileConstruct(T, 180F)//3 True DONE } }, {//1 True {//2 False new TileConstruct(STRAIGHT, 90F),//3 False DONE new TileConstruct(T, -90F)//3 True DONE }, {//2 True new TileConstruct(T, 90F),//3 False DONE new TileConstruct(ALL, 0F)//3 True DONE } } } }; private final String blockId; public LinkedTile(int index, String blockId) throws SlickException, ArrayIndexOutOfBoundsException { super(index); this.blockId = blockId; } public LinkedTile(int index, int length, boolean gravity, boolean locked, String blockId) { super(index, length, gravity, locked); this.blockId = blockId; } public String getBlockId() { return blockId; } } <file_sep>package drtetris; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Random; import java.util.Scanner; import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; public class Level { private String name; private String[] blocks; private Image background; private Field field; private final Random random; //Decides the name, background, and spawning blocks of a level by reading the level.config file public Level(String local, boolean isField) throws SlickException, IOException { random = new Random(); File dir = new File(Config.LEVELDIRECTORY + local); if (!dir.isDirectory()) { throw new FileNotFoundException(); } field = isField ? new Field(MapReader.getMapFromFile(Config.LEVELDIRECTORY, local + "/field")) : new Field(new Tile[Config.FIELDHEIGHT][Config.FIELDWIDTH]); Scanner scanner = new Scanner(new File(dir.getAbsolutePath() + "/level.config")); while (scanner.hasNextLine()) { String line = scanner.nextLine(); String[] keyValue = line.split(":"); if (keyValue[0].toLowerCase().equals("name")) { name = keyValue[1]; } else if (keyValue[0].toLowerCase().equals("blocks")) { blocks = keyValue[1].split(","); } else if (keyValue[0].toLowerCase().equals("gamebackground")) { background = new Image("res/" + keyValue[1]); } } } public Block nextBlock() { try { return new Block(blocks[random.nextInt(blocks.length)]); } catch (IOException ex) { return null; } catch (NumberFormatException ex) { return null; } } public String getName() { return name; } public Image getBackground() { return background; } public Field getField() { return field; } } <file_sep>package drtetris; import java.awt.Color; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.Input; import org.newdawn.slick.SlickException; import org.newdawn.slick.UnicodeFont; import org.newdawn.slick.font.effects.ColorEffect; import org.newdawn.slick.state.GameState; import org.newdawn.slick.state.StateBasedGame; public class Options implements GameState { private final int id; private int difficulty; private int volume; private UnicodeFont font; private Image background; private int backgroundState; private Button backButton; private Button plusButton; private Button minusButton; private Button easyButton; private Button mediumButton; private Button extremeButton; public Options(int id, int backgroundState) { this.id = id; this.backgroundState = backgroundState; } @Override public int getID() { return id; } public void setBackgroundState(int id) { backgroundState = id; } public int getDifficulty() { return difficulty; } public float getVolume() { return ((float) volume) / 100f; } @Override public void init(GameContainer gc, StateBasedGame sbg) throws SlickException { try { //Initializes the buttons and backgrounds of the options menu difficulty = ((MainMenu) sbg.getState(DrTetris.MAIN_MENU)).getSaveHandler().getDifficulty(); volume = ((MainMenu) sbg.getState(DrTetris.MAIN_MENU)).getSaveHandler().getVolume(); background = new Image(Config.OPTIONSBACKGROUND); backButton = new Button(Config.BACKBUTTON, 250, 500, 300, 60); plusButton = new Button(Config.PLUSBUTTON, 500, 395, 50, 50); minusButton = new Button(Config.MINUSBUTTON, 250, 395, 50, 50); easyButton = new Button(Config.EASYBUTTON, 250, 150, 300, 60); mediumButton = new Button(Config.MEDIUMBUTTON, 250, 212, 300, 60); extremeButton = new Button(Config.EXTREMEBUTTON, 250, 274, 300, 60); font = new UnicodeFont(Config.FONT, 36, false, false); font.addAsciiGlyphs(); font.getEffects().add(new ColorEffect(Color.BLACK)); font.loadGlyphs(); } catch (Exception e) { sbg.addState(new ErrorReport(DrTetris.ERR_REPORT, e)); sbg.enterState(DrTetris.ERR_REPORT); } } @Override public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException { try { //Draws all of the buttons and backgrounds of the options menu sbg.getState(backgroundState).render(gc, sbg, g); g.setFont(font); background.draw(); backButton.draw(); plusButton.draw(); minusButton.draw(); easyButton.draw(); mediumButton.draw(); extremeButton.draw(); g.drawString(String.valueOf(volume), 360, 403); } catch (Exception e) { sbg.addState(new ErrorReport(DrTetris.ERR_REPORT, e)); sbg.enterState(DrTetris.ERR_REPORT); } } private int volumeDelay = 250; @Override public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException { try { volumeDelay += delta; //Lets the difficulty be set from the buttons if (backButton.getClicked()) { sbg.enterState(backgroundState); backButton.setClicked(false); } if (easyButton.getClicked()) { difficulty = Config.EASY; easyButton.setClicked(false); } if (mediumButton.getClicked()) { difficulty = Config.MEDIUM; mediumButton.setClicked(false); } if (extremeButton.getClicked()) { difficulty = Config.EXTREME; extremeButton.setClicked(false); } //Lets the volume be altered with a + and - button if (volumeDelay >= 250) { if (plusButton.getClicked()) { if (volume < 100) { volume += 5; volumeDelay = 0; plusButton.setClicked(false); } } if (minusButton.getClicked()) { if (volume > 0) { volume -= 5; volumeDelay = 0; minusButton.setClicked(false); } } } //Makes the selected difficulty be pressed down at all times to show which difficult is set switch (difficulty) { case (Config.EASY): easyButton.setState(Button.SELECTED); break; case (Config.MEDIUM): mediumButton.setState(Button.SELECTED); break; case (Config.EXTREME): extremeButton.setState(Button.SELECTED); break; } } catch (Exception e) { sbg.addState(new ErrorReport(DrTetris.ERR_REPORT, e)); sbg.enterState(DrTetris.ERR_REPORT); } } @Override public void enter(GameContainer gc, StateBasedGame sbg) throws SlickException { } @Override public void leave(GameContainer gc, StateBasedGame sbg) throws SlickException { } @Override public void mouseWheelMoved(int i) { } @Override public void mouseClicked(int button, int x, int y, int clickCount) { } @Override public void mousePressed(int button, int x, int y) { backButton.mousePressed(button, x, y); plusButton.mousePressed(button, x, y); minusButton.mousePressed(button, x, y); easyButton.mousePressed(button, x, y); mediumButton.mousePressed(button, x, y); extremeButton.mousePressed(button, x, y); } @Override public void mouseReleased(int button, int x, int y) { backButton.mouseReleased(button, x, y); plusButton.mouseReleased(button, x, y); minusButton.mouseReleased(button, x, y); easyButton.mouseReleased(button, x, y); mediumButton.mouseReleased(button, x, y); extremeButton.mouseReleased(button, x, y); } @Override public void mouseMoved(int oldX, int oldY, int newX, int newY) { backButton.mouseMoved(oldX, oldY, newX, newY); plusButton.mouseMoved(oldX, oldY, newX, newY); minusButton.mouseMoved(oldX, oldY, newX, newY); easyButton.mouseMoved(oldX, oldY, newX, newY); mediumButton.mouseMoved(oldX, oldY, newX, newY); extremeButton.mouseMoved(oldX, oldY, newX, newY); } @Override public void mouseDragged(int oldX, int oldY, int newX, int newY) { backButton.mouseDragged(oldX, oldY, newX, newY); plusButton.mouseDragged(oldX, oldY, newX, newY); minusButton.mouseDragged(oldX, oldY, newX, newY); easyButton.mouseDragged(oldX, oldY, newX, newY); mediumButton.mouseDragged(oldX, oldY, newX, newY); extremeButton.mouseDragged(oldX, oldY, newX, newY); } @Override public void setInput(Input input) { } @Override public boolean isAcceptingInput() { return true; } @Override public void inputEnded() { } @Override public void inputStarted() { } @Override public void keyPressed(int i, char c) { } @Override public void keyReleased(int i, char c) { } @Override public void controllerLeftPressed(int i) { } @Override public void controllerLeftReleased(int i) { } @Override public void controllerRightPressed(int i) { } @Override public void controllerRightReleased(int i) { } @Override public void controllerUpPressed(int i) { } @Override public void controllerUpReleased(int i) { } @Override public void controllerDownPressed(int i) { } @Override public void controllerDownReleased(int i) { } @Override public void controllerButtonPressed(int i, int i1) { } @Override public void controllerButtonReleased(int i, int i1) { } } <file_sep>package drtetris; import java.awt.Color; import java.util.Random; import org.lwjgl.input.Keyboard; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.Input; import org.newdawn.slick.Music; import org.newdawn.slick.SlickException; import org.newdawn.slick.UnicodeFont; import org.newdawn.slick.font.effects.ColorEffect; import org.newdawn.slick.state.GameState; import org.newdawn.slick.state.StateBasedGame; public class InfiniteMode implements GameState { private final int id; private Random random; private UnicodeFont font; private Music music; private Image pausedOverlay; private Image gameoverOverlay; private Image levelNameBackground; private Button backButton; private Button pausedOptionsButton; private Button pausedExitButton; protected Level currentLevel; private Block nextBlock; private MovingBlock currentBlock; protected boolean challenge = false; private boolean gameover = false, paused = false; private double speed; private int stackDelay = 0, aDelay = 0, dDelay = 0; private int level = 0; private double difficulty; private boolean A = false, D = false; protected int levelCount = 0; protected int highestLevel; private Throwable exception; public InfiniteMode(int id) { this.id = id; } @Override public int getID() { return id; } public void setDifficulty(int difficulty) { this.difficulty = difficulty; } public void setLevel(int level) { try { this.level = level; currentLevel = new Level(String.valueOf(level), challenge); currentBlock = new MovingBlock(currentLevel.nextBlock(), TileMap.ROTATENONE, Config.DEFAULTX, Config.DEFAULTY); nextBlock = currentLevel.nextBlock(); stackDelay = 0; aDelay = 0; dDelay = 0; paused = false; gameover = false; } catch (Exception e) { exception = e; } } public int getLevel() { return level; } protected int nextLevel() { levelCount++; highestLevel = Math.max(highestLevel, levelCount); return random.nextInt(Config.NUMBEROFLEVELS); } public int getHighestLevel() { return highestLevel; } @Override public void init(GameContainer gc, StateBasedGame sbg) { try { difficulty = (double) ((Options) sbg.getState(DrTetris.OPTIONS)).getDifficulty(); music = new Music(Config.GAMEBACKGROUNDMUSIC); currentLevel = new Level(String.valueOf(level), challenge); pausedOverlay = new Image(Config.PAUSESCREEN); gameoverOverlay = new Image(Config.GAMEOVERSCREEN); levelNameBackground = new Image(Config.LEVELNAMEBACKGROUND); backButton = new Button(Config.BACKBUTTON, 250, 335, 300, 60); pausedOptionsButton = new Button(Config.INNEROPTIONSBUTTON, 250, 400, 300, 60); pausedExitButton = new Button(Config.INNEREXITBUTTON, 250, 465, 300, 60); currentBlock = new MovingBlock(currentLevel.nextBlock(), TileMap.ROTATENONE, Config.DEFAULTX, Config.DEFAULTY); nextBlock = currentLevel.nextBlock(); speed = challenge ? (Config.BASESPEED) * ((difficulty / 4) + .8) : (Config.BASESPEED + Config.SPEEDINCREMENT * level) * (difficulty + .8); random = new Random(); highestLevel = challenge ? highestLevel = ((MainMenu) sbg.getState(DrTetris.MAIN_MENU)).getSaveHandler().getChallengeLevel() : ((MainMenu) sbg.getState(DrTetris.MAIN_MENU)).getSaveHandler().getInfiniteLevel(); font = new UnicodeFont(Config.FONT, 14, false, false); font.addAsciiGlyphs(); font.getEffects().add(new ColorEffect(Color.WHITE)); font.loadGlyphs(); } catch (Exception e) { sbg.addState(new ErrorReport(DrTetris.ERR_REPORT, e)); sbg.enterState(DrTetris.ERR_REPORT); } } @Override public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException { try { g.setFont(font); currentLevel.getBackground().draw(); if (currentLevel.getField().getState() == Field.NORMAL) { currentBlock.draw(Config.FIELDX, Config.FIELDY); } nextBlock.draw(Config.NEXTBLOCKX, Config.NEXTBLOCKY); currentLevel.getField().draw(Config.FIELDX, Config.FIELDY); levelNameBackground.draw(642, 273); g.drawString(challenge ? currentLevel.getName() : String.valueOf(levelCount + 1), 643, 281); if (!challenge) { g.drawString("Highest: " + highestLevel, 0, 0); } if (gameover) { gameoverOverlay.draw(); backButton.draw(); } else if (paused) { pausedOverlay.draw(); backButton.draw(); pausedOptionsButton.draw(); pausedExitButton.draw(); } } catch (Exception e) { sbg.addState(new ErrorReport(DrTetris.ERR_REPORT, e)); sbg.enterState(DrTetris.ERR_REPORT); } } @Override public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException { try { if (exception != null) { sbg.addState(new ErrorReport(DrTetris.ERR_REPORT, exception)); sbg.enterState(DrTetris.ERR_REPORT); } music.setVolume(((Options) sbg.getState(DrTetris.OPTIONS)).getVolume()); if (speed > Config.SPEEDLIMIT) { speed = Config.SPEEDLIMIT; } if (paused) { if (backButton.getClicked()) { level = 0; backButton.setClicked(false); sbg.enterState(DrTetris.MAIN_MENU); } if (pausedExitButton.getClicked()) { ((MainMenu) sbg.getState(DrTetris.MAIN_MENU)).save(sbg); gc.exit(); } if (pausedOptionsButton.getClicked()) { ((Options) sbg.getState(DrTetris.OPTIONS)).setBackgroundState(sbg.getCurrentStateID()); sbg.enterState(DrTetris.OPTIONS); pausedOptionsButton.setClicked(false); } } if (gameover) { if (backButton.getClicked()) { level = 0; backButton.setClicked(false); sbg.enterState(DrTetris.MAIN_MENU); } } if (!paused && !gameover) { currentLevel.getField().update(delta); } switch (currentLevel.getField().getState()) { case Field.CONTINUE: if (challenge) { nextLevel(); if (getLevel() >= Config.NUMBEROFLEVELS - 1) { sbg.enterState(DrTetris.WIN); } else { sbg.enterState(DrTetris.LEVEL_SELECTION); } gameover = false; paused = false; } else { level = nextLevel(); currentLevel = new Level(String.valueOf(level), challenge); currentBlock = new MovingBlock(currentLevel.nextBlock(), TileMap.ROTATENONE, Config.DEFAULTX, Config.DEFAULTY); nextBlock = currentLevel.nextBlock(); speed = (Config.BASESPEED) * (difficulty / 4 + 1); } break; case Field.END: gameover = true; break; case Field.ANIMATE: break; default: if (!paused && !gameover) { if (A) { aDelay += delta; } else { aDelay = 0; } if (D) { dDelay += delta; } else { dDelay = 0; } if (aDelay >= Config.XMOVEDELAY) { double speed = Config.BASEXSPEED + Config.SPEEDXINCREMENT * level; if (speed > Config.SPEEDXLIMIT) { speed = Config.SPEEDXLIMIT; } int xDelta = -(int) ((aDelay - Config.XMOVEDELAY) * speed); if (xDelta < 0) { for (int i = -1; i >= xDelta && currentLevel.getField().isRoom(currentBlock.getMap(), currentBlock.getX() + i, (int) currentBlock.getY(), Config.STACKTOLERANCE, false); i--) { currentBlock.modX(-1); currentLevel.getField().yLimit(currentBlock, Config.STACKTOLERANCE); } aDelay = Config.XMOVEDELAY; } } if (dDelay >= Config.XMOVEDELAY) { double speed = Config.BASEXSPEED + Config.SPEEDXINCREMENT * level; if (speed > Config.SPEEDXLIMIT) { speed = Config.SPEEDXLIMIT; } int xDelta = (int) ((dDelay - Config.XMOVEDELAY) * speed); if (xDelta > 0) { for (int i = 1; i <= xDelta && currentLevel.getField().isRoom(currentBlock.getMap(), currentBlock.getX() + i, (int) currentBlock.getY(), Config.STACKTOLERANCE, false); i++) { currentBlock.modX(1); currentLevel.getField().yLimit(currentBlock, Config.STACKTOLERANCE); } dDelay = Config.XMOVEDELAY; } } if (!currentLevel.getField().isRoom(currentBlock, Config.STACKTOLERANCE, true)) { if (stackDelay >= Config.BLOCKDELAY) { currentLevel.getField().addMap(currentBlock); currentBlock = new MovingBlock(nextBlock, TileMap.ROTATENONE, Config.DEFAULTX, Config.DEFAULTY); nextBlock = currentLevel.nextBlock(); stackDelay = 0; aDelay = 0; dDelay = 0; } else { stackDelay += delta; } } else { currentBlock.modY(delta * speed); currentLevel.getField().yLimit(currentBlock, Config.STACKTOLERANCE); stackDelay = 0; } } } } catch (Exception e) { sbg.addState(new ErrorReport(DrTetris.ERR_REPORT, e)); sbg.enterState(DrTetris.ERR_REPORT); } } @Override public void enter(GameContainer gc, StateBasedGame sbg) throws SlickException { try { music.loop(1F, ((Options) sbg.getState(DrTetris.OPTIONS)).getVolume()); difficulty = (double) ((Options) sbg.getState(DrTetris.OPTIONS)).getDifficulty(); speed = challenge ? (Config.BASESPEED) * ((difficulty / 4) + .8) : (Config.BASESPEED + Config.SPEEDINCREMENT * level) * (difficulty + .8); gameover = false; } catch (Exception e) { sbg.addState(new ErrorReport(DrTetris.ERR_REPORT, e)); sbg.enterState(DrTetris.ERR_REPORT); } } @Override public void leave(GameContainer gc, StateBasedGame sbg) throws SlickException { } @Override public void mouseWheelMoved(int i) { } @Override public void mouseClicked(int i, int i1, int i2, int i3) { } @Override public void mousePressed(int button, int x, int y) { if (paused) { backButton.mousePressed(button, x, y); pausedOptionsButton.mousePressed(button, x, y); pausedExitButton.mousePressed(button, x, y); } if (gameover) { backButton.mousePressed(button, x, y); } } @Override public void mouseReleased(int button, int x, int y) { if (paused) { backButton.mouseReleased(button, x, y); pausedOptionsButton.mouseReleased(button, x, y); pausedExitButton.mouseReleased(button, x, y); } if (gameover) { backButton.mouseReleased(button, x, y); } } @Override public void mouseMoved(int oldX, int oldY, int newX, int newY) { if (paused) { backButton.mouseMoved(oldX, oldY, newX, newY); pausedOptionsButton.mouseMoved(oldX, oldY, newX, newY); pausedExitButton.mouseMoved(oldX, oldY, newX, newY); } if (gameover) { backButton.mouseMoved(oldX, oldY, newX, newY); } } @Override public void mouseDragged(int oldX, int oldY, int newX, int newY) { if (paused) { backButton.mouseDragged(oldX, oldY, newX, newY); pausedOptionsButton.mouseDragged(oldX, oldY, newX, newY); pausedExitButton.mouseDragged(oldX, oldY, newX, newY); } if (gameover) { backButton.mouseDragged(oldX, oldY, newX, newY); } } @Override public void setInput(Input input) { } @Override public boolean isAcceptingInput() { return true; } @Override public void inputEnded() { } @Override public void inputStarted() { } @Override public void keyPressed(int key, char c) { try { if (!paused && !gameover) { switch (key) { case Keyboard.KEY_Q: currentBlock.modRotation(Block.ROTATELEFT); if (currentLevel.getField().isRoom(currentBlock, Config.STACKTOLERANCE, false)) { currentLevel.getField().yLimit(currentBlock, Config.STACKTOLERANCE); } else { currentBlock.modRotation(Block.ROTATERIGHT); } break; case Keyboard.KEY_E: currentBlock.modRotation(Block.ROTATERIGHT); if (currentLevel.getField().isRoom(currentBlock, Config.STACKTOLERANCE, false)) { currentLevel.getField().yLimit(currentBlock, Config.STACKTOLERANCE); } else { currentBlock.modRotation(Block.ROTATELEFT); } break; case Keyboard.KEY_A: if (currentLevel.getField().isRoom(currentBlock.getMap(currentBlock.getRotation()), currentBlock.getX() - 1, currentBlock.getY(), Config.STACKTOLERANCE, false)) { currentBlock.modX(-1); currentLevel.getField().yLimit(currentBlock, Config.STACKTOLERANCE); } A = true; D = false; break; case Keyboard.KEY_D: if (currentLevel.getField().isRoom(currentBlock.getMap(currentBlock.getRotation()), currentBlock.getX() + 1, currentBlock.getY(), Config.STACKTOLERANCE, false)) { currentBlock.modX(1); currentLevel.getField().yLimit(currentBlock, Config.STACKTOLERANCE); } D = true; A = false; break; case Keyboard.KEY_S: speed = 2 * (challenge ? (Config.BASESPEED) * ((difficulty / 4) + .8) : (Config.BASESPEED + Config.SPEEDINCREMENT * level) * (difficulty + .8)); break; case Keyboard.KEY_P: speed = challenge ? (Config.BASESPEED) * ((difficulty / 4) + .8) : (Config.BASESPEED + Config.SPEEDINCREMENT * level) * (difficulty + .8); paused = true; break; } } else { if (key == Keyboard.KEY_P) { paused = false; } } } catch (Exception e) { exception = e; } } @Override public void keyReleased(int key, char c) { try { if (!paused && !gameover) { switch (key) { case Keyboard.KEY_S: speed = challenge ? (Config.BASESPEED) * ((difficulty / 4) + .8) : (Config.BASESPEED + Config.SPEEDINCREMENT * level) * (difficulty + .8); break; case Keyboard.KEY_A: A = false; D = false; break; case Keyboard.KEY_D: A = false; D = false; break; } } } catch (Exception e) { exception = e; } } @Override public void controllerLeftPressed(int i) { } @Override public void controllerLeftReleased(int i) { } @Override public void controllerRightPressed(int i) { } @Override public void controllerRightReleased(int i) { } @Override public void controllerUpPressed(int i) { } @Override public void controllerUpReleased(int i) { } @Override public void controllerDownPressed(int i) { } @Override public void controllerDownReleased(int i) { } @Override public void controllerButtonPressed(int i, int i1) { } @Override public void controllerButtonReleased(int i, int i1) { } }
1f6d97a3854c086a5f0b46b97201760e10409c30
[ "Java" ]
8
Java
RHSBPASoftwareDevelopment2014/DrTetris
b0a0002d68f4fa6d02fafaf90f2d23da3ac9bc4e
2e2c8416baeec5ba05c99af054b52fa4e8f872b9
refs/heads/master
<repo_name>crowdfavorite/wp-cf-links<file_sep>/views/import.php <div class="wrap"> <?php echo cflk_nav('import'); ?> <table class="widefat" style="margin-bottom:10px;"> <thead> <tr> <th scope="col"><?php _e('Export Link Data','cf-links'); ?></th> </tr> </thead> <tbody> <tr> <td> <select id="list-export" onChange="changeExportList()"> <option value="0"><?php _e('Select List:', 'cf-links'); ?></option> <?php if (is_array($links_lists) && !empty($links_lists)) { foreach ($links_lists as $key => $value) { echo '<option value="'.$key.'">'.$value['nicename'].'</option>'; } } ?> </select> <input alt="" title="Export <?php echo $cflk['nicename']; ?>" class="thickbox button" type="button" value="<?php _e('Export', 'cf-links'); ?>" id="cflk-export-btn" /> </td> </tr> </tbody> </table> <form action="<?php echo admin_url(); ?>" method="post" id="cflk-create"> <table class="widefat"> <thead> <tr> <th scope="col"><?php _e('Enter Data From Export', 'cf-links'); ?></th> </tr> </thead> <tbody> <tr> <td> <textarea name="cflk_import" rows="15" style="width:100%;"></textarea> </td> </tr> </tbody> </table> <p class="submit" style="border-top: none;"> <input type="hidden" name="cf_action" value="cflk_insert_new" /> <input type="hidden" name="cflk_create" id="cflk_create" value="import_list" /> <input type="submit" name="submit" class="button-primary button" id="cflk-submit" value="<?php _e('Import List', 'cf-links'); ?>" /> </p> </form> </div><file_sep>/views/message-import-problem.php <div id="message_import_problem" class="updated fade" style="display: none;"> <p><?php _e('A problem has been detected while using the import. Please see highlighted items below to fix.', 'cf-links'); ?></p> </div> <file_sep>/views/message-list-error.php <div id="message" class="updated fade"> <p><?php _e('You were directed to this page in error. Please <a href="'.admin_url('options-general.php?page=cf-links.php').'">go here</a> to edit options for this plugin.', 'cf-links'); ?></p> </div> <file_sep>/views/message-updated.php <div id="message" class="updated fade"<?php echo (!empty($_GET['cflk_message']) ? '' : ' style="display:none;"'); ?>> <p><?php _e('Settings updated.', 'cf-links'); ?></p> </div> <file_sep>/views/message-list-create.php <div id="message_create" class="updated fade"> <p><?php _e('List Created.', 'cf-links'); ?></p> </div> <file_sep>/js/admin.js // When the document is ready set up our sortable with its inherant function(s) jQuery(document).ready(function() { jQuery("#cflk-list").sortable({ handle : ".handle", update : function () { jQuery("input#cflk-log").val(jQuery("#cflk-list").sortable("serialize")); }, opacity: 0.5, stop: cflk_levels_refactor }); jQuery('input[name="link_edit"]').click(function() { location.href = "options-general.php?page=cf-links.php&cflk_page=edit&link=" + jQuery(this).attr('rel'); return false; }); jQuery('tr.tr_holder').each(function() { jQuery('#message_import_problem').show(); }); jQuery('.cflk_edit_link').live('click', function(e) { editNicename(); e.preventDefault(); }); jQuery("#cflk-nicename-submit").live('click', function() { var cflk_key = jQuery("input[name=cflk_key]").val(); var cflk_nicename_value = jQuery("input[name=cflk_nicename]").val(); cflkAJAXSaveNicename(cflk_key, cflk_nicename_value); return false; }); jQuery(".cflk-show").click(function(e) { var _this = jQuery(this); var id = _this.attr('id').replace('cflk-show-', ''); jQuery("#"+id+"-TemplateTag").slideToggle(); e.preventDefault(); }); jQuery(".cflk-hide").click(function(e) { var _this = jQuery(this); var id = _this.attr('id').replace('cflk-hide-', ''); jQuery("#"+id+"-TemplateTag").slideUp(); e.preventDefault(); }); }); function deleteLink(cflk_key,linkID) { if (confirm('Are you sure you want to delete this?')) { if (cflkAJAXDeleteLink(cflk_key,linkID)) { jQuery('#listitem_'+linkID).remove(); jQuery("#message_delete").show(); cflk_levels_refactor(); } return false; } } function deleteCreated(linkID) { if (confirm('Are you sure you want to delete this?')) { jQuery('#listitem_'+linkID).remove(); return false; } } function deleteMain(cflk_key) { if (confirm('Are you sure you want to delete this?')) { if (cflkAJAXDeleteMain(cflk_key)) { jQuery('#link_main_'+cflk_key).remove(); jQuery("#message_delete").show(); } return false; } } function editNicename() { jQuery('#cflk_nicename_h3').hide(); jQuery(".cflk_edit_link").hide(); jQuery('#cflk_nicename_input').show(); jQuery("#cflk_nicename").focus().select(); return false; } function cancelNicename() { jQuery('#cflk_nicename_input').hide(); jQuery('#cflk_nicename_h3').show(); jQuery(".cflk_edit_link").show(); } function editTitle(key) { jQuery('#cflk_'+key+'_title_edit').hide(); jQuery('#cflk_'+key+'_title_input').show(); } function clearTitle(key) { jQuery('#cflk_'+key+'_title_input').hide(); jQuery('#cflk_'+key+'_title_edit').show(); jQuery('#cflk_'+key+'_title').val(''); } function editDescription() { jQuery('#description_text').hide(); jQuery('#description_edit').show(); jQuery("textarea[name=cflk_description]").focus().select(); jQuery('#description_edit_btn').hide(); jQuery('#description_cancel_btn').show(); } function cancelDescription() { jQuery('#description_text').show(); jQuery('#description_edit').hide(); jQuery('#description_edit_btn').show(); jQuery('#description_cancel_btn').hide(); } function showLinkType(key) { var type = jQuery('#cflk_'+key+'_type option:selected').val(); jQuery('#'+type+'_'+key).show().siblings().hide(); } function addLink() { var id = new Date().valueOf(); var section = id.toString(); var html = jQuery('#newitem_SECTION').html().replace(/###SECTION###/g, section); jQuery('#cflk-list').append(html); jQuery('#listitem_'+section).show().find('td.link-value span:first-child').show(); // activates level indent buttons cflk_set_level_buttons('listitem_'+section); cflk_levels_refactor(); } function changeExportList() { var list = jQuery('#list-export').val(); var btn = jQuery('#cflk-export-btn'); btn.attr('alt', 'index.php?cflk_page=export&height=400&width=600&link='+list); } // Link Level Functionality // initialize the list for multiple levels jQuery(function(){ // prep cflk_set_level_buttons(); cflk_levels_refactor(); }); // initialize the level buttons function cflk_set_level_buttons(parent_id) { // add actions to the rest of the list-level modifiers if(parent_id == undefined) { parent_id = 'cflk-list'; } jQuery('#' + parent_id + ' button.level-decrement, #' + parent_id + ' button.level-increment').click(function() { clicked = jQuery(this); target = clicked.parents('div').children('input'); item_id = clicked.parents('li').attr('id').replace('listitem_',''); if (clicked.hasClass('level-increment') && cflk_can_increment_level(target)) { cflk_update_link_level(target,+1); } else if (clicked.hasClass('level-decrement') && cflk_can_decrement_level(target)) { cflk_update_link_level(target,-1); } cflk_levels_refactor(); return false; }); } // toggle the buttons visible state for wether it can be used or not function cflk_toggle_button_usability(current,blank_button) { jQuery(current).find('td.link-level button').each(function(i){ _this = jQuery(this); if(blank_button) { _this.css('opacity',0).addClass('disabled'); } else if(_this.hasClass('level-decrement') && !cflk_can_decrement_level(_this.parents('div').children('input'))) { _this.css('opacity',0.25).addClass('disabled'); } else if(_this.hasClass('level-increment') && !cflk_can_increment_level(_this.parents('div').children('input'))) { _this.css('opacity',0.25).addClass('disabled'); } else { _this.css('opacity',1).removeClass('disabled'); } }); } // move the link function cflk_update_link_level(obj,amount) { obj.val(parseInt(obj.val())+amount); obj.parents('li').attr('class','level-'+obj.val()); } // figure out if the item is allowed to go indent function cflk_can_increment_level(target) { // make sure we are no more than 1 more than the previous sibling prev_value = parseInt(target.parents('li').prev().find('td.link-level input.link-level-input').val()); if(parseInt(target.val())+1 > prev_value+1) { return false; } return true; } // figure out if the item is allowed to outdent function cflk_can_decrement_level(target) { if(target.val() == 0) { return false; } return true; } // refactor the list levels so that nobody is more than 1 level deeper than its parent function cflk_levels_refactor() { jQuery('#cflk-list li').each(function(i){ current = jQuery(this); var current_val = parseInt(current.find('td.link-level input.link-level-input').val()); // handle first row if(i == 0) { if(current_val > 0) { cflk_update_link_level(current.find('td.link-level input.link-level-input'),'-' + parseInt(current_val)+1); current.find('td.link-level input.link-level-input').val(0); } cflk_toggle_button_usability(current,true); prev = current; return; } // handle not first rows var prev_val = parseInt(prev.find('td.link-level input.link-level-input').val()); if(current_val > prev_val+1) { diff = current_val - (prev_val+1); cflk_update_link_level(current.find('td.link-level input.link-level-input'),parseInt('-'+diff)); } cflk_toggle_button_usability(current); prev = current; }); } // provide modal edit abilities function cflk_edit_select_modal(id,value,listname) { var container = jQuery('#' + listname + '_' + id + ' .select-modal-display'); var hidden = jQuery('#cflk-' + listname + '-' + id + '-value'); var currentvalue = hidden.val(); var value_id = hidden.attr('id'); var value_name = hidden.attr('name'); container.hide(); hidden.remove(); var select_container = jQuery('#' + listname + '-modal').clone(); select_container.find('select').attr('name',value_name).attr('id',value_id); select_container.find('option').each(function(){ this.selected = this.value == currentvalue; }); select_container.css({'display':'inline'}).insertAfter(container) .children('span#' + listname + '_list').css({'display':'inline'}) .siblings('input.modal-done').click(function(){ _this = jQuery(this); var new_value = jQuery('#cflk-' + listname + '-' + id + '-value').val(); var new_hidden = jQuery('<input type="hidden">') .attr('name',value_name) .attr('id',value_id) .val(new_value); container.append(new_hidden); jQuery('#' + listname + '_' + id + ' .select-modal-display').find('span').html(_this.siblings('span').children('select').find('option:selected').text()); select_container.remove(); select_container = null; // possibly feeble attempt at keeping memory use low container.show(); }); } // AJAX Functions function cflkAJAXDeleteLink(cflk_key, key) { var url = jQuery("#cflk-form").attr('action'); jQuery.post(url, { cf_action: 'cflk_delete_key', key: key, cflk_key: cflk_key }); return true; } function cflkAJAXDeleteMain(cflk_key) { var url = jQuery("#cflk-form").attr('action'); jQuery.post(url, { cf_action: 'cflk_delete', cflk_key: cflk_key }); return true; } function cflkAJAXSaveNicename(cflk_key, cflk_nicename) { var url = jQuery("#cflk-form").attr('action'); jQuery.post(url, { cf_action: 'cflk_edit_nicename', cflk_key: cflk_key, cflk_nicename: cflk_nicename }); jQuery("#cflk_nicename_text").text(cflk_nicename); jQuery("#cflk_nicename").val(cflk_nicename); jQuery("#cflk_nicename_h3").text(cflk_nicename); jQuery("#message").show(); cancelNicename(); return false; } <file_sep>/views/message-list-delete.php <div id="message_delete" class="updated fade"> <p><?php _e('List Deleted.', 'cf-links'); ?></p> </div> <file_sep>/views/dialog.php <html> <head> <title><?php _e('Select CF Links List', 'cf-links'); ?></title> <script type="text/javascript" src="<?php echo includes_url('js/jquery/jquery.js'); ?>"></script> <script type="text/javascript" src="<?php echo includes_url('js/tinymce/tiny_mce_popup.js'); ?>"></script> <script type='text/javascript' src='<?php echo includes_url('js/quicktags.js'); ?>'></script> <script type="text/javascript"> ;(function($) { $(function() { $(".cflk-list-link").live('click', function(e) { var key = $(this).attr('rel'); cflk_insert(key); e.preventDefault(); }); }); })(jQuery); function cflk_insert(key) { tinyMCEPopup.execCommand("mceBeginUndoLevel"); tinyMCEPopup.execCommand('mceInsertContent', false, '[cflk name="'+key+'"]'); tinyMCEPopup.execCommand("mceEndUndoLevel"); tinyMCEPopup.close(); return false; } </script> <style type="text/css"> .cflk-list { padding-left:10px; } </style> </head> <body> <?php if (is_array($cflk_list) && !empty($cflk_list)) { echo ' <p>'.__('Click on the name of the CF Links List below to add it to the content of the current post.', 'cf-links').'</p> <ul class="cflk-list"> '; foreach ($cflk_list as $cflk) { $options = maybe_unserialize(maybe_unserialize($cflk->option_value)); ?> <li> <a href="#" rel="<?php echo esc_attr($cflk->option_name); ?>" class="cflk-list-link"><?php echo esc_html($options['nicename']); ?></a> </li> <?php } echo '</ul>'; } else { echo '<p>'.__('No CF Links Lists have been setup. Please setup a list before proceeding.', 'cf-links').'</p>'; } ?> </body> </html><file_sep>/views/options-form.php <div class="wrap"> <?php echo cflk_nav('main'); ?> <form action="<?php echo admin_url(); ?>" method="post" id="cflk-form"> <table class="widefat"> <thead> <tr> <th scope="col"><?php _e('Links List', 'cf-links'); ?></th> <th scope="col" style="text-align: center;" width="80px"><?php _e('Links Count', 'cf-links'); ?></th> <th scope="col" style="text-align: center;" width="60px"><?php _e('Edit', 'cf-links'); ?></th> <th scope="col" style="text-align: center;" width="60px"><?php _e('Delete', 'cf-links'); ?></th> </tr> </thead> <tbody> <?php if (count($form_data) > 0) { foreach ($form_data as $key => $info) { ?> <tr id="link_main_<?php echo $key; ?>"> <td style="vertical-align: middle;"> <a href="<?php echo admin_url('options-general.php?page=cf-links.php&cflk_page=edit&link='.$key); ?>" style="font-weight: bold; font-size: 20px;"><?php echo $info['nicename']; ?></a> <br /> <?php _e('Show: ','cf-links'); ?><a href="#" id="cflk-show-<?php echo $key; ?>" class="cflk-show"><?php _e('Template Tag &amp; Shortcode','cf-links'); ?></a> <div id="<?php echo $key; ?>-TemplateTag" class="cflk-codebox" style="display:none;"> <div style="float: left;"> <?php _e('Template Tag: ', 'cf-links'); ?><code>&lt;?php if (function_exists("cflk_links")) { cflk_links("'.$key.'"); } ?&gt;</code> <br /> <?php _e('Shortcode: ', 'cf-links'); ?><code>[cflk_links name="<?php echo $key; ?>"]</code> </div> <div style="float: right;"> <a href="#" id="cflk-hide-<?php echo $key; ?>" class="cflk-hide"><?php _e('Hide','cf-links'); ?></a> </div> <div class="clear"></div> </div> </td> <td style="text-align: center; vertical-align: middle;" width="80px"> <?php echo $info['count']; ?> </td> <td style="text-align: center; vertical-align: middle;" width="60px"> <p class="submit" style="border-top: none; padding: 0; margin: 0;"> <input type="button" name="link_edit" value="<?php _e('Edit', 'cf-links'); ?>" class="button-secondary edit" rel="<?php echo $key; ?>" /> </p> </td> <td style="text-align: center; vertical-align: middle;" width="60px"> <p class="submit" style="border-top: none; padding: 0; margin: 0;"> <input type="button" id="link_delete_<?php echo $key; ?>" onclick="deleteMain('<?php echo $key; ?>')" value="<?php _e('Delete', 'cf-links'); ?>" /> </p> </td> </tr> <?php } } ?> </tbody> </table> </form> </div><file_sep>/views/new-list.php <div class="wrap"> <?php echo cflk_nav('create'); ?> <form action="<?php echo admin_url(); ?>" method="post" id="cflk-create"> <table class="widefat"> <thead> <tr> <th scope="col"><?php _e('Link List Name', 'cf-links'); ?></th> </tr> </thead> <tbody> <tr> <td> <input type="text" name="cflk_nicename" size="55" /> </td> </tr> </tbody> </table> <p class="submit" style="border-top: none;"> <input type="hidden" name="cf_action" value="cflk_insert_new" /> <input type="hidden" name="cflk_create" id="cflk_create" value="new_list" /> <input type="submit" name="submit" id="cflk-submit" value="<?php _e('Create List', 'cf-links'); ?>" /> </p> </form> </div> <file_sep>/cf-links.php <?php /* Plugin Name: CF Links Plugin URI: http://crowdfavorite.com Description: Advanced tool for adding collections of links, including pages, posts, and external URLs. Version: 1.4.4 Author: Crowd Favorite Author URI: http://crowdfavorite.com */ // ini_set('display_errors', '1'); ini_set('error_reporting', E_ALL); /** * * WP Admin Handling Functions * */ // Constants define('CFLK_VERSION', '1.4.4'); define('CFLK_DIR', trailingslashit(plugin_dir_path(__FILE__))); //plugin_dir_url seems to be broken for including in theme files if (file_exists(trailingslashit(get_template_directory()).'plugins/'.basename(dirname(__FILE__)))) { define('CFLK_DIR_URL', trailingslashit(trailingslashit(get_bloginfo('template_url')).'plugins/'.basename(dirname(__FILE__)))); } else { define('CFLK_DIR_URL', trailingslashit(plugins_url(basename(dirname(__FILE__))))); } load_plugin_textdomain('cf-links'); $cflk_types = array(); $cflk_inside_widget = false; /** * Adds all of the link types and their data * * @return void */ function cflk_link_types() { global $wpdb, $cflk_types, $blog_id; $pages = get_pages(array('hierarchical' => 1)); $categories = get_categories('get=all'); $authors = cflk_get_authors(); $page_data = array(); $category_data = array(); $author_data = array(); $wordpress_data = array(); $blog_data = array(); $site_data = array(); foreach ($pages as $page) { $page_data[$page->ID] = array( 'link' => $page->ID, 'description' => $page->post_title, 'ancestors' => get_post_ancestors($page) ); } foreach ($categories as $category) { $category_data[$category->slug] = array( 'link' => $category->term_id, 'description' => $category->name, 'count' => $category->count ); } foreach ($authors as $author) { $author_data[$author['login']] = array( 'link' => $author['id'], 'description' => $author['display_name'] ); } $wordpress_data = array( 'home' => array( 'link' => 'home', 'description' => __('Home','cf-links'), ), 'loginout' => array( 'link' => 'loginout', 'description' => __('Log In/Out','cf-links'), ), 'register' => array( 'link' => 'register', 'description' => __('Register/Site Admin','cf-links'), ), 'profile' => array( 'link' => 'profile', 'description' => __('Profile','cf-links'), ), 'main_rss' => array( 'link' => 'main_rss', 'description' => __('Site RSS','cf-links'), ), ); if (function_exists('get_blog_list')) { $sites = $wpdb->get_results("SELECT id, domain FROM $wpdb->site ORDER BY ID ASC", ARRAY_A); if (is_array($sites) && count($sites)) { foreach ($sites as $site) { $site_id = $site['id']; $blogs = $wpdb->get_results($wpdb->prepare("SELECT blog_id FROM $wpdb->blogs WHERE site_id = '%s' AND archived = '0' AND spam = '0' AND deleted = '0' ORDER BY blog_id ASC", $site_id), ARRAY_A); if (is_array($blogs)) { foreach ($blogs as $blog) { $details = get_blog_details($blog['blog_id']); $description = ''; if ($details->blog_id != $site['id']) { $description = '&mdash; '.$details->blogname; } else { $description = $details->blogname; } $blog_data[$details->blog_id] = array( 'link' => $details->blog_id, 'description' => $description, ); } } } } } $cflk_types = array( 'url' => array( 'type' => 'url', 'nicename' => __('URL','cf-links'), 'input' => 'text', 'data' => __('ex: http://example.com', 'cf-links'), ), 'rss' => array( 'type' => 'rss', 'nicename' => __('RSS','cf-links'), 'input' => 'text', 'data' => __('ex: http://example.com/feed', 'cf-links'), ), 'page' => array( 'type' => 'page', 'nicename' => __('Page','cf-links'), 'input' => 'select', 'data' => $page_data ), 'category' => array( 'type' => 'category', 'nicename' => __('Category', 'cf-links'), 'input' => 'select', 'data' => $category_data ), 'author' => array( 'type' => 'author', 'nicename' => __('Author', 'cf-links'), 'input' => 'select', 'data' => $author_data ), 'author_rss' => array( 'type' => 'author_rss', 'nicename' => __('Author RSS', 'cf-links'), 'input' => 'select', 'data' => $author_data ), 'wordpress' => array( 'type' => 'wordpress', 'nicename' => __('Wordpress', 'cf-links'), 'input' => 'select', 'data' => $wordpress_data ), ); if (function_exists('get_blog_list')) { $blog_type = array( 'blog' => array( 'type' => 'blog', 'nicename' => __('Blog','cf-links'), 'input' => 'select', 'data' => $blog_data ), ); $cflk_types = array_merge($cflk_types, $blog_type); } // Allow other link types to be added $cflk_types = apply_filters('cflk-types',$cflk_types); } // Only run this function on the proper pages, since we don't need all of this data processed anywhere else if (isset($_GET['cflk_page']) && $_GET['cflk_page'] == 'edit') { add_action('admin_init', 'cflk_link_types'); } /** * grab list of authors * pulls anyone with capabilities higher than subscriber * * @return array - list of authors */ function cflk_get_authors() { global $wpdb; $sql = " SELECT DISTINCT u.ID, u.user_nicename, u.display_name, u.user_login from {$wpdb->users} AS u, {$wpdb->usermeta} AS um WHERE u.user_login <> 'admin' AND u.ID = um.user_id AND um.meta_key LIKE '{$wpdb->prefix}capabilities' AND um.meta_value NOT LIKE '%subscriber%' ORDER BY u.user_nicename "; $results = array(); $users = $wpdb->get_results(apply_filters('cflk_get_authors_sql', $sql)); foreach ($users as $u) { $results[$u->ID] = array( 'id' => $u->ID, 'display_name' => $u->display_name, 'login' => $u->user_login ); } return apply_filters('cflk_get_authors', $results); } function cflk_menu_items() { add_options_page( __('CF Links', 'cf-links') , __('CF Links', 'cf-links') , 'manage_options' , basename(__FILE__) , 'cflk_check_page' ); } add_action('admin_menu', 'cflk_menu_items'); function cflk_check_page() { $check_page = ''; if (isset($_GET['cflk_page'])) { $check_page = $_GET['cflk_page']; } switch ($check_page) { case 'edit': cflk_edit(); break; case 'create': cflk_new(); break; case 'import': cflk_import(); break; case 'main': default: cflk_options_form(); break; } } function cflk_request_handler() { if (current_user_can('manage_options') && !empty($_POST['cf_action'])) { switch ($_POST['cf_action']) { case 'cflk_update_settings': $link_data = array(); if (!empty($_POST['cflk']) && is_array($_POST['cflk'])) { $link_data = stripslashes_deep($_POST['cflk']); } if (!empty($_POST['cflk_key']) && !empty($_POST['cflk_nicename'])) { cflk_process($link_data, $_POST['cflk_key'], $_POST['cflk_nicename'], $_POST['cflk_description']); } wp_redirect(admin_url('options-general.php?page=cf-links.php&cflk_page=edit&link='.urlencode($_POST['cflk_key']).'&cflk_message=updated')); die(); break; case 'cflk_delete': if (!empty($_POST['cflk_key'])) { cflk_delete($_POST['cflk_key']); } die(); break; case 'cflk_delete_key': if (!empty($_POST['cflk_key']) && !empty($_POST['key'])) { cflk_delete_key($_POST['cflk_key'], $_POST['key']); } die(); break; case 'cflk_insert_new': $nicename = ''; $description = ''; $data = ''; if (!empty($_POST['cflk_create']) && $_POST['cflk_create'] == 'new_list') { if (!empty($_POST['cflk_nicename'])) { $nicename = $_POST['cflk_nicename']; $data = array(); } } if (!empty($_POST['cflk_create']) && $_POST['cflk_create'] == 'import_list') { if (!empty($_POST['cflk_import'])) { $import = maybe_unserialize(stripslashes(unserialize(urldecode($_POST['cflk_import'])))); $nicename = $import['nicename']; $description = $import['description']; $data = $import['data']; } } if ($nicename != '' && is_array($data)) { $cflk_key = cflk_insert_new($nicename, $description, $data); } wp_redirect(admin_url('options-general.php?page=cf-links.php&cflk_page=edit&link='.$cflk_key)); die(); break; case 'cflk_edit_nicename': if (!empty($_POST['cflk_nicename']) && !empty($_POST['cflk_key'])) { cflk_edit_nicename($_POST['cflk_key'], $_POST['cflk_nicename']); } die(); break; default: break; } } if (!empty($_GET['cflk_page'])) { switch ($_GET['cflk_page']) { case 'dialog': cflk_dialog(); break; case 'export': cflk_export_list($_GET['link']); break; default: break; } } } add_action('wp_loaded', 'cflk_request_handler'); add_action('wp_ajax_cflk_update_settings', 'cflk_request_handler'); function cflk_resources_handler() { if (!empty($_GET['cf_action'])) { switch ($_GET['cf_action']) { case 'cflk_admin_js': cflk_admin_js(); die(); break; case 'cflk_admin_css': cflk_admin_css(); die(); break; case 'cflk_front_js': cflk_front_js(); die(); break; } } } add_action('init', 'cflk_resources_handler', 1); function cflk_admin_css() { header('Content-type: text/css'); echo file_get_contents(CFLK_DIR.'css/admin.css'); echo apply_filters('cflk_admin_css', ''); exit(); } function cflk_front_js() { ?> <script type="text/javascript"> jQuery(document).ready(function() { //jQuery('.cflk-opennewwindow a').attr('target','_blank'); jQuery('.cflk-opennewwindow a').click(function(){ window.open(this.href); return false; }); }); </script> <?php } function cflk_admin_js() { header('Content-type: text/javascript'); echo file_get_contents(CFLK_DIR.'js/admin.js'); echo apply_filters('cflk_admin_js', ''); exit(); } /** * * Enqueue the CSS/JS in the proper place * */ if (is_admin() && !empty($_GET['page']) && $_GET['page'] == basename(__FILE__)) { wp_enqueue_script('jquery'); wp_enqueue_script('jquery-ui-core'); wp_enqueue_script('jquery-ui-sortable'); wp_enqueue_script('cflk-admin-js', site_url('index.php?cf_action=cflk_admin_js'), array('jquery', 'jquery-ui-core', 'jquery-ui-sortable'), CFLK_VERSION); wp_enqueue_style('cflk-admin-css', site_url('index.php?cf_action=cflk_admin_css'), array(), CFLK_VERSION); if (!empty($_GET['cflk_page']) && $_GET['cflk_page'] == 'import') { wp_enqueue_script('thickbox'); wp_enqueue_style('thickbox', site_url('wp-includes/js/thickbox/thickbox.css'), array()); } } /** * * CF Links Admin Interface Functions * */ /** * This is the main options page display for the plugin. This page displays information about all of the lists that have been created * * @return void */ function cflk_options_form() { $cflk_list = cflk_get_list_links(); $form_data = array(); if (is_array($cflk_list) && !empty($cflk_list)) { foreach ($cflk_list as $key => $cflk) { $form_data[$key] = array('nicename' => $cflk['nicename'], 'count' => $cflk['count']); } } if (!empty($_GET['cflk_message'])) { switch ($_GET['cflk_message']) { case 'create': include('views/message-list-create.php'); break; case 'delete': include('views/message-list-delete.php'); break; } } include('views/options-form.php'); } /** * This is the new List form. * * @return void */ function cflk_new() { include('views/new-list.php'); } /** * This is the Import. It provides the ability Import a list from another location, and display list data to export to another location * * @return void */ function cflk_import() { $links_lists = cflk_get_list_links(); include('views/import.php'); } /** * This is the List Edit form. This displays the large form for editing all of the links in a list * * @return void */ function cflk_edit() { if (empty($_GET['link'])) { include('views/message-list-error.php'); return; } global $wpdb, $cflk_types; $cflk_key = $_GET['link']; $cflk = maybe_unserialize(get_option($cflk_key)); is_array($cflk) ? $cflk_count = count($cflk) : $cflk_count = 0; include('views/edit.php'); } function cflk_nav($page = '', $list = '') { $main_text = ''; $add_text = ''; $import_text = ''; switch ($page) { case 'main': $main_text = 'class="current"'; break; case 'create': $add_text = ' class="current"'; break; case 'import': $import_text = ' class="current"'; break; default: break; } ob_start(); include('views/nav.php'); $cflk_nav = ob_get_clean(); return $cflk_nav; } function cflk_edit_select($type) { $select = array(); $select['url_show'] = 'style="display: none;"'; $select['url_select'] = ''; $select['rss_show'] = 'style="display: none;"'; $select['rss_select'] = ''; $select['page_show'] = 'style="display: none;"'; $select['page_select'] = ''; $select['category_show'] = 'style="display: none;"'; $select['category_select'] = ''; $select['wordpress_show'] = 'style="display: none;"'; $select['wordpress_select'] = ''; $select['author_show'] = 'style="display: none;"'; $select['author_select'] = ''; $select['author_rss_show'] = 'style="display: none;"'; $select['author_rss_select'] = ''; $select['blog_show'] = 'style="display: none;"'; $select['blog_select'] = ''; switch ($type) { case 'url': $select['url_show'] = 'style=""'; $select['url_select'] = 'selected=selected'; break; case 'rss': $select['rss_show'] = 'style=""'; $select['rss_select'] = 'selected=selected'; break; case 'page': $select['page_show'] = 'style=""'; $select['page_select'] = 'selected=selected'; break; case 'category': $select['category_show'] = 'style=""'; $select['category_select'] = 'selected=selected'; break; case 'wordpress': $select['wordpress_show'] = 'style=""'; $select['wordpress_select'] = 'selected=selected'; break; case 'author': $select['author_show'] = 'style=""'; $select['author_select'] = 'selected=selected'; break; case 'author_rss': $select['author_rss_show'] = 'style=""'; $select['author_rss_select'] = 'selected=selected'; break; case 'blog': $select['blog_show'] = 'style=""'; $select['blog_select'] = 'selected=selected'; break; default: $select['url_show'] = 'style=""'; $select['url_select'] = 'selected=selected'; break; } return apply_filters('cflk-edit-select',$select,$type); } function cflk_get_type_input($type_array, $show, $key, $show_count, $value) { $return = ''; extract($type_array); $return .= '<span id="'.$type.'_'.$key.'" '.($show == $nicename ? '' : 'style="display: none;"').'>'; switch ($input) { case 'text': $return .= '<input type="text" name="cflk['.$key.']['.$type.']" id="cflk_'.$key.'_'.$type.'" size="50" value="'.strip_tags($value).'" /><br />'.$data; break; case 'select': $return .= '<select name="cflk['.$key.']['.$type.']" id="cflk_'.$key.'_'.$type.'" style="max-width: 410px; width: 90%;">'; foreach ($data as $info) { $selected = ''; $count_text = ''; if ($value == $info['link']) { $selected = ' selected=selected'; } if ($show_count == 'yes' && isset($info['count'])) { $count_text = ' ('.$info['count'].')'; } if($type == 'page' && isset($info['ancestors']) && count($info['ancestors'])) { $info['description'] = str_repeat('&nbsp;',count($info['ancestors'])*3).$info['description']; } $return .= '<option value="'.$info['link'].'"'.$selected.'>'.$info['description'].$count_text.'</option>'; } if($value == 'HOLDER' && $show == 'style=""') { $return .= '<option value="HOLDER" selected=selected>'.__('IMPORTED ITEM DOES NOT EXIST, PLEASE CHOOSE ANOTHER ITEM', 'cf-links').'</option>'; } $return .= '</select>'; if ($value == 'HOLDER' && $show == 'style=""') { switch ($type) { case 'page': $type_show = 'Page'; break; case 'category': $type_show = 'Category'; break; case 'author': $type_show = 'Author'; break; case 'author_rss': $type_show = 'Author RSS'; break; } $return .= '<br /><span id="holder_'.$type.'_'.$key.'" style="font-weight:bold;">'.__('Imported item ID does not exist in the system.<br />Please create a new '.$type_show.', then select it from the list above.','cf-links').'</span>'; } break; case 'select-modal': foreach($data as $item) { if($item['link'] == $value) { $display = $item['description']; break; } } $return .= ' <input type="hidden" name="cflk['.$key.']['.$type.']" id="cflk-'.$type.'-'.$key.'-value" value="'.strip_tags($value).'"/> <div class="select-modal-display"><span>'.$display.'</span> <input type="button" class="button" id="edit-'.$key.'-'.$type.'" name="edit-'.$key.'-'.$type.'" value="Edit" onclick="cflk_edit_select_modal(\''.$key.'\',\''.$value.'\',\''.$type.'\'); return false;"/></div> '; break; } $return .= '</span>'; return $return; } /** * * CF Links TinyMCE Handling Functions * */ function cflk_dialog() { global $wpdb; $cflk_list = $wpdb->get_results($wpdb->prepare("SELECT option_name, option_value FROM $wpdb->options WHERE option_name LIKE %s",'cfl-%')); include('views/dialog.php'); die(); } function cflk_register_button($buttons) { array_push($buttons, '|', "cfLinksBtn"); return $buttons; } function cflk_add_tinymce_plugin($plugin_array) { $plugin_array['cflinks'] = CFLK_DIR_URL.'js/editor_plugin.js'; return $plugin_array; } function cflk_addtinymce() { if (!current_user_can('edit_posts') && !current_user_can('edit_pages')) return; if (get_user_option('rich_editing') == 'true') { add_filter("mce_external_plugins", "cflk_add_tinymce_plugin"); add_filter('mce_buttons', 'cflk_register_button'); } } add_action('init', 'cflk_addtinymce'); /** * * CF Links Data Handling Functions * */ function cflk_process($cflk_data = array(), $cflk_key = '', $cflk_nicename = '', $cflk_description = '') { if ($cflk_key == '' && $cflk_nicename == '') { return false; } $new_data = array(); foreach ($cflk_data as $key => $info) { if ($info['type'] == '') { unset($cflk_data[$key]); } else { $opennew = false; $type = $info['type']; if (isset($info['opennew'])) { $opennew = true; } $nofollow = false; if (isset($info['nofollow'])) { $nofollow = true; } if (isset($type) && $type != '') { $new_data[] = array( 'title' => stripslashes($info['title']), 'type' => $type, 'link' => stripslashes($info[$type]), 'cat_posts' => ($type == 'category' && isset($info['category_posts']) && $info['category_posts'] != '' ? true : false), 'level' => intval($info['level']), 'nofollow' => $nofollow, 'opennew' => $opennew ); } } } $settings = array( 'key' => $cflk_key, 'nicename' => stripslashes($cflk_nicename), 'description' => stripslashes($cflk_description), 'data' => $new_data ); $settings = apply_filters('cflk_save_list_settings',$settings); do_action('cflk_save_list', $settings); update_option($cflk_key, $settings); } function cflk_delete_key($cflk_key, $remove_key) { $cflk = maybe_unserialize(get_option($cflk_key)); if(isset($cflk['data'][$remove_key])) { unset($cflk['data'][$remove_key]); } update_option($cflk_key, $cflk); return true; } function cflk_delete($cflk_key) { if ($cflk_key == '') { return false; } $delete_keys = array(); $widgets = maybe_unserialize(get_option('cf_links_widget')); $sidebars = maybe_unserialize(get_option('sidebars_widgets')); if (is_array($widgets) && is_array($sidebars)) { foreach ($widgets as $key => $widget) { if ($widget['select'] == $cflk_key) { unset($widgets[$key]); foreach ($sidebars as $sidebars_key => $sidebar) { if (is_array($sidebar)) { foreach ($sidebar as $sb_key => $value) { if($value == 'cf-links-'.$key) { unset($sidebar[$sb_key]); } } $sidebars[$sidebars_key] = $sidebar; } } update_option('sidebars_widgets', $sidebars); } } } do_action('cflk_delete_list',$cflk_key); $res = delete_option($cflk_key); // send response header('Content-type: text/javascript'); ob_end_clean(); if($res) { //echo '{"success":true}'; // would like to use this, but SACK doesn't seem to like json echo '1'; } else { //echo '{"success":false}'; echo '0'; } exit; } function cflk_insert_new($nicename = '', $description = '', $data = array(), $insert_key = false) { if ($nicename == '') { return false; } // check to see if a specific key was requested and if that specific key already exists if($insert_key !== false) { $check_list = get_option($key); if(is_array($check_list)) { return false; } } $pages = $categories = $authors = $blogs = array(); $page_object = get_pages(); foreach ($page_object as $page) { array_push ($pages, $page->ID); } $category_object = get_categories('get=all'); foreach ($category_object as $category) { array_push ($categories, $category->term_id); } $author_object = get_users_of_blog($wpdb->blog_id); foreach ($author_object as $author) { array_push ($authors, $author->user_id); } if (function_exists ('get_blog_list')) { $blog_object = get_blog_list(); foreach ($blog_object as $key => $blog) { array_push ($blogs, $blog['blog_id']); } } $check_name = cflk_name_check(stripslashes($nicename)); foreach ($data as $key => $item) { if ($item['type'] == 'page') { if(!in_array($item['link'],$pages)) { $item['link'] = 'HOLDER'; } } if ($item['type'] == 'category') { if(!in_array($item['link'],$categories)) { $item['link'] = 'HOLDER'; } } if ($item['type'] == 'author') { if(!in_array($item['link'],$authors)) { $item['link'] = 'HOLDER'; } } if ($item['type'] == 'author_rss') { if(!in_array($item['link'],$authors)) { $item['link'] = 'HOLDER'; } } if (function_exists('get_blog_list')) { if ($item['type'] == 'blog') { if(!in_array($item['link'],$blogs)) { $item['link'] = 'HOLDER'; } } } $data[$key]['link'] = $item['link']; } $settings = array('nicename' => $check_name[1], 'description' => $description, 'data' => $data); // if key hasn't already been defined, pull the value from the name check routine if(!$insert_key) { $insert_key = $check_name[0]; } // insert and return add_option($insert_key, $settings); return $insert_key; } function cflk_name_check($name) { global $wpdb; $i=1; $option_name = 'cfl-'.sanitize_title($name); $title = $name; $original_option = $option_name; $original_title = $title; while(count($wpdb->get_results($wpdb->prepare("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '%s'", $option_name))) > 0) { $option_name = $original_option.$i; $title = $original_title.$i; $i++; } return array($option_name,$title); } function cflk_edit_nicename($cflk_key = '', $cflk_nicename = '') { if ($cflk_key != '' && $cflk_nicename != '') { $cflk = maybe_unserialize(get_option($cflk_key)); if ($cflk['nicename'] != $cflk_nicename) { $cflk['nicename'] = stripslashes($cflk_nicename); } update_option($cflk_key, $cflk); } } function cflk_get_list_links($blog = 0) { global $wpdb, $blog_id; // if we're on MU and another blog's details have been requested, change the options table assignment if (!is_null($blog_id) && $blog != 0) { $options = 'wp_'.$wpdb->escape($blog).'_options'; } else { $options = $wpdb->options; } $cflk_list = $wpdb->get_results($wpdb->prepare("SELECT option_name, option_value FROM {$options} WHERE option_name LIKE %s", 'cfl-%')); $return = array(); if (is_array($cflk_list)) { foreach ($cflk_list as $cflk) { $options = maybe_unserialize(maybe_unserialize($cflk->option_value)); $return[$cflk->option_name] = array( 'nicename' => $options['nicename'], 'description' => $options['description'], 'count' => count($options['data']), ); } return $return; } return false; } /** * * CF Links Widget Handling Functions * */ function cflk_widget( $args, $widget_args = 1 ) { global $cflk_inside_widget; $cflk_inside_widget = true; extract( $args, EXTR_SKIP ); if ( is_numeric($widget_args) ) $widget_args = array( 'number' => $widget_args ); $widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) ); extract( $widget_args, EXTR_SKIP ); $options = get_option('cf_links_widget'); if ( !isset($options[$number]) ) return; $title = $options[$number]['title']; $select = $options[$number]['select']; echo $before_widget; if (!empty($title)) { echo $before_title . $title . $after_title; } echo cflk_get_links($select); echo $after_widget; $cflk_inside_widget = false; } function cflk_widget_control( $widget_args = 1 ) { global $wp_registered_widgets, $wpdb; static $updated = false; if ( is_numeric($widget_args) ) $widget_args = array( 'number' => $widget_args ); $widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) ); extract( $widget_args, EXTR_SKIP ); $options = get_option('cf_links_widget'); if ( !is_array($options) ) $options = array(); if ( !$updated && !empty($_POST['sidebar']) ) { $sidebar = (string) $_POST['sidebar']; $sidebars_widgets = wp_get_sidebars_widgets(); if ( isset($sidebars_widgets[$sidebar]) ) $this_sidebar =& $sidebars_widgets[$sidebar]; else $this_sidebar = array(); foreach ( $this_sidebar as $_widget_id ) { if ( 'cf_links_widget' == $wp_registered_widgets[$_widget_id]['callback'] && isset($wp_registered_widgets[$_widget_id]['params'][0]['number']) ) { $widget_number = $wp_registered_widgets[$_widget_id]['params'][0]['number']; if ( !in_array( "cf-links-$widget_number", $_POST['widget-id'] ) ) unset($options[$widget_number]); } } foreach ( (array) $_POST['cfl-links'] as $widget_number => $cfl_links_instance ) { if ( !isset($cfl_links_instance['title']) && isset($options[$widget_number]) ) continue; $title = trim(strip_tags(stripslashes($cfl_links_instance['title']))); $select = $cfl_links_instance['select']; $options[$widget_number] = compact('title','select'); } update_option('cf_links_widget', $options); $updated = true; } if ( -1 == $number ) { $title = ''; $select = ''; $number = '%i%'; } else { $title = attribute_escape($options[$number]['title']); $select = $options[$number]['select']; } $cflk_list = $wpdb->get_results($wpdb->prepare("SELECT option_name, option_value FROM $wpdb->options WHERE option_name LIKE %s",'cfl-%')); $form_data = array(); foreach ($cflk_list as $cflk) { $options = maybe_unserialize(maybe_unserialize($cflk->option_value)); $push = array('option_name' => $cflk->option_name, 'nicename' => $options['nicename']); array_push($form_data,$push); } ?> <p> <label for="cfl-links-title-<?php echo $number; ?>"><?php _e('Title: ', 'cf-links'); ?></label> <br /> <input id="cfl-links-title-<?php echo $number; ?>" name="cfl-links[<?php echo $number; ?>][title]" class="widefat" type="text" value="<?php print (strip_tags($title)); ?>" /> </p> <p> <label for="cfl-links-select-<?php echo $number; ?>"><?php _e('Links List: ', 'cf-links'); ?></label> <br /> <select id="cfl-links-select-<?php echo $number; ?>" name="cfl-links[<?php echo $number; ?>][select]" class="widefat"> <?php foreach ($form_data as $data => $info) { if ($info['option_name'] == $select) { $selected = 'selected=selected'; } else { $selected = ''; } ?> <option value="<?php print (htmlspecialchars($info['option_name'])); ?>" <?php print ($selected); ?>><?php print (htmlspecialchars($info['nicename'])); ?></option> <?php } ?> </select> </p> <p> <a href="<?php bloginfo('wpurl') ?>/wp-admin/options-general.php?page=cf-links.php"><?php _e('Edit Links','cf-links') ?></a> </p> <input type="hidden" id="cfl-links-submit-<?php echo $number; ?>" name="cfl-links[<?php echo $number; ?>][submit]" value="1" /> <?php } function cflk_widget_register() { if ( !$options = get_option('cf_links_widget') ) $options = array(); $widget_ops = array('classname' => 'cf_links_widget', 'description' => __('Widget for showing links entered in the Advanced Links settings page (Version 1.0, upgrade to 2.0 to continue functionality).','cf-links')); $name = __('CF Links 1.0', 'cf-links'); $id = false; foreach ( array_keys($options) as $o ) { if ( !isset($options[$o]['title']) ) continue; $id = "cf-links-$o"; wp_register_sidebar_widget( $id, $name, 'cflk_widget', $widget_ops, array( 'number' => $o ) ); wp_register_widget_control( $id, $name, 'cflk_widget_control', array( 'id_base' => 'cf-links' ), array( 'number' => $o ) ); } if ( !$id ) { wp_register_sidebar_widget( 'cf-links-1', $name, 'cflk_widget', $widget_ops, array( 'number' => -1 ) ); wp_register_widget_control( 'cf-links-1', $name, 'cflk_widget_control', array( 'id_base' => 'cf-links' ), array( 'number' => -1 ) ); } } add_action( 'widgets_init', 'cflk_widget_register' ); /** * * CF Links Data Retrieval Functions * */ function cflk_handle_shortcode($attrs, $content=null) { if (is_array($attrs) && isset($attrs['name'])) { return cflk_get_links($attrs['name']); } return false; } // Main Shortcodes add_shortcode('cflk', 'cflk_handle_shortcode',11); add_shortcode('cflk_links','cflk_handle_shortcode',11); // Kept in for legacy purposes add_shortcode('cfl_links', 'cflk_handle_shortcode',11); /** * Check if a givet links list exists * @param string $key - id of the list being targeted * @return bool */ function cflk_links_list_exists($key) { $list = cflk_get_links_data($key); if (is_array($list)) { return true; } else { return false; } } /** * Return all relevant data about a list * * @param string $key - id of the list being targeted * @return mixed - array or false. */ function cflk_get_links_data($key) { $links = get_option($key); if (empty($links)) { return false; } $links = maybe_unserialize($links); $links['key'] = $key; $links = cflk_get_link_info($links); return apply_filters('cflk_get_links_data', $links); } /** * Build a links list based on the passed in key and args. * This function is called as a template tag and inside widgets. * * @param string $key * @param array $args * @return html */ function cflk_get_links($key = null, $args = array()) { if (!$key) { return ''; } $defaults = array( 'before' => '<ul class="cflk-list '.$key.'">', 'after' => '</ul>', 'child_before' => '<ul class="cflk-list-nested">', 'child_after' => '</ul>', 'location' => 'template' ); $args = apply_filters('cflk_list_args',array_merge($defaults, $args),$key); $args['server_current'] = $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]; // make sure we have a level designator in the list $args['before'] = cflk_ul_ensure_level_class($args['before']); $args['child_before'] = cflk_ul_ensure_level_class($args['child_before']); $args['key'] = $key; $list = cflk_get_links_data($key); if (!is_array($list) || $list == FALSE) { echo 'Could not find link list: '.htmlspecialchars($key); return; } $ret = ''; $i = 0; $listcount = 0; // Process the list to see if the href is empty, if it is remove it from the list // so we don't have extra <li>'s that are not needed foreach ($list['data'] as $key => $data) { if (empty($data['href']) && empty($data['title'])) { unset($list['data'][$key]); // This is here so we don't have array keys that go from 0 to 2 when an item is unset. // This is a problem when we go through and print out the list because it needs all of // the keys in order so it doesn't miss them, or something like that $list['data'] = array_merge($list['data']); } } $ret = cflk_build_list_items($list['data'], $args); $ret = apply_filters('cflk_get_links', $ret, $list, $args); return $ret; } /** * Make sure we have a level-x classname on the $args['before'] for proper listed nest labeling * Pulls the <ul> tag from the $before var with substr because it is more reliable than pulling * the UL via regex with all the permutations and different wrappers and other items that can be * included in the $before variable - SP * * if no classname is present, we add the entire class attribute, else we add to the existing attribute * * @param string $before * @return string */ function cflk_ul_ensure_level_class($before) { // fish out the <ul> and its attributes $ul_start = strpos($before,'<ul'); $ul_end = (strpos($before,'>',$ul_start)+1)-$ul_start; $ul = substr($before,$ul_start,$ul_end); // munge if(!preg_match("|class=|", $ul)) { // add a class attribute $ul_n = preg_replace("|(<ul.*?)(>)|","$1 class=\"level-0\"$2",$ul); } elseif(!preg_match("|class=\".*?(level-[0-9])\"|",$ul)) { // modify the existing class attribute $ul_n = preg_replace("|(<ul.*?class=\".*?)(\".*?>)|","$1 level-0$2",$ul); } return str_replace($ul,$ul_n,$before); } /** * recursive function for putting together list items and handling nesting. * Does some cleanup on the previous iteration of the code, but is not a full rewrite. * Handles a flat list so we don't have to reformat the data array - time permitting * this will be modified to work off a nested data array to ease the recursion limits * on finding the first/last item in nested lists. * * Because the data array is flat, we need the global for array positioning after recursing. * * @param array $items * @param array $args * @param int $start * @return html */ function cflk_build_list_items(&$items,$args,$start=0) { global $cflk_i; extract($args, EXTR_SKIP); // increment the level $before = ($start == 0 ? $args['before'] : $args['child_before']); $ret = preg_replace("|(level-[0-9])|","level-".$items[$start]['level'],$before); for($cflk_i = $start; $cflk_i < count($items), $data = $items[$cflk_i]; $cflk_i++) { if (is_array($data)) { $li_class = ''; if ($data['type'] == 'category') { if ($data['link'] == the_category_id(false)) { $li_class .= 'cflk-current-category '; } } // see if we're first or last if(!isset($items[$cflk_i-1])) { $li_class .= 'cflk-first '; } elseif(!isset($items[$cflk_i+1])) { $li_class .= 'cflk-last '; } // see if we're the current page /* Wordpress urls always have a trailingslash, make sure we have one on the $data['href'] */ if ($server_current == str_replace(array('http://', 'http://www.'), '', trailingslashit($data['href']))) { $li_class .= apply_filters('cflk_li_class_current', 'cflk-current'); } // build & filter link $link = ''; if (!empty($data['href'])) { $rel = ''; if (!empty($data['rel'])) { $rel = ' rel="'.$data['rel'].'"'; } $link .= '<a href="'.$data['href'].'" class="a-level-'.$data['level'].'"'.$rel.'>'; } $link .= strip_tags($data['text']); if (!empty($data['href'])) { $link .= '</a>'; } $link = apply_filters('cflk-link-item',$link,$data,$key); // put it all together $ret .= '<li class="'.$data['class'].' '.$li_class.'">'.$link; if($items[$cflk_i+1]['level'] > $data['level']) { $ret .= cflk_build_list_items($items,$args,++$cflk_i); } $ret .= '</li>'; // if we're at the end of this level then break the loop if(!isset($items[$cfkl_i+1]) || $items[$cflk_i+1]['level'] < $data['level']) { break; } } } $after = ($start == 0 ? $args['after'] : $args['child_after']); return $ret.$after; } function cflk_links($key, $args = array()) { echo cflk_get_links($key, $args); } function cflk_get_link_info($link_list,$merge=true) { $data = array(); if(is_array($link_list)) { foreach ($link_list['data'] as $key => $link) { // legacy compatability: add level if not present - SP if(!isset($link['level'])) { $link['level'] == 0; } $href = ''; $text = ''; $type_text = ''; $other = ''; $sanitized_href = ''; // 'type' is everything up to the first - $type = (false === strpos($link['type'],'-') ? $link['type'] : substr($link['type'],0,strpos($link['type'],'-'))); switch ($type) { case 'url': $href = htmlspecialchars($link['link']); $type_text = strip_tags($link['link']); break; case 'rss': $href = htmlspecialchars($link['link']); $type_text = strip_tags($link['link']); $other = 'rss'; break; case 'post': case 'page': $postinfo = get_post(htmlspecialchars($link['link'])); if (isset($postinfo->post_status) && in_array($postinfo->post_status, array('publish', 'inherit'))) { $type_text = $postinfo->post_title; $href = get_permalink(htmlspecialchars($link['link'])); } break; case 'category': $cat_info = get_category(intval($link['link']),OBJECT,'display'); if (is_a($cat_info,'stdClass')) { $href = get_category_link($cat_info->term_id); $type_text = attribute_escape($cat_info->cat_name); if ($link['cat_posts']) { $type_text .= ' ('.$link_cat_info->count.')'; } } break; case 'wordpress': $get_link = cflk_get_wp_type($link['link']); if (is_array($get_link)) { $href = $get_link['link']; $type_text = $get_link['text']; if ($link['link'] == 'main_rss') { $other = 'rss'; } } break; case 'author': $userdata = get_userdata($link['link']); if (is_a($userdata, 'stdClass')) { $type_text = $userdata->display_name; $href = get_author_posts_url($link['link'], $userdata->user_nicename); } else if (is_a($userdata, 'WP_User')) { $type_text = $userdata->data->display_name; $href = get_author_posts_url($userdata->data->ID, $userdata->data->user_nicename); } break; case 'author_rss': $userdata = get_userdata($link['link']); if (is_a($userdata, 'stdClass')) { $type_text = $userdata->display_name; $other = 'rss'; $href = get_author_feed_link($link['link']); } else if (is_a($userdata, 'WP_User')) { $type_text = $userdata->data->display_name; $other = 'rss'; $href = get_author_feed_link($userdata->data->ID); } break; case 'blog': case 'site': $bloginfo = cflk_get_blog_type($link['link']); if (is_array($bloginfo)) { $href = $bloginfo['link']; $type_text = $bloginfo['text']; } break; default: break; } if (empty($link['title'])) { $text = $type_text; } else { $text = strip_tags($link['title']); } $class = $link_list['key'].'_'.md5($href); if ($other == 'rss') { $class .= ' cflk-feed'; } if ($link['opennew']) { $class .= ' cflk-opennewwindow'; add_action('wp_footer', 'cflk_front_js'); } $rel = ''; if ($link['nofollow']) { $rel .= 'nofollow'; } if ($href != '') { // removed array push to preserve data key associations for later merging $data[$key] = array('id' => $key, 'href' => $href, 'text' => $text, 'class' => $class, 'rel' => $rel); } } if($merge) { // return the entire link list merged with the new data foreach($link_list['data'] as $key => $list_item) { if (is_array($data[$key])) { $link_list['data'][$key] = array_merge($list_item,$data[$key]); } } return $link_list; } else { // return just the new data return $data; } } } function cflk_get_blog_type($id) { if (!empty($id) && $id != 0) { $link = ''; $text = ''; $details = get_blog_details($id); $link = $details->siteurl; $text = $details->blogname; if ($link != '' && $text != '') { return array('text' => $text, 'link' => $link); } } return false; } function cflk_get_wp_type($type) { $link = ''; $text = ''; switch ($type) { case 'home': $link = get_bloginfo('url'); $text = 'Home'; break; case 'loginout': // wordpress 2.7 adds convenience functions around the login/logout urls global $wp_version; if (!is_user_logged_in()) { $link = (version_compare($wp_version,'2.7','<') ? site_url('wp-login.php','login') : wp_login_url()); $text = 'Log in'; } else { $link = (version_compare($wp_version,'2.7','<') ? site_url('wp-login.php?action=logout','login') : wp_logout_url()); $text = 'Log Out'; } break; case 'register': if (!is_user_logged_in()) { if (get_option('users_can_register')) { $link = site_url('wp-login.php?action=register','login'); $text = 'Register'; } } else { if (current_user_can('manage_options')) { $link = admin_url(); $text = 'Site Admin'; } } break; case 'profile': if (is_user_logged_in()) { $link = admin_url('profile.php'); $text = 'Profile'; } break; case 'main_rss': $text = get_bloginfo('name'); $link = get_bloginfo('rss2_url'); break; } if ($link != '' && $text != '') { return array('text' => $text, 'link' => $link); } return false; } function cflk_export_list($key) { global $wpdb; $cflk_list = $wpdb->get_results($wpdb->prepare("SELECT option_name, option_value FROM $wpdb->options WHERE option_name LIKE '".$wpdb->escape($key)."'")); foreach ($cflk_list as $key => $value) { $export = urlencode(serialize($value->option_value)); ?> <textarea rows="20" style="width:600px;"><?php echo $export; ?></textarea> <?php } die(); } /** * * CF Links Deprecated Functions * */ function get_links_template($key) { return cflk_get_links($key); } function links_template($key, $before = '', $after = '') { $args = array(); if($before != '') { $args['before'] = $before; } if($after != '') { $args['after'] = $after; } echo cflk_get_links($key, $args); } // CF README HANDLING /** * Enqueue the readme function */ function cflk_add_readme() { if (function_exists('cfreadme_enqueue')) { cfreadme_enqueue('cf-links', 'cflk_readme'); } } add_action('admin_init', 'cflk_add_readme'); /** * return the contents of the links readme file * replace the image urls with full paths to this plugin install * * @return string */ function cflk_readme() { $file = realpath(dirname(__FILE__)).'/readme/readme.txt'; if (is_file($file) && is_readable($file)) { $markdown = file_get_contents($file); $markdown = preg_replace('|!\[(.*?)\]\((.*?)\)|','![$1]('.WP_PLUGIN_URL.'/cf-links/readme/$2)',$markdown); return $markdown; } return null; } ?> <file_sep>/views/nav.php <?php echo screen_icon().'<h2>'.__('CF Links', 'cf-links').'</h2>'; ?> <ul class="subsubsub"> <li> <a href="<?php echo admin_url('options-general.php?page=cf-links.php&cflk_page=main'); ?>" <?php echo $main_text; ?>><?php _e('Links Lists', 'cf-links'); ?></a> | </li> <li> <a href="<?php echo admin_url('options-general.php?page=cf-links.php&cflk_page=create'); ?>" <?php echo $add_text; ?>><?php _e('New Links List', 'cf-links'); ?></a> | </li> <li> <a href="<?php echo admin_url('options-general.php?page=cf-links.php&cflk_page=import'); ?>" <?php echo $import_text; ?>><?php _e('Import/Export Links List', 'cf-links'); ?></a> | </li> <li> <a href="<?php echo admin_url('widgets.php'); ?>"><?php _e('Edit Widgets','cf-links'); ?></a> </li> </ul> <?php if ($list != '') { ?> <h3 style="clear:both;"> <?php _e('Links Options for: ', 'cf-links'); ?> <span id="cflk_nicename_h3"><?php echo $list; ?></span> &nbsp;<a href="#" class="cflk_edit_link"><?php _e('Edit', 'cf-links'); ?></a> <span id="cflk_nicename_input" style="display:none;"> <input type="text" name="cflk_nicename" id="cflk_nicename" value="<?php echo esc_attr($list); ?>" /> <input type="button" name="cflk-nicename-submit" id="cflk-nicename-submit" class="button" value="<?php _e('Save', 'cf-links'); ?>" /> <input type="button" name="link_nicename_cancel" id="link_nicename_cancel" class="button" value="<?php _e('Cancel', 'cf-links'); ?>" onClick="cancelNicename()" /> </span> </h3> <?php } ?><file_sep>/js/editor_plugin.js (function() { tinymce.create('tinymce.plugins.cflinks', { init: function(ed, url) { pluginUrl = url.replace('js', ''); imageUrl = pluginUrl+'images/link-list.gif'; this.editor = ed; ed.addCommand('cfLinks', function() { var se = ed.selection; ed.windowManager.open({ title: 'Select CF Links List', file: 'options-general.php?page=cf-links.php&cflk_page=dialog', width: 350 + parseInt(ed.getLang('cflinks.delta_width', 0)), height: 450 + parseInt(ed.getLang('cflinks.delta_height', 0)), inline: 1 }, { plugin_url: pluginUrl }); }); ed.addButton('cfLinksBtn', { title: 'CF Links', cmd: 'cfLinks', image : imageUrl }); ed.onNodeChange.add(function(ed, cm, n, co) { cm.setDisabled('cfLinks', co && n.nodeName != 'A'); cm.setActive('cfLinks', n.nodeName == 'A' && !n.name); }); }, getInfo: function() { return { longname: 'CF Links', author: 'Crowd Favorite', authorurl: 'http://crowdfavorite.com', infourl: 'http://crowdfavorite.com', version: "1.2" }; } }); tinymce.PluginManager.add('cflinks', tinymce.plugins.cflinks); })();<file_sep>/views/edit.php <div class="wrap"> <?php include('message-updated.php'); include('message-link-delete.php'); include('message-import-problem.php'); ?> <form action="<?php echo admin_url(); ?>" method="post" id="cflk-form"> <?php echo cflk_nav('edit', htmlspecialchars($cflk['nicename'])); ?> <table class="widefat" style="margin-bottom: 10px;"> <thead> <tr> <th scope="col" colspan="2"> <?php _e('Description', 'cf-links'); ?> </th> </tr> </thead> <tr> <td> <div id="description_text"> <p> <?php if (!empty($cflk['description'])) { echo esc_html($cflk['description']); } else { echo '<span style="color: #999999;">'.__('No Description has been set for this list. Click the edit button to enter a description. &rarr;', 'cf-links').'</span>'; } ?> </p> </div> <div id="description_edit" style="display:none;"> <textarea name="cflk_description" rows="5" style="width:100%;"><?php echo esc_textarea($cflk['description']); ?></textarea> </div> </td> <td width="150px" style="text-align:right; vertical-align:middle;"> <div id="description_edit_btn"> <input type="button" class="button" id="link_description_btn" value="<?php _e('Edit', 'cf-links'); ?>" onClick="editDescription()" /> </div> <div id="description_cancel_btn" style="display:none;"> <input type="button" class="button" id="link_description_cancel" value="<?php _e('Cancel', 'cf-links'); ?>" onClick="cancelDescription()" /> </div> </td> </tr> </table> <table class="widefat"> <thead> <tr> <th scope="col" class="link-level"><?php _e('Level','cf-links'); ?></th> <th scope="col" class="link-order" style="text-align: center;"><?php _e('Order', 'cf-links'); ?></th> <th scope="col" class="link-type"><?php _e('Type', 'cf-links'); ?></th> <th scope="col" class="link-value"><?php _e('Link', 'cf-links'); ?></th> <th scope="col" class="link-text"><?php _e('Link Text (Optional)', 'cf-links'); ?></th> <th scope="col" class="link-open-new"><?php _e('New Window', 'cf-links'); ?></th> <th scope="col" class="link-nofollow"><?php _e('No Follow', 'cf-links'); ?></th> <th scope="col" class="link-delete"><?php _e('Delete', 'cf-links'); ?></th> </tr> </thead> </table> <ul id="cflk-list"> <?php if ($cflk_count > 0 && is_array($cflk['data']) && !empty($cflk['data'])) { foreach ($cflk['data'] as $key => $setting) { $tr_class = ''; if($setting['link'] == 'HOLDER') { $tr_class = ' class="tr_holder"'; } ?> <li id="listitem_<?php echo $key; ?>" class="level-<?php echo $setting['level']; ?>"> <table class="widefat"> <tr<?php echo $tr_class; ?>> <td class="link-level"> <div> <input type="hidden" class="link-level-input" name="cflk[<?php echo $key; ?>][level]" value="<?php echo $setting['level']; ?>" /> <button class="level-decrement decrement-<?php echo $key; ?>">&laquo;</button> <button class="level-increment increment-<?php echo $key; ?>">&raquo;</button> </div> </td> <td class="link-order" style="text-align: center; vertical-align:middle;"> <img src="<?php echo CFLK_DIR_URL; ?>images/arrow_up_down.png" class="handle" alt="move" /> </td> <td class="link-type" style="vertical-align:middle;"> <select name="cflk[<?php echo $key; ?>][type]" id="cflk_<?php echo $key; ?>_type" onChange="showLinkType(<?php echo $key; ?>)"> <?php $type_selected = ''; foreach ($cflk_types as $type) { $selected = ''; if($type['type'] == $setting['type']) { $selected = ' selected="selected"'; $type_selected = $type['nicename']; } echo '<option value="'.$type['type'].'"'.$selected.'>'.$type['nicename'].'</option>'; } ?> </select> </td> <td class="link-value" style="vertical-align:middle;"> <?php foreach ($cflk_types as $type) { echo cflk_get_type_input($type, $type_selected, $key, $setting['cat_posts'], $setting['link']); } ?> </td> <td class="link-text" style="vertical-align:middle;"> <?php if (strip_tags($setting['title']) == '') { $edit_show = ''; $input_show = ' style="display:none;"'; } else { $edit_show = ' style="display:none;"'; $input_show = ''; } ?> <span id="cflk_<?php echo $key; ?>_title_edit"<?php echo $edit_show; ?>> <input type="button" class="button" id="link_edit_title_<?php echo $key; ?>" value="<?php _e('Edit Text', 'cf-links'); ?>" onClick="editTitle('<?php echo $key; ?>')" /> </span> <span id="cflk_<?php echo $key; ?>_title_input"<?php echo $input_show; ?>> <input type="text" id="cflk_<?php echo $key; ?>_title" name="cflk[<?php echo $key; ?>][title]" value="<?php echo esc_attr($setting['title']); ?>" style="max-width: 150px;" /> <input type="button" class="button" id="link_clear_title_<?php echo $key; ?>" value="<?php _e('&times;', 'cf-links'); ?>" onClick="clearTitle('<?php echo $key; ?>')" /> </span> </td> <td class="link-open-new" style="text-align: center; vertical-align:middle;"> <?php $opennew = ''; if ($setting['opennew']) { $opennew = ' checked="checked"'; } ?> <input type="checkbox" id="link_opennew_<?php echo $key; ?>" name="cflk[<?php echo $key; ?>][opennew]"<?php echo $opennew; ?> /> </td> <td class="link-nofollow" style="text-align: center; vertical-align:middle;"> <?php $nofollow = ''; if ($setting['nofollow']) { $nofollow = ' checked="checked"'; } ?> <input type="checkbox" id="link_nofollow_<?php echo $key; ?>" name="cflk[<?php echo $key; ?>][nofollow]"<?php echo $nofollow; ?> /> </td> <td class="link-delete" style="text-align: center; vertical-align:middle;"> <input type="button" class="button" id="link_delete_<?php echo $key; ?>" value="<?php _e('Delete', 'cf-links'); ?>" onClick="deleteLink('<?php echo $cflk_key; ?>','<?php echo $key; ?>')" /> </td> </tr> </table> </li> <?php } } ?> </ul> <table class="widefat"> <tr> <td style="text-align:left;"> <input type="button" class="button" name="link_add" id="link_add" value="<?php _e('Add New Link', 'cf-links'); ?>" onClick="addLink()" /> </td> </tr> </table> <p class="submit" style="border-top: none;"> <input type="hidden" name="cf_action" value="cflk_update_settings" /> <input type="hidden" name="cflk_key" value="<?php echo esc_attr($cflk_key); ?>" /> <input type="submit" name="submit" id="cflk-submit" value="<?php _e('Update Settings', 'cf-links'); ?>" class="button-primary button" /> </p> </form> <div id="newitem_SECTION"> <li id="listitem_###SECTION###" class="level-0" style="display:none;"> <table class="widefat"> <tr> <td class="link-level"> <div> <input type="hidden" class="link-level-input" name="cflk[###SECTION###][level]" value="0" /> <button class="level-decrement">&laquo;</button> <button class="level-increment">&raquo;</button> </div> </td> <td class="link-order" style="text-align: center;"><img src="<?php echo CFLK_DIR_URL; ?>images/arrow_up_down.png" class="handle" alt="move" /></td> <td class="link-type"> <select name="cflk[###SECTION###][type]" id="cflk_###SECTION###_type" onChange="showLinkType('###SECTION###')"> <?php foreach ($cflk_types as $type) { $select_settings[$type['type'].'_select'] = ''; if ($type['type'] == 'url') { $select_settings[$type['type'].'_select'] = ' selected="selected"'; } echo '<option value="'.$type['type'].'"'.$select_settings[$type['type'].'_select'].'>'.$type['nicename'].'</option>'; } ?> </select> </td> <td class="link-value"> <?php $key = '###SECTION###'; foreach ($cflk_types as $type) { $select_settings[$type['type'].'_show'] = 'style="display: none;"'; if ($type['type'] == 'url') { $select_settings[$type['type'].'_show'] = 'style=""'; } echo cflk_get_type_input($type, $select_settings[$type['type'].'_show'], $key, '', ''); } ?> </td> <td class="link-text"> <span id="cflk_###SECTION###_title_edit" style="display: none"> <input type="button" class="button" id="link_edit_title_###SECTION###" value="<?php _e('Edit Text', 'cf-links'); ?>" onClick="editTitle('###SECTION###')" /> </span> <span id="cflk_###SECTION###_title_input"> <input type="text" id="cflk_###SECTION###_title" name="cflk[###SECTION###][title]" value="" style="max-width: 150px;" /> <input type="button" class="button" id="link_clear_title_###SECTION###" value="<?php _e('&times;', 'cf-links'); ?>" onClick="clearTitle('###SECTION###')" /> <br /> <?php _e('ex: Click Here','cf-links'); ?> </span> </td> <td class="link-open-new" style="text-align: center; vertical-align:middle;"> <input type="checkbox" id="link_opennew_###SECTION###" name="cflk[###SECTION###][opennew]" /> </td> <td class="link-nofollow" style="text-align: center; vertical-align:middle;"> <input type="checkbox" id="link_nofollow_###SECTION###" name="cflk[###SECTION###][nofollow]" /> </td> <td class="link-delete" style="text-align: center;"> <input type="button" class="button" id="link_delete_###SECTION###" value="<?php _e('Delete', 'cf-links'); ?>" onClick="deleteLink('<?php echo $cflk_key; ?>', '###SECTION###')" /> </td> </tr> </table> </li> </div> <?php // select-modal placeholder //dp($cflk_types); foreach ($cflk_types as $type) { if($type['input'] == 'select-modal') { $select_settings[$type['type'].'_show'] = 'style="display: none;"'; // fool cflk_get_type_input in to giving us a select list $type['input'] = 'select'; echo ' <div id="'.$type['type'].'-modal" class="'.$type['type'].'-modal" style="display: none;"> '.cflk_get_type_input($type, $select_settings[$type['type'].'_show'], 'list', '', '').' <input type="button" name="'.$type['type'].'-set" value="Done" class="modal-done button"/> </div> '; } } // Allow other plugins the ability to display info on this page echo apply_filters('cflk_edit', '', $cflk_key); ?> </div><!--.wrap--><file_sep>/views/message-link-delete.php <div id="message_delete" class="updated fade" style="display: none;"> <p><?php _e('Link deleted.', 'cf-links'); ?></p> </div> <file_sep>/readme/readme.txt ## <a id="advanced-links-list">CF Links</a> ### Creating a Links list 1. Click the "Add Links List" link 2. Add the links list name to the field provided 3. Click the "Create New Link List" button to create the list ### Adding/Removing Links #### Adding Links 1. To add a link to the list, click on the name of the list or click the "Edit" button on the Links Options main page 2. Click on the "Add Link" button at the bottom of the screen to add a new link 3. Select the Link "Type" from the drop down 4. Add or select the link in the "Link" area 5. Edit the Link Text or leave it blank 6. To have the link automatically open in a new window, check the New Window checkbox 7. Click the "Update Settings" button at the bottom of the screen to save changes ##### Link Types 1. URL - This type gives the user the ability to add any url desired. - The user needs to add a URL link in the "Link" section - The Link Text area is optional. If nothing is entered in this area the URL will be displayed. 2. RSS Feed - This type is the same as URL - When displayed this type will display a RSS image in front of the URL to denote that it is an RSS Feed 3. Page - This type will display a link to the Page selected - The Link Text area is optional. If nothing is entered in this area the Page Title will be displayed. 4. Category - This type gives the user the ability to add a link to a Category - The Link Text area is optional. If nothing is entered in this area the Category Title will be displayed. 5. WordPress - This type gives the user the ability to link to WordPress special links - Links available 1. Home - This is the WordPress home page 2. Log In/Out - This is a link to the WordPress login page. If the user is logged in it displays a log out link 3. Register/Site Admin - Site Admin is displayed when the user is logged in. If the "Membership" general setting is selected, the "Register" link is displayed 4. Profile - This displays a link to the users profile page. If the user is not logged in, nothing will display 5. Site RSS - This displays a link to the sites main RSS feed. It also displays a RSS image when the link is displayed - The Link Text area is optional. If nothing is entered in this area the WordPress Link Text will be displayed. 6. Author RSS - This type displays a link to the selected author's rss feed. It also displays an RSS image - The Link Text area is optional. If nothing is entered in this area the Author Display Name will be displayed. 7. Blog - This type displays a link to the blog selected. - The Link Text is optional. If nothing is entered the name of the blog will be displayed #### Removing Links 1. To remove a link from the list, click on the name of the list or click the "Edit" button on the Links Options main page 2. Click the "Remove" button next to the link to be removed 3. A confirmation box will be displayed to confirm link deletion 4. Click the "Update Settings" button at the bottom of the screen to save changes ### Editing the Links List name 1. Click the "Edit" link next to the links list name 2. Edit the list name in the box 3. Click "Save" to save the changes 4. Click "Cancel" to ignore the changes ### Deleting a Links List 1. On the main links list page, click the "Delete" button 2. A dialog box will request confirmation ### Display Options - The links lists can be displayed in multiple ways 1. Widget - The user can add a widget, and select the link list from the drop down - If the links are longer than expected, they can be shortened usig the "Link Length" drop down 1. If the "Link Length" is set to 0 the link will not be shortened 2. Template Tag - If the user clicks on the "Template Tag" link on the main links page, it will display the PHP link to be put into the template 3. Shortcode - If the user clicks on the "Shortcode" link on the main links page, it will display the Shortcode to be put into the content - A TinyMCE button is also added to the Post/Page writing pages. Directions for adding links using TinyMCE are listed below ### Adding Links using TinyMCE 1. Click on a post or page to edit, or create a new page 2. Put the cursor in the post area where the links list should be added 3. Click on the cog link for links list 4. Click on the links list from the list of links lists 5. Click on the "X" at the top right of the box to close the dialog box 6. The Shortcode will automatically be added to the post where the cursor was before the list was selected
8cdf2f45bfbabbfce06207a84d497a896e3f8f79
[ "JavaScript", "Text", "PHP" ]
16
PHP
crowdfavorite/wp-cf-links
fbabee31af04ad338c9f063d57a51dfa0521150f
dc6a38dfff070a4d4ea43112751174b0bb7a35a3
refs/heads/master
<file_sep>const Color = { primary: "#84EAC0", secondary: { light: "#FFE7E2", main: "#F6D2E3", dark: "#D21D3A", }, white: "#f4f4f4", }; export default Color; <file_sep>import { createContext, useCallback, useState } from 'react'; // set context type export type AlignContext = { align: boolean; setCurrentAlign: (currentAlign: boolean) => void; }; // context default value const DEFAULT_ALIGN_CONTEXT: AlignContext = { align: false, // eslint-disable-next-line @typescript-eslint/no-empty-function setCurrentAlign: () => {}, }; // context export const alignContext = createContext<AlignContext>(DEFAULT_ALIGN_CONTEXT); // custom Hook export const useAlign = (): AlignContext => { const [align, setAlign] = useState(false); const setCurrentAlign = useCallback((current: boolean): void => { setAlign(current); }, []); return { align, setCurrentAlign, }; }; <file_sep>export type circleSize = "lg" | "md" | "sm"; <file_sep>import { ConceptNetAPI } from 'api'; import { createContext, useCallback, useState } from 'react'; // set context type export type APIContext = { data: ConceptNetAPI | null; setCurrentData: (currentData: ConceptNetAPI | null) => void; }; // context default value const DEFAULT_API_CONTEXT: APIContext = { data: null, // eslint-disable-next-line @typescript-eslint/no-empty-function setCurrentData: () => {}, }; // context export const apiContext = createContext<APIContext>(DEFAULT_API_CONTEXT); // custom Hook export const useAPI = (): APIContext => { const [data, setData] = useState<ConceptNetAPI | null>(null); const setCurrentData = useCallback((current: ConceptNetAPI | null): void => { setData(current); }, []); return { data, setCurrentData, }; }; <file_sep>export interface ConceptNetAPI { "@context": string[]; "@id": string; edges: Edge[]; view: View; } export interface Edge { "@id": string; "@type": EdgeType; dataset: Dataset; end: End; license: License; rel: Rel; sources: Source[]; start: End; surfaceText: null | string; weight: number; } export enum EdgeType { Edge = "Edge", } export enum Dataset { DConceptnet4Ja = "/d/conceptnet/4/ja", DJmdict = "/d/jmdict", DKyotoYahoo = "/d/kyoto_yahoo", } export interface End { "@id": string; "@type": EndType; label: string; language: Language; term: string; sense_label?: string; } export enum EndType { Node = "Node", } export enum Language { De = "de", En = "en", Fr = "fr", Ja = "ja", Nl = "nl", } export enum License { CcBy40 = "cc:by/4.0", CcBySa40 = "cc:by-sa/4.0", } export interface Rel { "@id": string; "@type": RelType; label: string; } export enum RelType { Relation = "Relation", } export interface Source { "@id": string; "@type": SourceType; activity?: Activity; contributor?: string; process?: string; } export enum SourceType { Source = "Source", } export enum Activity { SActivityKyotoYahoo = "/s/activity/kyoto_yahoo", SActivityOmcsNadyaJp = "/s/activity/omcs/nadya.jp", } export interface View { "@id": string; "@type": string; comment: string; firstPage: string; nextPage: string; paginatedProperty: string; } <file_sep>export const circlePosition = (itemNum: number, itemWidth: number): React.CSSProperties[] => { const deg = 360.0 / itemNum; const red = (deg * Math.PI) / 180.0; const props: React.CSSProperties[] = []; const circleR = itemWidth * 3.0; for (let i = 0; i < itemNum; i++) { const left = Math.cos(red * i) * circleR + circleR; const top = Math.sin(red * i) * circleR + circleR; props.push({ left: `${left}px`, top: `${top}px`, }); } return props; }; <file_sep>import { ConceptNetAPI } from 'api'; import axios from 'axios'; export const getApiData = async (str: string): Promise<ConceptNetAPI | null> => { const url = `http://api.conceptnet.io/c/ja/${str}`; const JsonData = await axios .get(url) .then(res => { return res.data as ConceptNetAPI; }) .catch(err => { console.log(err); return null; }); return JsonData; };
0180e1d8405bb0321725775480e8fbb2909577fc
[ "TypeScript" ]
7
TypeScript
ragnar1904/conceptnet
9c56a0880a03e840aa47a2ed73f25ee6c9505575
5dbb72fa9445711e2b7749e0d5ebc9edf03c819a
refs/heads/master
<file_sep> class TimerDashboard extends React.Component{ constructor(props){ super(props) this.state = { timers:[] }; } handleCreateFormSubmit = (timer) =>{ this.createTimer(timer); } createTimer = (timer) => { const t = helpers.newTimer(timer); client.createTimer(t) this.setState({ timers:this.state.timers.concat(t) }) } handleUpdateFormSubmit = (timer) => { this.updateTimer(timer); } updateTimer = (timer) =>{ const updated_timers = this.state.timers.map(timers => { if (timers.id === timer.id){ timers.title = timer.title timers.project = timer.project return timers } else{ return timers } }) helpers.findById(updated_timers,timer.id,(ele)=>{ client.updateTimer(ele) }) this.setState({timers:updated_timers}) } handleDeleteTimer = (timerId) =>{ this.removeTimerFromServer(timerId) } removeTimerFromServer = (timerId)=>{ const newTimers = this.state.timers.filter(element =>{ if(element.id !== timerId){ return element } }) helpers.findById(this.state.timers,timerId,(ele)=>{ client.deleteTimer(ele) }) this.setState({timers:newTimers}) } Timer_Started = (timerId) =>{ this.UpdateElapsed(timerId) } Timer_Stopped = (timerId) =>{ this.UpdateRunningSince(timerId) } UpdateRunningSince = (timerId) => { const now = Date.now() this.setState({timers:this.state.timers.map(ele=>{ if(ele.id === timerId){ const lastelapsed = now - ele.runningSince return Object.assign({},ele,{elapsed:ele.elapsed+lastelapsed,runningSince:null}) } else{ return ele } })}) helpers.findById(this.state.timers,timerId,(ele)=>{ const data = {id:ele.id,stop:now} client.stopTimer(data) }) } UpdateElapsed = (timerId) =>{ const now = Date.now() this.setState({timers:this.state.timers.map(ele =>{ if (ele.id === timerId){ return Object.assign({},ele,{runningSince:now}) } else{ return ele } }) } ) helpers.findById(this.state.timers,timerId,(ele)=>{ const data = {id:ele.id,start:now} client.startTimer(data) }) } componentDidMount(){ client.getTimers((Servertimers)=>{ this.setState({timers:Servertimers}) }) } render(){ return( <div className = 'ui three column centered grid'> <div className = 'column'> <EditableTimerList timers ={this.state.timers} onFormSubmit = {this.handleUpdateFormSubmit} DeleteTimer = {this.handleDeleteTimer} Timer_Started = {this.Timer_Started} Timer_Stopped = {this.Timer_Stopped} /> <ToggleableTimerForm handleFormSubmit = {this.handleCreateFormSubmit} /> </div> </div> ) } } class ToggleableTimerForm extends React.Component{ constructor (props){ super(props) this.state = { isOpen:false } } formOpen =(val) =>{ this.setState({isOpen:true}) } isFormOpen = () =>{ if (this.state.isOpen){ this.setState({isOpen:false}) } else{ this.setState({isOpen:true}) } } onFormSubmit = (ele) => { this.props.handleFormSubmit(ele) this.setState({isOpen:false}) } render(){ if (this.state.isOpen === false){ return ( <div className = 'ui basic content center aligned segment'> <button className ='ui basic button icon'onClick ={this.formOpen}> <i className ='plus icon'/> </button> </div>) }else{ return ( <TimerForm form = {this.isFormOpen} onSubmit = {this.onFormSubmit} /> ) } } } class EditableTimerList extends React.Component{ constructor(props){ super(props) } render(){ let AlreadySetTimers = this.props.timers.sort((a,b)=>{ b.elapsed - a.elapsed }) console.log(AlreadySetTimers) const AllTimers = AlreadySetTimers.map(ele =>{ return <EditableTimer key = {'timer-'+ele.id} id = {ele.id} title = {ele.title} project = {ele.project} timer = {ele.elapsed} UpdateTimer = {this.props.onFormSubmit} removeTimerDashboard = {this.props.DeleteTimer} runningSince = {ele.runningSince} Timer_Started = {this.props.Timer_Started} Timer_Stopped = {this.props.Timer_Stopped} /> }) return( <div id = 'timers'> {AllTimers} </div> ) } } class EditableTimer extends React.Component{ constructor(props){ super(props) this.state = { editFormOpen:false } } UpdateTimerForm = (ele) =>{ this.props.UpdateTimer(ele) this.setState({editFormOpen:false}) } isFormOpen = () =>{ this.setState({editFormOpen:true}) } closeForm = ()=>{ this.setState({editFormOpen:false}) } render(){ if (this.state.editFormOpen){ return( <TimerForm id ={this.props.id} title = {this.props.title} project = {this.props.project} form = {this.isFormOpen} onCancel = {this.closeForm} onSubmit = {this.UpdateTimerForm} /> ) }else{ return( <Timer id = {this.props.id} title = {this.props.title} project = {this.props.project} timer = {this.props.timer} runningSince = {this.props.runningSince} onSubmit = {this.props.onSubmit} form = {this.isFormOpen} removeTimer = {this.props.removeTimerDashboard} Timer_Started = {this.props.Timer_Started} Timer_Stopped = {this.props.Timer_Stopped} /> ) } } } class TimerForm extends React.Component{ constructor(props){ super(props) this.state = { title:this.props.title || '', project:this.props.project || '' } } create_update_timer = (text) =>{ this.props.onSubmit({ id:this.props.id, title:this.state.title, project:this.state.project }) } updateProject =(e)=>{ this.setState({project:e.target.value}) } updateTitle = (e) =>{ this.setState({title:e.target.value}) } render(){ const submitText = this.props.id ? 'Update':'Create' return( <div className = 'ui centered card'> <div className = 'content'> <div className = 'ui form'> <div className = 'field'> <label>Title</label> <input type = 'text' value={this.state.title} onChange={this.updateTitle}/> </div> <div className = 'field'> <label>Project</label> <input type = 'text' value={this.state.project} onChange={this.updateProject}/> </div> <div className = 'ui two bottom attached buttons'> <button className ='ui basic blue button' onClick ={this.create_update_timer}> {submitText} </button> <button className ='ui basic red button'onClick ={this.props.onCancel}> Cancel </button> </div> </div> </div> </div> ) } } class Timer extends React.Component{ constructor(props){ super(props) } startTimer = ()=>{ this.props.Timer_Started(this.props.id) } stopTimer = ()=>{ this.props.Timer_Stopped(this.props.id) } componentDidMount(){ this.forceUpdateInterval = setInterval(() => this.forceUpdate(),50) } componentWillUnmount(){ clearInterval(this.forceUpdateInterval) } deleteTimer =() => { this.props.removeTimer(this.props.id) } updateForm = () =>{ this.props.form() } render(){ const elapsedString = helpers.renderElapsedString(this.props.timer,this.props.runningSince) return( <div className='ui centered card'> <div className='content'> <div className='header'> {this.props.title} </div> <div className='meta'> {this.props.project} </div> <div className='center aligned description'> <h2> {elapsedString} </h2> </div> <div className='extra content'> <span className='right floated edit icon' onClick = {this.updateForm}> <i className='edit icon' /> </span> <span className='right floated trash icon' onClick = {this.deleteTimer}> <i className='trash icon' /> </span> </div> </div> <TimerButton runningSince = {this.props.runningSince} startTimer = {this.startTimer} stopTimer ={this.stopTimer} /> </div> ) } } class TimerButton extends React.Component { constructor(props){ super(props) } startButton= () =>{ this.props.startTimer() } stopButton = () =>{ this.props.stopTimer() } render(){ if (this.props.runningSince){ return( <div className='ui bottom attached blue basic button' onClick = {this.stopButton}> Stop </div>) }else{ return( <div className='ui bottom attached blue basic button' onClick = {this.startButton}> Start </div>) } } } ReactDOM.render(<TimerDashboard/>,document.getElementById('content'))
10aec832513756d292c52f133af4fb32728dcc49
[ "JavaScript" ]
1
JavaScript
kraju3/React-TimerApp
8f63e6fa4b3e1198ce6e2e090582ad070af6b55f
a2c12e99a1e4090fa499f3c0ea1c301d08c2c97a
refs/heads/master
<file_sep> const Discord = require("discord.js"); const fs = require("fs"); const botconfig = require("./botconfig.json"); const bot = new Discord.Client({disableEveryone: true}); bot.commands = new Discord.Collection(); let cooldown = new Set(); let cdseconds = 5; fs.readdir("./commands/", (err, files) => { if(err) console.log(err); let jsfile = files.filter(f => f.split(".").pop() === "js"); if(jsfile.length <= 0){ console.log("Couldn't find commands."); return; } jsfile.forEach((f, i) =>{ let props = require(`./commands/${f}`); console.log(`${f} loaded!`); bot.commands.set(props.help.name, props); }); }); bot.on("ready", async () => { console.log(`${bot.user.username} is loaded and online on ${bot.guilds.size} servers!`); bot.user.setActivity(`b.commands`) }); bot.on('guildMemberAdd', member => { const channel = member.guild.channels.find(ch => ch.name === 'welcome to the hood'); if (!channel) return; let welcomeembed = new Discord.RichEmbed() .setAuthor(member.user.username, member.user.displayAvatarURL) .setThumbnail(member.user.displayAvatarURL) .setTimestamp() .addField(`<:addMember:518733392402186240> Welcome to the server, **${member.user.tag}**`, `Thanks for joining with us, ${member}`) .setColor(`#409cd9`) channel.send(welcomeembed); }); bot.on('guildMemberRemove', member => { const channel = member.guild.channels.find(ch => ch.name === 'welcome to the hood'); if (!channel) return; let goodbyeembed = new Discord.RichEmbed() .setAuthor(member.user.username, member.user.displayAvatarURL) .setTimestamp() .addField(`<:remMember:518733397783347200> sayonara, **${member.user.tag}**`, `<a:wave:512259019386126337> We hope to see you again, ${member}`) .setColor(`#ff3320`) channel.send(goodbyeembed); }); bot.on("message", async message => { if (message.author.bot) return; if (message.channel.type === "dm") return; // Prefixes config. let prefixes = JSON.parse(fs.readFileSync("./prefixes.json", "utf8")); if(!prefixes[message.guild.id]){ prefixes[message.guild.id] = { prefixes: botconfig.prefix }; } let prefix = prefixes[message.guild.id].prefixes; // Blacklisted words. let blacklisted = ["fuck", "faggot", "nigga", "nigger", "pussy", "rape", "dick", "pussi", "porn", "dildo", "nazi", "hitler", "penis", "boob", "cunt", "cum", "bitch", "nude", "cock", "twat", "hentai", "anal", "spank", "blowjob", "futanari", "vagina"]; let foundInText = false; for (var i in blacklisted) { if (message.content.toLowerCase().includes(blacklisted[i].toLowerCase())) foundInText = true; } if (foundInText) { if(message.member.hasPermission("MANAGE_MESSAGES")) return; message.delete(); let badword = new Discord.RichEmbed() .setAuthor(message.member.displayName, message.author.displayAvatarURL) .setDescription("<a:hyperpinged:511872097304313859> Message yeeted!") .setColor("#f44242") .addField("<:Content_Blocked:523798974876876810> \`ur msg contains inappropriate letters or words, yeeted.\` <a:BoiGifFixed:511160003667689484>", message.author) message.channel.send(badword).then(msg => {msg.delete(10850)}); } // Blacklisted off-site links. let blacklistedA = ["discord.gg", "robuxgiver.ml"]; let foundInTextA = false; for (var i in blacklistedA) { if (message.content.toLowerCase().includes(blacklistedA[i].toLowerCase())) foundInTextA = true; } if (foundInTextA) { if(message.member.hasPermission("MANAGE_MESSAGES")) return; if (message.channel.name == '??adversting??') return; message.delete(); let offsitestuff = new Discord.RichEmbed() .setAuthor(message.member.displayName, message.author.displayAvatarURL) .setDescription("<a:hyperpinged:511872097304313859> Message deleted!") .setColor("#f44242") .addField("<:Content_Blocked:523798974876876810> \`ur msg contains off-site links, yeeted.\` <a:BoiGifFixed:511160003667689484>", message.author) message.channel.send(offsitestuff).then(msg => {msg.delete(10850)}); } if(!message.content.startsWith(prefix)) return; // Cooldown feature. if(cooldown.has(message.author.id)){ message.delete(); let cooldownbotsystem = new Discord.RichEmbed() .setAuthor(message.member.displayName, message.author.displayAvatarURL) .setDescription("<a:hyperpinged:511872097304313859> Bot cooldown!") .setColor("#f44242") .addField("<a:timer:511872188341682187> \`You have to wait for 5 seconds!\` <a:BoiGifFixed:511160003667689484>", message.author,true) return message.channel.send(cooldownbotsystem).then(msg => {msg.delete(6850)}); } if(!message.member.hasPermission("MANAGE_MESSAGES")){ cooldown.add(message.author.id); } let messageArray = message.content.split(" "); let cmd = messageArray[0]; let args = messageArray.slice(1); let commandfile = bot.commands.get(cmd.slice(prefix.length)); if(commandfile) commandfile.run(bot,message,args); setTimeout(() => { cooldown.delete(message.author.id) }, cdseconds * 1000) }); bot.login(process.env.token); <file_sep># frisbee-max For educational purposes. Credits to Zendovo & TheSourceCode for their useful guides & tutorial on how to host a bot on Heroku. <file_sep>const Discord = require("discord.js"); module.exports.run = async (bot, message, args) => { message.channel.send(`rn i have 2 commands, "ping" and "amogus <- this shit retard"`); } module.exports.help = { name: "commands" }
a7223bcd0a59ca1496167e83a0b18a1291b79698
[ "JavaScript", "Markdown" ]
3
JavaScript
t64x/Birb
5ece2bfcecc72d8efc916fa893c0f0602be82063
5c21d8648c14b6e7591bd5bb49fe58d816dadb29
refs/heads/master
<repo_name>Sanaqamar123/empWageComputation<file_sep>/empWageComputation.sh #!/bin/bash -x echo "Welcome to Employee Wage Computation Program" #Checking of employee attendance num=$((RANDOM%2)) if [ $num -eq 1 ] then echo "Employee is present" else echo "Employee is absent" fi #Calulate daily wage of employee WagePerHour=20; FullDay=8; WagePerDay=$(($WagePerHour*$FullDay)); echo "Total wage per day :" $WagePerDay PartTimeHour=8; PartTimeWage=$(($WagePerHour*$PartTimeHour)); WorkingDayPerMonth=20; TotalWagePerMonth=$(($WorkingDayPerMonth*$WagePerDay)); echo "Total Wage Per Month : "$TotalWagePerMonth function getWorkHour(){ case $1 in 1 ) WorkHour=8;; 2 ) WorkHour=8;; *) WorkHour=0;; esac echo "Work hour =" $WorkHour } WorkDonePerDay=$( getWorkHour $((RANDOM%3)) ); declare -a store #declare array to store wages with day day=1; while [ $day -le $WorkingDayPerMonth ] do Wage=$(($WagePerDay*$day)) day=$(($day+1)); store[$day]=$Wage done declare -a array #Array store daily wage and monthly wage array=($WagePerDay $TotalWagePerMonth) echo "Daily wage along with Total wage :" ${array[@]} echo "Wage for $day :" ${store[@]} #print wages day by day
d564a5895239bdd056aa540bc768d82d069033f5
[ "Shell" ]
1
Shell
Sanaqamar123/empWageComputation
ceaa1762c3aa724354da986495a58fd2e82ae613
55501e75e24adbba061f841a7b80f54e36d0862e
refs/heads/master
<repo_name>CraztTy/myhome<file_sep>/src/main/java/com/zzp/myhome/MyhomeApplication.java package com.zzp.myhome; import org.apache.catalina.Context; import org.apache.catalina.connector.Connector; import org.apache.coyote.http11.AbstractHttp11Protocol; import org.apache.tomcat.util.descriptor.web.SecurityCollection; import org.apache.tomcat.util.descriptor.web.SecurityConstraint; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.boot.web.servlet.server.ServletWebServerFactory; import org.springframework.context.annotation.Bean; @SpringBootApplication @MapperScan("com.zzp.myhome.dao") public class MyhomeApplication { public static void main(String[] args) { SpringApplication.run(MyhomeApplication.class, args); } //Tomcat large file upload connection reset @Bean public TomcatServletWebServerFactory containerFactory() { return new TomcatServletWebServerFactory() { protected void customizeConnector(Connector connector) { int maxSize = 50000000; super.customizeConnector(connector); connector.setMaxPostSize(maxSize); connector.setMaxSavePostSize(maxSize); if (connector.getProtocolHandler() instanceof AbstractHttp11Protocol) { ((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(maxSize); logger.info("Set MaxSwallowSize "+ maxSize); } } }; } } <file_sep>/src/main/java/com/zzp/myhome/utils/BaseConstant.java package com.zzp.myhome.utils; /** * @author : ZHANGZP * @Description : * @Creation Date: 2019/3/5 */ public interface BaseConstant { int getCode(); String getMsg(); public static enum CommonConstant implements BaseConstant { REDIS_ERROR(510, "Redis错误"), TOKEN_GEN_ERROR(511, "Token生成失败"); private String msg; private int code; private CommonConstant(int i, String s) { this.code = i; this.msg = s; } public int getCode() { return this.code; } public String getMsg() { return this.msg; } } } <file_sep>/README.md # myhome 家用小系统集合 日后持续更新 <file_sep>/src/main/java/com/zzp/myhome/utils/R.java package com.zzp.myhome.utils; import com.alibaba.fastjson.JSON; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author : ZHANGZP * @Description : * @Creation Date: 2019/3/5 */ public class R extends HashMap<String, Object> { private static final long serialVersionUID = 1L; public R() { this.put((String)"code", 0); this.put((String)"msg", "success"); } public static R error() { return error(500, "未知异常,请联系管理员"); } public static R error(String msg) { return error(500, msg); } public static R error(int code, String msg) { R r = new R(); r.put((String)"code", code); r.put((String)"msg", msg); return r; } public static R ok(String msg) { R r = new R(); r.put((String)"msg", msg); return r; } public static R data(Object obj) { R r = new R(); r.put("data", obj); return r; } public static R ok(Map<String, Object> map) { R r = new R(); r.putAll(map); return r; } public boolean isErr() { int code = (Integer)this.get("code"); return code != 0; } public int getCode() { return (Integer)this.get("code"); } public String getMsg() { return (String)this.get("msg"); } public static R ok() { return new R(); } public R put(String key, Object value) { super.put(key, value); return this; } public <T> T getData(Class<T> clazz) { Object data = this.get("data"); if (data != null) { String s = JSON.toJSONString(data); return JSON.parseObject(s, clazz); } else if (this.isErr()) { ZRException zrException = new ZRException(this.getMsg()); zrException.setCode(this.getCode()); throw zrException; } else { throw new ZRException("返回内容为空"); } } public <T> List<T> getDataList(Class<T> clazz) { Object data = this.get("data"); if (data != null) { String s = JSON.toJSONString(data); return JSON.parseArray(s, clazz); } else if (this.isErr()) { ZRException zrException = new ZRException(this.getMsg()); zrException.setCode(this.getCode()); throw zrException; } else { throw new ZRException("返回内容为空"); } } private class ParameterizedTypeImpl implements ParameterizedType { Class clazz; public ParameterizedTypeImpl(Class clz) { this.clazz = clz; } public Type[] getActualTypeArguments() { return new Type[]{this.clazz}; } public Type getRawType() { return List.class; } public Type getOwnerType() { return null; } } } <file_sep>/src/main/java/com/zzp/myhome/service/serviceImpl/FileServiceImpl.java package com.zzp.myhome.service.serviceImpl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.zzp.myhome.dao.FileDao; import com.zzp.myhome.entity.FileEntity; import com.zzp.myhome.service.FileService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * @author : ZHANGZP * @Description : * @Creation Date: 2019/3/5 */ @Service("FileService") public class FileServiceImpl implements FileService { @Autowired private FileDao fileDao; @Override public void insert(FileEntity fileEntity) { fileDao.insert(fileEntity.getFileName(),fileEntity.getFilePath()); } @Override public PageInfo<FileEntity> selectAll(int pageNum, int pageSize) { PageHelper.startPage(pageNum, pageSize); List<FileEntity> fileEntityList = fileDao.selectAll(); PageInfo result = new PageInfo(fileEntityList); return result; } } <file_sep>/src/main/java/com/zzp/myhome/utils/ZRException.java package com.zzp.myhome.utils; /** * @author : ZHANGZP * @Description : * @Creation Date: 2019/3/5 */ public class ZRException extends RuntimeException{ private static final long serialVersionUID = 1L; private String msg; private int code = 500; public ZRException(BaseConstant baseConstant) { super(baseConstant.getMsg()); this.msg = baseConstant.getMsg(); this.code = baseConstant.getCode(); } public ZRException(String msg) { super(msg); this.msg = msg; } public ZRException(BaseConstant baseConstant, Throwable e) { super(baseConstant.getMsg(), e); this.msg = baseConstant.getMsg(); } public String getMsg() { return this.msg; } public void setMsg(String msg) { this.msg = msg; } public int getCode() { return this.code; } public void setCode(int code) { this.code = code; } }
9155316dd7fa08081a2cfdb5b18ed829e3d0c6e5
[ "Markdown", "Java" ]
6
Java
CraztTy/myhome
d1239fcb9081351336f8a460c55050485853580e
d49b647a96c2ff93c100ac331ed3e9c0a93f3a2c
refs/heads/master
<repo_name>br0xen/user-config<file_sep>/cfgedit/main.go package main import ( "fmt" "os" userConfig "github.com/br0xen/user-config" ) const AppName = "cfgedit" func main() { if len(os.Args) < 2 { printHelp() os.Exit(1) } whichConfig := os.Args[1] cfg, err := userConfig.NewConfig(whichConfig) if err != nil { fmt.Println("Couldn't find config directory: " + whichConfig) os.Exit(1) } op := "list" if len(os.Args) >= 3 { op = os.Args[2] } switch op { case "list": fmt.Println(cfg.GetKeyList()) } } func printHelp() { fmt.Println("Usage: " + AppName + " <which config> <operation>") fmt.Println(" <which-config> is ~/.config/<which-config>") fmt.Println(" <operation> can just be 'list' right now") } <file_sep>/addon_config.go package userConfig import ( "bytes" "errors" "fmt" "io/ioutil" "os" "strings" ) // AddonConfig is an additional ConfigFile type AddonConfig struct { Name string `toml:"-"` Path string `toml:"-"` Values map[string]map[string]string `toml:"-"` } // NewAddonConfig generates a Additional Config struct func NewAddonConfig(name, path string) (*AddonConfig, error) { af := &AddonConfig{Name: name, Path: path} af.Values = make(map[string]map[string]string) // Check if file exists //var f os.FileInfo var err error if _, err = os.Stat(af.GetFullPath()); os.IsNotExist(err) { if err = af.Save(); err != nil { return af, err } } if err := af.Load(); err != nil { return af, err } return af, nil } /** START of ConfigFile Interface Implementation **/ // GetName returns the name of this config file func (af *AddonConfig) GetName() string { return af.Name } // GetPath returns the path of this config file func (af *AddonConfig) GetPath() string { return af.Path } // Load loads config files into the config func (af *AddonConfig) Load() error { if strings.TrimSpace(af.Name) == "" || strings.TrimSpace(af.Path) == "" { return errors.New("Invalid ConfigFile Name: " + af.GetFullPath()) } // Config files end with .toml tomlData, err := ioutil.ReadFile(af.GetFullPath()) if err != nil { return err } fmt.Println(tomlData) // TODO: Figure out loading this into the struct //if _, err := toml.Decode(string(tomlData), &af); err != nil { // return err //} return nil } // Save writes the config to file(s) func (af *AddonConfig) Save() error { buf := new(bytes.Buffer) // TODO: Figure out writing struct to buf //if err := toml.NewEncoder(buf).Encode(af); err != nil { // return err //} return ioutil.WriteFile(af.GetFullPath(), buf.Bytes(), 0644) } // Set sets a key/value pair in af, if unable to save, revert to old value // (and return the error) func (af *AddonConfig) Set(category, k, v string) error { if _, ok := af.Values[category]; !ok { af.Values[category] = make(map[string]string) } oldVal := af.Values[category][k] af.Values[category][k] = v if err := af.Save(); err != nil { af.Values[category][k] = oldVal return err } return nil } // Get gets a key/value pair from af func (af *AddonConfig) Get(category, k string) string { if _, ok := af.Values[category]; !ok { return "" } return af.Values[category][k] } // GetFullPath returns the full path & filename to the config file func (af *AddonConfig) GetFullPath() string { return af.Path + "/" + af.Name + ".toml" } /** END of ConfigFile Interface Implementation **/ <file_sep>/config.go // Package userConfig eases the use of config files in a user's home directory package userConfig import ( "errors" "os" "strings" "time" "github.com/casimir/xdg-go" ) // Config is a stuct for managing the config type Config struct { name string generalConfig *GeneralConfig } // NewConfig generates a Config struct func NewConfig(name string) (*Config, error) { c := &Config{name: name} if err := c.Load(); err != nil { return c, err } return c, nil } // GetKeyList at the config level returns all keys in the <c.name>.conf file func (c *Config) GetKeyList() []string { return c.generalConfig.GetKeyList() } // Set at the config level sets a value in the <c.name>.conf file func (c *Config) Set(k, v string) error { return c.generalConfig.Set(k, v) } // SetBytes at the config level sets a value in the <c.name>.conf file func (c *Config) SetBytes(k string, v []byte) error { return c.generalConfig.SetBytes(k, v) } // SetInt saves an integer (as a string) in the <c.name>.conf file func (c *Config) SetInt(k string, v int) error { return c.generalConfig.SetInt(k, v) } // SetDateTime saves a time.Time (as a string) in the <c.name>.conf file func (c *Config) SetDateTime(k string, v time.Time) error { return c.generalConfig.SetDateTime(k, v) } // SetArray saves a string slice in the <c.name>.conf file func (c *Config) SetArray(k string, v []string) error { return c.generalConfig.SetArray(k, v) } // Get at the config level retrieves a value from the <c.name>.conf file func (c *Config) Get(k string) string { return c.generalConfig.Get(k) } // GetBytes at the config level retrieves a value from the <c.name>.conf file // and returns it as a byte slice func (c *Config) GetBytes(k string) []byte { return c.generalConfig.GetBytes(k) } // GetInt at the config level retrieves a value from the <c.name>.conf file // and returns it as an integer (or an error if conversion fails) func (c *Config) GetInt(k string) (int, error) { return c.generalConfig.GetInt(k) } // GetDateTime at the config level retrieves a value from the <c.name>.conf file func (c *Config) GetDateTime(k string) (time.Time, error) { return c.generalConfig.GetDateTime(k) } func (c *Config) GetArray(k string) ([]string, error) { return c.generalConfig.GetArray(k) } // DeleteKey at the config level removes a key from the <c.name>.conf file func (c *Config) DeleteKey(k string) error { return c.generalConfig.DeleteKey(k) } // GetConfigPath just returns the config path func (c *Config) GetConfigPath() string { return c.generalConfig.Path } // Load loads config files into the config func (c *Config) Load() error { var err error if strings.TrimSpace(c.name) == "" { return errors.New("Invalid Config Name: " + c.name) } var cfgPath string app := xdg.App{Name: c.name} cfgPath = app.ConfigPath("") if cfgPath != "" { if err = c.verifyOrCreateDirectory(cfgPath); err != nil { return err } } // Load general config if c.generalConfig, err = NewGeneralConfig(c.name, cfgPath); err != nil { return err } return nil } // Save writes the config to file(s) func (c *Config) Save() error { if c.generalConfig == nil { return errors.New("Bad setup.") } return c.generalConfig.Save() } // verifyOrCreateDirectory is a helper function for building an // individual directory func (c *Config) verifyOrCreateDirectory(path string) error { var tstDir *os.File var tstDirInfo os.FileInfo var err error if tstDir, err = os.Open(path); err != nil { if err = os.Mkdir(path, 0755); err != nil { return err } if tstDir, err = os.Open(path); err != nil { return err } } if tstDirInfo, err = tstDir.Stat(); err != nil { return err } if !tstDirInfo.IsDir() { return errors.New(path + " exists and is not a directory") } // We were able to open the path and it was a directory return nil } <file_sep>/config_file.go // Package userConfig eases the use of config files in a user's home directory package userConfig import ( "bytes" "encoding/json" "errors" "io/ioutil" "os" "strconv" "strings" "time" "github.com/BurntSushi/toml" ) // GeneralConfig is the basic config structure // All configs make with package userConfig will have this file type GeneralConfig struct { Name string `toml:"-"` Path string `toml:"-"` ConfigFiles []string `toml:"additional_config"` RawFiles []string `toml:"raw_files"` Values map[string]string `toml:"general"` } // NewGeneralConfig generates a General Config struct func NewGeneralConfig(name, path string) (*GeneralConfig, error) { gf := &GeneralConfig{Name: name, Path: path} gf.ConfigFiles = []string{} gf.RawFiles = []string{} gf.Values = make(map[string]string) if err := gf.Load(); err != nil { return gf, err } return gf, nil } // Load loads config files into the config func (gf *GeneralConfig) Load() error { if strings.TrimSpace(gf.Name) == "" || strings.TrimSpace(gf.Path) == "" { return errors.New("Invalid ConfigFile Name: " + gf.Path + string(os.PathSeparator) + gf.Name) } // Config files end with .conf cfgPath := gf.Path + string(os.PathSeparator) + gf.Name + ".conf" tomlData, err := ioutil.ReadFile(cfgPath) if err != nil { // Couldn't find the file, save a new one if err = gf.Save(); err != nil { return err } } if _, err := toml.Decode(string(tomlData), &gf); err != nil { return err } return nil } // Save writes the config to file(s) func (gf *GeneralConfig) Save() error { buf := new(bytes.Buffer) cfgPath := gf.Path + string(os.PathSeparator) + gf.Name + ".conf" if err := toml.NewEncoder(buf).Encode(gf); err != nil { return err } return ioutil.WriteFile(cfgPath, buf.Bytes(), 0644) } // GetKeyList returns a list of all keys in the config file func (gf *GeneralConfig) GetKeyList() []string { var ret []string for k, _ := range gf.Values { ret = append(ret, k) } return ret } // Set sets a key/value pair in gf, if unable to save, revert to old value // (and return the error) func (gf *GeneralConfig) Set(k, v string) error { oldVal := gf.Values[k] gf.Values[k] = v if err := gf.Save(); err != nil { gf.Values[k] = oldVal return err } return nil } // SetBytes at the config level sets a value in the <c.name>.conf file func (gf *GeneralConfig) SetBytes(k string, v []byte) error { return gf.Set(k, string(v)) } // SetInt sets an integer value (as a string) in the config file func (gf *GeneralConfig) SetInt(k string, v int) error { return gf.Set(k, strconv.Itoa(v)) } // SetDateTime sets a DateTime value (as a string) in the config file func (gf *GeneralConfig) SetDateTime(k string, v time.Time) error { return gf.Set(k, v.Format(time.RFC3339)) } // SetArray sets a string slice value (as a string) in the config file func (gf *GeneralConfig) SetArray(k string, v []string) error { b, e := json.Marshal(v) if e != nil { return e } return gf.SetBytes(k, b) } // Get gets a key/value pair from gf func (gf *GeneralConfig) Get(k string) string { return gf.Values[k] } // GetInt gets a key/value pair from gf and return it as an integer // An error if it can't be converted func (gf *GeneralConfig) GetInt(k string) (int, error) { return strconv.Atoi(gf.Get(k)) } // GetDateTime gets a key/value pair from gf and returns it as a time.Time // An error if it can't be converted func (gf *GeneralConfig) GetDateTime(k string) (time.Time, error) { return time.Parse(time.RFC3339, gf.Get(k)) } // GetBytes gets a key/value pair from gf and returns it as a byte slice // Or an error if it fails for whatever reason func (gf *GeneralConfig) GetBytes(k string) []byte { return []byte(gf.Get(k)) } func (gf *GeneralConfig) GetArray(k string) ([]string, error) { var ret []string err := json.Unmarshal(gf.GetBytes(k), &ret) return ret, err } // DeleteKey removes a key from the file func (gf *GeneralConfig) DeleteKey(k string) error { oldVal := gf.Get(k) delete(gf.Values, k) if err := gf.Save(); err != nil { gf.Values[k] = oldVal return err } return nil } <file_sep>/README.md # user-config A go library for easily managing config files/directories in your XDGConfig directory<file_sep>/cfgedit/README.md cfgedit ==== This is a simple utility for editing toml config files from the command line. It's basically a manual testing app for github.com/br0xen/user-config
340f47f0e01ccf35e68f47053cf13be2a48d63f3
[ "Markdown", "Go" ]
6
Go
br0xen/user-config
16e743ec93a27e510b5f5ff2acdb9ea8947e0ccf
ee0df9eee632514ae2f0e76193187690b535866b
refs/heads/master
<file_sep>package com.example.webview; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.app.NotificationManager; import android.app.NotificationChannel; import android.app.Notification; import android.app.PendingIntent; import android.content.Intent; import android.graphics.BitmapFactory; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import com.google.android.material.snackbar.Snackbar; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationCompat.Action; import androidx.core.app.NotificationCompat.BigPictureStyle; import androidx.core.app.NotificationCompat.BigTextStyle; import androidx.core.app.NotificationCompat.InboxStyle; import androidx.core.app.NotificationCompat.MessagingStyle; import androidx.core.app.NotificationManagerCompat; import androidx.core.app.Person; import androidx.core.app.RemoteInput; import androidx.core.app.TaskStackBuilder; import androidx.core.content.ContextCompat; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import com.example.webview.ui.main.MainFragment; public class MainActivity extends AppCompatActivity { private final String CHANNEL_ID = "personal_notifications"; private final int NOTIFICATION_ID = 001; private Button button; public void onCreate(Bundle savedInstanceState) { final Context context = this; super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); button = (Button) findViewById(R.id.buttonUrl); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(context, WebViewActivity.class); startActivity(intent); displayNotification(arg0); } }); } public void displayNotification(View view) { createNotificationChannel(); NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID); builder.setSmallIcon(R.drawable.ic_sms_notification); builder.setContentTitle("Con-X"); builder.setContentText("There is a potential hotspot in your area!"); builder.setPriority(NotificationCompat.PRIORITY_HIGH); NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); notificationManager.notify(NOTIFICATION_ID, builder.build()); } private void createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { CharSequence name = "Personal Notifications"; String description = "Con-X notification system"; int importance = NotificationManager.IMPORTANCE_HIGH; NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, name, importance); notificationChannel.setDescription(description); NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); notificationManager.createNotificationChannel(notificationChannel); } } }
5c36f4142e378a25216777c103458d116cc8f26d
[ "Java" ]
1
Java
m22pi7/ConXAppAndroid
4c27f18d2f2f4a2b1c479809b74c9bda1a757e7e
cd8493197aba7c3e268bab9cd8182f220dbf0a2b
refs/heads/master
<repo_name>ConnorDCrawford/Homify<file_sep>/src/model/Homeowner/Validate.java package model.Homeowner; /** * Validate.java * Homify * * Created by <NAME> on 3/5/16. * Copyright © 2016 <NAME>. All rights reserved. */ public class Validate { public StringData errorMessages; private Boolean success = false; public Validate() { this.errorMessages = new StringData(); } public Validate(StringData stringData) { this(); validate(stringData); } /** * Validates the given Homeowner string model, writing field errors to this.errorMessages. * Indicates successful validation by writing to this.success * @param stringData The Order string model to be validated */ private void validate(StringData stringData) { Boolean success = true; if (stringData.homeownerFN.length() == 0) { errorMessages.homeownerFN = "First name is a required field."; success = false; } if (stringData.homeownerLN.length() == 0) { errorMessages.homeownerLN = "Last name is a required field."; success = false; } if (stringData.homeownerPwd.length() < 6) { errorMessages.homeownerPwd = "Password must be at least 6 characters long."; success = false; } if (stringData.homeownerEmail.length() == 0) { errorMessages.homeownerEmail = "Email address is a required field."; success = false; } if (stringData.homeownerZIP.length() != 5) { errorMessages.homeownerZIP = "ZIP code must be at least 5 digits."; success = false; } else if (!stringData.homeownerZIP.matches("[0-9]+")) { errorMessages.homeownerZIP = "ZIP code can only contain numbers."; success = false; } if (stringData.homeownerRoleID.equals("")) { errorMessages.homeownerRoleID = "Please select a role."; success = false; } this.success = success; } /** * Indicates if last attempt at validation was successful * @return True: Validation successful; False: Validation unsuccessful */ public Boolean wasSuccessful() { return this.success; } } <file_sep>/src/model/Contractor/Validate.java package model.Contractor; /** * Validate.java * Homify * * Created by <NAME> on 3/5/16. * Copyright © 2016 <NAME>. All rights reserved. */ public class Validate { public StringData errorMessages; private Boolean success = false; public Validate() { this.errorMessages = new StringData(); } public Validate(StringData stringData) { this(); validate(stringData); } /** * Validates the given Contractor string model, writing field errors to this.errorMessages. * Indicates successful validation by writing to this.success * @param stringData The Order string model to be validated */ private void validate(StringData stringData) { Boolean success = true; if (stringData.contractorName.length() == 0) { errorMessages.contractorName = "Contractor name is a required field."; success = false; } if (stringData.contractorEmail.length() == 0) { errorMessages.contractorEmail = "Contractor email is a required field."; success = false; } if (stringData.contractorPwd.length() < 6) { errorMessages.contractorPwd = "Password must be at least 6 characters long."; success = false; } if (stringData.contractorZIP.length() != 5) { errorMessages.contractorZIP = "ZIP code must be at least 5 digits."; success = false; } else if (!stringData.contractorZIP.matches("[0-9]+")) { errorMessages.contractorZIP = "ZIP code can only contain numbers."; success = false; } if (stringData.contractorServiceID.equals("")) { errorMessages.contractorServiceID = "Please select a type of service"; success = false; } this.success = success; } /** * Indicates if last attempt at validation was successful * @return True: Validation successful; False: Validation unsuccessful */ public Boolean wasSuccessful() { return this.success; } } <file_sep>/src/model/Homeowner/Logon.java package model.Homeowner; /** * Logon.java * Homify * * Created by <NAME> on 2/16/16. * Copyright © 2016 <NAME>. All rights reserved. */ import dbUtils.DbConn; import dbUtils.FormatUtils; import java.sql.PreparedStatement; import java.sql.ResultSet; public class Logon { /** * Finds the user with the given email and password. Used for logging in user. * @param dbc An open database connection. * @param emailAddress The desired user's email address * @param userPwd The desired user's password * @return A string model of the Homeowner, or null if not found */ public static StringData find(DbConn dbc, String emailAddress, String userPwd) { StringData foundHO = new StringData(); try { // Get MD5 of password String pwdDigest = FormatUtils.getMD5forString(userPwd); System.out.println(pwdDigest); String sql = "select homeowner_id, homeowner_firstname, homeowner_lastname, homeowner_zip" + " from Homeowner where homeowner_email = ? and homeowner_password_digest = ?"; PreparedStatement stmt = dbc.getConn().prepareStatement(sql); stmt.setString(1, emailAddress); stmt.setString(2, pwdDigest); ResultSet results = stmt.executeQuery(); if (results.next()) { foundHO.homeownerID = results.getObject("homeowner_id").toString(); foundHO.homeownerEmail = emailAddress; // take from parameter rather than DB foundHO.homeownerFN = results.getObject("homeowner_firstname").toString(); foundHO.homeownerLN = results.getObject("homeowner_lastname").toString(); foundHO.homeownerZIP = results.getObject("homeowner_zip").toString(); return foundHO; } else { return null; // means customer not found with given credentials. } } catch (Exception e) { foundHO.errorMsg = "Exception thrown in Logon.find(): " + e.getMessage(); return foundHO; } } } <file_sep>/src/view/OrderView.java package view; /** * OrderView.java * Homify * * Created by <NAME> on 3/1/16. * Copyright © 2016 <NAME>. All rights reserved. */ // classes imported from java.sql.* import java.sql.PreparedStatement; import java.sql.ResultSet; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; // classes in my project import dbUtils.*; import model.CombinedStringData; import model.Order.StringData; import model.StringDataList; public class OrderView { protected static StringData dbRowToStringData(ResultSet results) { StringData order = new StringData(); try { order.order_id = FormatUtils.formatInteger(results.getObject("order_id"));; order.order_price = FormatUtils.formatDollar(results.getObject("order_price")); order.order_date = FormatUtils.formatDate(results.getObject("order_date")); order.order_request = FormatUtils.formatString(results.getObject("order_request")); order.order_homeowner_id = FormatUtils.formatInteger(results.getObject("order_homeowner_id")); order.order_contractor_id = FormatUtils.formatInteger(results.getObject("order_contractor_id")); } catch (Exception e) { order.errorMsg = "Error in OrderView.dbRowToStringData: " + e.getMessage(); } return order; } /** * Returns an Order StringData model containing the info for the order with the specified ID. * @param orderID the ID of the desired Order. * @param dbc an open database connection. * @return the StringData for the specified ID */ public static StringData getOrder(String orderID, DbConn dbc) { PreparedStatement stmt; ResultSet results; StringData order = new StringData(); try { String sql = "SELECT order_id, order_price, order_date, order_request, order_homeowner_id, order_contractor_id " + "FROM `Order` " + "WHERE order_id = ?"; stmt = dbc.getConn().prepareStatement(sql); stmt.setString(1, orderID); results = stmt.executeQuery(); if (results.first()) { order = dbRowToStringData(results); } } catch (Exception e) { order.errorMsg = "Exception thrown in OrderView.getOrder(): " + e.getMessage(); } return order; } /** * This method returns a HTML table displaying all the records of the Order table. * @param cssTableClass The name of a CSS style that will be applied to the HTML table. * (This style should be defined in the JSP page (header or style sheet referenced by the page). * @param dbc an open database connection. * @param updateURL a string containing the URL to the update page, with a single parameter for ID * @return An string containing the HTML code of a table containing every order */ public static String listAllOrders(String cssTableClass, DbConn dbc, String updateURL) { // String type could have been used, but StringBuilder is more efficient // in this case where we are just appending StringBuilder sb = new StringBuilder(""); PreparedStatement stmt; ResultSet results; try { String sql = "SELECT order_id, order_price, order_date, order_request, contractor_name, contractor_email, " + "homeowner_firstname, homeowner_lastname, homeowner_email " + "FROM `Order`, Contractor, Homeowner " + "WHERE `Order`.order_homeowner_id = Homeowner.homeowner_id " + "AND `Order`.order_contractor_id = Contractor.contractor_id " + "ORDER BY order_id"; stmt = dbc.getConn().prepareStatement(sql); results = stmt.executeQuery(); // Set up table header sb.append("<table class='"); sb.append(cssTableClass); sb.append("'>"); sb.append("<tr>"); sb.append("<th>Order ID</th>"); sb.append("<th>Order Price</th>"); sb.append("<th>Order Date</th>"); sb.append("<th>Order Request</th>"); sb.append("<th>Contractor Name</th>"); sb.append("<th>Contractor Email</th>"); sb.append("<th>Homeowner Name</th>"); sb.append("<th>Homeowner Email</th>"); sb.append("<th/>"); if (updateURL.length() > 0) { sb.append("<th/>"); } // Add results to table while (results.next()) { sb.append("<tr>"); sb.append(FormatUtils.formatIntegerTd(results.getObject("order_id"))); sb.append(FormatUtils.formatDollarTd(results.getObject("order_price"))); sb.append(FormatUtils.formatDateTd(results.getObject("order_date"))); sb.append(FormatUtils.formatStringTd(results.getObject("order_request"))); sb.append(FormatUtils.formatStringTd(results.getObject("contractor_name"))); sb.append(FormatUtils.formatStringTd(results.getObject("contractor_email"))); sb.append("<td style='text-align:left'>"); sb.append(FormatUtils.formatString(results.getObject("homeowner_firstname"))); // don't add td since we want to combine first and last name sb.append(" "); sb.append(FormatUtils.formatString(results.getObject("homeowner_lastname"))); sb.append("</td>"); sb.append(FormatUtils.formatStringTd(results.getObject("homeowner_email"))); String id = FormatUtils.formatInteger(results.getObject("order_id")); if (updateURL.length() > 0) { sb.append(String.format("<td><a href='%s=%s'>Edit</a></td>", updateURL, id)); } sb.append(String.format("<td><a href='javascript:deleteRow(%s)'><img src='icons/delete.png'></a></td>", id)); sb.append("</tr>\n"); } sb.append("</table>"); results.close(); stmt.close(); return sb.toString(); } catch (Exception e) { return "Exception thrown in OrderView.listAllOrders(): " + e.getMessage() + "<br/> partial output: <br/>" + sb.toString(); } } /** * Lists all orders made by a given user * @param cssTableClass The CSS class name for the table * @param dbc The database connection * @param userID The desired user's ID * @return An string containing the HTML code of a table containing the user's orders, or a link prompting user to add an order if none exist */ public static String listUserOrders(String cssTableClass, DbConn dbc, String userID) { StringBuilder sb = new StringBuilder(""); PreparedStatement stmt = null; ResultSet results = null; try { String sql = "SELECT order_price, order_date, order_request, contractor_name, contractor_email " + "FROM `Order`, Contractor " + "WHERE `Order`.order_homeowner_id = ?" + "AND `Order`.order_contractor_id = Contractor.contractor_id " + "ORDER BY order_date"; stmt = dbc.getConn().prepareStatement(sql); stmt.setString(1, userID); // search for only specified user results = stmt.executeQuery(); // No results, so user has not created any orders yet. Prompt to create one rather than showing empty table. if (!results.first()) sb.append("Looks like you don't have any orders yet. <a href='insertOrder.jsp'>Create one now.</a>"); // Results > 0, so show table else { // Set up table header sb.append("<table class='"); sb.append(cssTableClass); sb.append("'>"); sb.append("<tr>"); sb.append("<th>Order Price</th>"); sb.append("<th>Order Date</th>"); sb.append("<th>Order Request</th>"); sb.append("<th>Contractor Name</th>"); sb.append("<th>Contractor Email</th>"); // Add results to table results.beforeFirst(); // Go back to start since we moved cursor to check first while (results.next()) { sb.append("<tr>"); sb.append(FormatUtils.formatDollarTd(results.getObject("order_price"))); sb.append(FormatUtils.formatDateTd(results.getObject("order_date"))); sb.append(FormatUtils.formatStringTd(results.getObject("order_request"))); sb.append(FormatUtils.formatStringTd(results.getObject("contractor_name"))); sb.append(FormatUtils.formatStringTd(results.getObject("contractor_email"))); sb.append("</tr>\n"); } sb.append("</table>"); results.close(); stmt.close(); } return sb.toString(); } catch (Exception e) { return "Exception thrown in OrderView.listUserOrders(): " + e.getMessage() + "<br/> partial output: <br/>" + sb.toString(); } } /** * Searches the database for Orders with the given parameters, ignoring parameter if it is empty * @param cssTableClass The CSS class name for the table * @param dbc The database connection * @param homeownerId Search parameter - user ID * @param contractorId Search parameter - contractor ID * @param startDate Search parameter - Start date of date range * @param endDate Search parameter - End date of date range * @return An string containing the HTML code of a table containing the search results */ public static String search(String cssTableClass, DbConn dbc, String homeownerId, String contractorId, String startDate, String endDate) { StringBuilder sb = new StringBuilder(""); PreparedStatement stmt; ResultSet results; try { String sql = "SELECT * FROM `Order`, Contractor, Homeowner " + "WHERE `Order`.order_contractor_id = Contractor.contractor_id " + "AND `Order`.order_homeowner_id = Homeowner.homeowner_id "; if (homeownerId.length() > 0) sql += "AND Homeowner.homeowner_id = ? "; if (contractorId.length() > 0) sql += "AND Contractor.contractor_id = ? "; if (startDate.length() > 0) sql += "AND order_date > ? "; if (endDate.length() > 0) sql += "AND order_date < ? "; sql += "ORDER BY order_date"; stmt = dbc.getConn().prepareStatement(sql); // Format dates for SQL format (yyyy-mm-dd) int count = 1; if (homeownerId.length() > 0) { stmt.setString(count, homeownerId); // search for user with specified email count++; } if (contractorId.length() > 0) { stmt.setString(count, contractorId); // search for contractor with specified email count++; } if (startDate.length() > 0) { // Format startDate startDate = formatDate(startDate); if (startDate.length() == 0) { return "ERROR: Invalid date format"; } stmt.setString(count, startDate); count++; } if (endDate.length() > 0) { // Format endDate endDate = formatDate(endDate); if (endDate.length() == 0) { return "ERROR: Invalid date format"; } stmt.setString(count, endDate); } results = stmt.executeQuery(); // Set up table header sb.append("<table class='"); sb.append(cssTableClass); sb.append("'>"); sb.append("<tr>"); sb.append("<th>Order Price</th>"); sb.append("<th>Order Date</th>"); sb.append("<th>Order Request</th>"); sb.append("<th>Contractor Name</th>"); sb.append("<th>Contractor Email</th>"); sb.append("<th>Homeowner Name</th>"); sb.append("<th>Homeowner Email</th>"); // Add results to table while (results.next()) { sb.append("<tr>"); sb.append(FormatUtils.formatDollarTd(results.getObject("order_price"))); sb.append(FormatUtils.formatDateTd(results.getObject("order_date"))); sb.append(FormatUtils.formatStringTd(results.getObject("order_request"))); sb.append(FormatUtils.formatStringTd(results.getObject("contractor_name"))); sb.append(FormatUtils.formatStringTd(results.getObject("contractor_email"))); sb.append("<td style='text-align:left'>"); sb.append(FormatUtils.formatString(results.getObject("homeowner_firstname"))); // don't add td since we want to combine first and last name sb.append(" "); sb.append(FormatUtils.formatString(results.getObject("homeowner_lastname"))); sb.append("</td>"); sb.append(FormatUtils.formatStringTd(results.getObject("homeowner_email"))); sb.append("</tr>\n"); } sb.append("</table>"); results.close(); stmt.close(); return sb.toString(); } catch (Exception e) { return "Exception thrown in OrderSql.listAllUsers(): " + e.getMessage() + "<br/> partial output: <br/>" + sb.toString(); } } public static StringDataList getOrderList(DbConn dbc, String homeownerId, String contractorId, String startDate, String endDate) { StringDataList orderList = new StringDataList(0); PreparedStatement stmt; ResultSet results; try { String sql = "SELECT * FROM `Order`, Contractor, Homeowner " + "WHERE `Order`.order_contractor_id = Contractor.contractor_id " + "AND `Order`.order_homeowner_id = Homeowner.homeowner_id "; if (homeownerId.length() > 0) sql += "AND Homeowner.homeowner_id = ? "; if (contractorId.length() > 0) sql += "AND Contractor.contractor_id = ? "; if (startDate.length() > 0) sql += "AND order_date > ? "; if (endDate.length() > 0) sql += "AND order_date < ? "; sql += "ORDER BY order_date"; stmt = dbc.getConn().prepareStatement(sql); int count = 1; if (homeownerId.length() > 0) { stmt.setString(count, homeownerId); // search for user with specified email count++; } if (contractorId.length() > 0) { stmt.setString(count, contractorId); // search for contractor with specified email count++; } if (startDate.length() > 0) { // Format startDate startDate = formatDate(startDate); if (startDate.length() == 0) { orderList.dbError = "ERROR: Invalid date format"; return orderList; } stmt.setString(count, startDate); count++; } if (endDate.length() > 0) { // Format endDate endDate = formatDate(endDate); if (endDate.length() == 0) { orderList.dbError = "ERROR: Invalid date format"; return orderList; } stmt.setString(count, endDate); } results = stmt.executeQuery(); CombinedStringData order; while (results.next()) { order = new CombinedStringData(); order.orderStringData = dbRowToStringData(results); order.homeownerStringData = UserView.dbRowToStringData(results); order.contractorStringData = ContractorView.dbRowToStringData(results); orderList.stringDataList.add(order); } results.close(); stmt.close(); } catch (Exception e) { orderList.dbError = e.getMessage(); } return orderList; } private static String formatDate(String dateString) { /* Because of Chrome's HTML5 date pickers, which do not let the programmer define the date format, * it is necessary to first try to format the date with my format, then if it fails check for Chrome's format. */ try { // My format SimpleDateFormat df = new SimpleDateFormat("MM/dd/yy"); Date date = df.parse(dateString); df.applyPattern("yyyy-MM-dd"); return df.format(date); } catch (ParseException my_pe) { try { // Chrome format SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Date date = df.parse(dateString); df.applyPattern("yyyy-MM-dd"); return df.format(date); } catch (ParseException chrome_pe) { // Both fail return ""; } } } } <file_sep>/src/model/Contractor/StringData.java package model.Contractor; /** * StringData.java * Homify * * Created by <NAME> on 2/15/16. * Copyright © 2016 <NAME>. All rights reserved. */ public class StringData { public String contractorID = ""; public String contractorName = ""; public String contractorEmail = ""; public String contractorPwd = ""; public String contractorZIP = ""; public String contractorInfo = ""; public String contractorServiceID = ""; public String errorMsg = ""; public String toString() { return "Homeowner ID: " + this.contractorID + ", Email: " + this.contractorEmail + ", Password: " + this.contractorPwd + ", Name: " + this.contractorName + ", ZIP: " + this.contractorZIP + ", Info: " + this.contractorInfo + ", Service ID: " + this.contractorServiceID; } } <file_sep>/src/model/CombinedStringData.java package model; /** * CombinedStringData * Homify * * Created by <NAME> on 4/6/16. * Copyright © 2016 <NAME>. All rights reserved. */ public class CombinedStringData { public model.Homeowner.StringData homeownerStringData; public model.Contractor.StringData contractorStringData; public model.Order.StringData orderStringData; } <file_sep>/src/model/Order/DbMods.java package model.Order; import dbUtils.DbConn; import javax.servlet.http.HttpServletResponse; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Types; /** * DbMods * Homify * <p> * Created by <NAME> on 3/28/16. * Copyright © 2016 <NAME>. All rights reserved. */ public class DbMods { /** * Validates Order information, inserts a new order into the database upon success * @param stringData The string model for the Order * @param dbConn The database connection * @param response The implicit HttpServletResponse, used for redirecting back to orders page * @return A Order string model containing any errors from validation */ public static StringData insert(StringData stringData, DbConn dbConn, HttpServletResponse response) { CallableStatement stmt = null; Validate validate = new Validate(stringData); if (validate.wasSuccessful() && dbConn.getErr().length() == 0) { try { Boolean hasPrice = stringData.order_price.length() > 0; Boolean hasDate = stringData.order_date.length() > 0; Boolean hasRequest = stringData.order_request.length() > 0; String sql = "INSERT INTO `Order` (order_price, order_date, order_request, order_homeowner_id, order_contractor_id) " + "VALUES (?, ?, ?, ?, ?)"; stmt = dbConn.getConn().prepareCall(sql); // prepareStatement(sql); if (hasPrice) stmt.setString(1, stringData.order_price); else stmt.setNull(1, Types.DECIMAL); if (hasDate) stmt.setString(2, stringData.order_date); else stmt.setNull(2, Types.DATE); if (hasRequest) stmt.setString(3, stringData.order_request); else stmt.setNull(3, Types.LONGVARCHAR); stmt.setString(4, stringData.order_homeowner_id); stmt.setString(5, stringData.order_contractor_id); stmt.execute(); validate.errorMessages.errorMsg = ""; response.sendRedirect("orders.jsp"); } catch (Exception e) { validate.errorMessages.errorMsg = "Exception thrown in OrderView.insert: " + e.getMessage(); } } return validate.errorMessages; } /** * Validates Order information, updates order in the database upon success * @param stringData The string model for the Order * @param dbConn The database connection * @param response The implicit HttpServletResponse, used for redirecting back to orders page * @return A Order string model containing any errors from validation */ public static StringData update(StringData stringData, DbConn dbConn, HttpServletResponse response) { PreparedStatement stmt = null; Validate validate = new Validate(stringData); if (validate.wasSuccessful() && dbConn.getErr().length() == 0) { try { Boolean hasPrice = stringData.order_price.length() > 0; Boolean hasDate = stringData.order_date.length() > 0; Boolean hasRequest = stringData.order_request.length() > 0; String sql = "UPDATE `Order` " + "SET order_price=?, order_date=?, order_request=?, order_homeowner_id=?, order_contractor_id=? " + "WHERE order_id=?"; stmt = dbConn.getConn().prepareStatement(sql); if (hasPrice) stmt.setString(1, stringData.order_price); else stmt.setNull(1, Types.DECIMAL); if (hasDate) stmt.setString(2, stringData.order_date); else stmt.setNull(2, Types.DATE); if (hasRequest) stmt.setString(3, stringData.order_request); else stmt.setNull(3, Types.LONGVARCHAR); stmt.setString(4, stringData.order_homeowner_id); stmt.setString(5, stringData.order_contractor_id); stmt.setString(6, stringData.order_id); stmt.execute(); validate.errorMessages.errorMsg = ""; response.sendRedirect("orders.jsp"); } catch (Exception e) { validate.errorMessages.errorMsg = "Exception thrown in OrderView.insert" + e.getMessage(); } } return validate.errorMessages; } /** * Deletes a record from the Order table * @param ID The ID of Order * @param dbc The database connection * @param response The implicit HttpServletResponse, used for redirecting back to orders page * @return A string containing the error code */ public static String delete(String ID, DbConn dbc, HttpServletResponse response) { PreparedStatement stmt; String errorMsg; try { String sql = "DELETE FROM `Order` WHERE order_id=?"; stmt = dbc.getConn().prepareStatement(sql); stmt.setString(1, ID); stmt.execute(); errorMsg = ""; response.sendRedirect("orders.jsp"); } catch (SQLException sqlException) { errorMsg = String.format("handleError(%s);", sqlException.getErrorCode()); } catch (Exception e) { errorMsg = String.format("handleError(%s);", e.getMessage()); } return errorMsg; } } <file_sep>/src/dbUtils/MakeSelectTag.java package dbUtils; import java.sql.PreparedStatement; import java.sql.ResultSet; /** * MakeSelectTag.java * Homify * * Created by <NAME> on 3/4/16. * Copyright © 2016 <NAME>. All rights reserved. */ public class MakeSelectTag { /** * Creates an HTML select form containing the results of the given mySQL statement * @param dbc An open database connection. * @param selectName The name of the select form (i.e. <select name="[selectName]">...) * @param sqlStmt The mySQL statement, the results of which will create the options for the select form * @param selectedId The ID of the option which will show as selected. Will show default option if null or empty * @param optionDesc The name of the default option (e.g. "Select a Color"). Selected on first rendering. * @return The HTML code for the select form generated from the results. Only contains default option if no results. */ public static String makeSelectTag(DbConn dbc, String selectName, String sqlStmt, String selectedId, String optionDesc) { StringBuilder sb = new StringBuilder(""); PreparedStatement stmt = null; ResultSet results = null; // <select> ... sb.append("<select name = '"); sb.append(selectName); sb.append("'>"); // <option>Default Option</option> sb.append("<option value = ''"); if (selectedId == null || selectedId.equals(optionDesc)) sb.append(" selected='selected'"); sb.append(">"); sb.append(optionDesc); sb.append("</option>"); try { stmt = dbc.getConn().prepareStatement(sqlStmt); results = stmt.executeQuery(); // ...<option>Results</option>... while (results.next()) { int resultId = results.getInt(1); String resultName = FormatUtils.formatString(results.getString(2)); sb.append("<option value='"+resultId+"'"); if (selectedId.equals(resultId+"")) sb.append(" selected='selected'"); sb.append(">"); sb.append(resultName); sb.append("</option>\n"); } results.close(); stmt.close(); } catch (Exception e) { System.out.println(dbc.getErr()); } sb.append("</select>\n"); return sb.toString(); } } <file_sep>/web/includes/AJAX_Search.js function $(element) { return document.getElementById(element); } function ajaxGetSelectTags() { //alert ('sending request'); var url = "SelectTags_Web_API.jsp"; //alert("url is " + url); httpReq.open("GET", url); httpReq.onreadystatechange = ajaxCallbackSelectTags; httpReq.send(null); } function ajaxCallbackSelectTags() { //alert('handling response'); if (httpReq.readyState == 4 && httpReq.status == 200) { var response = httpReq.responseText; console.log("response text is " + response); // wrap the json in parentheses to avoid tripping over javascript ambiguity... response = "(" + response + ")"; var obj = eval(response); console.log(obj); if (obj == null) { $("databaseError").innerHTML = "Null Object?"; return; } if (obj.dbError == null) { $("databaseError").innerHTML = "Null database error?"; return; } if (obj.dbError.length > 0) { $("databaseError").innerHTML = obj.dbError; return; } jsBuildSelectTag(obj.userSelectTag.list, 'userId', 'userSpan'); jsBuildSelectTag(obj.contractorSelectTag.list, 'contractorId', 'contractorSpan'); $("databaseError").innerHTML = obj.dbError; // Get table data once completed ajaxGetData(); } } function jsBuildSelectTag(optionList, tagId, parentId) { // console.log("tagId: " + tagId); // console.log("parentId: " + parentId); var parent = document.getElementById(parentId); // get ref to parent element // Create a select tag, set it's id and append this tag to the parent. var selectList = document.createElement("select"); selectList.id = tagId; parent.appendChild(selectList); //Create and append the options // i in optionList just iterates i from 0 to length of list-1. for (i in optionList) { // new Option() input parameters are displayed option, option value. var myOption = new Option(optionList[i].name, optionList[i].id); // displayed option, option value selectList.appendChild(myOption); } } function ajaxGetData() { //alert ('sending request'); var url = "DataSearch_Web_API.jsp"; if ($("userId") != null) { url += "?hID=" + $("userId").value; url += "&cID=" + $("contractorId").value; url += "&startDate=" + $("start_date").value; url += "&endDate=" + $("end_date").value; } //alert("url is " + url); httpReq.open("GET", url); httpReq.onreadystatechange = ajaxCallbackData; httpReq.send(null); $("resultTable").innerHTML = ""; } function ajaxCallbackData() { //alert('handling response'); console.log(httpReq.responseText); if (httpReq.readyState == 4 && httpReq.status == 200) { var response = httpReq.responseText; // alert("response text is " + response); // wrap the json in parentheses to avoid tripping over javascript ambiguity... response = "(" + response + ")"; var obj = eval(response); if (obj.dbError == null) { $("orderTable").innerHTML = "Search is currently unavailable."; debugger; return; } if (obj.dbError.length > 0) { $("orderTable").innerHTML = "Error: " + obj.dbError; debugger; return; } if (parseInt(obj.listSize) == 0) { $("orderTable").innerHTML = "No Orders Match Your Search"; debugger; return; } var userDictionary; var contractorDictionary; var newTable = $("resultTable"); var newRow; var priceCell; var dateCell; var requestCell; var cNameCell; var cEmailCell; var hNameCell; var hEmailCell; // Add data to table for (i in obj.stringDataList) { var j = 0; var current = obj.stringDataList[i]; // Add rows newRow = newTable.insertRow(i); // Add cells priceCell = newRow.insertCell(j++); dateCell = newRow.insertCell(j++); requestCell = newRow.insertCell(j++); cNameCell = newRow.insertCell(j++); cEmailCell = newRow.insertCell(j++); hNameCell = newRow.insertCell(j++); hEmailCell = newRow.insertCell(j); // Fill in data priceCell.innerHTML = current.orderStringData.order_price; dateCell.innerHTML = current.orderStringData.order_date; requestCell.innerHTML = current.orderStringData.order_request; cNameCell.innerHTML = current.contractorStringData.contractorName; cEmailCell.innerHTML = current.contractorStringData.contractorEmail; hNameCell.innerHTML = current.homeownerStringData.homeownerFN+" "+current.homeownerStringData.homeownerLN; hEmailCell.innerHTML = current.homeownerStringData.homeownerEmail; } // Create table header newRow = newTable.insertRow(0); var th = document.createElement("TH"); th.innerHTML = "Order Price"; newRow.appendChild(th); var th = document.createElement("TH"); th.innerHTML = "Order Date"; newRow.appendChild(th); var th = document.createElement("TH"); th.innerHTML = "Order Request"; newRow.appendChild(th); var th = document.createElement("TH"); th.innerHTML = "Contractor Name"; newRow.appendChild(th); var th = document.createElement("TH"); th.innerHTML = "Contractor Email"; newRow.appendChild(th); var th = document.createElement("TH"); th.innerHTML = "Homeowner Name"; newRow.appendChild(th); var th = document.createElement("TH"); th.innerHTML = "Homeowner Email"; newRow.appendChild(th); } } // MAIN PROGRAM //Make the XMLHttpRequest Object var httpReq; if (window.XMLHttpRequest) { httpReq = new XMLHttpRequest(); //For Firefox, Safari, Opera } else if (window.ActiveXObject) { httpReq = new ActiveXObject("Microsoft.XMLHTTP"); //For IE 5+ } else { alert('ajax not supported'); } ajaxGetSelectTags();<file_sep>/src/model/Order/Validate.java package model.Order; import java.util.Date; import java.text.ParseException; import java.text.SimpleDateFormat; /** * Validate.java * Homify * * Created by <NAME> on 3/5/16. * Copyright © 2016 <NAME>. All rights reserved. */ public class Validate { public StringData errorMessages; private Boolean success = false; public Validate() { this.errorMessages = new StringData(); } public Validate(StringData stringData) { this(); validate(stringData); } /** * Validates the given Order string model, writing field errors to this.errorMessages. * Indicates successful validation by writing to this.success * @param stringData The Order string model to be validated */ private void validate(StringData stringData) { Boolean success = true; if (stringData.order_price.length() != 0) { try { if (stringData.order_price.charAt(0) == '$') { stringData.order_price = stringData.order_price.substring(1); } double d = Double.parseDouble(stringData.order_price); } catch(NumberFormatException nfe) { errorMessages.order_price = "Price must be a numeric value."; success = false; } } if (stringData.order_date.length() != 0) { try { SimpleDateFormat df = new SimpleDateFormat("MM/dd/yy"); Date date = df.parse(stringData.order_date); df.applyPattern("yy-MM-dd"); stringData.order_date = df.format(date); } catch (ParseException e) { errorMessages.order_date = "Please enter date in MM/DD/YYYY format."; success = false; } } if (stringData.order_homeowner_id.length() == 0){ errorMessages.order_homeowner_id = "Homeowner is a required field."; success = false; } if (stringData.order_contractor_id.length() == 0) { errorMessages.order_contractor_id = "Contractor is a required field."; success = false; } this.success = success; } /** * Indicates if last attempt at validation was successful * @return True: Validation successful; False: Validation unsuccessful */ public Boolean wasSuccessful() { return this.success; } } <file_sep>/src/model/Homeowner/StringData.java package model.Homeowner; /** * StringData.java * Homify * * Created by <NAME> on 2/15/16. * Copyright © 2016 <NAME>. All rights reserved. */ public class StringData { public String homeownerID = ""; public String homeownerFN = ""; public String homeownerLN = ""; public String homeownerEmail = ""; public String homeownerPwd = ""; public String homeownerZIP = ""; public String homeownerRoleID = ""; public String errorMsg = ""; public String toString() { return "Homeowner ID: " + this.homeownerID + ", Email: " + this.homeownerEmail + ", Password: " + <PASSWORD>.homeownerPwd + ", First name: " + this.homeownerFN + ", Last name: " + this.homeownerLN + ", ZIP: " + this.homeownerZIP + ", Role ID: " + this.homeownerRoleID; } } <file_sep>/src/view/UserView.java package view; /** * UserView.java * Homify * * Created by <NAME> on 3/1/16. * Copyright © 2016 <NAME>. All rights reserved. */ // classes imported from java.sql.* import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; // classes in my project import dbUtils.*; import model.Homeowner.StringData; public class UserView { protected static StringData dbRowToStringData(ResultSet results) { StringData user = new StringData(); try { user.homeownerID = FormatUtils.formatInteger(results.getObject("homeowner_id"));; user.homeownerFN = FormatUtils.formatString(results.getObject("homeowner_firstname")); user.homeownerLN = FormatUtils.formatString(results.getObject("homeowner_lastname")); user.homeownerEmail = FormatUtils.formatString(results.getObject("homeowner_email")); user.homeownerZIP = FormatUtils.formatInteger(results.getObject("homeowner_zip")); user.homeownerRoleID = FormatUtils.formatInteger(results.getObject("homeowner_role_id")); } catch (Exception e) { user.errorMsg = "Error in UserView.dbRowToStringData: " + e.getMessage(); } return user; } /** * Returns a Homeowner StringData model containing the info for the user with the specified ID. * @param userID the ID of the desired Homeowner. * @param dbc an open database connection. * @return the StringData for the specified ID */ public static StringData getUser(String userID, DbConn dbc) { PreparedStatement stmt; ResultSet results; StringData user = new StringData(); try { String sql = "SELECT homeowner_id, homeowner_firstname, homeowner_lastname, homeowner_email, " + "homeowner_password_digest, homeowner_zip, homeowner_create_time, homeowner_role_id " + "FROM Homeowner " + "WHERE homeowner_id = ?"; stmt = dbc.getConn().prepareStatement(sql); stmt.setString(1, userID); results = stmt.executeQuery(); if (results.first()) { user = dbRowToStringData(results); } } catch (Exception e) { user.errorMsg = "Exception thrown in UserView.getUser(): " + e.getMessage(); } return user; } /** * This method returns a HTML table displaying all the records of the Homeowner table. * @param cssTableClass The name of a CSS style that will be applied to the HTML table. * (This style should be defined in the JSP page (header or style sheet referenced by the page). * @param dbc an open database connection. * @param updateURL a string containing the URL to the update page, with a single parameter for ID * @return An string containing the HTML code of a table containing every user */ public static String listAllUsers(String cssTableClass, DbConn dbc, String updateURL) { // String type could have been used, but StringBuilder is more efficient in this case where we are just appending StringBuilder sb = new StringBuilder(""); PreparedStatement stmt; ResultSet results; try { String sql = "SELECT homeowner_id, homeowner_firstname, homeowner_lastname, homeowner_email, " + "homeowner_password_digest, homeowner_zip, homeowner_create_time, homeowner_role_id, role_id, role_name " + "FROM Homeowner, UserRole " + "WHERE Homeowner.homeowner_role_id = UserRole.role_id " + "ORDER BY homeowner_id"; stmt = dbc.getConn().prepareStatement(sql); results = stmt.executeQuery(); // Set up table header sb.append("<table class='"); sb.append(cssTableClass); sb.append("'>"); sb.append("<tr>"); sb.append("<th>User ID</th>"); sb.append("<th>User First Name</th>"); sb.append("<th>User Last Name</th>"); sb.append("<th>User Email</th>"); sb.append("<th>User Password MD5</th>"); sb.append("<th>User ZIP</th>"); sb.append("<th>User Active Since</th>"); sb.append("<th>User Role</th>"); sb.append("<th/>"); if (updateURL.length() > 0) { sb.append("<th/>"); } // Add results to table while (results.next()) { sb.append("<tr>"); sb.append(FormatUtils.formatIntegerTd(results.getObject("homeowner_id"))); sb.append(FormatUtils.formatStringTd(results.getObject("homeowner_firstname"))); sb.append(FormatUtils.formatStringTd(results.getObject("homeowner_lastname"))); sb.append(FormatUtils.formatStringTd(results.getObject("homeowner_email"))); sb.append(FormatUtils.formatStringTd(results.getObject("homeowner_password_digest"))); sb.append(FormatUtils.formatIntegerTd(results.getObject("homeowner_zip"))); sb.append(FormatUtils.formatDateTd(results.getObject("homeowner_create_time"))); sb.append(FormatUtils.formatStringTd(results.getObject("role_name"))); String id = FormatUtils.formatInteger(results.getObject("homeowner_id")); if (updateURL.length() > 0) { sb.append(String.format("<td><a href='%s=%s'>Edit</a></td>", updateURL, id)); } sb.append(String.format("<td><a href='javascript:deleteRow(%s)'><img src='icons/delete.png'></a></td>", id)); sb.append("</tr>\n"); } sb.append("</table>"); results.close(); stmt.close(); return sb.toString(); } catch (Exception e) { return "Exception thrown in UserView.listAllUsers(): " + e.getMessage() + "<br/> partial output: <br/>" + sb.toString(); } } public static StringData[] getUserList(DbConn dbc) { ArrayList<StringData> userList = new ArrayList<>(0); PreparedStatement stmt; ResultSet results; try { String sql = "SELECT homeowner_id, homeowner_firstname, homeowner_lastname, homeowner_email, " + "homeowner_password_digest, homeowner_zip, homeowner_create_time, homeowner_role_id, role_id, role_name " + "FROM Homeowner, UserRole " + "WHERE Homeowner.homeowner_role_id = UserRole.role_id " + "ORDER BY homeowner_id"; stmt = dbc.getConn().prepareStatement(sql); results = stmt.executeQuery(); StringData user; while (results.next()) { user = dbRowToStringData(results); userList.add(user); } results.close(); stmt.close(); } catch (Exception e) { System.out.println(e.getMessage()); } StringData[] usersArray = new StringData[userList.size()]; return userList.toArray(usersArray); } }<file_sep>/src/model/Contractor/DbMods.java package model.Contractor; import dbUtils.DbConn; import dbUtils.FormatUtils; import javax.servlet.http.HttpServletResponse; import java.sql.PreparedStatement; import java.sql.Types; import java.sql.SQLException; /** * DbMods * Homify * <p> * Created by <NAME> on 3/28/16. * Copyright © 2016 <NAME>. All rights reserved. */ public class DbMods { /** * Validates Contractor information, inserts a new user into the database upon success * @param stringData The string model for the Contractor * @param dbConn The database connection * @param response The implicit HttpServletResponse, used for redirecting back to contractors page * @return A Contractor string model containing any errors from validation */ public static StringData insert(StringData stringData, DbConn dbConn, HttpServletResponse response) { PreparedStatement stmt; Validate validate = new Validate(stringData); if (validate.wasSuccessful() && dbConn.getErr().length() == 0) { try { Boolean hasInfo = stringData.contractorInfo.length() > 0; String sql = "INSERT INTO Contractor (contractor_name, contractor_email, contractor_password_digest, contractor_zip, contractor_info, services_service_id) " + "VALUES (?, ?, ?, ?, ?, ?)"; stmt = dbConn.getConn().prepareStatement(sql); stmt.setString(1, stringData.contractorName); stmt.setString(2, stringData.contractorEmail); stmt.setString(3, FormatUtils.getMD5forString(stringData.contractorPwd)); stmt.setString(4, stringData.contractorZIP); if (hasInfo) stmt.setString(5, stringData.contractorInfo); else stmt.setNull(5, Types.LONGVARCHAR); stmt.setString(6, stringData.contractorServiceID); stmt.execute(); validate.errorMessages.errorMsg = ""; response.sendRedirect("contractors.jsp"); } catch (Exception e) { validate.errorMessages.errorMsg = e.getMessage(); } } return validate.errorMessages; } /** * Validates Contractor information, updates contractor in the database upon success * @param stringData The string model for the Contractor * @param dbConn The database connection * @param response The implicit HttpServletResponse, used for redirecting back to contractors page * @return A Contractor string model containing any errors from validation */ public static StringData update(StringData stringData, DbConn dbConn, HttpServletResponse response) { PreparedStatement stmt; Validate validate = new Validate(stringData); if (validate.wasSuccessful() && dbConn.getErr().length() == 0) { try { Boolean hasInfo = stringData.contractorInfo.length() > 0; String sql = "UPDATE Contractor " + "SET contractor_name=?, contractor_email=?, contractor_password_digest=?, contractor_zip=?, contractor_info=?, services_service_id=? " + "WHERE contractor_id=?"; stmt = dbConn.getConn().prepareStatement(sql); stmt.setString(1, stringData.contractorName); stmt.setString(2, stringData.contractorEmail); stmt.setString(3, FormatUtils.getMD5forString(stringData.contractorPwd)); stmt.setString(4, stringData.contractorZIP); if (hasInfo) stmt.setString(5, stringData.contractorInfo); else stmt.setNull(5, Types.LONGVARCHAR); stmt.setString(6, stringData.contractorServiceID); stmt.setString(7, stringData.contractorID); stmt.execute(); validate.errorMessages.errorMsg = ""; response.sendRedirect("contractors.jsp"); } catch (Exception e) { validate.errorMessages.errorMsg = e.getMessage(); } } return validate.errorMessages; } /** * Deletes a record from the Contractor table * @param ID The ID of Contractor * @param dbc The database connection * @param response The implicit HttpServletResponse, used for redirecting back to orders page * @return A string containing the error code */ public static String delete(String ID, DbConn dbc, HttpServletResponse response) { PreparedStatement stmt; String errorMsg = ""; try { String sql = "DELETE FROM Contractor WHERE contractor_id=?"; stmt = dbc.getConn().prepareStatement(sql); stmt.setString(1, ID); stmt.execute(); errorMsg = ""; response.sendRedirect("contractors.jsp"); } catch (SQLException sqlException) { errorMsg = String.format("handleError(%s);", sqlException.getErrorCode()); } catch (Exception e) { errorMsg = String.format("handleError(%s);", e.getMessage()); } return errorMsg; } } <file_sep>/src/model/StringDataList.java package model; import java.util.ArrayList; /** * StringDataList * Homify * * Created by <NAME> on 4/6/16. * Copyright © 2016 <NAME>. All rights reserved. */ public class StringDataList { public ArrayList stringDataList; public String dbError = ""; public StringDataList(int listSize) { this.stringDataList = new ArrayList<>(listSize); } }
36191babf75b076da68064f833d2ce7261bb58f4
[ "JavaScript", "Java" ]
14
Java
ConnorDCrawford/Homify
34b944d28dd1f68af8fbbe2ca60881c6ecc2a8a7
476c556e7fbb68dcf3cefcb9558660c1fc8de83e
refs/heads/master
<file_sep>package com.insidethemindofgio.toasty; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.TimerTask; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class RSS { private String feed; private ArrayList<String> cache = new ArrayList<String>(); private RSSItem last = null; private int maxTime; private Toasty toasty; public RSS(String feed, int maxTime) { this.maxTime = maxTime * 1000; this.feed = feed; toasty = new Toasty(); } public RSSItem getLast() { return this.last; } public int eat() throws Exception { int count = 0; DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); URL url = new URL(feed); URLConnection con = url.openConnection(); con.setConnectTimeout(maxTime); con.setReadTimeout(maxTime); Document doc = docBuilder.parse(con.getInputStream()); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("item"); for(int i = 0; i < nList.getLength(); i++) { Node nNode = nList.item(i); if(nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; String guid = getTagValue("guid", eElement); if(!cache.contains(guid)) { cache.add(guid); } } count++; } return count; } public ArrayList<RSSItem> poll() throws Exception { boolean done = false; long start = time(); ArrayList<RSSItem> items = new ArrayList<RSSItem>(); while(time() < start + maxTime && !done) { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); URL url = new URL(feed); URLConnection con = url.openConnection(); con.setConnectTimeout(maxTime); con.setReadTimeout(maxTime); Document doc = docBuilder.parse(con.getInputStream()); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("item"); String feedTitle = null; NodeList titleList = doc.getElementsByTagName("channel"); for(int i = 0; i < titleList.getLength(); i++) { Node nNode = titleList.item(i); if(nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; feedTitle = getTagValue("title", eElement); break; } } for(int i = 0; i < nList.getLength(); i++) { Node nNode = nList.item(i); if(nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; String articleTitle = getTagValue("title", eElement); String articleLink = getTagValue("link", eElement); String articleGuid = getTagValue("guid", eElement); if(!cache.contains(articleGuid)) { cache.add(articleGuid); } else { continue; } RSSItem item = new RSSItem(articleTitle, articleLink, feedTitle); items.add(item); last = item; } } done = true; } return items; } private static String getTagValue(String sTag, Element eElement) { NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes(); Node nValue = (Node) nlList.item(0); return nValue.getNodeValue(); } public long time() { return System.currentTimeMillis() / 1000; } public class PollTask extends TimerTask { @Override public void run() { try { toasty._poll(); } catch (Exception e) { e.printStackTrace(); } } } public class RSSItem { private String title; private String link; private String feedTitle; public RSSItem(String title, String link, String feedTitle) { this.title = title; this.link = link; this.feedTitle = feedTitle; } public String getTitle() { return this.title; } public String getLink() { return this.link; } public String getFeedTitle() { return this.feedTitle; } } }<file_sep>package com.insidethemindofgio.toasty; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; public class MySQL { private Utils utils = new Utils(); private Config config; public MySQL(Config config) { this.config = config; } public boolean testDBConnection() { try { Connection con = DriverManager.getConnection(config.SQLUrl, config.SQLUsername, config.SQLPassword); con.close(); } catch (SQLException e) { return false; } return true; } public void setupMySql() { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public Connection getSQLConnection() { try { return DriverManager.getConnection(config.SQLUrl, config.SQLUsername, config.SQLPassword); } catch (SQLException e) { e.printStackTrace(); } return null; } public Map<String, TriggerResponse> getTriggers() { Map<String, TriggerResponse> ret = new HashMap<String, TriggerResponse>(); String SQL = "SELECT * FROM `gio`.`triggers`"; try { Connection con = getSQLConnection(); PreparedStatement statement = con.prepareStatement(SQL); ResultSet result = statement.executeQuery(); while(result.next()) { TriggerResponse tr = new TriggerResponse(result.getString(2), result.getString(3), utils.count(result.getString(2), " ")); ret.put(result.getString(2), tr); } } catch(SQLException e) { e.printStackTrace(); } return ret; } public Map<String, String> getConfig() { Map<String, String> ret = new HashMap<String, String>(); String SQL = "SELECT * FROM `gio`.`config`"; try { Connection con = getSQLConnection(); PreparedStatement statement = con.prepareStatement(SQL); ResultSet result = statement.executeQuery(); while(result.next()) { ret.put(result.getString(2), result.getString(3)); } } catch(SQLException e) { e.printStackTrace(); } return ret; } public boolean addTrigger(String trigger, String response) { int updateSuccessful = 0; Connection con = getSQLConnection(); String query = "INSERT INTO `gio`.`triggers` (`id`, `name`, `response`) VALUES (NULL, '" + trigger + "', '" + response + "')"; try { PreparedStatement statement = con.prepareStatement(query); updateSuccessful = statement.executeUpdate(); statement.close(); } catch (SQLException e) { e.printStackTrace(); } return updateSuccessful != 0; } public boolean delTrigger(String trigger) { int updateSuccessful = 0; Connection con = getSQLConnection(); String query = "DELETE FROM `gio`.`triggers` WHERE `triggers`.`name` = '" + trigger + "'"; try { PreparedStatement statement = con.prepareStatement(query); updateSuccessful = statement.executeUpdate(); statement.close(); } catch (SQLException e) { e.printStackTrace(); } return updateSuccessful != 0; } public boolean setConfigOption(String name, String value) { int updateSuccessful = 0; Connection con = getSQLConnection(); String query; query = "SELECT * FROM `config` WHERE `name` = '" + name + "'"; try { PreparedStatement statement = con.prepareStatement(query); ResultSet res = statement.executeQuery(); int i = 0; while(res.next()) { i++; } if(i == 0) { query = "INSERT INTO `gio`.`config` (`id`, `name`, `value`) VALUES (NULL, '" + name + "', '" + value + "')"; } else { query = "UPDATE `gio`.`config` SET `value` = '" + value + "' WHERE `config`.`name` = '" + name + "'"; } PreparedStatement ss = con.prepareStatement(query); updateSuccessful = ss.executeUpdate(); statement.close(); } catch (SQLException e) { e.printStackTrace(); } return updateSuccessful != 0; } }
3faf5742218c31410456c6323378cd5f6f2203af
[ "Java" ]
2
Java
Tim-R/Toasty
cb423893bba1603837eaf464a363edb32d98bbe9
5dbe4bbcfa4cd049f4fee418867acc84dae2084c
refs/heads/master
<repo_name>luis-cmrodrigues/bdDataBaseAppExample<file_sep>/src/class4dbapp/Departamento.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package class4dbapp; /** * * @author luis_ */ public class Departamento { private int num; private String nome; private String local; public Departamento(int num, String nome, String local) { this.num = num; this.nome = nome; this.local = local; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getLocal() { return local; } public void setLocal(String local) { this.local = local; } @Override public String toString() { return "Departamento{" + "num=" + num + ", nome=" + nome + ", local=" + local + '}'; } }
07ffddc2ccef59f574273e28f08604dc202d3725
[ "Java" ]
1
Java
luis-cmrodrigues/bdDataBaseAppExample
2f5cb4f9347d9879ff7e8a131b0946320efd7b6d
9eee5b21228bb0e8a030c3ae6c9c841c096567e2
refs/heads/master
<repo_name>kannanraghupathy/spingboot-flyway<file_sep>/src/main/resources/db/migration/V2__Add_country_field_to_athletes_table.sql ALTER TABLE athletes ADD COLUMN country VARCHAR(200);<file_sep>/src/main/resources/db/migration/V3__Create_index_first_name_in_athletes_table.sql CREATE INDEX first_name_idx ON athletes (first_name);<file_sep>/src/test/resources/data.sql INSERT INTO athletes (first_name, last_name) VALUES ('Usain', 'Bolt'); INSERT INTO athletes (first_name, last_name) VALUES ('Dafne', 'Schnippers'); <file_sep>/src/test/java/com/zoltanaltfatter/SpringBootFlywayApplicationTests.java package com.zoltanaltfatter; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.assertEquals; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = SpringBootFlywayApplication.class) public class SpringBootFlywayApplicationTests { @Autowired private JdbcTemplate template; @Test public void testDefaultSettings() throws Exception { assertEquals(new Integer(2), this.template.queryForObject("SELECT COUNT(*) from athletes", Integer.class)); } } <file_sep>/src/main/db/Dockerfile FROM postgres:9.5.1 MAINTAINER <EMAIL> ENV POSTGRES_USER docker ENV POSTGRES_DB mydb COPY 1_schema.sql /docker-entrypoint-initdb.d/ COPY 2_data.sql /docker-entrypoint-initdb.d/ <file_sep>/src/main/db/2_data.sql INSERT INTO athletes (first_name, last_name) VALUES ('Usain', 'Bolt'); INSERT INTO athletes (first_name, last_name) VALUES ('Dafne', 'Schnippers'); INSERT INTO athletes (first_name, last_name) VALUES ('Carl', 'Lewis'); INSERT INTO athletes (first_name, last_name) VALUES ('Evgeny', 'Plyushchenko'); <file_sep>/src/main/db/1_schema.sql --- creates an athletes_id_seq sequence which is owned by the athletes.id (dropping the table also drop the sequence) CREATE TABLE athletes ( id BIGSERIAL, first_name varchar(255) not null, last_name varchar(255) not null, PRIMARY KEY (id) );<file_sep>/docker-compose.yml version: '2' services: postgres: image: athletes-datastore-image container_name: athletes-datastore build: build/db ports: - "5432:5432" web: image: athletes-service-image container_name: athletes-service build: build/libs depends_on: - postgres # athletes-datastore will be started before the athletes-service ports: - "8080:8080" links: - postgres<file_sep>/Readme.md Database migration with [Flyway](https://flywaydb.org/) Example for blog post: http://zoltanaltfatter.com/2016/03/14/database-migration-with-flyway ``` $ ./gradlew clean build $ docker-compose up ``` In the logs it is visible that the database changes are applied ``` o.f.core.internal.util.VersionPrinter : Flyway 4.0 by Boxfuse o.f.c.i.dbsupport.DbSupportFactory : Database: jdbc:postgresql://postgres/mydb (PostgreSQL 9.5) o.f.core.internal.command.DbValidate : Successfully validated 2 migrations (execution time 00:00.024s) o.f.c.i.metadatatable.MetaDataTableImpl : Creating Metadata table: "public"."schema_version" o.f.core.internal.command.DbBaseline : Successfully baselined schema with version: 1 o.f.core.internal.command.DbMigrate : Current version of schema "public": 1 o.f.core.internal.command.DbMigrate : Migrating schema "public" to version 2 - Add country field to athletes table o.f.core.internal.command.DbMigrate : Migrating schema "public" to version 3 - Create index first name in athletes table o.f.core.internal.command.DbMigrate : Successfully applied 2 migrations to schema "public" (execution time 00:00.047s) ``` Connect to the postgresql instance (using your own DOCKER_HOST IP) ``` psql -h 192.168.99.100 -d mydb -U docker ``` the `schema_version` records the applied changes: ``` installed_rank | version | description | type | script | checksum | installed_by | installed_on | execution_time | success ----------------+---------+-------------------------------------------+----------+---------------------------------------------------+------------+--------------+----------------------------+----------------+--------- 1 | 1 | << Flyway Baseline >> | BASELINE | << Flyway Baseline >> | | docker | 2016-03-14 09:24:38.979852 | 0 | t 2 | 2 | Add country field to athletes table | SQL | V2__Add_country_field_to_athletes_table.sql | -674532233 | docker | 2016-03-14 09:24:39.043319 | 4 | t 3 | 3 | Create index first name in athletes table | SQL | V3__Create_index_first_name_in_athletes_table.sql | 1143920342 | docker | 2016-03-14 09:24:39.064954 | 4 | t ``` Clean after yourself: ``` docker-compose down -v --rmi=all ``` <file_sep>/src/main/java/com/zoltanaltfatter/SpringBootFlywayApplication.java package com.zoltanaltfatter; import com.fasterxml.jackson.annotation.JsonIgnore; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import javax.persistence.*; import java.util.List; @SpringBootApplication /** * Available profiles --spring.profiles.active=h2 or --spring.profiles.active=postgresql * * http --pretty=colors --verbose :8080/v1/athletes */ public class SpringBootFlywayApplication { public static void main(String[] args) { SpringApplication.run(SpringBootFlywayApplication.class, args); } } @Entity @Table(name = "athletes") class Athlete { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false) private String firstName; @Column(nullable = false) private String lastName; // optional private String country; // for JPA to work protected Athlete() { } public Long getId() { return id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } } @RepositoryRestResource(collectionResourceRel = "athletes", path = "/athletes") interface AthleteRepository extends CrudRepository<Athlete, Long> { List<Athlete> findByFirstNameIgnoreCase(@Param("firstName") String firstName); }
c9f98c9aae4b0556052bf2063500eb34e27dcd04
[ "SQL", "YAML", "Markdown", "Java", "Dockerfile" ]
10
SQL
kannanraghupathy/spingboot-flyway
1e2fd9b0ba95b5ed19ef07e0bac43ae757df17b7
d7d030f2d1b71af821ebe6975654c00a768c369f
refs/heads/master
<repo_name>Smiley98/mod2<file_sep>/mod2/m2WeightedTimer.cpp #include "m2WeightedTimer.h" m2WeightedTimer::m2WeightedTimer(size_t sampleCount) { m_samples.resize(sampleCount); } void m2WeightedTimer::sample(float duration) { if (m_index > m_samples.size() - 1) { m_index = 0; float total = 0.0f; for (float i : m_samples) total += i; total /= m_samples.size(); printf("%f\n", total); } m_samples[m_index++] = duration; }<file_sep>/mod2/m2StreamingDemo.cpp #include "m2StreamingDemo.h" #include "m2ScreenQuad.h" #include "m2Shader.h" #include "m2Utilities.h" m2StreamingDemo::m2StreamingDemo() { for (size_t i = 0; i < m_textures.size(); i++) m_textures[i].initialize(std::to_string(i + 1) + ".jpg"); m2ShaderProgram& sp = m2ShaderProgram::getProgram(TEXTURE_TEST); sp.bind(); sp.setInt("u_texture", 0); glActiveTexture(GL_TEXTURE0); } m2StreamingDemo::~m2StreamingDemo() { } void m2StreamingDemo::update() { //This must happen sequentially since a rendering context cannot be current for more than one thread :( for (size_t i = 0; i < m_textures.size(); i++) m_textures[i].copy(); } void m2StreamingDemo::render() { for (size_t i = 0; i < m_textures.size(); i++) m_textures[i].uploadBegin(); for (size_t i = 0; i < m_textures.size(); i++) m_textures[i].uploadEnd(); m2ScreenQuad::render(); } <file_sep>/mod2/m2ArrayObject.h #pragma once #include <glad/glad.h> #include <glm/glm.hpp> struct m2ArrayObject { m2ArrayObject() { glGenVertexArrays(1, &m_vao); } virtual ~m2ArrayObject() { glDeleteVertexArrays(1, &m_vao); } protected: GLuint m_vao; }; <file_sep>/mod2/m2Singleton.h #pragma once template<class T> class m2Singleton { public: m2Singleton(T&&) = delete; m2Singleton(const T&) = delete; m2Singleton& operator=(T&&) = delete; m2Singleton& operator=(const T&) = delete; static T& instance(); protected: m2Singleton(); virtual ~m2Singleton(); }; template<class T> inline T& m2Singleton<T>::instance() { static T inst; return inst; } template<class T> inline m2Singleton<T>::~m2Singleton() { } template<class T> inline m2Singleton<T>::m2Singleton() { } <file_sep>/mod2/m2ScreenQuad.h #pragma once #include <glad/glad.h> //Put stuff like bloom in here. For now I'm just testing stuff that makes use of full screen quads (soon to be full screen triangles)! class m2Application; class m2ScreenQuad { friend class m2Application; public: static void render(); private: static void init(); static void shutdown(); };<file_sep>/mod2/m2Timer.h #pragma once #include <chrono> class m2Timer { public: void start(std::chrono::steady_clock::time_point now); float elapsed() const; private: std::chrono::steady_clock::time_point m_start; }; <file_sep>/mod2/m2TextureDemo.cpp #include "m2TextureDemo.h" #include "m2ScreenQuad.h" #include "m2Shader.h" #include "m2Utilities.h" #include "m2Timer.h" #include "m2WeightedTimer.h" #include <stb/stb_image.h> #include <cstdio> #include <array> #include <thread> #include <string> m2TextureDemo::m2TextureDemo() { initialize(); } m2TextureDemo::~m2TextureDemo() { shutdown(); } void m2TextureDemo::initialize() { int channels; m_image = stbi_load("Textures/5.jpg", &m_width, &m_height, &channels, STBI_rgb_alpha); m_imageSize = m_width * m_height * STBI_rgb_alpha; glGenTextures(1, &m_texture); glBindTexture(GL_TEXTURE_2D, m_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, m_width, m_height, 0, GL_BGRA, GL_UNSIGNED_BYTE, nullptr); m2ShaderProgram& sp = m2ShaderProgram::getProgram(TEXTURE_TEST); sp.bind(); sp.setInt("u_texture", 0); glActiveTexture(GL_TEXTURE0); } void m2TextureDemo::render() { static m2WeightedTimer sampler; static m2Timer timer; timer.start(std::chrono::steady_clock::now()); upload(); sampler.sample(timer.elapsed()); m2ScreenQuad::render(); } void m2TextureDemo::shutdown() { if (m_image) { stbi_image_free(m_image); m_image = nullptr; } if (m_texture) { glDeleteTextures(1, &m_texture); m_texture = GL_NONE; } } void m2TextureDemo::upload() { glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, m_width, m_height, GL_BGRA, GL_UNSIGNED_BYTE, m_image); glFlush(); glFinish(); }<file_sep>/mod2/m2RayMarcher.h #pragma once #define GLM_FORCE_SWIZZLE #include "m2ScreenQuad.h" class m2RayMarcher { public: m2RayMarcher(); ~m2RayMarcher(); static void render(); }; <file_sep>/mod2/m2Texture.h #pragma once #include <glad/glad.h> #include <string> class m2Texture { public: static void queryOptimalFormat(); void initialize(const std::string& fileName); void shutdown(); void copy(); void uploadBegin(); void uploadEnd(); void downloadBegin(); void downloadEnd(); private: static GLint s_format; GLuint m_texture = GL_NONE; unsigned char* m_image = nullptr; int m_width = 0, m_height = 0, m_imageSize = 0; GLuint m_uploadPBO = GL_NONE; GLsync m_uploadFence = GL_NONE; GLubyte* m_uploadMemory = nullptr; //Not dealing with downloading atm. //GLuint m_downloadPBO = GL_NONE; //GLsync m_downloadFence = GL_NONE; //GLubyte* m_downloadMemory = nullptr; void fence(GLsync& sync); void wait(const GLsync& sync); };<file_sep>/mod2/m2Timer.cpp #include "m2Timer.h" #include <cstdio> void m2Timer::start(std::chrono::steady_clock::time_point now) { m_start = now; } float m2Timer::elapsed() const { using namespace std::chrono; return duration_cast<duration<float>>(steady_clock::now() - m_start).count(); } <file_sep>/mod2/m2Application.h #pragma once #include "m2Texture.h" //Forward declaring won't shorten compile times cause nothing includes m2Application, but it does make it clear which dependencies are in use. class m2Window; class m2Timing; class m2StreamingDemo; class m2Application { public: m2Application(); ~m2Application(); void run(); private: m2StreamingDemo* m_streamingDemo = nullptr; m2Window& m_window; m2Timing& m_timing; inline void update(); inline void render(); inline void tick(float); }; <file_sep>/mod2/main.cpp #include "m2Application.h" int main() { m2Application application; application.run(); return 0; }<file_sep>/mod2/m2RayEngine.cpp #include "m2RayEngine.h" m2RayEngine::m2RayEngine() { } m2RayEngine::~m2RayEngine() { } <file_sep>/mod2/m2RayMarcher.cpp #include "m2RayMarcher.h" #include "m2ScreenQuad.h" #include "m2Shader.h" #include "m2Window.h" #include "m2Timing.h" #include "m2Utilities.h" #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/euler_angles.hpp> //#include "m2MemberDelegate.h" //I can't believe I can't figure this out on my own... #ifndef min #define min(a,b) (((a) < (b)) ? (a) : (b)) #endif #ifndef max #define max(a,b) (((a) > (b)) ? (a) : (b)) #endif static m2Window& window = m2Window::instance(); m2RayMarcher::m2RayMarcher() { } m2RayMarcher::~m2RayMarcher() { } inline glm::mat3 lookAtDirection(const glm::vec3& eye, const glm::vec3& centre, const glm::vec3& up) { glm::vec3 front = glm::normalize(centre - eye); glm::vec3 right = glm::normalize(glm::cross(front, up)); glm::vec3 above = glm::cross(right, front); return glm::mat3( glm::vec3(right), glm::vec3(above), glm::vec3(-front) ); } void m2RayMarcher::render() { //The distance to the projection plane is the screen resolution * the tangent of half the field of view. static const glm::vec2 resolution(window.getClientWidth(), window.getClientHeight()); static const float fieldOfView = glm::radians(45.0f); static const float projectionDistance = -(min(resolution.x, resolution.y) * 0.5f * (tanf(fieldOfView * 0.5f))); //printf("%f\n", projectionDistance);-223. //Warning, the projection math is wrong! Should be as follows: //const float opp = max(resolution.x, resolution.y) * 0.5f; //const float tanTheta = tanf(fieldOfView * 0.5f);//Fov should be changed from 45 to something above 60 after this fix. //const float invAdj = tanTheta / opp; //static const float projectionDistance = 1 / invAdj; static const float nearPlane = 0.001f; static const float farPlane = 100.0f; static const glm::vec3 cameraTranslation(0.0f, 0.0f, 3.0f); //Eye. static const glm::vec3 cameraTarget(0.0f); //Centre. static const glm::vec3 worldUp(0.0f, 1.0f, 0.0f); //Up (y-axis). static const glm::mat3 cameraRotation = lookAtDirection(cameraTranslation, cameraTarget, worldUp); float time = m2Timing::instance().elapsedTime(); float period = sinf(time) * 0.5f + 0.5f; glm::mat4 modelTransform(1.0f); modelTransform[3] = glm::vec4(2.0f, 0.0f, 0.0f, 1.0f); m2ShaderProgram& program = m2ShaderProgram::getProgram(RAYMARCH_SANDBOX); program.bind(); //Models program.setMat4("u_modelTransform", modelTransform); //View program.setMat3("u_cameraRotation", cameraRotation); program.setVec3("u_cameraTranslation", cameraTranslation); //Projection program.setVec2("u_resolution", resolution); program.setFloat("u_projectionDistance", projectionDistance); program.setFloat("u_nearPlane", nearPlane); program.setFloat("u_farPlane", farPlane); //Utility program.setFloat("u_time", time); program.setFloat("u_period", period); m2ScreenQuad::render(); } <file_sep>/mod2/m2Shader.h #pragma once #include <glad/glad.h> #include <glm/glm.hpp> #include <string> #include <vector> #include <unordered_map> enum m2ShaderPrograms : GLenum { LINE, RAY, QUAD_TEST, RAYMARCH_SANDBOX, UNIFORM_TEST_1, UNIFORM_TEST_2, TEXTURE_TEST, NUM_SHADERS }; enum m2Shaders : GLenum { VERTEX = GL_VERTEX_SHADER, GEOMETRY = GL_GEOMETRY_SHADER, FRAGMENT = GL_FRAGMENT_SHADER }; class m2ShaderProgram; class m2Shader { friend m2ShaderProgram; public: m2Shader(m2Shaders, const std::string&); ~m2Shader(); private: GLuint m_shaderHandle; }; class m2ShaderProgram { public: m2ShaderProgram(); ~m2ShaderProgram(); static void init(); static void shutdown(); static m2ShaderProgram& getProgram(m2ShaderPrograms); static void drawLine(); m2ShaderProgram& add(const m2Shader&); m2ShaderProgram& link(); m2ShaderProgram& bind(); m2ShaderProgram& unbind(); m2ShaderProgram& setInt(const std::string&, int); m2ShaderProgram& setInt(const std::string&, unsigned int, int*); m2ShaderProgram& setFloat(const std::string&, float); m2ShaderProgram& setFloat(const std::string&, unsigned int, float*); m2ShaderProgram& setVec2(const std::string&, float[2]); m2ShaderProgram& setVec2(const std::string&, const glm::vec2&); m2ShaderProgram& setVec2(const std::string&, unsigned int, float[2]); m2ShaderProgram& setVec2(const std::string&, unsigned int, const glm::vec2&); m2ShaderProgram& setVec3(const std::string&, float[3]); m2ShaderProgram& setVec3(const std::string&, const glm::vec3&); m2ShaderProgram& setVec3(const std::string&, unsigned int, float[3]); m2ShaderProgram& setVec3(const std::string&, unsigned int, const glm::vec3&); m2ShaderProgram& setVec4(const std::string&, float[4]); m2ShaderProgram& setVec4(const std::string&, const glm::vec4&); m2ShaderProgram& setVec4(const std::string&, unsigned int, float*); m2ShaderProgram& setVec4(const std::string&, unsigned int, glm::vec4*); m2ShaderProgram& setMat3(const std::string&, float[9]); m2ShaderProgram& setMat3(const std::string&, const glm::mat3&); m2ShaderProgram& setMat3(const std::string&, unsigned int, float*); m2ShaderProgram& setMat3(const std::string&, unsigned int, glm::mat3*); m2ShaderProgram& setMat4(const std::string&, float*); m2ShaderProgram& setMat4(const std::string&, const glm::mat4&); m2ShaderProgram& setMat4(const std::string&, unsigned int, float*); m2ShaderProgram& setMat4(const std::string&, unsigned int, glm::mat4*); //GLint getAttribLocation(std::string); //glBindAttribLocation or glBindFragDataLocation specifies input/output. //It might be worth while to do this for each shader so that we're guarenteed we're reading/writing what we expec to. //ie ensure we're not pointing to normals when we think we're pointing to uvs. private: //Cache uniform locations. std::unordered_map<std::string, GLuint> m_uniforms; //Must store shaders in order to detatch them. More efficient than using glGetProgramiv to retrieve shader objects. std::vector<m2Shader> m_shaders; GLuint m_programHandle; //This is a good one! I can't have any static variables that require OpenGL to be initialized. //static m2ShaderProgram s_programs[Shaders::NUM_SHADERS]; static m2ShaderProgram* s_programs; inline GLint getUniformHandle(const std::string&); }; //I overload functions rather than pass default parameters for sending 1 element vs multiple elements because it is faster to call 1f when possible rather than 1fv all the time. //Moreover, only floats are sent. unsigned ints, doubles, and weird matrices (m * n where m != n and non-float matrices) aren't included because supporting //those additional types seems unnecessary. *Still not a good idea to template cause gl needs to differentiate between float and double. At the same time, we could hack //together something that makse a gl call based on the memory size of the data to send rather than the actual type. But like most hacks, we run into errors like treating //a as b ie floats as ints when we shouldn't be. Thus, of all the areas to get stupid, this isn't one of them (just like loading images or making a math library). //As for memory, shaders are like shared pointers. They won't be deleted until they are no longer attached to a program object. Thus, either delete the program or //detatch the shaders. Can detatch/delete (detach in my case cause we want to share our shaders) after [successful] link. //For reference, deleteShader() queues shader for deletion, won't delete if attached to a program. deleteProgram() won't delete if bound. Detatches (but doesn't //delete) shaders linked to the program. //Basically, have programs delete shaders if you don't wanna explicitly control the lifetimes of shaders. However, be mindful if having programs dictate shader //lifetimes when sharing shaders. The best thing to do in both cases is put all your shaders and programs in the same scope. Contruct all shaders before any programs.<file_sep>/mod2/m2Timing.h #pragma once #include "m2Singleton.h" class m2Timing : public m2Singleton<m2Timing> { friend class m2Singleton<m2Timing>; friend class m2Application; public: ~m2Timing(); float elapsedTime(); float frameTime(); private: m2Timing(); float m_elapsedTime; float m_frameTime; }; <file_sep>/mod2/m2StreamingDemo.h #pragma once #include "m2Texture.h" #include <array> class m2StreamingDemo { public: m2StreamingDemo(); ~m2StreamingDemo(); void update(); void render(); private: //8k textures; performance decreases 35ms per frame per additional texture. //4k textures; performance decreases 10ms per frame per additional texture. //1k textures; performance decreases 3ms per frame per additional texture. //*CPU data is inaccurate as it was measured with a threading model that violated the standard.* //8k texture; performance decreases 13ms per CPU update per additional texture. //4k texture; performance decreases 3ms per CPU update per additional texture. //1k texture; performance decreases ~1ms per CPU update per additional texture. //8k texture; performance decreases 23 ms per GPU update per additional texture. //4k texture; performance decreases 6 ms per GPU update per additional texture. //1k texture; performance decreases ~1.3ms per GPU update per additional texture. std::array<m2Texture, 5> m_textures; };<file_sep>/mod2/m2PBODemo.cpp #include "m2PBODemo.h" #include "m2ScreenQuad.h" #include "m2Utilities.h" #include "m2Timer.h" #include "m2WeightedTimer.h" m2PBODemo::m2PBODemo() { GLbitfield flags = GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT; glGenBuffers(1, &m_pbo); glBindBuffer(GL_PIXEL_UNPACK_BUFFER, m_pbo); glBufferStorage(GL_PIXEL_UNPACK_BUFFER, m_imageSize, nullptr, flags | GL_DYNAMIC_STORAGE_BIT); m_memory = static_cast<GLubyte*>(glMapBufferRange(GL_PIXEL_UNPACK_BUFFER, 0, m_imageSize, flags)); memcpy(m_memory, m_image, m_imageSize); } m2PBODemo::~m2PBODemo() { glDeleteBuffers(1, &m_pbo); } void m2PBODemo::render() { static m2WeightedTimer sampler; static m2Timer timer; timer.start(std::chrono::steady_clock::now()); upload(); wait(); sampler.sample(timer.elapsed()); m2ScreenQuad::render(); } void m2PBODemo::fence() { //Create a new sync point and delete the old one. if (m_fence) glDeleteSync(m_fence); m_fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); } void m2PBODemo::wait() { //Stall CPU until fence is signalled. if (m_fence) { while (glClientWaitSync(m_fence, GL_SYNC_FLUSH_COMMANDS_BIT, 1) == GL_TIMEOUT_EXPIRED) {} } } void m2PBODemo::upload() { glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, m_width, m_height, GL_BGRA, GL_UNSIGNED_BYTE, nullptr); fence(); }<file_sep>/mod2/m2Window.h #pragma once #include "m2Singleton.h" struct Rect { union { struct { int x, y, w, h; }; struct { int values[4]; }; }; }; struct GLFWwindow; class m2Window : public m2Singleton<m2Window> { friend class m2Singleton<m2Window>; friend void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods); friend void framebuffer_callback(GLFWwindow* window, int key, int scancode); public: ~m2Window(); bool isOpen(); //Sends a close event. Does not force-close. Force-closing won't be a thing. void close(); //Polls events and swaps buffers. void swapBuffers(); //Wrapper for glViewport. void viewport(int x, int y, int w, int h); Rect getClientRect(); //Rect getWindowRect(); //No window or client setters. Our application has no need to do that! Leave modification to callbacks. int getClientX(); int getClientY(); int getClientWidth(); int getClientHeight(); //Our application has no need to manipulate the actual window values. Use the client instead cause we're only concerned with the display. //int getWindowX(); //int getWindowY(); //int getWindowWidth(); //int getWindowHeight(); private: m2Window(); GLFWwindow* m_window; //int m_windowX = 0; //int m_windowY = 0; //int m_windowWidth = 0; //int m_windowHeight= 0; int m_clientX = 0; int m_clientY = 0; int m_clientWidth = 1920; int m_clientHeight = 1080; };<file_sep>/mod2/m2Shader.cpp #include "m2Shader.h" #include "m2Utilities.h" //Again, can't have static members that require gl to be initialized. //m2ShaderProgram m2ShaderProgram::s_programs[Shaders::NUM_SHADERS]; m2ShaderProgram* m2ShaderProgram::s_programs = nullptr; m2Shader::m2Shader(m2Shaders ShaderType, const std::string& path) { //Create shader. m_shaderHandle = glCreateShader(ShaderType); //Store shader source as an l-value c-string (gl needs a string double pointer). std::string source = m2Utils::loadTextFile(path); const GLchar* const sourceCstr = source.c_str(); //Add source to m2Shader. glShaderSource(m_shaderHandle, 1, &sourceCstr, nullptr); //Compile m2Shader, log error if compilation error. glCompileShader(m_shaderHandle); GLint isCompiled = GL_FALSE; glGetShaderiv(m_shaderHandle, GL_COMPILE_STATUS, &isCompiled); if (!isCompiled) { GLint maxLength = 0; glGetShaderiv(m_shaderHandle, GL_INFO_LOG_LENGTH, &maxLength); std::vector<GLchar> errorLog(maxLength); glGetShaderInfoLog(m_shaderHandle, maxLength, &maxLength, errorLog.data()); glDeleteShader(m_shaderHandle); fprintf(stderr, "Shader compilation error: %s\n", errorLog.data()); } } m2Shader::~m2Shader() { glDeleteShader(m_shaderHandle); } m2ShaderProgram::m2ShaderProgram() { m_programHandle = glCreateProgram(); } m2ShaderProgram::~m2ShaderProgram() { glDeleteProgram(m_programHandle); } m2ShaderProgram& m2ShaderProgram::add(const m2Shader& shader) { glAttachShader(m_programHandle, shader.m_shaderHandle); m_shaders.push_back(shader); return *this; } m2ShaderProgram& m2ShaderProgram::link() { //Link m2Shader, log error if linker error. glLinkProgram(m_programHandle); GLint isLinked = GL_FALSE; glGetProgramiv(m_programHandle, GL_LINK_STATUS, &isLinked); if (!isLinked) { GLint maxLength = 0; glGetProgramiv(m_programHandle, GL_INFO_LOG_LENGTH, &maxLength); std::vector<GLchar> errorLog(maxLength); glGetProgramInfoLog(m_programHandle, maxLength, &maxLength, &errorLog[0]); glDeleteProgram(m_programHandle); std::printf("Shader linker error: %s\n", errorLog.data()); } //Don't do this. The destructor deletes them which implicitly detatches them(I think). Must leave attached in order to share. //for (m2Shader& m2Shader : m_shaders) // glDetachShader(m_programHandle, m2Shader.m_shaderHandle); return *this; } m2ShaderProgram& m2ShaderProgram::bind() { glUseProgram(m_programHandle); return *this; } m2ShaderProgram& m2ShaderProgram::unbind() { glUseProgram(GL_NONE); return *this; } m2ShaderProgram& m2ShaderProgram::setInt(const std::string& index, int value) { glUniform1i(getUniformHandle(index), value); return *this; } m2ShaderProgram& m2ShaderProgram::setInt(const std::string& index, unsigned int amount, int* values) { glUniform1iv(getUniformHandle(index), amount, values); return *this; } m2ShaderProgram& m2ShaderProgram::setFloat(const std::string& index, float value) { glUniform1f(getUniformHandle(index), value); return *this; } m2ShaderProgram& m2ShaderProgram::setFloat(const std::string& index, unsigned int amount, float* values) { glUniform1fv(getUniformHandle(index), amount, values); return *this; } m2ShaderProgram& m2ShaderProgram::setVec2(const std::string& index, float values[2]) { glUniform2f(getUniformHandle(index), values[0], values[1]); return *this; } m2ShaderProgram& m2ShaderProgram::setVec2(const std::string& index, const glm::vec2& values) { glUniform2f(getUniformHandle(index), values[0], values[1]); return *this; } m2ShaderProgram& m2ShaderProgram::setVec2(const std::string& index, unsigned int amount, float values[2]) { glUniform2fv(getUniformHandle(index), amount, values); return *this; } m2ShaderProgram& m2ShaderProgram::setVec2(const std::string& index, unsigned int amount, const glm::vec2& values) { glUniform2fv(getUniformHandle(index), amount, &values[0]); return *this; } m2ShaderProgram& m2ShaderProgram::setVec3(const std::string& index, float values[3]) { glUniform3f(getUniformHandle(index), values[0], values[1], values[2]); return *this; } m2ShaderProgram & m2ShaderProgram::setVec3(const std::string& index, const glm::vec3& values) { glUniform3f(getUniformHandle(index), values[0], values[1], values[2]); return *this; } m2ShaderProgram& m2ShaderProgram::setVec3(const std::string& index, unsigned int amount, float values[3]) { glUniform3fv(getUniformHandle(index), amount, values); return *this; } m2ShaderProgram& m2ShaderProgram::setVec3(const std::string& index, unsigned int amount, const glm::vec3& values) { glUniform3fv(getUniformHandle(index), amount, &values[0]); return *this; } m2ShaderProgram& m2ShaderProgram::setVec4(const std::string& index, float values[4]) { glUniform4f(getUniformHandle(index), values[0], values[1], values[2], values[3]); return *this; } m2ShaderProgram& m2ShaderProgram::setVec4(const std::string& index, const glm::vec4& values) { glUniform4f(getUniformHandle(index), values[0], values[1], values[2], values[3]); return *this; } m2ShaderProgram& m2ShaderProgram::setVec4(const std::string& index, unsigned int amount, float* values) { glUniform4fv(getUniformHandle(index), amount, values); return *this; } m2ShaderProgram& m2ShaderProgram::setVec4(const std::string& index, unsigned int amount, glm::vec4* values) { glUniform4fv(getUniformHandle(index), amount, &values[0].x); return *this; } m2ShaderProgram& m2ShaderProgram::setMat3(const std::string& index, float values[9]) { glUniformMatrix3fv(getUniformHandle(index), 1, GL_FALSE, values); return *this; } m2ShaderProgram& m2ShaderProgram::setMat3(const std::string& index, const glm::mat3& values) { glUniformMatrix3fv(getUniformHandle(index), 1, GL_FALSE, &values[0].x); return *this; } m2ShaderProgram& m2ShaderProgram::setMat3(const std::string& index, unsigned int amount, float* values) { glUniformMatrix3fv(getUniformHandle(index), amount, GL_FALSE, values); return *this; } m2ShaderProgram& m2ShaderProgram::setMat3(const std::string& index, unsigned int amount, glm::mat3* values) { glUniformMatrix3fv(getUniformHandle(index), amount, GL_FALSE, &values[0][0].x); return *this; } m2ShaderProgram& m2ShaderProgram::setMat4(const std::string& index, float* values) { glUniformMatrix4fv(getUniformHandle(index), 1, GL_FALSE, values); return *this; } m2ShaderProgram& m2ShaderProgram::setMat4(const std::string& index, const glm::mat4& values) { glUniformMatrix4fv(getUniformHandle(index), 1, GL_FALSE, &values[0].x); return *this; } m2ShaderProgram& m2ShaderProgram::setMat4(const std::string& index, unsigned int amount, float *values) { glUniformMatrix4fv(getUniformHandle(index), amount, GL_FALSE, values); return *this; } m2ShaderProgram& m2ShaderProgram::setMat4(const std::string& index, unsigned int amount, glm::mat4* values) { glUniformMatrix4fv(getUniformHandle(index), amount, GL_FALSE, &values[0][0].x); return *this; } void m2ShaderProgram::init() { s_programs = new m2ShaderProgram[NUM_SHADERS]; std::string sdir = "Shaders/"; //Vertex Shaders: m2Shader v_passThrough(VERTEX, sdir + "PassThrough.vert"); m2Shader v_ray(VERTEX, sdir + "Ray.vert"); m2Shader v_screenQuad(VERTEX, sdir + "ScreenQuad.vert"); //Geometry Shaders: m2Shader g_line(GEOMETRY, sdir + "Line.geom"); m2Shader g_ray(GEOMETRY, sdir + "Ray.geom"); //Fragment Shaders: m2Shader f_uniformColour(FRAGMENT, sdir + "UniformColour.frag"); m2Shader f_ray(FRAGMENT, sdir + "Ray.frag"); m2Shader f_randomColour(FRAGMENT, sdir + "RandomColour.frag"); m2Shader f_screenQuadTest(FRAGMENT, sdir + "ScreenQuadTest.frag"); m2Shader f_raymarchingSandbox(FRAGMENT, sdir + "RaymarchingSandbox.frag"); m2Shader f_textureTest(FRAGMENT, sdir + "TextureTest.frag"); //Programs: s_programs[LINE].add(v_passThrough); s_programs[LINE].add(g_line); s_programs[LINE].add(f_uniformColour); s_programs[LINE].link(); s_programs[RAY].add(v_ray); s_programs[RAY].add(g_ray); s_programs[RAY].add(f_ray); //s_programs[RAY].add(f_randomColour); s_programs[RAY].link(); s_programs[RAYMARCH_SANDBOX].add(v_screenQuad); s_programs[RAYMARCH_SANDBOX].add(f_raymarchingSandbox); s_programs[RAYMARCH_SANDBOX].link(); s_programs[TEXTURE_TEST].add(v_screenQuad); s_programs[TEXTURE_TEST].add(f_textureTest); s_programs[TEXTURE_TEST].link(); } void m2ShaderProgram::shutdown() { delete[] s_programs; } m2ShaderProgram& m2ShaderProgram::getProgram(m2ShaderPrograms shader) { return s_programs[shader]; } void m2ShaderProgram::drawLine() { //Must bind a random vao cause you're not allowed to render if the null vao is bound. static GLuint vao; static bool generated = false; if (!generated) { glGenVertexArrays(1, &vao); generated = true; } m2ShaderProgram& sp = getProgram(LINE); sp.bind(); sp.setVec3("u_colour", glm::vec3(1.0f)); glBindVertexArray(vao); glDrawArrays(GL_POINTS, 0, 1); } /*GLint m2ShaderProgram::getAttribLocation(std::string attribName) { if (m_attributes.find(attribName) == m_attributes.end()) m_attributes[attribName] = glGetAttribLocation(m_programHandle, attribName.c_str()); return m_attributes[attribName]; }*/ GLint m2ShaderProgram::getUniformHandle(const std::string& uniformName) { if (m_uniforms.find(uniformName) == m_uniforms.end()) m_uniforms[uniformName] = glGetUniformLocation(m_programHandle, uniformName.c_str()); return m_uniforms[uniformName]; } <file_sep>/mod2/m2TextureDemo.h #pragma once #include <glad/glad.h> class m2TextureDemo { public: m2TextureDemo(); ~m2TextureDemo(); void initialize(); void render(); void shutdown(); protected: GLuint m_texture = GL_NONE; unsigned char* m_image = nullptr; int m_width = 0, m_height = 0, m_imageSize = 0; private: void upload(); };<file_sep>/mod2/m2Timing.cpp #include "m2Timing.h" m2Timing::m2Timing() { } m2Timing::~m2Timing() { } float m2Timing::elapsedTime() { return m_elapsedTime; } float m2Timing::frameTime() { return m_frameTime; } <file_sep>/mod2/m2Texture.cpp #include "m2Texture.h" //Apparently I only need to define this once, no compiler/link order jank!? #define STB_IMAGE_IMPLEMENTATION #include <stb/stb_image.h> namespace { const GLbitfield flags = GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT; const GLenum uploadTarget = GL_PIXEL_UNPACK_BUFFER; //const GLenum downloadTarget = GL_PIXEL_PACK_BUFFER; } GLint m2Texture::s_format; void m2Texture::queryOptimalFormat() { glGetInternalformativ(GL_TEXTURE_2D, GL_RGBA8, GL_TEXTURE_IMAGE_FORMAT, 1, &s_format); } void m2Texture::initialize(const std::string& fileName) { //Image loading is taken care of in the xr engine. We just need to transfer data asynchronously. static std::string tdir = "Textures/"; int channels; m_image = stbi_load((tdir + fileName).c_str(), &m_width, &m_height, &channels, STBI_rgb_alpha); m_imageSize = m_width * m_height * STBI_rgb_alpha; glGenBuffers(1, &m_uploadPBO); glBindBuffer(uploadTarget, m_uploadPBO); glBufferStorage(uploadTarget, m_imageSize, nullptr, flags | GL_MAP_WRITE_BIT | GL_DYNAMIC_STORAGE_BIT); m_uploadMemory = static_cast<GLubyte*>(glMapBufferRange(uploadTarget, 0, m_imageSize, flags | GL_MAP_WRITE_BIT)); memcpy(m_uploadMemory, m_image, m_imageSize); //glGenBuffers(1, &m_downloadPBO); //glBindBuffer(downloadTarget, m_downloadPBO); //glBufferStorage(downloadTarget, m_imageSize, nullptr, flags | GL_MAP_READ_BIT | GL_DYNAMIC_STORAGE_BIT); //m_downloadMemory = static_cast<GLubyte*>(glMapBufferRange(downloadTarget, 0, m_imageSize, flags | GL_MAP_READ_BIT)); //memcpy(m_downloadMemory, m_image, m_imageSize); //Might have to change to reflect size of framebuffer rather than texture. glGenTextures(1, &m_texture); glBindTexture(GL_TEXTURE_2D, m_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, m_width, m_height, 0, s_format, GL_UNSIGNED_BYTE, nullptr); } void m2Texture::shutdown() { glDeleteTextures(1, &m_texture); glDeleteBuffers(1, &m_uploadPBO); //glDeleteBuffers(1, &m_downloadPBO); stbi_image_free(m_image); } void m2Texture::copy() { memcpy(m_uploadMemory, m_image, m_imageSize); } void m2Texture::uploadBegin() { //memcpy(m_uploadMemory, m_image, m_imageSize); glBindTexture(GL_TEXTURE_2D, m_texture); glBindBuffer(uploadTarget, m_uploadPBO); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, m_width, m_height, s_format, GL_UNSIGNED_BYTE, nullptr); fence(m_uploadFence); } void m2Texture::uploadEnd() { wait(m_uploadFence); } void m2Texture::downloadBegin() { //glGetTextureSubImage is also an option, core in GL 4.5 //glReadPixels(0, 0, m_width, m_height, GL_BGRA, GL_UNSIGNED_BYTE, nullptr); //fence(m_downloadFence); } void m2Texture::downloadEnd() { //wait(m_downloadFence); //memcpy to some external buffer or return data? //return m_downloadMemory;//Be careful with this. Be sure to copy rather than reassign this as its GL mapped memory! } void m2Texture::fence(GLsync& sync) { //Create a new sync point and delete the old one. if (sync) glDeleteSync(sync); sync = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); } void m2Texture::wait(const GLsync& sync) { //Stall CPU until fence is signalled. if (sync) { while (glClientWaitSync(sync, GL_SYNC_FLUSH_COMMANDS_BIT, 1) == GL_TIMEOUT_EXPIRED) {} } } <file_sep>/mod2/m2Application.cpp #include "m2Application.h" //Prevent glfw from including the base gl header (gl.h) so glad can include it. #define GLFW_INCLUDE_NONE #include <GLFW/glfw3.h> #include <glad/glad.h> #include <chrono> #include <cstdio> #include "m2Window.h" #include "m2Timing.h" #include "m2Timer.h" #include "m2WeightedTimer.h" #include "m2Utilities.h" #include "m2Shader.h" #include "m2RayRenderer.h" #include "m2RayMarcher.h" #include "m2TextureDemo.h" #include "m2PBODemo.h" #include "m2StreamingDemo.h" #define LOG_FPS false m2Application::m2Application() : m_window(m2Window::instance()), m_timing(m2Timing::instance()) { m2ScreenQuad::init(); m2ShaderProgram::init(); m_streamingDemo = new m2StreamingDemo; } m2Application::~m2Application() { delete m_streamingDemo; m2ShaderProgram::shutdown(); m2ScreenQuad::shutdown(); } void m2Application::run() { static m2Timer timer; while (m_window.isOpen()) { timer.start(std::chrono::steady_clock::now()); update(); render(); m_window.swapBuffers(); tick(timer.elapsed()); } } inline void m2Application::update() { glfwPollEvents(); //m_streamingDemo->update(); } inline void m2Application::render() { glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //m_streamingDemo->render(); //Batched line rendering demo: //static m2RayRenderer rayRenderer(0, m_window.getClientWidth(), 1); //rayRenderer.render(); //Raymarching demo: m2RayMarcher::render(); //Naive texture upload benchmark: /* static m2TextureDemo naiveDemo; naiveDemo.render(); //*/ //Accelerated texture upload benchmark: /* static m2PBODemo acceleratedDemo; acceleratedDemo.render(); //*/ } inline void m2Application::tick(float frameTime) { m_timing.m_frameTime = frameTime; m_timing.m_elapsedTime += frameTime; #if LOG_FPS static m2WeightedTimer sampler; sampler.sample(frameTime); #endif } <file_sep>/mod2/m2Utilities.h #pragma once #include <glm/glm.hpp> #include <string> #include <chrono> #include <cstdio> namespace m2Utils { std::string loadTextFile(const std::string& path); //Converts from (-1.0, 1.0) to (0.0, 1.0); float bias(float); //Converts from (0.0, 1.0) to (-1.0, 1.0); float unbias(float); float screenToNdcX(float value); float screenToNdcY(float value); float ndcToScreenX(float value); float ndcToScreenY(float value); //float screenToNdc(float value, float range, float offset = 0.0f); //float ndcToScreen(float value, float range, float offset = 0.0f); glm::vec2 screenToNdc(const glm::vec2&); glm::vec2 ndcToScreen(const glm::vec2&); float cross(const glm::vec2&, const glm::vec2&); void printMatrix(const glm::mat4& matrix); template<typename T = glm::vec3> void printVector(const T& vector) { for (unsigned i = 0; i < vector.length(); i++) printf("%f ", vector[i]); printf("\n"); } }<file_sep>/mod2/m2ScreenQuad.cpp #include "m2ScreenQuad.h" static GLuint screenQuadVao; static GLuint screenQuadVbo; void m2ScreenQuad::render() { glBindVertexArray(screenQuadVao); glDrawArrays(GL_TRIANGLES, 0, 6); } void m2ScreenQuad::init() { float quadData[] = { 1.0f, 1.0f,// 0.0f, -1.0f, 1.0f,// 0.0f, 1.0f, -1.0f,// 0.0f, -1.0f, -1.0f,// 0.0f, 1.0f, -1.0f,// 0.0f, -1.0f, 1.0f,// 0.0f }; glGenVertexArrays(1, &screenQuadVao); glGenBuffers(1, &screenQuadVbo); glBindVertexArray(screenQuadVao); glBindBuffer(GL_ARRAY_BUFFER, screenQuadVbo); glEnableVertexAttribArray(0); glBufferData(GL_ARRAY_BUFFER, sizeof(quadData), quadData, GL_STATIC_DRAW); //glBufferData(GL_ARRAY_BUFFER, 6 * 2 * sizeof(float), quadData, GL_STATIC_DRAW); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, GL_NONE); glBindVertexArray(GL_NONE); } void m2ScreenQuad::shutdown() { glDeleteVertexArrays(1, &screenQuadVao); glDeleteBuffers(1, &screenQuadVbo); }<file_sep>/mod2/m2Window.cpp #include "m2Window.h" //Prevent glfw from including the base gl header (gl.h) so glad can include it. #define GLFW_INCLUDE_NONE #pragma comment (lib, "glfw3.lib") #pragma comment (lib, "opengl32.lib") #include <GLFW/glfw3.h> #include <glad/glad.h> #include <cstdio> void error_callback(int error, const char* description) { fprintf(stderr, "GLFW error: %s\n", description); } void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GLFW_TRUE); } void framebuffer_callback(GLFWwindow* window, int width, int height) { m2Window& w = m2Window::instance(); w.m_clientWidth = width; w.m_clientHeight = height; glViewport(w.m_clientX, w.m_clientY, width, height); printf("Client resized to %i by %i.\n", width, height); } m2Window::m2Window() : m_window(nullptr) { //1. Initialize window and other primary initial glfw code like setting the error callback. glfwInit(); glfwSetErrorCallback(error_callback); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 4); m_window = glfwCreateWindow(1280, 720, "PRIMEOPS 2", nullptr, nullptr); //2. Obtain modern gl. glfwMakeContextCurrent(m_window); gladLoadGL(); //3. Set set callbacks for events. glfwSetKeyCallback(m_window, key_callback); glfwSetFramebufferSizeCallback(m_window, framebuffer_callback); //4. *IMPORTANT* Set the visible area to match the client rather than the window. The client is essentially the "canvas" whereas the window contains stuff we don't want like boarders and scroll bars! glfwGetFramebufferSize(m_window, &m_clientWidth, &m_clientHeight); glViewport(0, 0, m_clientWidth, m_clientHeight); //5. Set the interval at which the buffers swap. Double buffer by default, but at an interval of 0 (which leads to screen tear). glfwSwapInterval(1); } m2Window::~m2Window() { glfwTerminate(); } bool m2Window::isOpen() { return !glfwWindowShouldClose(m_window); } void m2Window::close() { glfwSetWindowShouldClose(m_window, 1); } void m2Window::swapBuffers() { glfwSwapBuffers(m_window); } int m2Window::getClientX() { return m_clientX; } int m2Window::getClientY() { return m_clientY; } int m2Window::getClientWidth() { return m_clientWidth; } int m2Window::getClientHeight() { return m_clientHeight; } void m2Window::viewport(int x, int y, int w, int h) { glViewport(x, y, w, h); m_clientX = x; m_clientY = y; m_clientWidth = w; m_clientHeight = h; } Rect m2Window::getClientRect() { return Rect{ m_clientX, m_clientY, m_clientWidth, m_clientHeight }; } /*Rect m2Window::getWindowRect() { return Rect{ m_windowX, m_windowY, m_windowWidth, m_windowHeight }; } int m2Window::getWindowX() { return m_windowX; } int m2Window::getWindowY() { return m_windowY; } int m2Window::getWindowWidth() { return m_windowWidth; } int m2Window::getWindowHeight() { return m_windowHeight; }*/ <file_sep>/mod2/m2Line2.cpp #include "m2Line2.h" #include "m2Utilities.h" m2Line2::m2Line2(const glm::vec2& a, const glm::vec2& b) : p1(a), p2(b) { } m2Line2::m2Line2() { } m2Line2::~m2Line2() { } bool m2Line2::intersect(const m2Line2& a, const m2Line2& b, glm::vec2 & poi) { using namespace m2Utils; //r and s glm::vec2 r(a.p2.x - a.p1.x, a.p2.y - a.p2.y); glm::vec2 s(b.p2.x - b.p1.x, b.p2.y - b.p2.y); float d = cross(r, s); //u and t are scalar values of parameterics float u = (cross(b.p1, r) - cross(a.p1, r)) / d; float t = (cross(b.p1, s) - cross(a.p1, s)) / d; if ((0 <= u) && (u <= 1) && (0 <= t) && (t <= 1)) { poi = glm::vec2(r.x * t + a.p1.x, r.y * t + a.p1.y); return true; } return false; }<file_sep>/mod2/m2WeightedTimer.h #pragma once #include <vector> class m2WeightedTimer { public: m2WeightedTimer(size_t sampleCount = 16); void sample(float duration); private: std::vector<float> m_samples; size_t m_index; }; <file_sep>/mod2/m2Line3.cpp #include "m2Line3.h" m2Line3::m2Line3(const glm::vec3& a, const glm::vec3& b) : p1(a), p2(b) { } m2Line3::m2Line3() { } m2Line3::~m2Line3() { }<file_sep>/mod2/m2PBODemo.h #pragma once #include "m2TextureDemo.h" class m2PBODemo : public m2TextureDemo { public: m2PBODemo(); ~m2PBODemo(); void render(); private: GLuint m_pbo = GL_NONE; GLubyte* m_memory = nullptr; GLsync m_fence = nullptr; void fence(); void wait(); void upload(); }; <file_sep>/mod2/m2Transform.cpp #include "m2Transform.h" #include <glm/gtc/matrix_transform.hpp> #include "m2Utilities.h" #include <cstdio> const glm::mat4 m2Transform::s_mIdentity = glm::mat4(1.0f); const glm::vec4 m2Transform::s_vIdentity = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f); const glm::vec3 m2Transform::s_up = glm::vec3(0.0f, 1.0f, 0.0f); m2Transform::m2Transform() : m_transformation(s_mIdentity), m_orientation(glm::quat()), m_scale(glm::vec3(1.0f)), m_parent(nullptr) { } m2Transform::~m2Transform() { } glm::mat4 m2Transform::getWorldTransformation() { //Recursively combine transformations. if (m_parent) return m_parent->getWorldTransformation() * m_transformation; return m_transformation; } glm::vec3 m2Transform::getWorldPosition() { return getWorldTransformation() * s_vIdentity; } glm::vec3 m2Transform::getWorldTranslation() { //Recursively combine translations. if (m_parent) return m_parent->getWorldTranslation() + m_transformation[3].xyz; return m_transformation[3]; } glm::vec3 m2Transform::getWorldRotation() { //Recursively combine orientations. return glm::degrees(glm::eulerAngles(_getWorldOrientation())); } const glm::mat4 & m2Transform::getLocalTransformation() { return m_transformation; } glm::vec3 m2Transform::getLocalPosition() { //Add update check here for most up to date info and to remove dirty flag from [0][3]. return m_transformation * s_vIdentity; } glm::vec3 m2Transform::getLocalTranslation() { return m_transformation[3]; } glm::vec3 m2Transform::getLocalRotation() { return glm::degrees(glm::eulerAngles(m_orientation)); } float m2Transform::getLocalRotationX() { return glm::degrees(glm::pitch(m_orientation)); } float m2Transform::getLocalRotationY() { return glm::degrees(glm::yaw(m_orientation)); } float m2Transform::getLocalRotationZ() { return glm::degrees(glm::roll(m_orientation)); } glm::vec3 m2Transform::getScale() { return m_scale; } float m2Transform::getScaleX() { return m_scale.x; } float m2Transform::getScaleY() { return m_scale.y; } float m2Transform::getScaleZ() { return m_scale.z; } glm::mat3 m2Transform::getDirections() { return glm::mat3_cast(m_orientation); } glm::vec3 m2Transform::getFront() { //See glm::mat3_cast(q); const glm::quat& q = m_orientation; return glm::vec3(2.0f * (q.x * q.z + q.w * q.y), 2.0f * (q.y * q.z - q.w * q.x), 1.0f - 2.0f * (q.x * q.x + q.y * q.y)); } glm::vec3 m2Transform::getRight() { //See glm::mat3_cast(q); const glm::quat& q = m_orientation; return glm::vec3(1.0f - 2.0f * (q.y * q.y + q.z * q.z), 2.0f * (q.x * q.y + q.w * q.z), 2.0f * (q.x * q.z - q.w * q.y)); } glm::vec3 m2Transform::getAbove() { //See glm::mat3_cast(q); const glm::quat& q = m_orientation; return glm::vec3(2.0f * (q.x * q.y - q.w * q.z), 1.0f - 2.0f * (q.x * q.x + q.z * q.z), 2.0f * (q.y * q.z + q.x * q.x)); } void m2Transform::setFront(glm::vec3 front) { glm::vec3 right(glm::cross(s_up, front)); glm::vec3 above(glm::cross(front, right)); _setDirections(front, right, above);//Converts to radians. } void m2Transform::setRight(glm::vec3 right) { glm::vec3 front(glm::cross(right, s_up)); glm::vec3 above(glm::cross(front, right)); _setDirections(front, right, above);//Converts to radians. } void m2Transform::setAbove(glm::vec3 above) { glm::vec3 right(glm::cross(s_up, above)); glm::vec3 front(glm::cross(right, above)); _setDirections(front, right, above);//Converts to radians. } void m2Transform::setTranslation(glm::vec3 translation) { m_transformation[3].xyz = translation; } void m2Transform::setTranslation(float x, float y, float z) { m_transformation[3].x = x; m_transformation[3].y = y; m_transformation[3].z = z; } void m2Transform::setRotation(glm::vec3 rotation) { //Might want to compute deltas rather than a straight-up assignment. Internal rotation order + gl coordinate system + model orientation should suffice though. m_orientation = glm::quat(glm::radians(rotation)); } void m2Transform::setRotation(float x, float y, float z) { //No function tunneling this time!! m_orientation = glm::quat(glm::radians(glm::vec3(x, y, z))); } void m2Transform::setRotationX(float x) { glm::vec3 angles(glm::eulerAngles(m_orientation)); angles.x = glm::radians(x); m_orientation = glm::quat(angles); } void m2Transform::setRotationY(float y) { glm::vec3 angles(glm::eulerAngles(m_orientation)); angles.y = glm::radians(y); m_orientation = glm::quat(angles); } void m2Transform::setRotationZ(float z) { glm::vec3 angles(glm::eulerAngles(m_orientation)); angles.z = glm::radians(z); m_orientation = glm::quat(angles); } void m2Transform::setDeltaTranslation(glm::vec3 translation) { m_transformation[3].xyz += translation; } void m2Transform::setDeltaTranslation(float x, float y, float z) { m_transformation[3].x += x; m_transformation[3].y += y; m_transformation[3].z += z; } void m2Transform::setDeltaRotation(glm::vec3 rotation) { m_orientation = glm::quat(glm::radians(rotation)) * m_orientation; } void m2Transform::setDeltaRotation(float x, float y, float z) { m_orientation = glm::quat(glm::radians(glm::vec3(x, y, z))) * m_orientation; } void m2Transform::setDeltaRotationX(float x) { m_orientation = glm::quat(glm::radians(glm::vec3(x, 0.0f, 0.0f))) * m_orientation; } void m2Transform::setDeltaRotationY(float y) { m_orientation = glm::quat(glm::radians(glm::vec3(0.0f, y, 0.0f))) * m_orientation; } void m2Transform::setDeltaRotationZ(float z) { m_orientation = glm::quat(glm::radians(glm::vec3(0.0f, 0.0f, z))) * m_orientation; } void m2Transform::setScale(glm::vec3 scale) { m_scale = scale; } void m2Transform::setScale(float scale) { m_scale = glm::vec3(scale); } void m2Transform::setScaleX(float x) { m_scale.x = x; } void m2Transform::setScaleY(float y) { m_scale.y = y; } void m2Transform::setScaleZ(float z) { m_scale.z = z; } inline glm::quat m2Transform::_getWorldOrientation() { //Order is root * A * B * C * etc. Despite being called from a potential leaf node, the multiplications doesn't start till root. if (m_parent) return m_parent->_getWorldOrientation() * m_orientation; return m_orientation; } inline void m2Transform::_setDirections(glm::vec3 front, glm::vec3 right, glm::vec3 above) { //Make a rotation matrix, then turn it into a quaternion. The matrix construction overhead is worth what glm is doing cause quat_cast() is difficult! m_orientation = glm::quat_cast(glm::mat3(glm::radians(right), glm::radians(above), glm::radians(front))); } inline const m2Transform & m2Transform::getParent() { } inline void m2Transform::setParent(const m2Transform &) { } <file_sep>/mod2/m2RayRenderer.h #pragma once #include "m2ArrayObject.h" #include <vector> class m2RayRenderer : public m2ArrayObject { public: m2RayRenderer(float xMin, float xMax, unsigned int thickness = 1); virtual ~m2RayRenderer(); void render(); private: std::vector<glm::vec4> m_colours; std::vector<float> m_heights; const float m_xMin, m_xMax; const unsigned int m_thickness; const unsigned int m_count; const float m_step; const float m_halfScreenHeight; GLuint m_cbo; //Colour buffer object. GLuint m_hbo; //Height buffer object. }; <file_sep>/mod2/m2Utilities.cpp #include "m2Utilities.h" #include "m2Window.h" #include <array> #include <fstream> static m2Window& window = m2Window::instance(); void m2Utils::printMatrix(const glm::mat4 & matrix) { for (int i = 0; i < 4; i++) printf("%f %f %f %f\n", matrix[0][i], matrix[1][i], matrix[2][i], matrix[3][i]); printf("\n"); } std::string m2Utils::loadTextFile(const std::string& path) { std::ifstream file(path); return std::string( (std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>() ); } float m2Utils::bias(float value) { return value * 0.5f + 0.5f; } float m2Utils::unbias(float value) { return value * 2.0f - 1.0f; } float m2Utils::screenToNdcX(float value) { return (value - window.getClientX()) / ((float)window.getClientWidth() * 0.5f) - 1.0f; } float m2Utils::screenToNdcY(float value) { return (value - window.getClientY()) / ((float)window.getClientHeight() * 0.5f) - 1.0f; } float m2Utils::ndcToScreenX(float value) { return (value + 1.0f) * (float)window.getClientWidth() * 0.5f + window.getClientX(); } float m2Utils::ndcToScreenY(float value) { return (value + 1.0f) * (float)window.getClientHeight() * 0.5f + window.getClientY(); } /*float m2Utils::screenToNdc(float value, float range, float offset) { return (value - offset) / range * 0.5f - 1.0f; } float m2Utils::ndcToScreen(float value, float range, float offset) { return (value + 1.0f) * range * 0.5f + offset; }*/ glm::vec2 m2Utils::screenToNdc(const glm::vec2& coordinates) { return glm::vec2( (coordinates.x - window.getClientX()) / (float)window.getClientWidth() * 0.5f - 1.0f, (coordinates.y - window.getClientY()) / (float)window.getClientHeight() * 0.5f - 1.0f ); } glm::vec2 m2Utils::ndcToScreen(const glm::vec2& coordinates) { return glm::vec2( (coordinates.x + 1.0f) * (float)window.getClientWidth() * 0.5f + window.getClientX(), (coordinates.y + 1.0f) * (float)window.getClientHeight() * 0.5f + window.getClientY() ); } float m2Utils::cross(const glm::vec2& a, const glm::vec2& b) { return a.x * b.y - a.y * b.x; } <file_sep>/mod2/m2Line3.h #pragma once #include <glm/glm.hpp> struct m2Line3 { m2Line3(const glm::vec3&, const glm::vec3&); m2Line3(); ~m2Line3(); const glm::vec3 p1; const glm::vec3 p2; }; <file_sep>/mod2/m2RayEngine.h #pragma once //Should be named "Caster" or "RayCaster" or "RayRenderer", but I went with this for old time sake! //Not sure how to structure this. Should probably make it a pure renderer rather than storing level data and all that. class m2RayEngine { public: m2RayEngine(); ~m2RayEngine(); private: }; <file_sep>/mod2/m2Line2.h #pragma once #include <glm/glm.hpp> struct m2Line2 { m2Line2(const glm::vec2&, const glm::vec2&); m2Line2(); ~m2Line2(); bool intersect(const m2Line2&, const m2Line2&, glm::vec2& poi); const glm::vec2 p1; const glm::vec2 p2; }; <file_sep>/mod2/m2RayRenderer.cpp #include "m2RayRenderer.h" #include "m2Window.h" #include "m2Shader.h" #include "m2Utilities.h" #include <glad/glad.h> #include <glm/gtc/random.hpp> #include <vector> static m2Window& window = m2Window::instance(); m2RayRenderer::m2RayRenderer(float xMin, float xMax, unsigned int thickness) : m_xMin(xMin), m_xMax(xMax), m_thickness(thickness), m_count(xMax - xMin / thickness), //Step is 2 / count cause we're going from -1 to +1 which is a range of 2. m_step(2.0f / (float)m_count), m_halfScreenHeight(m2Window::instance().getClientHeight() / 2) { m_colours.resize(m_count); m_heights.resize(m_count); assert(thickness > 0); glBindVertexArray(m_vao); glGenBuffers(1, &m_cbo); glGenBuffers(1, &m_hbo); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, m_cbo); for (unsigned int i = 0; i < m_count; i++) m_colours[i] = glm::linearRand(glm::vec4(0.0f), glm::vec4(1.0f)); glBufferData(GL_ARRAY_BUFFER, m_count * sizeof(glm::vec4), m_colours.data(), GL_STATIC_DRAW); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(glm::vec4), nullptr); glBindBuffer(GL_ARRAY_BUFFER, m_hbo); for (unsigned int i = 0; i < m_count; i++) m_heights[i] = glm::linearRand(500.0f, (float)window.getClientHeight() / 2.0f); glBufferData(GL_ARRAY_BUFFER, m_count * sizeof(float), m_heights.data(), GL_STATIC_DRAW); glVertexAttribPointer(1, 1, GL_FLOAT, GL_FALSE, sizeof(float), nullptr); glBindVertexArray(GL_NONE); } m2RayRenderer::~m2RayRenderer() { glDeleteBuffers(1, &m_cbo); glDeleteBuffers(1, &m_hbo); } void m2RayRenderer::render() { glBindBuffer(GL_ARRAY_BUFFER, m_cbo); for(unsigned int i = 0; i < m_count; i++) m_colours[i] = glm::linearRand(glm::vec4(0.0f), glm::vec4(1.0f)); glBufferSubData(GL_ARRAY_BUFFER, 0, m_count * sizeof(glm::vec4), m_colours.data()); glBindBuffer(GL_ARRAY_BUFFER, m_hbo); for (unsigned int i = 0; i < m_count; i++) m_heights[i] = glm::linearRand(0.0f, (float)window.getClientHeight() / 2.0f); glBufferSubData(GL_ARRAY_BUFFER, 0, m_heights.size() * sizeof(float), m_heights.data()); m2ShaderProgram& rayShader = m2ShaderProgram::getProgram(RAY); rayShader.bind(); rayShader.setFloat("u_start", m2Utils::screenToNdcX(m_xMin)); rayShader.setFloat("u_step", m_step); rayShader.setFloat("u_rayOrigin", (float)window.getClientHeight() / 2.0f); rayShader.setFloat("u_clientY", (float)window.getClientY()); rayShader.setFloat("u_clientHeight", (float)window.getClientHeight()); glBindVertexArray(m_vao); glDrawArrays(GL_POINTS, 0, m_count); }<file_sep>/mod2/m2Transform.h #pragma once #define GLM_FORCE_SWIZZLE #include <glm/glm.hpp> #include <glm/gtc/quaternion.hpp> class m2Transform { public: m2Transform(); ~m2Transform(); glm::mat4 getWorldTransformation(); glm::vec3 getWorldPosition(); glm::vec3 getWorldTranslation(); glm::vec3 getWorldRotation(); const glm::mat4& getLocalTransformation(); glm::vec3 getLocalPosition(); glm::vec3 getLocalTranslation(); glm::vec3 getLocalRotation(); float getLocalRotationX(); float getLocalRotationY(); float getLocalRotationZ(); glm::vec3 getScale(); float getScaleX(); float getScaleY(); float getScaleZ(); glm::mat3 getDirections(); glm::vec3 getFront(); glm::vec3 getRight(); glm::vec3 getAbove(); //Right and above will correct automatically. void setFront(glm::vec3); //Front and above will correct automatically. void setRight(glm::vec3); //Front and right will correct automatically. void setAbove(glm::vec3); void setTranslation(glm::vec3); void setRotation(glm::vec3); void setTranslation(float, float, float); void setRotation(float, float, float); void setRotationX(float); void setRotationY(float); void setRotationZ(float); void setDeltaTranslation(glm::vec3); void setDeltaRotation(glm::vec3); void setDeltaTranslation(float, float, float); void setDeltaRotation(float, float, float); void setDeltaRotationX(float); void setDeltaRotationY(float); void setDeltaRotationZ(float); void setScale(glm::vec3); void setScale(float); void setScaleX(float); void setScaleY(float); void setScaleZ(float); private: glm::mat4 m_transformation; glm::quat m_orientation;//Consider making a euler rotation as well for ease of access unless I can make a quick getter to deduce form the quat. glm::vec3 m_scale; m2Transform* m_parent; //Encode the pointer across xy and the dirty flag in z! //Actually don't cause then you'll fuck concatenation. static const glm::mat4 s_mIdentity; static const glm::vec4 s_vIdentity; static const glm::vec3 s_up; inline glm::quat _getWorldOrientation(); inline void _setDirections(glm::vec3 front, glm::vec3 right, glm::vec3 above); inline const m2Transform& getParent(); inline void setParent(const m2Transform&); };
61c71184c974f36b48b0ff49ed0cd4e56ae3db40
[ "C", "C++" ]
39
C++
Smiley98/mod2
f7b4e4b558f77e4c2acad0c51dbba0d8f0d38f32
0f4c896fe05621c6cddae0013b8948307e4f2230
refs/heads/master
<repo_name>SaneelDaniel/quiz-app-back-end<file_sep>/README.md # Server - Full-Stack Quiz App The back-end REST-API for the quiz app, built with node.js and express.js, it has end points to fetch the QuizdData from a Mongo Database ( App live with gh-pages at https://saneeldaniel.github.io/quiz-app-deploy/ ) This is a server model for a basic full-stack quiz-app, with multiple choice questions. The back-end REST-API is built with node.js and express.js, it has end points to fetch the QuizdData from a Mongoo Database The back-end server is deployed over Heroku Cloud platform, the database is hosted on Atlas with AWS. (EndPoint: https://mongo-quiz-rest.herokuapp.com/quizes/QuizCollection) QuizSchema = ({ questionID: { type: Number, }, questionString: { type: String, }, choices: { type: Array, }, rightChoice: { type: String, }, }); <file_sep>/routes/quizes.js const express = require("express"); const router = express.Router(); var MongoClient = require("mongodb").MongoClient; const fs = require("fs"); let rawdata = fs.readFileSync(process.cwd() + "/routes/" + "config.json"); let config = JSON.parse(rawdata); const dbName = config.DB_NAME; router.get("/QuizCollection", async (req, res) => { try { MongoClient.connect( process.env.DB_CONNECTION, { useNewUrlParser: true, useUnifiedTopology: true }, (error, client) => { if (error) { console.log(error); } database = client.db(process.env.DB_NAME); var cursor = database .collection("quizCollection") .find({}) .toArray((error, result) => { if (error) { console.log("error .....", error); } var resultCollection = []; result.forEach(function (err, data) { resultCollection.push(data); }); console.log(resultCollection); res.setHeader("Content-Type", "application/json"); res.status(200).json(result); }); } ); } catch (err) { console.log(err); res.status(404).json({ message: err.message }); } }); module.exports = router; <file_sep>/db/Quiz.js const mongoose = require("mongoose"); const quizSchema = mongoose.Schema({ questionID: { type: Number, }, questionString: { type: String, }, choices: { type: Array, }, rightChoice: { type: String, }, }); module.exports = Quiz = mongoose.model("quizCollection", quizSchema); <file_sep>/server.js const express = require("express"); const fs = require("fs"); const app = express(); const connectDB = require("./db/Connection"); let rawdata = fs.readFileSync(process.cwd() + "/routes/" + "config.json"); let config = JSON.parse(rawdata); //connectDB(); app.use(express.json({ extended: false })); app.use((req, res, next) => { res.header("Access-Control-Allow-Origin", "*"); res.header( "Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization" ); if (req.method === "OPTIONS") { res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, GET"); return res.status(200).json({}); } next(); }); //routes const quizRoute = require("./routes/quizes"); app.use("/quizes", quizRoute); const PORT = process.env.PORT || 4000; app.listen(PORT, () => console.log("Server running at port:", PORT)); <file_sep>/db/Connection.js const mongoose = require("mongoose"); require("dotenv/config"); var MongoClient = require("mongodb").MongoClient; const fs = require("fs"); let rawdata = fs.readFileSync(process.cwd() + "/routes/" + "config.json"); let config = JSON.parse(rawdata); const databaseName = config.DB_NAME; const URI = config.DB_CONNECTION; var database; const connectionParams = { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true, }; const connectDB = () => MongoClient.connect( URI, { useNewUrlParser: true, useUnifiedTopology: true }, (error, client) => { if (error) { console.log(error); } database = client.db(databaseName); console.log("Database connection successful", databaseName); console.log(database.collection("quizCollection")); } ); module.exports = database; module.exports = connectDB;
c362b05e5c869d83c2b66cb0e930630757d201eb
[ "Markdown", "JavaScript" ]
5
Markdown
SaneelDaniel/quiz-app-back-end
ad6a55d9b136efa97054659a9d77855b47fdfcf4
24ade5983445afb4990453446c8e7ae57e734796
refs/heads/main
<file_sep>// // MainListView.swift // Pryaniky.com // // Created by <NAME> on 21.03.2021. // import UIKit protocol IMainListViewType: class { var tableView: UITableView { get } } final class MainListView: UIView { private weak var viewController: MainListViewController? private var listItems = UITableView() init(viewController: MainListViewController) { self.viewController = viewController super.init(frame: .zero) self.setupView() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: SetupConstraints private extension MainListView { func setupView() { self.backgroundColor = .white self.setupListItems() } func setupListItems() { self.addSubview(self.listItems) self.listItems.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ self.listItems.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor), self.listItems.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor), self.listItems.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor), self.listItems.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor) ]) } } // MARK: IMainListViewType extension MainListView: IMainListViewType { var tableView: UITableView { self.listItems } } <file_sep>// // MainListModel.swift // Pryaniky.com // // Created by <NAME> on 21.03.2021. // import Foundation struct MainListModel: Codable { let data: [RootData]? let view: [String]? } struct RootData: Codable { let name: String? let data: ObjectData? } struct ObjectData: Codable { let text: String? let url: String? let selectedId: Int? let variants: [Variants]? } struct Variants: Codable { let id: Int? let text: String? } /* { "data": [{ "name": "hz", "data": { "text": "Текстовый блок" } }, { "name": "picture", "data": { "url": "https://pryaniky.com/static/img/logo-a-512.png", "text": "Пряники" } }, { "name": "selector", "data": { "selectedId": 1, "variants": [{ "id": 1, "text": "Вариант раз" }, { "id": 2, "text": "Вариант два" }, { "id": 3, "text": "Вариант три" } ] } } ], "view": ["hz", "selector", "picture", "hz"] } */ <file_sep>// // CustomImageView.swift // Pryaniky.com // // Created by <NAME> on 29.03.2021. // import UIKit let imageCache = NSCache<AnyObject, AnyObject>() class CustomImageView: UIImageView { private var spinner = UIActivityIndicatorView(style: .large) private var queryService: IQueryService init(queryService: IQueryService) { self.queryService = queryService super.init(image: UIImage()) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension CustomImageView { func loadImage(from url: URL) { self.image = nil self.addSpinner() if let imageFromCache = imageCache.object(forKey: url.absoluteString as AnyObject) as? UIImage { self.image = imageFromCache self.removeSpinner() return } self.queryService.getDataAt(url: url, completion: { (data, error) in guard let newImage = UIImage(data: data) else { return } imageCache.setObject(newImage, forKey: url.absoluteString as AnyObject) DispatchQueue.main.async { self.image = newImage self.removeSpinner() } }) } } private extension CustomImageView { func addSpinner() { self.addSubview(self.spinner) self.spinner.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ self.spinner.centerYAnchor.constraint(equalTo: self.centerYAnchor), self.spinner.centerXAnchor.constraint(equalTo: self.centerXAnchor) ]) self.spinner.startAnimating() } func removeSpinner() { self.spinner.removeFromSuperview() } } <file_sep>// // Factory.swift // Pryaniky.com // // Created by <NAME> on 29.03.2021. // import UIKit enum UIElement { case label(String) case imageView(String) } final class Factory { static let singleton = Factory(queryService: QueryService()) private var queryService: IQueryService private init(queryService: IQueryService) { self.queryService = queryService } func create(ui: UIElement) -> UIView { switch ui { case .label(let text): let label = UILabel() label.text = text return label case .imageView(let url): let imageView = CustomImageView(queryService: self.queryService) if let url = URL(string: url) { imageView.loadImage(from: url) } return imageView } } } <file_sep>// // MainListViewModel.swift // Pryaniky.com // // Created by <NAME> on 21.03.2021. // import Foundation import RxSwift protocol IMainListViewModelInput: class { // Входной протокол func fetchData() var list: PublishSubject<[String]> { get } var item: BehaviorSubject<RootData?> { get } } protocol IMainListViewModelOutput: class { // Выходной протокол var selectedItemName: String { get set } } final class MainListViewModel { private var model: MainListModel private var queryService: IQueryService private var url = "https://pryaniky.com/static/json/sample.json" private var listItems = PublishSubject<[String]>() private var selectedItems = BehaviorSubject<RootData?>(value: nil) private var listItemsData = [RootData]() private let disposeBag = DisposeBag() init(model: MainListModel, queryService: IQueryService) { self.model = model self.queryService = queryService } } private extension MainListViewModel { func fetchDataModel() { if let url = URL(string: self.url) { self.queryService.dataFrom(url: url).subscribe(onNext: { listModel in if let data = listModel.view { self.listItems.onNext(data) self.listItems.onCompleted() } self.listItemsData = listModel.data ?? [] }).disposed(by: disposeBag) } } } // MARK: IMainViewViewModelInput extension MainListViewModel: IMainListViewModelInput { var item: BehaviorSubject<RootData?> { self.selectedItems } func fetchData() { self.fetchDataModel() } var list: PublishSubject<[String]> { get { self.listItems } } } // MARK: IMainListViewModelOutput extension MainListViewModel: IMainListViewModelOutput { var selectedItemName: String { get { return "" } set { for item in listItemsData{ if item.name == newValue { self.selectedItems.onNext(item) } } } } } <file_sep>// // DetailViewController.swift // Pryaniky.com // // Created by <NAME> on 25.03.2021. // import UIKit import RxSwift import RxCocoa class DetailViewController: UIViewController { private var customView = DetailView() private var viewModel: MainListViewModel private var disposeBag = DisposeBag() init(viewModel: MainListViewModel) { self.viewModel = viewModel super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.setupViewData() } override func loadView() { self.view = customView } } extension DetailViewController { func setupViewData() { self.viewModel.item.subscribe(onNext: { item in self.navigationItem.title = item?.name let stack = UIStackView() stack.axis = .vertical stack.distribution = .equalSpacing stack.spacing = 50 stack.alignment = .center if let text = item?.data?.text { stack.addArrangedSubview(Factory.singleton.create(ui: .label(text))) } if let url = item?.data?.url { stack.addArrangedSubview(Factory.singleton.create(ui: .imageView(url))) } self.customView.stack = stack }).disposed(by: self.disposeBag) } } <file_sep># Podfile use_frameworks! target 'Pryaniky.com' do pod 'Alamofire', '~> 5.2' pod 'RxSwift', '6.1.0' pod 'RxCocoa', '6.1.0' end <file_sep>// // AppCoordinator.swift // Pryaniky.com // // Created by <NAME> on 21.03.2021. // import UIKit import RxSwift import RxCocoa final class AppCoordinator { private let window: UIWindow private let disposeBag = DisposeBag() private var navigationController: UINavigationController? private var detailView: DetailViewController? init(window: UIWindow) { self.window = window } func start() { let model = MainListModel(data: nil, view: nil) let viewModel = MainListViewModel(model: model, queryService: QueryService()) let viewController = MainListViewController(viewModel: viewModel) self.navigationController = UINavigationController(rootViewController: viewController) viewModel.item.subscribe(onNext: { item in if item != nil { self.changeView(DetailViewController(viewModel: viewModel)) } }).disposed(by: disposeBag) window.rootViewController = navigationController window.makeKeyAndVisible() } func changeView(_ viewController: UIViewController) { guard let nc = self.navigationController else { return } if !nc.viewControllers.contains(viewController) { nc.pushViewController(viewController, animated: true) } } } <file_sep>// // MainListViewController.swift // Pryaniky.com // // Created by <NAME> on 21.03.2021. // import UIKit import RxSwift import RxCocoa final class MainListViewController: UIViewController { private var viewModel: MainListViewModel private var customView: IMainListViewType? private let disposeBag = DisposeBag() private let cellId = "cellId" init(viewModel: MainListViewModel) { self.viewModel = viewModel super.init(nibName: nil, bundle: nil) self.customView = MainListView(viewController: self) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { self.view = customView as? UIView } override func viewDidLoad() { super.viewDidLoad() self.setupTable() } } private extension MainListViewController { func setupTable() { guard let tableView = self.customView?.tableView else { return } tableView.register(UITableViewCell.self, forCellReuseIdentifier: self.cellId) tableView.delegate = self self.viewModel.list.bind(to: tableView.rx.items(cellIdentifier: self.cellId, cellType: UITableViewCell.self)) { (row, item, cell) in cell.textLabel?.text = item }.disposed(by: disposeBag) tableView.rx.modelSelected(String.self).subscribe(onNext: { item in print("SelectedItem: \(item)") self.viewModel.selectedItemName = item }).disposed(by: disposeBag) self.viewModel.fetchData() } } // MARK: UITableViewDelegate extension MainListViewController: UITableViewDelegate { } <file_sep>// // QueryService.swift // Pryaniky.com // // Created by <NAME> on 22.03.2021. // import Foundation import RxSwift import UIKit protocol IQueryService: class { func dataFrom(url: URL) -> Observable<MainListModel> func getDataAt(url: URL, completion: @escaping (Data, String) -> Void) } final class QueryService { private let defaultSession = URLSession(configuration: .default) private var dataTask: URLSessionDataTask? private var errorMessage = "" private var responseData = Data() typealias QueryResult = (Data, String) -> Void } private extension QueryService { func JSONParse(data: Data) -> (MainListModel, String) { var errorDescription = "" var entityModel = MainListModel(data: nil, view: nil) do { entityModel = try JSONDecoder().decode(MainListModel.self, from: data) } catch let error { errorDescription = error.localizedDescription } return (entityModel, errorDescription) } } // MARK: IQueryService extension QueryService: IQueryService { func getDataAt(url: URL, completion: @escaping QueryResult) { self.dataTask?.cancel() self.dataTask = defaultSession.dataTask(with: url) { [weak self] data, response, error in defer { self?.dataTask = nil } self?.responseData = Data() self?.errorMessage = "" if let error = error { self?.errorMessage = "Data task error: \(error.localizedDescription)\n" } else if let data = data, let response = response as? HTTPURLResponse { if response.statusCode == 200 { self?.responseData = data } else { self?.errorMessage = "Data task error: code \(response.statusCode)\n" } } DispatchQueue.global(qos: .userInitiated).async { completion(self?.responseData ?? Data(), self?.errorMessage ?? "") } } self.dataTask?.resume() } func dataFrom(url: URL) -> Observable<MainListModel> { return Observable.create { [weak self] observer -> Disposable in var responseData = Data() var model = MainListModel(data: nil, view: nil) self?.getDataAt(url: url) { (data, error) in if error == "" { responseData = data model = self?.JSONParse(data: responseData).0 ?? MainListModel(data: nil, view: nil) observer.onNext(model) } else { print(error) observer.onError(error as! Error) } } return Disposables.create { } } } } <file_sep>// // DetailView.swift // Pryaniky.com // // Created by <NAME> on 25.03.2021. // import UIKit import RxSwift import RxCocoa protocol IDetailViewType: class { var stack: UIStackView { get set } } final class DetailView: UIView { private var scrollView: UIScrollView = { let scrollView = UIScrollView() scrollView.backgroundColor = .white return scrollView }() private var stackView: UIStackView = { let stackView = UIStackView() stackView.alignment = .center return stackView }() private enum Constraints { static let verticalOffset: CGFloat = 20 } override init(frame: CGRect) { super.init(frame: .zero) self.setupView() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } private extension DetailView { func setupView() { self.backgroundColor = .white self.setupConstraints() } func setupConstraints() { self.addSubview(self.scrollView) self.scrollView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ self.scrollView.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor), self.scrollView.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor), self.scrollView.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor), self.scrollView.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor) ]) self.scrollView.addSubview(self.stackView) self.stackView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ self.stackView.topAnchor.constraint(equalTo: self.scrollView.topAnchor, constant: Constraints.verticalOffset), self.stackView.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor), self.stackView.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor), self.stackView.bottomAnchor.constraint(equalTo: self.scrollView.bottomAnchor) ]) } } // MARK: IDetailViewType extension DetailView: IDetailViewType { var stack: UIStackView { get { self.stackView } set { self.stackView = newValue self.setupConstraints() self.layoutIfNeeded() } } }
e1416fbcc01b8906b7d77cf59c8ae73242d61098
[ "Swift", "Ruby" ]
11
Swift
Vasiliy-70/Pryaniky.com
f5ceef79aa77b9e45ce4b0fad6a2f04496b1de2f
a2658eef70f1e7a702a387f5aadbf09c0ebdf76e
refs/heads/master
<repo_name>jackey90/machine_learning<file_sep>/collective_intelligence/chapter2/recommendations.py # A dictionary of movie critics and their ratings of a small # set of movies critics = { "<NAME>": { "Lady in the Water": 2.5, "Snakes on a Plane": 3.5, "Just My Luck": 3, "Superman Returns": 3.5, "You, Me and Dupree": 2.5, "The Night Listener": 3 }, "<NAME>": { "Lady in the Water": 3, "Snakes on a Plane": 3.5, "Just My Luck": 1.5, "Superman Returns": 5, "The Night Listener": 3, "You, Me and Dupree": 3.5 }, "<NAME>": { "Lady in the Water": 2.5, "Snakes on a Plane": 3, "Superman Returns": 3.5, "The Night Listener": 4 }, "<NAME>": { "Snakes on a Plane": 3.5, "Just My Luck": 3, "The Night Listener": 4.5, "Superman Returns": 4, "You, Me and Dupree": 2.5 }, "<NAME>": { "Lady in the Water": 3, "Snakes on a Plane": 4, "Just My Luck": 2, "Superman Returns": 3, "The Night Listener": 3, "You, Me and Dupree": 2 }, "<NAME>": { "Lady in the Water": 3, "Snakes on a Plane": 4, "The Night Listener": 3, "Superman Returns": 5, "You, Me and Dupree": 3.5 }, "Toby": { "Snakes on a Plane": 4.5, "You, Me and Dupree": 1, "Superman Returns": 4 } } import math def sim_distance(data, person1, person2): si = {} for item in data[person1]: if item in data[person2]: si[item] = 1 if len(si) == 0: return 0 sum_of_squares = sum( [pow(data[person1][item] - data[person2][item], 2) for item in data[person1] if item in data[person2]]) return 1 / (1 + sum_of_squares) def sim_pearson(data, p1, p2): si = {} for item in data[p1]: # find the same item if item in data[p2]: si[item] = 1 n = len(si) if n == 0: return 0 sum1 = sum([data[p1][it] for it in si]) sum2 = sum([data[p2][it] for it in si]) sum1Sq = sum([pow(data[p1][it], 2) for it in si]) sum2Sq = sum([pow(data[p2][it], 2) for it in si]) pSum = sum([data[p1][it] * data[p2][it] for it in si]) num = pSum - (sum1 * sum2 / n) den = math.sqrt((sum1Sq - pow(sum1, 2) / n) * (sum2Sq - pow(sum2, 2) / n)) if den == 0: return 0 r = num / den return r def topMatches(data,person,n=5,similarity=sim_pearson): scores=[(similarity(data,person,other),other) for other in data if other != person] scores.sort() scores.reverse() return scores[0:n] def getRecommendations(data,person,similarity=sim_pearson): totals={} simSums={} for other in data: #skip self if other == person: continue sim = similarity(data,person,other) if sim <= 0 : continue for item in data[other]: # item not in my list if item not in data[person] or data[person][item] == 0: totals.setdefault(item,0) totals[item] += data[other][item]*sim simSums.setdefault(item,0) simSums[item] += sim rankings=[(total/simSums[item],item) for item,total in totals.items()] rankings.sort() rankings.reverse() return rankings def transformData(data): result={} for person in data: for item in data[person]: result.setdefault(item,{}) result[item][person]=data[person][item] return result <file_sep>/collective_intelligence/chapter2/ch2.py __author__ = 'jackey90' from recommendations import critics from recommendations import sim_distance from recommendations import sim_pearson from recommendations import topMatches from recommendations import getRecommendations from recommendations import transformData #print critics['<NAME>'] #print sim_distance(critics, "<NAME>", "<NAME>") #print sim_distance(critics, "<NAME>", "<NAME>") #print topMatches(critics,"<NAME>", 6, sim_pearson) #print getRecommendations(critics,'Toby') movies=transformData(critics) print topMatches(movies,'Just My Luck')
99041784e3d035defd57af271de6a8db23b453fc
[ "Python" ]
2
Python
jackey90/machine_learning
e36cdd42a0b811896b77ec83ff3960ecc370a4b4
594d6553cc3790e00977b8c856f2c4c82d591e78
refs/heads/master
<repo_name>diegolfavero/bakend-challenge-acme<file_sep>/README.md # bakend-challenge-acme Invillia Avaliation # URL Git da Avaliação: https://github.com/diegolfavero/bakend-challenge-acme.git # Simulando uma possível V0 deste Challenge: A tarefa foi dividida em 4 projetos, e visa mudar a arquitetura do sistema monolítico para uma arquitetura micro serviços da empresa ACME. Procurei priorizar a implementação dos serviços, Testes utilizando as chamadas dos Endpoints com o Postman, Testes com JUnit, Segurança, Clean Code, Criação de Database e estabelecer um Padrão de Projeto para entregas futuras. # "Nice to have features" implementadas: * Database (Armazenamento dos Dados das informações e registros.) - Foi utilizado o MySql. * Security (Prover autenticação, segurança e permissões de acesso.) - Foi utilizada a Basic Authentication do Spring Security. User: admin Password: <PASSWORD> * Clean Code (Código com clareza, de fácil entendimento e leitura.) # "Nice to have features" não implementadas (não houve tempo até o término do prazo) e utilizaria em possíveis próximas entregas: * Asynchronous processing (Dois ou mais Processos são realizados simultaneamente, sem necessidade do término de uma tarefa para iniciar outra.) - Utilizaria Processamento assíncrono com JMS, Filas, Messages, Queues para controle. * Docker (Centralizador em Containers de ambientes e aplicações, auxiliando na criação e administração.) * AWS (Plataforma de serviços em nuvem para criação de produtos, soluções e aplicativos para empresas.) - Utilizaria para maior Escalabilidade e Resiliência * Swagger (Ferramenta que auxilia na documentação de APIs.) - Utilizaria para melhorar a documentação e modelagem da aplicação. - Melhoria da Padronização para RNs e Tratamento de Exceções. - Faria mais Testes JUnit nas demais camadas (Controller, Repository). - Utilização de H2 Database Engine.<file_sep>/payment/src/main/java/br/com/acme/payment/repository/PaymentAcmeRepository.java package br.com.acme.payment.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import br.com.acme.payment.model.PaymentAcme; public interface PaymentAcmeRepository extends JpaRepository<PaymentAcme, Integer> { public List<PaymentAcme> findAll(); } <file_sep>/store/src/test/java/br/com/acme/store/service/StoreAcmeServiceTest.java package br.com.acme.store.service; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.springframework.test.context.junit4.SpringRunner; import br.com.acme.store.model.StoreAcme; import br.com.acme.store.repository.StoreAcmeRepository; @RunWith(SpringRunner.class) public class StoreAcmeServiceTest { @InjectMocks private StoreAcmeService storeAcmeService; @Mock private StoreAcmeRepository storeAcmeRepository; @Rule public final ExpectedException exception = ExpectedException.none(); private static final Integer ID = Integer.parseInt("1"); private final String address = "address"; private final String name = "name"; private StoreAcme storeAcme; private List<StoreAcme> listStoreAcme; @Before public void setup() { storeAcme = new StoreAcme(ID, name, address); listStoreAcme = new ArrayList<StoreAcme>(); listStoreAcme.add(storeAcme); } @Test public void save() { Mockito.when(storeAcmeRepository.save(Mockito.any(StoreAcme.class))).thenReturn(storeAcme); StoreAcme retorno = storeAcmeService.save(storeAcme); assertNotNull(retorno); assertNotNull(retorno.getId()); } @Test public void findAll() { Mockito.when(storeAcmeRepository.findAll()).thenReturn(listStoreAcme); List<StoreAcme> retorno = storeAcmeService.findAll(); assertNotNull(retorno); } @Test public void findById() { Mockito.when(storeAcmeRepository.findById(Mockito.anyInt())).thenReturn(Optional.of(storeAcme)); Optional<StoreAcme> retorno = storeAcmeService.findById(ID); assertNotNull(retorno); } @Test public void findByIdInvalid() { Mockito.when(storeAcmeRepository.findById(Mockito.anyInt())).thenReturn(null); Optional<StoreAcme> retorno = storeAcmeService.findById(ID); assertNull(retorno); } } <file_sep>/refund/src/main/java/br/com/acme/refund/util/AcmeStatusUtil.java package br.com.acme.refund.util; public interface AcmeStatusUtil { public String AGUARDANDO = "AGUARDANDO"; public String FATURADA = "FATURADA"; } <file_sep>/payment/src/main/java/br/com/acme/payment/controller/PaymentController.java package br.com.acme.payment.controller; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import br.com.acme.payment.model.OrderAcme; import br.com.acme.payment.model.PaymentAcme; import br.com.acme.payment.service.OrderAcmeService; import br.com.acme.payment.service.PaymentAcmeService; @RestController public class PaymentController { @Autowired private PaymentAcmeService paymentService; @Autowired private OrderAcmeService orderAcmeService; // ENDPOINT: INSERIR PAYMENT @RequestMapping(value = "/payment/insert", method = RequestMethod.POST) public ResponseEntity<String> insertPayment(@RequestParam("status") String status, @RequestParam("number_card") Long numberCard, @RequestParam("date") String date, @RequestParam("id_order") Integer idOrder) { Optional<OrderAcme> optionalOrderAcme = this.orderAcmeService.findById(idOrder); if (optionalOrderAcme == null) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } else { try { PaymentAcme payment = new PaymentAcme(); payment.setNumberCard(numberCard); payment.setStatus(status); payment.setOrder(optionalOrderAcme.get()); DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); Date paymDate = dateFormat.parse(date); payment.setPaymDate(paymDate); this.paymentService.save(payment); } catch (ParseException e) { e.printStackTrace(); return new ResponseEntity<String>("Error to insert Payment!", HttpStatus.INTERNAL_SERVER_ERROR); } return new ResponseEntity<String>("Payment inserted successfully.", HttpStatus.OK); } } // ENDPOINT: PESQUISAR TODOS @RequestMapping(value = "/payment/findAll", method = RequestMethod.GET) public ResponseEntity<List<PaymentAcme>> findAll() { List<PaymentAcme> listaPayment = this.paymentService.findAll(); if (listaPayment == null) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } return new ResponseEntity<List<PaymentAcme>>(listaPayment, HttpStatus.OK); } } <file_sep>/store/src/main/java/application.properties spring.datasource.initialize=true spring.datasource.url=jdbc:mysql://127.0.0.10:3306/store_db?useTimezone=true&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=<PASSWORD> spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.jpa.hibernate.ddl-auto=update spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect server.port = 8080<file_sep>/order/src/main/java/br/com/acme/order/repository/OrderItemAcmeRepository.java package br.com.acme.order.repository; import java.util.List; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import br.com.acme.order.model.OrderItemAcme; public interface OrderItemAcmeRepository extends JpaRepository<OrderItemAcme, Integer> { public Optional<OrderItemAcme> findById(Integer id); public List<OrderItemAcme> findAll(); } <file_sep>/refund/src/main/java/br/com/acme/refund/model/OrderAcme.java package br.com.acme.refund.model; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; @Entity public class OrderAcme implements Serializable { /** * */ private static final long serialVersionUID = 331053547347390218L; @Id @GeneratedValue(strategy= GenerationType.IDENTITY) private Integer id; @ManyToMany @JoinTable(name = "order_order_item_acme", joinColumns = { @JoinColumn(name = "id_order") }, inverseJoinColumns = { @JoinColumn(name = "id_order_item") }) private List<OrderItemAcme> orderItemAcme; @Column(name = "address") private String address; @Column(name = "confirm_date") private Date confirmDate; @Column(name = "status") private String status; public OrderAcme(Integer id, String address, Date confirmDate, String status) { super(); this.id = id; this.address = address; this.confirmDate = confirmDate; this.status = status; this.orderItemAcme = new ArrayList<>(); } public OrderAcme() { super(); this.orderItemAcme = new ArrayList<>(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Date getConfirmDate() { return confirmDate; } public void setConfirmDate(Date confirmDate) { this.confirmDate = confirmDate; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public List<OrderItemAcme> getOrderItemAcme() { return orderItemAcme; } public void setOrderItemAcme(List<OrderItemAcme> orderItemAcme) { this.orderItemAcme = orderItemAcme; } } <file_sep>/payment/src/main/java/br/com/acme/payment/service/OrderAcmeService.java package br.com.acme.payment.service; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import br.com.acme.payment.model.OrderAcme; @Service public class OrderAcmeService { @Autowired private OrderAcmeService orderAcmeRepository; public OrderAcme save(OrderAcme orderAcme) { return this.orderAcmeRepository.save(orderAcme); } public List<OrderAcme> findAll() { return this.orderAcmeRepository.findAll(); } public Optional<OrderAcme> findById(Integer id) { return this.orderAcmeRepository.findById(id); } public List<OrderAcme> findByStatus(String status) { return this.orderAcmeRepository.findByStatus(status); } } <file_sep>/db.sql create database invillia_db; use invillia_db; create table if not exists order_acme( id integer auto_increment primary key, address varchar(255) not null, confirm_date date not null, status varchar(255) not null ); create table if not exists order_item_acme( id integer auto_increment primary key, descricao varchar(255) not null, preco decimal(10,2) not null, quantidade integer not null ); create table if not exists order_order_item_acme( id_order integer not null, id_order_item integer not null, primary key (id_order, id_order_item), foreign key (id_order) references order_acme(id), foreign key (id_order_item) references order_item_acme(id) ); create table if not exists payment( id integer auto_increment primary key, status varchar(255) not null, number_card bigint not null, paym_date date not null ); create table if not exists payment_order( id_order integer not null, id_payment integer not null, primary key (id_order, id_payment), foreign key (id_order) references order_acme(id), foreign key (id_payment) references payment(id) ); create table if not exists store( id integer auto_increment primary key, name varchar(255) not null, address varchar(255) not null ); commit;<file_sep>/order/src/test/java/br/com/acme/order/service/OrderAcmeServiceTest.java package br.com.acme.order.service; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Optional; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.springframework.test.context.junit4.SpringRunner; import br.com.acme.order.model.OrderAcme; import br.com.acme.order.repository.OrderAcmeRepository; @RunWith(SpringRunner.class) public class OrderAcmeServiceTest { @InjectMocks private OrderAcmeService orderAcmeService; @Mock private OrderAcmeRepository orderAcmeRepository; @Rule public final ExpectedException exception = ExpectedException.none(); private static final Integer ID = Integer.parseInt("1"); private final String address = "address"; private final String date = "2018-01-01"; private final String status = "AGUARDANDO"; private OrderAcme orderAcme; private List<OrderAcme> listOrderAcme; @Before public void setup() { try { DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); Date dataFormatada = dateFormat.parse(date); orderAcme = new OrderAcme(ID, address, dataFormatada, status); listOrderAcme = new ArrayList<OrderAcme>(); listOrderAcme.add(orderAcme); } catch (Exception e) { e.printStackTrace(); } } @Test public void save() { Mockito.when(orderAcmeRepository.save(Mockito.any(OrderAcme.class))).thenReturn(orderAcme); OrderAcme retorno = orderAcmeService.save(orderAcme); assertNotNull(retorno); assertNotNull(retorno.getId()); } @Test public void findAll() { Mockito.when(orderAcmeRepository.findAll()).thenReturn(listOrderAcme); List<OrderAcme> retorno = orderAcmeService.findAll(); assertNotNull(retorno); } @Test public void findById() { Mockito.when(orderAcmeRepository.findById(Mockito.anyInt())).thenReturn(Optional.of(orderAcme)); Optional<OrderAcme> retorno = orderAcmeService.findById(ID); assertNotNull(retorno); } @Test public void findByStatus() { Mockito.when(orderAcmeRepository.findByStatus(Mockito.anyString())).thenReturn(listOrderAcme); List<OrderAcme> retorno = orderAcmeService.findByStatus(status); assertNotNull(retorno); } @Test public void findByIdInvalid() { Mockito.when(orderAcmeRepository.findById(Mockito.anyInt())).thenReturn(null); Optional<OrderAcme> retorno = orderAcmeService.findById(ID); assertNull(retorno); } } <file_sep>/store/src/main/java/br/com/acme/store/controller/StoreAcmeController.java package br.com.acme.store.controller; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import br.com.acme.store.model.StoreAcme; import br.com.acme.store.service.StoreAcmeService; @RestController public class StoreAcmeController { @Autowired private StoreAcmeService storeAcmeService; // ENDPOINT: INSERIR STORE @RequestMapping(value = "/store/insert", method = RequestMethod.POST) public ResponseEntity<String> insertStore(@RequestParam("name") String name, @RequestParam("address") String address) { try { StoreAcme store = new StoreAcme(null, name, address); this.storeAcmeService.save(store); return new ResponseEntity<String>("Store inserted successfully." + store.getName(), HttpStatus.OK); } catch (Exception ex) { ex.printStackTrace(); return new ResponseEntity<String>("Error to insert Store.", HttpStatus.INTERNAL_SERVER_ERROR); } } // ENDPOINT: ATUALIZAR STORE @RequestMapping(value = "/store/update", method = RequestMethod.POST) public ResponseEntity<String> updateStore(@RequestParam("id") Integer id, @RequestParam("name") String name, @RequestParam("address") String address) { try { Optional<StoreAcme> store = this.storeAcmeService.findById(id); if (store != null) { StoreAcme storeUpdate = store.get(); storeUpdate.setName(name); storeUpdate.setAddress(address); this.storeAcmeService.save(storeUpdate); return new ResponseEntity<String>("Store updated successfully.", HttpStatus.OK); } else { return new ResponseEntity<String>("Store not found.", HttpStatus.FOUND); } } catch (Exception ex) { ex.printStackTrace(); return new ResponseEntity<String>("Error to update Store.", HttpStatus.INTERNAL_SERVER_ERROR); } } // ENDPOINT: PESQUISAR TODOS @RequestMapping(value = "/store/findAll", method = RequestMethod.GET) public ResponseEntity<List<StoreAcme>> findAll() { List<StoreAcme> listStore = this.storeAcmeService.findAll(); if (listStore == null) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } return new ResponseEntity<List<StoreAcme>>(listStore, HttpStatus.OK); } // ENDPOINT: PESQUISAR POR ID @RequestMapping(value = "/store/findById", method = RequestMethod.POST) public ResponseEntity<String> findById(@RequestParam("id") Integer id) { try { Optional<StoreAcme> store = this.storeAcmeService.findById(id); if (store != null) { return new ResponseEntity<String>("Store: " + store.get().getName() + ".", HttpStatus.OK); } else { return new ResponseEntity<String>("Store not found.", HttpStatus.FOUND); } } catch (Exception ex) { ex.printStackTrace(); return new ResponseEntity<String>("Error to find Store.", HttpStatus.INTERNAL_SERVER_ERROR); } } // ENDPOINT: EXCLUIR STORE @RequestMapping(value = "/store/delete", method = RequestMethod.POST) public ResponseEntity<String> deleteStore(@RequestParam("id") Integer id) { try { Optional<StoreAcme> store = this.storeAcmeService.findById(id); if (store != null) { this.storeAcmeService.delete(store.get()); return new ResponseEntity<String>("Store deleted successfully.", HttpStatus.OK); } else { return new ResponseEntity<String>("Store not found!", HttpStatus.FOUND); } } catch (Exception ex) { ex.printStackTrace(); return new ResponseEntity<String>("Error to find Store.", HttpStatus.INTERNAL_SERVER_ERROR); } } } <file_sep>/payment/target/classes/application.properties spring.datasource.initialize=true spring.datasource.url=jdbc:mysql://127.0.0.30:3306/payment_db?useTimezone=true&serverTimezone=UTC spring.datasource.username=root spring.datasource.password= spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.jpa.hibernate.ddl-auto=update spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect server.port = 8082
4490051b062350e5e2c7be91ea5cdd9e732dc058
[ "Markdown", "Java", "SQL", "INI" ]
13
Markdown
diegolfavero/bakend-challenge-acme
526217c12e5c01754f5c5b447f75283f93d15242
47bc17e29a75277aefb0fdc382400014b4f4bbb5
refs/heads/master
<file_sep> class Quotes attr_accessor :string, :author def initialize(string, author) @string = string @author = author end def quote_str return "#{string} - #{author}." end end Quotes_list = [ Quotes.new("Act as if what you do makes a difference. It does.", "<NAME>"), Quotes.new("Success is not final, failure is not fatal: it is the courage to continue that counts.", "<NAME>"), Quotes.new("Never bend your head. Always hold it high. Look the world straight in the eye.", "<NAME>"), Quotes.new("What you get by achieving your goals is not as important as what you become by achieving your goals.", "<NAME>"), Quotes.new("Believe you can and you're halfway there.", "<NAME>") ] class Summary attr_accessor :u_time, :u_stress, :u_goal, :input, :entry def to_s return ("to summarise: \n\n") + ("did you focus on yourself today: #{u_time}\n") + ("was today stressful: #{u_stress}\n")+ ("do you feel accomplished: #{u_goal}\n")+ ("this was your day rating: #{input}\n")+ ("and this was your entry: #{entry}\n\n") end end <file_sep>require "pastel" require "tty-prompt" require "tty-box" require "./classes.rb" prompt = TTY::Prompt.new(enable_color: true) pastel = Pastel.new diary_entry = true summary = Summary.new box = TTY::Box.frame(width:55, height:13, align: :center, title: {top_left: 'TERMINAL DIARY', bottom_right: '++++'}) do "\nWelcome to the terminal diary!\n note: this is an ANTI-social media app, for subjective use,\n you can choose to share your thoughts if you'd like,\n\n but you don't have to!!" end print pastel.yellow box prompt.keypress("Press space to continue\n", keys: [:space],) print pastel.blue"We'll start with 3 basic yes or no questions.\n " # save entries to the below responses summary.u_time = prompt.yes?(pastel.yellow"Did you put aside enough time for yourself today?") summary.u_stress = prompt.yes?(pastel.yellow"Was today a stressful day? ") summary.u_goal = prompt.yes?(pastel.yellow"Did you accomplish what you wanted today? ") puts pastel.blue "\n thank you for your feedback!\n" prompt.keypress("Press space to continue\n\n", keys: [:space]) summary.input = prompt.ask(pastel.blue"On a scale of 1 - 10 how would you rate you day? 1 being a bad day & 10 being a great one: ").to_i if summary.input >= 11 puts "\nyou must be having a really great day!! \n\n" elsif summary.input >= 7 puts "\nThat's great!! \n\n" # if response is 7 or greater return a simple "that's great" # before next step elsif summary.input <= 3 puts pastel.red TTY::Box.frame" perhaps it would be better to speak with your family or a professional, if you are having a really tough time there's also organisations like beyond blue on 1300 22 4636 that are there to help \n " # if the response is lower than 3, suggest that maybe the user # should speak to family, friends or a professional else puts "\nthat's good to hear \n\n" # if the response is between 4 and 7, put "you're doing ok" end # return here if the user chooses to write another entry while (diary_entry == true) box2 = TTY::Box.frame(width: 39, height: 12, align: :center, padding: 1, title: {bottom_right: '++++'}) do pastel.blue"thank you for your responses,\n would you like to write about \n your day? it can be a word or \n 2, or a full on essay,\n no pressure: " end print pastel.yellow box2 summary.entry = gets puts summary.to_s File.open("previous-entries.txt", "a") do |file| file.write( "#{summary.to_s}\n#{Quotes_list.sample.quote_str}\n\n---------------------------\n\n" ) end puts pastel.blue "\nWould you like to write another entry? (yes/no)" input = gets.chomp if input != "yes" diary_entry = false end end <file_sep> TERMINAL APP 1: Terminal diary OVERVIEW: The Terminal diary is an ANTI-social media app, for people who want to write about there experience, but don't know who to talk to and don't want to blast there opinions out in to the ether like so many social media applications do. It checks in with how your day was/is going starting with 3 simple yes or no questions, then asking for a 1 - 10 rating and then prompting you to make a diary entry. Write down anything you want, or split whatever's on your mind over multiple entries. At the end of your entry in the previous-entries.txt file an inspirational quote will also be generated. FEATURES: - 3 "yes or no" questions regarding: * stress * time management * goal orientation - rating for how your day is going take an opportunity to think about your day, how it affected you. - ability to write a diary entry write down how you're feeling, anything you want. whether it's a short sentence or a whole paragraph. - save the information to a text file on your PC The entry is then saved to the previous-entries text file, allowing you to go back and take a look at everything you've put down. - add an inspirational quote to the end of every entry after the diary entry is filled out and entered an inspirational quote is added to the previous entries file HOW TO INSTALL: clone from GITHUB using the URL: https://github.com/mmolloy88/terminal-app1.git GEMS USED: install the following gems to make sure the application will work smoothly pastel tty prompt tty-box Rubocop (this was used to check the code, not necessary to run Terminal diary) GETTING STARTED: once the the code has been cloned and the gems have been installed, run the core.rb file to start the app. TODO: increase pool of quotes add functionality that records time and date to each saved entry make macaroni art portrait to impress Bruce AUTHOR: <NAME> ACKNOWLEGMENTS: goodhousekeeping.com for the quotes Piotrmurach for developing the majority of the gems I've used in the code
5883280d3110e9d2ed43c24b68d35a84e53b5115
[ "Markdown", "Ruby" ]
3
Ruby
mmolloy88/terminal-app1
c744b504895e43f9cb569bff00b740de676e02a8
7f157edb33c999f143c7be6eb571f46d6d0ce25b
refs/heads/master
<repo_name>tyebu/parentStar<file_sep>/README.md # cloud_demo springCloud的demo <file_sep>/feign/src/main/java/com/star/feign/FeignService.java package com.star.feign; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; /** * @author Star.Wu * @date 2019/10/28 14:58 * @description **/ @FeignClient(value = "client", fallback = FeignServiceImpl.class) public interface FeignService { @RequestMapping(value = "/home",method = RequestMethod.GET) String sayHiFromClientOne(@RequestParam(value = "name") String name); }
c368c03e15667ffc50dbe5825a6f4250949bfc05
[ "Markdown", "Java" ]
2
Markdown
tyebu/parentStar
dc309fd38f672f2001779214cacddad2caf33780
b7108eda6ed289b9116068ea39cb1fa0792a683a
refs/heads/master
<repo_name>hirasaki1985/selenium_testcodes<file_sep>/requirements.txt selenium==3.7.0 python-box==3.1.1 <file_sep>/README.md selenium_testcodes ==== ## pyenv, anacondaのインストール(mac) ``` ### install pyenv anaconda $ brew update $ brew upgrade $ brew install pyenv $ pyenv --version $ pyenv install anaconda3-5.0.0 $ pyenv versions $ pyenv global anaconda3-5.0.0 ### add bash $ echo 'eval "$(pyenv init -)"' >> ~/.bash_profile $ source ~/.bash_profile $ which conda ``` ## ダウンロード ``` $ git clone https://github.com/hirasaki1985/selenium_testcodes.git $ cd selenium_testcodes ``` ## 環境構築 ``` $ conda create --name selenium python=3.6 $ source activate selenium (selenium)$ python -V (selenium)$ pip install -r requirements.txt ``` ## 実行 ``` $ source activate selenium (selenium)$ python src/main.py -m sample -p test_sample ``` ## 参考 [Macにanacondaをインストールする→ライブラリの追加](https://qiita.com/berry-clione/items/24fb5d97e4c458c0fc28) [PythonでSeleniumを使ってスクレイピング (基礎)](https://qiita.com/kinpira/items/383b0fbee6bf229ea03d) [ChromeDriver - WebDriver for Chrome](https://sites.google.com/a/chromium.org/chromedriver/home) [Pythonでディクショナリを扱う時に便利なライブラリ「Box」](http://co.bsnws.net/article/246) [webdriver](http://www.seleniumhq.org/projects/webdriver/) ## Author [m.hirasaki](https://github.com/hirasaki1985) <file_sep>/src/main.py # coding: utf-8 import os, sys import argparse from selenium import webdriver from logging import getLogger, StreamHandler, INFO, DEBUG import commons.functions as common import modules.sample.sample as sample logger = getLogger(__name__) handler = StreamHandler() handler.setLevel(DEBUG) logger.setLevel(DEBUG) logger.addHandler(handler) def main(args): """ 最初に実行される関数. @param args コンソールで渡された引数をdict型にしたもの """ # ドライバーのロード driver = getDriver(args) config = common.read_config(os.path.abspath(os.path.dirname(__file__)) + "/../" + args.config) # お問い合わせ画面の場合 if args.module_name == "sample": sample.main(driver, args, config[args.stage]); driver.quit() driver.close() def getDriver(args, driver_path ="librarys/selenium_drivers/chromedriver"): """ seleniumのdvierを返す. @param args コマンドライン引数 @param driver_path ドライバーへのパス。標準はchrome @return dvierインスタンス """ return webdriver.Chrome(os.path.abspath(os.path.dirname(__file__)) + '/' + driver_path) if __name__ == '__main__': # 引数のチェック、dictの作成 parser = argparse.ArgumentParser() parser.add_argument("-module_name", "-m", help="please input module_name", required=True) parser.add_argument("-program_name", "-p", help="please input program_name", required=True) parser.add_argument("-config", "-c", help="example ... config/environments.json", default="config/environments.json") parser.add_argument("-stage", "-s", help="local, staging, production", default="local") args = parser.parse_args() # main実行 main(args) <file_sep>/src/modules/sample/sample.py # coding: utf-8 import os, sys import time, re from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from logging import getLogger, StreamHandler, INFO, DEBUG from commons.functions import * logger = getLogger(__name__) handler = StreamHandler() handler.setLevel(DEBUG) logger.setLevel(DEBUG) logger.addHandler(handler) def main(driver, args, config): """ サンプル機能 @param driver seleniumのドライバー @param args コマンドライン引数 @param config 読み込まれたconfigファイル """ logger.debug("## %s()", sys._getframe().f_code.co_name) logger.debug(args) logger.debug(config) if args.program_name == "test_sample": exec_test_sample(driver, args, config) sys.exit() return None def exec_test_sample(driver, args, config): """ test_sampleのメインロジック @param driver seleniumのドライバー @param args コマンドライン引数 @param config 読み込まれたconfigファイル """ ## 読み込んだconfig["file_sample"]数分ループ for (i, line) in read_file(config["file_sample"]): logger.debug("line[%s] is %s", i, line) # URL取得 driver.get(config["url"]) WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'q'))) # 入力 driver.find_element_by_id('q').send_keys(line) # クリック #driver.find_element_by_class_name('btnK').click() driver.find_element_by_id('btnK').click() WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'lst-ib'))) # 表示されている場合 if driver.find_element_by_id('lst-ib').is_displayed(): # クリック driver.find_element_by_class_name('success').click() else: pass # キャプチャを取得 capture_path = os.path.abspath(os.path.dirname(__file__)) + '/../' + config["screenshot_path"] + get_screenshot_filename(config, i) logger.info(capture_path) # キャプチャ保存 driver.save_screenshot(capture_path)
00bb7628cfde98f3a6e6d63ae4886b490a8495fe
[ "Markdown", "Python", "Text" ]
4
Text
hirasaki1985/selenium_testcodes
c547b592f2761104ffe62ffbbadd26ed72dc04f2
47b9933295e2cab8bb7082eb14d4d36487b080f6
refs/heads/master
<repo_name>0pd/intellij-rust<file_sep>/src/main/kotlin/org/rust/ide/annotator/cargoCheck/RsCargoCheckAnnotatorPass.kt /* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.annotator.cargoCheck import com.intellij.codeHighlighting.DirtyScopeTrackingHighlightingPassFactory import com.intellij.codeHighlighting.TextEditorHighlightingPass import com.intellij.codeHighlighting.TextEditorHighlightingPassRegistrar import com.intellij.codeInsight.daemon.impl.* import com.intellij.lang.annotation.AnnotationSession import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.runReadAction import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.module.ModuleUtil import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.util.BackgroundTaskUtil import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.psi.PsiFile import com.intellij.psi.impl.AnyPsiChangeListener import com.intellij.psi.impl.PsiManagerImpl import com.intellij.util.messages.MessageBus import com.intellij.util.ui.update.MergingUpdateQueue import com.intellij.util.ui.update.Update import org.rust.cargo.project.settings.rustSettings import org.rust.cargo.project.settings.toolchain import org.rust.cargo.project.workspace.PackageOrigin import org.rust.lang.core.psi.RsFile import org.rust.lang.core.psi.ext.containingCargoPackage class RsCargoCheckAnnotatorPass( private val factory: RsCargoCheckAnnotatorPassFactory, private val file: PsiFile, private val editor: Editor ) : TextEditorHighlightingPass(file.project, editor.document), DumbAware { private val annotationHolder: AnnotationHolderImpl = AnnotationHolderImpl(AnnotationSession(file)) private var annotationInfo: Lazy<RsCargoCheckAnnotationResult?>? = null private val annotationResult: RsCargoCheckAnnotationResult? get() = annotationInfo?.value private lateinit var disposable: Disposable override fun doCollectInformation(progress: ProgressIndicator) { annotationHolder.clear() if (file !is RsFile || !isAnnotationPassEnabled) return val cargoPackage = file.containingCargoPackage if (cargoPackage?.origin != PackageOrigin.WORKSPACE) return val project = file.project disposable = createDisposableOnAnyPsiChange(project.messageBus).also { Disposer.register(ModuleUtil.findModuleForFile(file) ?: project, it) } annotationInfo = RsCargoCheckUtils.checkLazily( project.toolchain ?: return, project, disposable, cargoPackage.workspace.contentRoot, cargoPackage.name, isOnFly = true ) } override fun doApplyInformationToEditor() { if (annotationInfo == null || !isAnnotationPassEnabled) return val update = object : Update(file) { override fun run() { BackgroundTaskUtil.runUnderDisposeAwareIndicator(disposable, Runnable { val annotationResult = annotationResult ?: return@Runnable runReadAction { ProgressManager.checkCanceled() doApply(annotationResult) ProgressManager.checkCanceled() doFinish(highlights) } }) } override fun canEat(update: Update?): Boolean = true } factory.scheduleExternalActivity(update) } private fun doApply(annotationResult: RsCargoCheckAnnotationResult) { if (file !is RsFile || !file.isValid) return try { annotationHolder.createAnnotationsForFile(file, annotationResult) } catch (t: Throwable) { if (t is ProcessCanceledException) throw t LOG.error(t) } } private fun doFinish(highlights: List<HighlightInfo>) { val document = document ?: return ApplicationManager.getApplication().invokeLater({ UpdateHighlightersUtil.setHighlightersToEditor( myProject, document, 0, file.textLength, highlights, colorsScheme, id ) DaemonCodeAnalyzerEx.getInstanceEx(myProject).fileStatusMap.markFileUpToDate(document, id) }, ModalityState.stateForComponent(editor.component)) } private val highlights: List<HighlightInfo> get() = annotationHolder.map(HighlightInfo::fromAnnotation) private val isAnnotationPassEnabled: Boolean get() = file.project.rustSettings.useCargoCheckAnnotator companion object { private val LOG: Logger = Logger.getInstance(RsCargoCheckAnnotatorPass::class.java) } } class RsCargoCheckAnnotatorPassFactory( project: Project, registrar: TextEditorHighlightingPassRegistrar ) : DirtyScopeTrackingHighlightingPassFactory { private val myPassId: Int = registrar.registerTextEditorHighlightingPass( this, null, null, false, -1 ) private val cargoCheckQueue = MergingUpdateQueue( "CargoCheckQueue", TIME_SPAN, true, MergingUpdateQueue.ANY_COMPONENT, project, null, false ) override fun createHighlightingPass(file: PsiFile, editor: Editor): TextEditorHighlightingPass? { FileStatusMap.getDirtyTextRange(editor, passId) ?: return null return RsCargoCheckAnnotatorPass(this, file, editor) } override fun getPassId(): Int = myPassId fun scheduleExternalActivity(update: Update) = cargoCheckQueue.queue(update) companion object { private const val TIME_SPAN: Int = 300 } } private fun createDisposableOnAnyPsiChange(messageBus: MessageBus): Disposable { val child = Disposer.newDisposable("Dispose on PSI change") messageBus.connect(child).subscribe( PsiManagerImpl.ANY_PSI_CHANGE_TOPIC, object : AnyPsiChangeListener.Adapter() { override fun beforePsiChanged(isPhysical: Boolean) { Disposer.dispose(child) } } ) return child } <file_sep>/src/main/kotlin/org/rust/ide/inspections/RsCargoCheckInspection.kt /* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.inspections import com.intellij.codeInsight.daemon.impl.AnnotationHolderImpl import com.intellij.codeInsight.daemon.impl.HighlightInfo import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInspection.* import com.intellij.lang.annotation.Annotation import com.intellij.lang.annotation.AnnotationSession import com.intellij.lang.annotation.HighlightSeverity import com.intellij.openapi.application.runReadAction import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.psi.PsiFile import com.intellij.util.containers.ContainerUtil import org.rust.cargo.project.model.CargoProject import org.rust.cargo.project.model.cargoProjects import org.rust.cargo.project.settings.toolchain import org.rust.cargo.project.workspace.PackageOrigin import org.rust.cargo.runconfig.command.workingDirectory import org.rust.ide.actions.RsRunCargoCheckAction.Companion.CARGO_PROJECT import org.rust.ide.annotator.cargoCheck.RsCargoCheckAnnotationResult import org.rust.ide.annotator.cargoCheck.RsCargoCheckUtils import org.rust.ide.annotator.cargoCheck.createAnnotationsForFile import org.rust.lang.core.psi.RsFile import org.rust.lang.core.psi.ext.containingCargoPackage import org.rust.lang.core.psi.isRustFile import java.util.* class RsCargoCheckInspection : GlobalSimpleInspectionTool() { override fun inspectionStarted( manager: InspectionManager, globalContext: GlobalInspectionContext, problemDescriptionsProcessor: ProblemDescriptionsProcessor ) { val cargoProject = findCargoProject(manager.project, globalContext) ?: return val annotationInfo = checkProjectLazily(cargoProject) ?: return // TODO: do something if the user changes project documents val annotationResult = annotationInfo.value ?: return globalContext.putUserData(ANNOTATION_RESULT, annotationResult) } override fun checkFile( file: PsiFile, manager: InspectionManager, problemsHolder: ProblemsHolder, globalContext: GlobalInspectionContext, problemDescriptionsProcessor: ProblemDescriptionsProcessor ) { if (file !is RsFile || file.containingCargoPackage?.origin != PackageOrigin.WORKSPACE) return val annotationResult = globalContext.getUserData(ANNOTATION_RESULT) ?: return val annotationHolder = AnnotationHolderImpl(AnnotationSession(file)) annotationHolder.createAnnotationsForFile(file, annotationResult) val problemDescriptors = convertToProblemDescriptors(annotationHolder, file) for (descriptor in problemDescriptors) { problemsHolder.registerProblem(descriptor) } } override fun getDisplayName(): String = DISPLAY_NAME override fun getShortName(): String = INSPECTION_SHORT_NAME companion object { const val DISPLAY_NAME: String = "Cargo Check" const val INSPECTION_SHORT_NAME: String = "RsCargoCheck" private val ANNOTATION_RESULT: Key<RsCargoCheckAnnotationResult> = Key.create("ANNOTATION_RESULT") private fun checkProjectLazily(cargoProject: CargoProject): Lazy<RsCargoCheckAnnotationResult?>? = runReadAction { RsCargoCheckUtils.checkLazily( cargoProject.project.toolchain ?: return@runReadAction null, cargoProject.project, cargoProject.project, cargoProject.workingDirectory, null, isOnFly = false ) } /** TODO: Use [ProblemDescriptorUtil.convertToProblemDescriptors] instead */ private fun convertToProblemDescriptors(annotations: List<Annotation>, file: PsiFile): Array<ProblemDescriptor> { if (annotations.isEmpty()) return ProblemDescriptor.EMPTY_ARRAY val problems = ContainerUtil.newArrayListWithCapacity<ProblemDescriptor>(annotations.size) val quickFixMappingCache = ContainerUtil.newIdentityHashMap<IntentionAction, LocalQuickFix>() for (annotation in annotations) { if (annotation.severity === HighlightSeverity.INFORMATION || annotation.startOffset == annotation.endOffset && !annotation.isAfterEndOfLine) { continue } val (startElement, endElement) = if (annotation.startOffset == annotation.endOffset && annotation.isAfterEndOfLine) { val element = file.findElementAt(annotation.endOffset - 1) Pair(element, element) } else { Pair(file.findElementAt(annotation.startOffset), file.findElementAt(annotation.endOffset - 1)) } if (startElement == null || endElement == null) continue val quickFixes = toLocalQuickFixes(annotation.quickFixes, quickFixMappingCache) val highlightType = HighlightInfo.convertSeverityToProblemHighlight(annotation.severity) val descriptor = ProblemDescriptorBase( startElement, endElement, annotation.message, quickFixes, highlightType, annotation.isAfterEndOfLine, null, true, false ) problems.add(descriptor) } return problems.toTypedArray() } private fun toLocalQuickFixes( fixInfos: List<Annotation.QuickFixInfo>?, quickFixMappingCache: IdentityHashMap<IntentionAction, LocalQuickFix> ): Array<LocalQuickFix> { if (fixInfos == null || fixInfos.isEmpty()) return LocalQuickFix.EMPTY_ARRAY return fixInfos.map { fixInfo -> val intentionAction = fixInfo.quickFix if (intentionAction is LocalQuickFix) { intentionAction } else { var lqf = quickFixMappingCache[intentionAction] if (lqf == null) { lqf = ExternalAnnotatorInspectionVisitor.LocalQuickFixBackedByIntentionAction(intentionAction) quickFixMappingCache[intentionAction] = lqf } lqf } }.toTypedArray() } } private fun findCargoProject(project: Project, globalContext: GlobalInspectionContext): CargoProject? { globalContext.getUserData(CARGO_PROJECT)?.let { return it } val cargoProjects = project.cargoProjects cargoProjects.allProjects.singleOrNull()?.let { return it } val virtualFile = FileEditorManager.getInstance(project) .selectedFiles.firstOrNull { it.isRustFile && it.isInLocalFileSystem } return virtualFile?.let { cargoProjects.findProjectForFile(it) } } } <file_sep>/src/test/kotlin/org/rust/ide/annotator/fixes/ApplySuggestionFixTest.kt /* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.annotator.fixes import org.intellij.lang.annotations.Language import org.rust.cargo.RsWithToolchainTestBase import org.rust.cargo.project.settings.rustSettings import org.rust.fileTree import org.rust.replaceCaretMarker class ApplySuggestionFixTest : RsWithToolchainTestBase() { override fun setUp() { super.setUp() project.rustSettings.data = project.rustSettings.data.copy(useCargoCheckAnnotator = true) } fun `test rustc suggestion (machine applicable)`() = checkFixByText(""" fn main() { let <weak_warning>x</weak_warning> = 0; } """, """ fn main() { let _x = 0; } """) fun `test rustc suggestion (maybe incorrect)`() = checkFixByText(""" fn main() { if <error>1 <- 2</error> {} } """, """ fn main() { if 1< -2 {} } """) fun `test rustc suggestion (has placeholders)`() = checkFixByText(""" struct S { x: i32, y: i32 } impl S { fn new() -> Self { <error>Self</error> } } """, """ struct S { x: i32, y: i32 } impl S { fn new() -> Self { Self { /* fields */ } } } """) fun `test rustc suggestion (unspecified)`() = checkFixByText(""" fn foo<'a>(x: &i32, y: &'a i32) -> &'a i32 { if x > y { <error>x</error> } else { y } } """, """ fn foo<'a>(x: &'a i32, y: &'a i32) -> &'a i32 { if x > y { x } else { y } } """) private fun checkFixByText(@Language("Rust") before: String, @Language("Rust") after: String) { fileTree { toml("Cargo.toml", """ [package] name = "hello" version = "0.1.0" authors = [] """) dir("src") { file("main.rs", before) } }.create() val filePath = "src/main.rs" myFixture.openFileInEditor(cargoProjectDirectory.findFileByRelativePath(filePath)!!) myFixture.checkHighlighting() val action = myFixture.getAllQuickFixes(filePath) .singleOrNull { it.text.startsWith("Rustc: ") } ?: return // BACKCOMPAT: Rust ??? myFixture.launchAction(action) myFixture.checkResult(replaceCaretMarker(after.trimIndent())) } }
8b13135cbbe760b76a680995529dae3da1b10cef
[ "Kotlin" ]
3
Kotlin
0pd/intellij-rust
d1cf2b902c6d49764df0908efbf33ab7030e2272
2ca29a604127dbd7af931e639117b8ee581aa3b7
refs/heads/master
<file_sep>const { protocol } = require('electron'); const path = require('path'); const fs = require('fs-extra'); const SCHEMES = [ 'twlv' ]; function setup () { protocol.registerFileProtocol('twlv', async (req, cb) => { let filePath = path.resolve(__dirname, '../app', req.url.slice(7)); let stat = await fs.stat(filePath); if (stat.isDirectory()) { filePath = path.join(filePath, 'index.html'); } cb(filePath); }); } module.exports = { setup, SCHEMES }; <file_sep>const TabGroup = require('electron-tabs'); let tabGroup = new TabGroup(); let tab = tabGroup.addTab({ title: '...', closable: false, src: 'twlv://ui', visible: true, active: true, webviewAttributes: { preload: './preload.js', }, ready: tab => { // Open dev tools for webview let webview = tab.webview; if (webview) { webview.addEventListener('dom-ready', () => { webview.openDevTools(); }); webview.addEventListener('page-title-updated', evt => { tab.setTitle(evt.title); }); } }, }); <file_sep># twlv-ui ## Run ```bash npm start -- --data-dir /path/to/dir/to/save/user/data ``` ## Environment Variables Several environment variables to set on development ### TWLV_DEBUG_SHELL open devtools for shell example: ```bash TWLV_DEBUG_SHELL=1 npm start ``` ### TWLV_DEBUG_APP open devtools for apps example: ```bash TWLV_DEBUG_APP=ui,chat npm start # will open devtools for ui and chat application ``` <file_sep>const { BrowserWindow } = require('electron'); const url = require('url'); const path = require('path'); const { get, set } = require('./config'); let instances = []; function createWindow () { let lastWindow = get('client', 'lastWindow') || { width: 1024, height: 700, devTools: false }; let { width, height, devTools } = lastWindow; let win = new BrowserWindow({ width, height }); // let win = new BrowserWindow({ width, height, frame: false }); let winUrl = url.format({ pathname: path.join(__dirname, '../renderer/index.html'), protocol: 'file:', slashes: true, }); win.loadURL(winUrl); if (process.env.TWLV_DEBUG_SHELL || devTools) { win.webContents.openDevTools(); } win.on('resize', function () { let [ width, height ] = win.getSize(); lastWindow.height = height; lastWindow.width = width; set('client', 'lastWindow', lastWindow); }); win.on('closed', function () { let index = instances.indexOf(win); if (index !== -1) { instances.splice(index, 1); } }); instances.push(win); return win; } function ensureWindow () { if (!instances.length) { createWindow(); } return instances[0]; } module.exports = { createWindow, ensureWindow }; <file_sep>(async function (twlv) { let { pid } = twlv.definition; render('#elDaemonStatus', pid ? 'running' : 'stopped'); render('#elDaemonPid', pid ? `PID(${pid})` : ''); if (pid) { let { status } = await twlv.get('/status'); render('#elSwarmStatus', status ? 'running' : 'stopped'); let apps = await twlv.get('/apps'); renderEach('#elSwamApps', apps); let channels = await twlv.get('/channels'); renderEach('#elSwamChannels', channels); let discoveries = await twlv.get('/discoveries'); renderEach('#elSwamDiscoveries', discoveries); } })(window.twlv); function query (selector) { if (typeof selector === 'string') { return document.querySelector(selector); } return selector; } function render (selector, value) { let el = query(selector); if (!el) { return; } if (el.nodeName === 'INPUT' || el.nodeName === 'TEXTAREA') { el.value = value; } else { el.textContent = value; } } function renderEach (selector, values) { let el = query(selector); if (!el._template) { let template = el.querySelector('template'); if (template) { el._template = document.importNode(template.content, true); } el.removeChild(template); } if (!el._template) { throw new Error('Fail render each, no template defined'); } el.innerHTML = ''; values.forEach(value => el.appendChild(renderTemplate(el._template, value))); } function renderTemplate (template, value) { let fragment = document.importNode(template, true); for (let i in value) { fragment.querySelectorAll(`[bind-prop="${i}"]`).forEach(el => { render(el, value[i]); }); } return fragment; } <file_sep>const { ModuleRegistry } = require('../../main/modules'); const assert = require('assert'); const path = require('path'); const fs = require('fs-extra'); const swarm = require('../../main/swarm'); let swarmInstance = swarm.setup(); process.on('unhandledRejection', r => { console.error('unhandledRejection', r); }); describe('ModuleRegistry', () => { beforeEach(() => { fs.removeSync('data'); }); afterEach(() => { fs.removeSync('data'); }); describe('#get()', () => { it('get builtin capabilities', () => { let registry = new ModuleRegistry(swarmInstance); assert('tcp' in registry.channel); assert('peer-lookup' in registry.app); assert.equal(registry.channel.tcp.type, 'builtin'); }); it('get module capabilities', () => { fs.mkdirpSync('data/node_modules/twlv-channel-foo'); fs.mkdirpSync('data/node_modules/twlv-discovery-bar'); fs.mkdirpSync('data/node_modules/twlv-app-baz'); fs.mkdirpSync('data/node_modules/something-else'); let registry = new ModuleRegistry(swarmInstance); assert('foo' in registry.channel); assert('bar' in registry.discovery); assert('baz' in registry.app); assert.equal(registry.channel.foo.type, 'module'); assert.equal(registry.channel.foo.path, path.resolve('data/node_modules/twlv-channel-foo')); }); }); describe('#install()', () => { it('install module to datadir', async () => { let registry = new ModuleRegistry(swarmInstance); assert.equal('mdns' in registry.discovery, false); await registry.install('discovery', 'mdns'); assert.equal('mdns' in registry.discovery, true); }).timeout(20000); }); describe('#uninstall()', () => { it('uninstall module from datadir', async () => { let registry = new ModuleRegistry(swarmInstance); assert.equal('mdns' in registry.discovery, false); await registry.install('discovery', 'mdns'); assert.equal('mdns' in registry.discovery, true); await registry.uninstall('discovery', 'mdns'); assert.equal('mdns' in registry.discovery, false); }).timeout(20000); }); }); <file_sep>const { ipcMain } = require('electron'); const fs = require('fs-extra'); const path = require('path'); const { get } = require('./config'); function setup () { ipcMain.on('twlv-daemon-definition', (evt, arg) => { console.info('ipc:twlv-daemon-definition'); let pid = getPid(); let { port } = getDaemonDefinition(); evt.returnValue = { pid, port }; }); } function getPid () { let pidFile = path.resolve(get('client', 'dataDir'), 'twlvd.pid'); let pid = null; if (fs.existsSync(pidFile)) { pid = Number(fs.readFileSync(pidFile).toString()); } return pid; } function getDaemonDefinition () { let port = get('daemon', 'port') || 12000; return { port }; } module.exports = { setup }; <file_sep>const { app, protocol } = require('electron'); const signal = require('./main/signal'); const protocols = require('./main/protocols'); const { ensureWindow } = require('./main/windows'); const config = require('./main/config'); const argv = require('minimist')(process.argv); const path = require('path'); const ipc = require('./main/ipc'); if (argv['data-dir']) { app.setPath('userData', path.resolve(argv['data-dir'])); } signal.setup(); config.setup(app.getPath('userData')); protocol.registerStandardSchemes(protocols.SCHEMES, { secure: true }); app.on('ready', () => { protocols.setup(); ipc.setup(); ensureWindow(); }); app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); } }); app.on('activate', () => { ensureWindow(); });
353c45850e9a441e52b44e0a6fd236a15e85e0f5
[ "JavaScript", "Markdown" ]
8
JavaScript
twlv/twlv-ui
bef6197f20d887f15c0c76c8ac1e0f310c664375
3a4ea8e45ca649323186e5ce8552ac8ca0b090fe
refs/heads/master
<repo_name>OscarSandell/AVL_Tree<file_sep>/labb_1/avl_tree-test.cpp /* * avl_tree-test.cc (c) <NAME>, IDA, 2007-05-02 */ // Få svenska tecken att fungera på Windows. // Måste vara innan #include "avl_tree.h", pga bugg i Windows-SDK: // https://developercommunity.visualstudio.com/content/problem/93889/error-c2872-byte-ambiguous-symbol.html #ifdef _WIN32 #include <Windows.h> struct Setup { Setup() { SetConsoleOutputCP(65001); SetConsoleCP(65001); } } setup; #endif #include <iostream> #include "avl_tree.h" using namespace std; int main() { AVL_Tree<int> avl_tree; for (int i = 1; i <= 11; i++) avl_tree.insert(i); try { cout << "AVL-träd efter insättning av 1, 2,..., 11:\n\n"; avl_tree.print_tree(cout); cout << endl; } catch (const exception& e) { cout << '\n' << e.what() << endl; cout << "AVL-träd innehåller efter insättning av 1, 2,..., 11:\n\n"; avl_tree.print(cout); cout << endl; } unsigned int choice; unsigned int value; while (true) { cout << endl; cout << "1 - Sätt in.\n"; cout << "2 - Ta bort.\n"; cout << "3 - Sök värde.\n"; cout << "4 - Sök minsta.\n"; cout << "5 - Sök största.\n"; cout << "6 - Töm trädet.\n"; cout << "7 - Skriv ut ordnat.\n"; cout << "8 - Skriv ut träd.\n"; cout << "0 - Avsluta.\n" << endl; cout << "Val: "; cin >> choice; cout << endl; try { switch (choice) { case 0: cout << "Slut." << endl; return 0; case 1: cout << "Värde att sätta in: "; cin >> value; avl_tree.insert(value); break; case 2: cout << "Värde att ta bort: "; cin >> value; avl_tree.remove(value); break; case 3: cout << "Värde att söka efter: "; cin >> value; if (avl_tree.member(value)) cout << "Värdet " << value << " finns i trädet." << endl; else cout << "Värdet " << value << " finns ej i trädet." << endl; break; case 4: if (avl_tree.empty()) cout << "Trädet är tomt!" << endl; else cout << "Minsta värdet i trädet är " << avl_tree.find_min() << endl; break; case 5: if (avl_tree.empty()) cout << "Trädet är tomt!" << endl; else cout << "Största värdet i trädet är " << avl_tree.find_max() << endl; break; case 6: /* Detta borde förstås bekräftas! */ avl_tree.clear(); cout << "Trädet är tömt!" << endl; break; case 7: if (avl_tree.empty()) { cout << "Trädet är tomt!" << endl; } else { avl_tree.print(cout); cout << endl; } break; case 8: if (avl_tree.empty()) { cout << "Trädet är tomt!" << endl; } else { avl_tree.print_tree(cout); cout << endl; } break; default: cout << "Felaktigt val!" << '\b' << endl; break; } } catch (const exception& e) { cout << e.what() << endl; } catch (...) { cout << "Ett okänt fel har inträffat." << endl; } } return 0; } <file_sep>/labb_1/simple_remove.cpp /** * remove() tar bort elementet x ur trädet t, om x finns. * * Comparable och Node_Pointer är formella typer som får specificeras på * något sätt (template-parameter, typedef eller ersättning med konkret typ). */ void remove(const Comparable &x, Node_Pointer &t) { if (t == nullptr) { return; // Här kan ett undantag genereras i stället ... } if (x < t->element) { remove(x, t->left); } else if (t->element < x) { remove(x, t->right); } else { // Sökt värde finns i noden t Node_Pointer tmp; if (t->left != nullptr && t->right != nullptr) { // Noden har två barn och ersätts med inorder efterföljare tmp = find_min(t->right); t->element = tmp->element; remove(t->element, t->right); } else { // Noden har inget eller ett barn tmp = t; if (t->left == nullptr) t = t->right; else t = t->left; delete tmp; } } } <file_sep>/labb_1/avl_tree.h /* * AVL_Tree.h (c) <NAME>, IDA, 2007-05-02 * uppdated to C++11 September 2015 * * When problems occur, the exception AVL_Tree_error is thrown. * * operator<< is assumed to be defined for Comparable. */ #ifndef AVLTREE_INC #define AVLTREE_INC 1 #include <iosfwd> #include <stdexcept> class AVL_Tree_error : public std::logic_error { public: explicit AVL_Tree_error(const std::string& what_arg) : std::logic_error(what_arg) {} }; template <typename Comparable> class AVL_Tree_Node; template <typename Comparable> class AVL_Tree { public: AVL_Tree(); AVL_Tree(const AVL_Tree &o); AVL_Tree(AVL_Tree &&o); ~AVL_Tree(); AVL_Tree &operator=(const AVL_Tree &rhs); AVL_Tree &operator=(AVL_Tree &&rhs); void insert(const Comparable &element); void remove(const Comparable &element); bool member(const Comparable &element) const; Comparable &find(const Comparable &element) const; Comparable &find_min() const; Comparable &find_max() const; void clear(); bool empty() const; void print(std::ostream&) const; void print_tree(std::ostream&) const; void swap(AVL_Tree &other); private: using Node = AVL_Tree_Node<Comparable>; using Node_Pointer = AVL_Tree_Node<Comparable>*; Node_Pointer root; }; template <typename Comparable> void swap(AVL_Tree<Comparable>&, AVL_Tree<Comparable>&); template <typename Comparable> std::ostream &operator<<(std::ostream&, const AVL_Tree<Comparable>&); #include "avl_tree.cpp" #endif <file_sep>/labb_1/avl_tree.cpp /* * AVL_Tree.tcc (c) <NAME>, IDA, 2007-05-02 * updated to C++11 September 2015 */ #include <iostream> #include <algorithm> #include <stdexcept> #include "avl_tree.h" #include <cstdlib> using namespace std; /* * AVL_Tree_Node. */ template <typename Comparable> class AVL_Tree_Node { private: friend class AVL_Tree<Comparable>; AVL_Tree_Node(const Comparable &element) : element{element}, left{}, right{}, height{} {} AVL_Tree_Node(const Comparable &element, AVL_Tree_Node *left, AVL_Tree_Node *right) : element{element}, left{left}, right{right}, height{} {} Comparable element; AVL_Tree_Node *left; AVL_Tree_Node *right; int height; // Aliases to simplify the code using Node = AVL_Tree_Node<Comparable>; using Node_Pointer = AVL_Tree_Node<Comparable> *; // The following functions are called from corresponding functions in AVL_Tree static void insert(const Comparable &, Node_Pointer &); static void remove(const Comparable &, Node_Pointer &); static void clear(Node_Pointer &); static Node_Pointer find(const Comparable &, const Node_Pointer); static Node_Pointer find_min(const Node_Pointer); static Node_Pointer find_max(const Node_Pointer); static void print(std::ostream &, const Node_Pointer); static void print_tree(std::ostream &, const Node_Pointer, int depth = 0); // This function implements deep copying static Node_Pointer clone(const Node_Pointer); // The following functions are internal help functions for AVL_Tree_Node static void single_rotate_with_left_child(Node_Pointer &); static void single_rotate_with_right_child(Node_Pointer &); static void double_rotate_with_left_child(Node_Pointer &); static void double_rotate_with_right_child(Node_Pointer &); static void calculate_height(const Node_Pointer); static int node_height(const Node_Pointer); static void indent(std::ostream &os, int level); }; /*=============================================* * * * AVL_Tree_Node * * * *=============================================*/ /** * AVL rotations and corrsponding help functions. */ /** * Return the height of a node (sub tree). */ template <typename Comparable> int AVL_Tree_Node<Comparable>::node_height(const Node_Pointer p) { return (p != nullptr ? p->height : -1); } /** * Adjust the height for node p. */ template <typename Comparable> void AVL_Tree_Node<Comparable>::calculate_height(const Node_Pointer p) { p->height = 1 + max(node_height(p->left), node_height(p->right)); } /** * Single rotation left-to-right using node k2 as pivot. */ template <typename Comparable> void AVL_Tree_Node<Comparable>::single_rotate_with_left_child(Node_Pointer &k2) { Node_Pointer k1 = k2->left; k2->left = k1->right; k1->right = k2; k2->height = max(node_height(k2->left), node_height(k2->right)) + 1; k1->height = max(node_height(k1->left), k2->height) + 1; k2 = k1; } /** * Single rotation right-to-left using node k1 as pivot. */ template <typename Comparable> void AVL_Tree_Node<Comparable>::single_rotate_with_right_child(Node_Pointer &k1) { Node_Pointer k2 = k1->right; k1->right = k2->left; k2->left = k1; k1->height = max(node_height(k1->right), node_height(k1->left)) + 1; k2->height = max(node_height(k2->right), k1->height) + 1; k1 = k2; } /** * Double rotation left-to-right using node k3 as pivot. */ template <typename Comparable> void AVL_Tree_Node<Comparable>::double_rotate_with_left_child(Node_Pointer &k3) { single_rotate_with_right_child(k3->left); single_rotate_with_left_child(k3); } /** * Double rotation right-to-left using node k3 as pivot. */ template <typename Comparable> void AVL_Tree_Node<Comparable>::double_rotate_with_right_child(Node_Pointer &k3) { single_rotate_with_left_child(k3->right); single_rotate_with_right_child(k3); } /* * Member functions for AVL_Tree_Node */ /** * Insert x in tree t as a new leaf. Check balance and adjust tree if needed. */ template <typename Comparable> void AVL_Tree_Node<Comparable>::insert(const Comparable &x, Node_Pointer &t) { if (t == nullptr) { t = new Node(x); return; } if (x < t->element) { insert(x, t->left); if (node_height(t->left) - node_height(t->right) == 2) if (x < t->left->element) single_rotate_with_left_child(t); else double_rotate_with_left_child(t); else calculate_height(t); } else if (t->element < x) { insert(x, t->right); if (node_height(t->right) - node_height(t->left) == 2) if (t->right->element < x) single_rotate_with_right_child(t); else double_rotate_with_right_child(t); else calculate_height(t); } else { throw AVL_Tree_error("insättning: finns redan"); } } /** * Print elements in ascending order. */ template <typename Comparable> void AVL_Tree_Node<Comparable>::print(ostream &os, const Node_Pointer t) { if (t != nullptr) { print(os, t->left); os << t->element << " "; print(os, t->right); } } /** * Print the tree in amazingly beautiful ASCII art. */ template <typename Comparable> void AVL_Tree_Node<Comparable>::print_tree(ostream &os, const Node_Pointer t, int depth) { if (t != nullptr) { print_tree(os, t->right, depth + 1); if (t->right != nullptr) { indent(os, depth); os << " /" << endl; } indent(os, depth); os << t->element << endl; if (t->left != nullptr) { indent(os, depth); os << " \\" << endl; } print_tree(os, t->left, depth + 1); } } /** * Copy the tree. */ template <typename Comparable> AVL_Tree_Node<Comparable> *AVL_Tree_Node<Comparable>::clone(const Node_Pointer t) { if (t != nullptr) return new Node(t->element, clone(t->left), clone(t->right)); else return nullptr; } /** * Look for x in the tree. If found, return av pointer to the node. * Otherwise, return nullptr. */ template <typename Comparable> AVL_Tree_Node<Comparable> *AVL_Tree_Node<Comparable>::find(const Comparable &x, const Node_Pointer t) { if (t == nullptr) return nullptr; else if (x < t->element) return find(x, t->left); else if (t->element < x) return find(x, t->right); else return t; } /** * Look for the smallest value (the leftmost node). Return pointer to that node. * In case of empty tree, return nullptr. */ template <typename Comparable> AVL_Tree_Node<Comparable> *AVL_Tree_Node<Comparable>::find_min(const Node_Pointer t) { if (t == nullptr) return nullptr; else if (t->left == nullptr) return t; else return find_min(t->left); } /** * Look for the biggest value (the rightmost node). Return pointer to that node. * In case of empty tree, return nullptr. */ template <typename Comparable> AVL_Tree_Node<Comparable> *AVL_Tree_Node<Comparable>::find_max(const Node_Pointer t) { Node_Pointer p = t; if (p != nullptr) { while (p->right != nullptr) p = p->right; } return p; } /** * Remove all nodes in the tree. */ template <typename Comparable> void AVL_Tree_Node<Comparable>::clear(Node_Pointer &t) { if (t != nullptr) { clear(t->left); clear(t->right); delete t; t = nullptr; } } /** * Make indent matching the current tree depth. */ template <typename Comparable> void AVL_Tree_Node<Comparable>::indent(ostream &os, int level) { for (int i = 0; i < level; ++i) os << " "; } /*=============================================* * * * AVL_Tree * * * *=============================================*/ /* * Constructors, destructor and assignment for AVL_Tree */ /** * Default constructor. */ template <typename Comparable> AVL_Tree<Comparable>::AVL_Tree() : root{nullptr} {} /** * Copy constructor. */ template <typename Comparable> AVL_Tree<Comparable>::AVL_Tree(const AVL_Tree &value) : root{Node::clone(value.root)} {} /** * Move constructor. */ template <typename Comparable> AVL_Tree<Comparable>::AVL_Tree(AVL_Tree &&value) : root{value.root} { value.root = nullptr; } /** * Destructor. */ template <typename Comparable> AVL_Tree<Comparable>::~AVL_Tree() { Node::clear(root); } /** * Assignment operator. */ template <typename Comparable> AVL_Tree<Comparable> &AVL_Tree<Comparable>::operator=(const AVL_Tree<Comparable> &rhs) { AVL_Tree tmp(rhs); swap(tmp); return *this; } /** * Move assignment operator. */ template <typename Comparable> AVL_Tree<Comparable> &AVL_Tree<Comparable>::operator=(AVL_Tree<Comparable> &&rhs) { swap(rhs); return *this; } /* * Public member functions for AVL_Tree */ /** * Insert x in the tree. */ template <typename Comparable> void AVL_Tree<Comparable>::insert(const Comparable &x) { Node::insert(x, root); } /** * Remove x from the tree. */ template <typename Comparable> void AVL_Tree<Comparable>::remove(const Comparable &x) { //throw AVL_Tree_error("remove: ska implementeras!"); Node::remove(x, root); } template <typename Comparable> void AVL_Tree_Node<Comparable>::remove(const Comparable &x, Node_Pointer &t) { if (t == nullptr) { return; // Här kan ett undantag genereras i stället ... } if (x < t->element) { remove(x, t->left); } else if (t->element < x) { remove(x, t->right); } else { // Sökt värde finns i noden t Node_Pointer tmp; if (t->left != nullptr && t->right != nullptr) { // Noden har två barn och ersätts med inorder efterföljare tmp = find_min(t->right); t->element = tmp->element; remove(t->element, t->right); } else { // Noden har inget eller ett barn tmp = t; if (t->left == nullptr) t = t->right; else t = t->left; delete tmp; return; } } int left_height{node_height(t->left)}; int right_height{node_height(t->right)}; int difference{left_height - right_height}; if (std::abs(difference) > 1) { if (difference < 0) { if (node_height(t->right->right) >= node_height(t->right->left)) { single_rotate_with_right_child(t); } else { double_rotate_with_right_child(t); } } else if (difference > 0) { if (node_height(t->left->left) >= node_height(t->left->right)) { single_rotate_with_left_child(t); } else { double_rotate_with_left_child(t); } } } else { calculate_height(t); } } /** * Check if tree contains x. */ template <typename Comparable> bool AVL_Tree<Comparable>::member(const Comparable &x) const { return Node::find(x, root) != nullptr; } /** * Look up value x in tree, return reference to that element. */ template <typename Comparable> Comparable &AVL_Tree<Comparable>::find(const Comparable &x) const { Node_Pointer tmp = Node::find(x, root); if (tmp == nullptr) throw AVL_Tree_error("sökt värde finns ej i trädet"); return tmp->element; } /** * Look up the smallest value in the tree, return reference to it. */ template <typename Comparable> Comparable &AVL_Tree<Comparable>::find_min() const { if (root == nullptr) throw AVL_Tree_error("försök att finna minst i tomt träd"); return Node::find_min(root)->element; } /** * Look up the largest value in the tree, return reference to it. */ template <typename Comparable> Comparable &AVL_Tree<Comparable>::find_max() const { if (root == nullptr) throw AVL_Tree_error("försök att finna störst i tomt träd"); return Node::find_max(root)->element; } /** * Check if tree is empty. */ template <typename Comparable> bool AVL_Tree<Comparable>::empty() const { return root == nullptr; } /** * Empty the tree. */ template <typename Comparable> void AVL_Tree<Comparable>::clear() { Node::clear(root); } /** * Print all values in the tree in ascending order. */ template <typename Comparable> void AVL_Tree<Comparable>::print(ostream &os) const { Node::print(os, root); } /** * Print the tree. */ template <typename Comparable> void AVL_Tree<Comparable>::print_tree(ostream &os) const { Node::print_tree(os, root, 0); } /** * Swap this and other. */ template <typename Comparable> void AVL_Tree<Comparable>::swap(AVL_Tree<Comparable> &other) { std::swap(root, other.root); } /** * Swap x and y. */ template <typename Comparable> void swap(AVL_Tree<Comparable> &x, AVL_Tree<Comparable> &y) { x.swap(y); } /** * Out-stream operator for AVL_Tree. */ template <typename Comparable> ostream &operator<<(ostream &os, const AVL_Tree<Comparable> &tree) { tree.print_tree(os); return os; } <file_sep>/labb_1/Makefile # # Makefile # CCC = g++ CCFLAGS += -std=c++17 -pedantic -Wall -g avl_tree-test: avl_tree-test.o $(CCC) $(CCFLAGS) -o avl_tree-test avl_tree-test.o avl_tree-test.o: avl_tree-test.cpp avl_tree.cpp $(CCC) $(CCFLAGS) -c avl_tree-test.cpp clean: @ \rm -f *.o zap: clean @ \rm -rf avl_tree-test *.o *~
52af583c1317c1eb8821842f06ba7ce98d658a2d
[ "Makefile", "C++" ]
5
C++
OscarSandell/AVL_Tree
9790d5eb041a829ed5295ac8c462641dc0011a8c
288720c4f768f9254274256e9cff5b950f72435c
refs/heads/master
<repo_name>Pradeep-CG/CoreDataRelation<file_sep>/CoreDataRelation/Controller/College/CollegeFormViewController.swift // // CollegeFormViewController.swift // CoreDataRelation // // Created by Pradeep on 25/12/19. // Copyright © 2019 Pradeep. All rights reserved. // import UIKit class CollegeFormViewController: UIViewController { // MARK: outlet @IBOutlet weak var txtCollegeName: UITextField! @IBOutlet weak var txtCollegeAddress: UITextField! @IBOutlet weak var txtCollegeCity: UITextField! @IBOutlet weak var txtCollegeUniversity: UITextField! @IBOutlet weak var saveBtn: UIButton! var formDetail:College? var isUpdate = false var selectedIndex = Int() // MARK: life cycle override func viewDidLoad() { super.viewDidLoad() txtCollegeName.text = formDetail?.name txtCollegeAddress.text = formDetail?.address txtCollegeCity.text = formDetail?.city txtCollegeUniversity.text = formDetail?.university // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) if isUpdate { saveBtn.setTitle("Update", for: .normal) } else{ saveBtn.setTitle("Save", for: .normal) } } } extension CollegeFormViewController{ @IBAction func buttonCollegeSaveClick(_ sender: Any) { collegeSaveData() self.navigationController?.popViewController(animated: true) } } extension CollegeFormViewController{ func collegeSaveData() { guard let collegeName = txtCollegeName.text else {return} guard let collegeAddress = txtCollegeAddress.text else {return} guard let collegeCity = txtCollegeCity.text else {return} guard let collegeUniversity = txtCollegeUniversity.text else {return} var collegeDict = [ "collegeName": collegeName, "collegeAddress":collegeAddress, "collegeCity":collegeCity, "collegeUniversity":collegeUniversity ] if isUpdate { isUpdate = false DatabaseHelper.sharedInstance.updateCollegeData(dict: collegeDict, index: selectedIndex) } else{ DatabaseHelper.sharedInstance.saveCollegeData(collegeDict: collegeDict) } } } <file_sep>/CoreDataRelation/Controller/College/CollegeDetailViewController.swift // // CollegeDetailViewController.swift // CoreDataRelation // // Created by Pradeep on 26/12/19. // Copyright © 2019 Pradeep. All rights reserved. // import UIKit class CollegeDetailViewController: UITableViewController { @IBOutlet weak var collegeNameLbl: UILabel! @IBOutlet weak var collegeUniversityLbl: UILabel! @IBOutlet weak var collegeAddressLbl: UILabel! @IBOutlet weak var collegeCityLbl: UILabel! @IBOutlet weak var studentLbl: UILabel! var detail:College? var index = Int() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { print(detail) collegeNameLbl.text = detail?.name collegeCityLbl.text = detail?.city collegeAddressLbl.text = detail?.address collegeUniversityLbl.text = detail?.university if let student = detail?.students?.allObjects as? [Student] { studentLbl.text = "\(student.count)" } else{ studentLbl.text = "0" } } @IBAction func onEditClick(_ sender: Any) { let collegeForm = self.storyboard?.instantiateViewController(withIdentifier: "CollegeFormViewController") as! CollegeFormViewController collegeForm.selectedIndex = index collegeForm.formDetail = detail collegeForm.isUpdate = true self.navigationController?.pushViewController(collegeForm, animated: true) } } extension CollegeDetailViewController{ override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.row == 4{ let studentlistVc = self.storyboard?.instantiateViewController(identifier: "StudentListViewController") as! StudentListViewController studentlistVc.college = detail self.navigationController?.pushViewController(studentlistVc, animated: true) } } } <file_sep>/CoreDataRelation/View/collegeTableViewCell.swift // // collegeTableViewCell.swift // CoreDataRelation // // Created by Pradeep on 25/12/19. // Copyright © 2019 Pradeep. All rights reserved. // import UIKit class collegeTableViewCell: UITableViewCell { @IBOutlet weak var lblCollegeUniversity: UILabel! @IBOutlet weak var lblCollegeCity: UILabel! @IBOutlet weak var lblCollegeName: UILabel! var collegeData:College!{ didSet{ lblCollegeName.text = collegeData.name lblCollegeCity.text = collegeData.city lblCollegeUniversity.text = collegeData.university } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } <file_sep>/CoreDataRelation/Controller/College/CollegeListViewController.swift // // CollegeListViewController.swift // CoreDataRelation // // Created by Pradeep on 25/12/19. // Copyright © 2019 Pradeep. All rights reserved. // import UIKit class CollegeListViewController: UIViewController { @IBOutlet weak var collegeListTblView: UITableView! var arrCollege = [College]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) arrCollege = DatabaseHelper.sharedInstance.getAllCollegeData() print("arr = \(arrCollege)") for data in arrCollege{ print(data.name!) print(data.city!) print(data.university!) } collegeListTblView.reloadData() } @IBAction func addButtonClicked(_ sender: Any) { let collegeForm = self.storyboard?.instantiateViewController(withIdentifier: "CollegeFormViewController") as! CollegeFormViewController self.navigationController?.pushViewController(collegeForm, animated: true) } } extension CollegeListViewController: UITableViewDelegate,UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arrCollege.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "collegeTableViewCell") as! collegeTableViewCell cell.collegeData = arrCollege[indexPath.row] return cell } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete{ arrCollege = DatabaseHelper.sharedInstance.deleteCollegeData(index: indexPath.row) collegeListTblView.deleteRows(at: [indexPath], with: .automatic) } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100.0 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { var detailVC = self.storyboard?.instantiateViewController(identifier: "CollegeDetailViewController") as! CollegeDetailViewController detailVC.index = indexPath.row detailVC.detail = arrCollege[indexPath.row] self.navigationController?.pushViewController(detailVC, animated: true) } } <file_sep>/CoreDataRelation/Controller/Student/StudentDetailViewController.swift // // StudentDetailViewController.swift // CoreDataRelation // // Created by Pradeep on 16/01/20. // Copyright © 2020 Pradeep. All rights reserved. // import UIKit class StudentDetailViewController: UIViewController { @IBOutlet weak var nameTxtfld: UITextField! @IBOutlet weak var emailtxtfld: UITextField! @IBOutlet weak var phoneTxtfld: UITextField! var college:College? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func saveBtnclick(_ sender: Any) { guard let name = nameTxtfld.text else { return } guard let email = emailtxtfld.text else { return } guard let phone = phoneTxtfld.text else { return } guard let collegeDetail = college else { return } var studentDict = [ "studentName": name, "studentEmail": email, "studentPhone": phone ] DatabaseHelper.sharedInstance.saveStudentData(studentDict: studentDict,college: collegeDetail) } } <file_sep>/CoreDataRelation/Controller/Student/StudentListViewController.swift // // StudentListViewController.swift // CoreDataRelation // // Created by Pradeep on 16/01/20. // Copyright © 2020 Pradeep. All rights reserved. // import UIKit class StudentListViewController: UIViewController { @IBOutlet weak var tblView: UITableView! var studentArr = [Student]() var college:College? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. tblView.register(UITableViewCell.self, forCellReuseIdentifier: "studentCell") } override func viewWillAppear(_ animated: Bool) { //studentArr = DatabaseHelper.sharedInstance.getAllStudentData() if college?.students?.allObjects != nil { studentArr = college?.students?.allObjects as! [Student] } tblView.reloadData() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ @IBAction func plusBtnClick(_ sender: UIBarButtonItem) { let studentdetailVc = self.storyboard?.instantiateViewController(identifier: "StudentDetailViewController") as! StudentDetailViewController studentdetailVc.college = college self.navigationController?.pushViewController(studentdetailVc, animated: true) } } extension StudentListViewController: UITableViewDelegate, UITableViewDataSource{ func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "studentCell", for: indexPath) if cell != nil { cell = UITableViewCell(style: .value2, reuseIdentifier: "studentCell") } cell.textLabel?.text = studentArr[indexPath.row].name cell.detailTextLabel?.text = studentArr[indexPath.row].email return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return studentArr.count } } <file_sep>/CoreDataRelation/DatabaseHelper/DatabaseHelper.swift // // DatabaseHelper.swift // CoreDataRelation // // Created by Pradeep on 25/12/19. // Copyright © 2019 Pradeep. All rights reserved. // import UIKit import CoreData class DatabaseHelper: NSObject { static let sharedInstance = DatabaseHelper() let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext func saveCollegeData(collegeDict:[String: String]) { let college = NSEntityDescription.insertNewObject(forEntityName: "College", into: context) as! College college.name = collegeDict["collegeName"] college.address = collegeDict["collegeAddress"] college.city = collegeDict["collegeCity"] college.university = collegeDict["collegeUniversity"] do { try context.save() } catch { print("error = \(error.localizedDescription)") } } func getAllCollegeData() -> [College] { var arrCollege = [College]() let fetchReq = NSFetchRequest<NSManagedObject>(entityName: "College") do { arrCollege = try context.fetch(fetchReq) as! [College] } catch { print("error = \(error.localizedDescription)") } return arrCollege } func deleteCollegeData(index:Int) -> [College]{ var collegeData = self.getAllCollegeData() context.delete(collegeData[index]) collegeData.remove(at: index) do { try context.save() } catch { print("error = \(error.localizedDescription)") } return collegeData } func updateCollegeData(dict:[String:String], index:Int) { var collegeDict = self.getAllCollegeData() collegeDict[index].name = dict["collegeName"] collegeDict[index].address = dict["collegeAddress"] collegeDict[index].city = dict["collegeCity"] collegeDict[index].university = dict["collegeUniversity"] do { try context.save() } catch { print("error = \(error.localizedDescription)") } } func saveStudentData(studentDict:[String: String], college: College) { let student = NSEntityDescription.insertNewObject(forEntityName: "Student", into: context) as! Student student.name = studentDict["studentName"] student.email = studentDict["studentEmail"] student.phone = studentDict["studentPhone"] student.university = college do { try context.save() } catch { print("error = \(error.localizedDescription)") } } func getAllStudentData() -> [Student] { var arrStudent = [Student]() let fetchReq = NSFetchRequest<NSManagedObject>(entityName: "Student") do { arrStudent = try context.fetch(fetchReq) as! [Student] } catch { print("error = \(error.localizedDescription)") } return arrStudent } }
896e3a5b7facdef62493537ee62ed5be37608ed0
[ "Swift" ]
7
Swift
Pradeep-CG/CoreDataRelation
837c7349e13b159623f84d02d2c6033f07c6dcca
1592f8eb38209357983a7841dcdfa3e64681857f
refs/heads/master
<file_sep>using Datos; using Entidades; using System; using System.Collections.Generic; namespace Logica { public class MensajeLN { public List<Mensaje> MostrarMensajeFitro(string busqueda) { List<Mensaje> Lista = new List<Mensaje>(); Mensaje oc; try { List<cp_ListarMensajeResult> auxLista = MensajeCD.ListarMensajeFiltro(busqueda); foreach (cp_ListarMensajeResult aux in auxLista) { oc = new Mensaje(aux.ID_Mensaje, (DateTime)aux.Fecha, aux.Remitente, aux.Mensaje, aux.Estado); Lista.Add(oc); } } catch (Exception ex) { throw new LogicaExcepciones("Error al listar el mensaje.", ex); } return Lista; } public List<VistaMensaje> MostrarVistaMensajeFitro(string busqueda) { List<VistaMensaje> Lista = new List<VistaMensaje>(); VistaMensaje oc; try { List<cp_ListarVistaMensajeResult> auxLista = MensajeCD.ListarVistaMensajeFiltro(busqueda); foreach (cp_ListarVistaMensajeResult aux in auxLista) { oc = new VistaMensaje(aux.ID_Mensaje, (DateTime)aux.Fecha, aux.Mensaje); Lista.Add(oc); } } catch (Exception ex) { throw new LogicaExcepciones("Error al listar los mensajes.", ex); } return Lista; } public bool CreateMensaje(Mensaje oc) { try { MensajeCD.InsertarMensaje(oc); return true; } catch (Exception ex) { throw new LogicaExcepciones("Error al crear el mensaje.", ex); } } public bool UpdateEstadoMsm(Mensaje oc) { try { MensajeCD.ActualizarEstadoMensajes(oc); return true; } catch (Exception ex) { throw new LogicaExcepciones("Error al Actualizar el estado del mensaje.", ex); } } } }<file_sep>using System; namespace Entidades { public class Mensaje { private int iD_Mensaje; private DateTime fecha; private string remitente; private string mensajes; private string estado; public Mensaje() { } public Mensaje(int iD_Mensaje, DateTime fecha, string remitente, string mensajes, string estado) { this.iD_Mensaje = iD_Mensaje; this.fecha = fecha; this.remitente = remitente; this.mensajes = mensajes; this.estado = estado; } public int ID_Mensaje { get => iD_Mensaje; set => iD_Mensaje = value; } public DateTime Fecha { get => fecha; set => fecha = value; } public string Remitente { get => remitente; set => remitente = value; } public string Mensajes { get => mensajes; set => mensajes = value; } public string Estado { get => estado; set => estado = value; } } } <file_sep>using System; using System.Drawing; using System.Windows.Forms; namespace AppSistemaInventarioPIEBM { public partial class Form1 : Form { public Form1() { InitializeComponent(); } public string correoUsuario; public string usuario; public string cargo; private void btnPaciente_Click(object sender, EventArgs e) { btnDash.BackColor = Color.Transparent; btnPaciente.BackColor = Color.FromArgb(237, 237, 237); FrmInventario fcm = new FrmInventario(); fcm.correoUsuario = correoUsuario; addPanel(fcm); } private void btnDash_Click(object sender, EventArgs e) { btnPaciente.BackColor = Color.Transparent; btnDash.BackColor = Color.FromArgb(237, 237, 237); FrmDashBoard fcm = new FrmDashBoard(); addPanel(fcm); } private void addPanel(Form frm) { if (this.PanelPrincipal.Controls.Count > 0) { this.PanelPrincipal.Controls.RemoveAt(0); } panel1.Visible = false; frm.TopLevel = false; this.PanelPrincipal.Controls.Add(frm); frm.Dock = DockStyle.Fill; frm.Show(); } private void pictureBox1_Click(object sender, EventArgs e) { if (bunifuSeparator1.Location.ToString().Equals("{X=12,Y=65}")) { bunifuSeparator1.Location = new Point(12, 44); linkLabel1.Visible = false; } else { bunifuSeparator1.Location = new Point(12, 65); linkLabel1.Visible = true; } } private void pictureBox4_Click(object sender, EventArgs e) { WindowState = FormWindowState.Minimized; } private void pictureBox5_Click(object sender, EventArgs e) { WindowState = FormWindowState.Normal; pictureBox5.Visible = false; pictureBox3.Visible = true; } private void pictureBox3_Click(object sender, EventArgs e) { WindowState = FormWindowState.Maximized; pictureBox3.Visible = false; pictureBox5.Visible = true; } int posY = 0; int posX = 0; private void panel2_MouseMove(object sender, MouseEventArgs e) { if (e.Button != MouseButtons.Left) { posX = e.X; posY = e.Y; } else { Left = Left + (e.X - posX); Top = Top + (e.Y - posY); } } private void pictureBox2_Click(object sender, EventArgs e) { FrmMessage fm = new FrmMessage(); fm.ShowDialog(); } private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { this.Hide(); FrmLogin fl = new FrmLogin(); fl.ShowDialog(); } private void panel5_Paint(object sender, PaintEventArgs e) { } private void Form1_Load(object sender, EventArgs e) { if (cargo.Equals("Administrador ") || cargo.Equals("Administradora ")) { btnDash.Enabled = true; } else { btnDash.Enabled = false; } lbUser.Text = usuario; lbCargo.Text = cargo; } private void panel2_Paint(object sender, PaintEventArgs e) { } } } <file_sep>using System; namespace Entidades { public class Producto { private int iD_Producto; private string articulos; private string estado; private string ubicacion; private int cantidad; private string descripcion; private DateTime fecha; private double precio_Aproximado; public Producto() { } public Producto(int iD_Producto, string articulos, string estado, string ubicacion, int cantidad, string descripcion, DateTime fecha, double precio_Aproximado) { this.iD_Producto = iD_Producto; this.articulos = articulos; this.estado = estado; this.ubicacion = ubicacion; this.cantidad = cantidad; this.descripcion = descripcion; this.fecha = fecha; this.precio_Aproximado = precio_Aproximado; } public int ID_Producto { get => iD_Producto; set => iD_Producto = value; } public string Articulos { get => articulos; set => articulos = value; } public string Estado { get => estado; set => estado = value; } public string Ubicacion { get => ubicacion; set => ubicacion = value; } public int Cantidad { get => cantidad; set => cantidad = value; } public string Descripcion { get => descripcion; set => descripcion = value; } public DateTime Fecha { get => fecha; set => fecha = value; } public double Precio_Aproximado { get => precio_Aproximado; set => precio_Aproximado = value; } } } <file_sep>namespace Entidades { public class Usuario { private int iD_Usuario; private string user; private string ocupacion; private string email; private string contras; public Usuario() { } public Usuario(int iD_Usuario, string user, string ocupacion, string email, string contras) { this.iD_Usuario = iD_Usuario; this.user = user; this.ocupacion = ocupacion; this.email = email; this.contras = contras; } public int ID_Usuario { get => iD_Usuario; set => iD_Usuario = value; } public string User { get => user; set => user = value; } public string Ocupacion { get => ocupacion; set => ocupacion = value; } public string Email { get => email; set => email = value; } public string Contras { get => contras; set => contras = value; } } } <file_sep>using Datos; using Entidades; using System; using System.Collections.Generic; namespace Logica { public class ProductoLN { public List<Producto> MostrarProductoFitro(string busqueda) { List<Producto> Lista = new List<Producto>(); Producto oc; try { List<cp_ListarProductoResult> auxLista = ProductoCD.ListarProductoFiltro(busqueda); foreach (cp_ListarProductoResult aux in auxLista) { oc = new Producto(aux.ID_Producto, aux.Producto, aux.Estado, aux.Ubicación, (int)aux.Cantidad, aux.Descripción, (DateTime)aux.Fecha, Convert.ToDouble(aux.Precio_Aproximado)); Lista.Add(oc); } } catch (Exception ex) { throw new LogicaExcepciones("Error al listar el articulo.", ex); } return Lista; } public List<VistaReporte> MostrarReporteFitro(string busqueda) { List<VistaReporte> Lista = new List<VistaReporte>(); VistaReporte oc; try { List<cp_ListarReporteMensajeResult> auxLista = ProductoCD.ListarVistaReporteFiltro(busqueda); foreach (cp_ListarReporteMensajeResult aux in auxLista) { oc = new VistaReporte(aux.ID_Producto, aux.Producto, aux.Estado, aux.Ubicación, (int)aux.Cantidad, aux.Descripción, (DateTime)aux.Fecha, (double)aux.Precio_Aproximado, aux.Usuario, aux.Ocupación, aux.Email); Lista.Add(oc); } } catch (Exception ex) { throw new LogicaExcepciones("Error al listar el reporte.", ex); } return Lista; } public bool CreateProducto(Producto oc) { try { ProductoCD.InsertarProducto(oc); return true; } catch (Exception ex) { throw new LogicaExcepciones("Error al crear el articulo.", ex); } } public bool UpdateProducto(Producto oc) { try { ProductoCD.ActualizarProducto(oc); return true; } catch (Exception ex) { throw new LogicaExcepciones("Error al Actualizar el articulo.", ex); } } public bool DeleteProducto(Producto oc) { try { ProductoCD.EliminarProducto(oc); return true; } catch (Exception ex) { throw new LogicaExcepciones("Error al eliminar el articulo.", ex); } } } } <file_sep>using System; namespace Entidades { public class VistaReporte { private int iD_Producto; private string producto; private string estado; private string ubicacion; private int cant; private string descrip; private DateTime fecha; private double precio_Aprox; private string usuario; private string ocupacion; private string email; public VistaReporte() { } public VistaReporte(int iD_Producto, string producto, string estado, string ubicacion, int cant, string descrip, DateTime fecha, double precio_Aprox, string usuario, string ocupacion, string email) { this.iD_Producto = iD_Producto; this.producto = producto; this.estado = estado; this.ubicacion = ubicacion; this.cant = cant; this.descrip = descrip; this.fecha = fecha; this.precio_Aprox = precio_Aprox; this.usuario = usuario; this.ocupacion = ocupacion; this.email = email; } public int ID_Producto { get => iD_Producto; set => iD_Producto = value; } public string Producto { get => producto; set => producto = value; } public string Estado { get => estado; set => estado = value; } public string Ubicacion { get => ubicacion; set => ubicacion = value; } public int Cant { get => cant; set => cant = value; } public string Descrip { get => descrip; set => descrip = value; } public DateTime Fecha { get => fecha; set => fecha = value; } public double Precio_Aprox { get => precio_Aprox; set => precio_Aprox = value; } public string Usuario { get => usuario; set => usuario = value; } public string Ocupacion { get => ocupacion; set => ocupacion = value; } public string Email { get => email; set => email = value; } } } <file_sep>using Entidades; using System; using System.Collections.Generic; using System.Linq; namespace Datos { public class MensajeCD { public static List<cp_ListarMensajeResult> ListarMensajeFiltro(string busqueda) { BDSoftPiebmDataContext DB = null; try { using (DB = new BDSoftPiebmDataContext()) { return DB.cp_ListarMensaje(busqueda).ToList(); } } catch (Exception ex) { throw new DatosExcepciones("Error al listar mensaje.", ex); } finally { DB = null; } } public static List<cp_ListarVistaMensajeResult> ListarVistaMensajeFiltro(string busqueda) { BDSoftPiebmDataContext DB = null; try { using (DB = new BDSoftPiebmDataContext()) { return DB.cp_ListarVistaMensaje(busqueda).ToList(); } } catch (Exception ex) { throw new DatosExcepciones("Error al listar mensajes.", ex); } finally { DB = null; } } public static void InsertarMensaje(Mensaje oc) { BDSoftPiebmDataContext DB = null; try { using (DB = new BDSoftPiebmDataContext()) { DB.cp_InsertarMensaje(oc.Fecha, oc.Remitente, oc.Mensajes, oc.Estado); DB.SubmitChanges(); } } catch (Exception ex) { throw new DatosExcepciones("Error al insertar el mensaje.", ex); } finally { DB = null; } } public static void ActualizarEstadoMensajes(Mensaje oc) { BDSoftPiebmDataContext DB = null; try { using (DB = new BDSoftPiebmDataContext()) { DB.cp_ActualizarEstadoMensaje(oc.ID_Mensaje, oc.Mensajes); DB.SubmitChanges(); } } catch (Exception ex) { throw new DatosExcepciones("Error al actualizar el estado del mensaje.", ex); } finally { DB = null; } } } } <file_sep>using Entidades; using System; using System.Collections.Generic; using System.Linq; namespace Datos { public class ProductoCD { public static List<cp_ListarProductoResult> ListarProductoFiltro(string busqueda) { BDSoftPiebmDataContext DB = null; try { using (DB = new BDSoftPiebmDataContext()) { return DB.cp_ListarProducto(busqueda).ToList(); } } catch (Exception ex) { throw new DatosExcepciones("Error al listar Articulo.", ex); } finally { DB = null; } } public static List<cp_ListarReporteMensajeResult> ListarVistaReporteFiltro(string busqueda) { BDSoftPiebmDataContext DB = null; try { using (DB = new BDSoftPiebmDataContext()) { return DB.cp_ListarReporteMensaje(busqueda).ToList(); } } catch (Exception ex) { throw new DatosExcepciones("Error al listar reporte.", ex); } finally { DB = null; } } public static void InsertarProducto(Producto oc) { BDSoftPiebmDataContext DB = null; try { using (DB = new BDSoftPiebmDataContext()) { DB.cp_InsertarProducto(oc.Articulos, oc.Estado, oc.Ubicacion, oc.Cantidad, oc.Descripcion, oc.Fecha, (decimal)oc.Precio_Aproximado); DB.SubmitChanges(); } } catch (Exception ex) { throw new DatosExcepciones("Error al insertar el Articulo.", ex); } finally { DB = null; } } public static void ActualizarProducto(Producto oc) { BDSoftPiebmDataContext DB = null; try { using (DB = new BDSoftPiebmDataContext()) { DB.cp_ActualizarProducto(oc.ID_Producto, oc.Articulos, oc.Estado, oc.Ubicacion, oc.Cantidad, oc.Descripcion, oc.Fecha, (decimal)oc.Precio_Aproximado); DB.SubmitChanges(); } } catch (Exception ex) { throw new DatosExcepciones("Error al actualizar el Articulo.", ex); } finally { DB = null; } } public static void EliminarProducto(Producto oc) { BDSoftPiebmDataContext DB = null; try { using (DB = new BDSoftPiebmDataContext()) { DB.cp_EliminarProducto(oc.ID_Producto); DB.SubmitChanges(); } } catch (Exception ex) { throw new DatosExcepciones("Error al eliminar el Articulo.", ex); } finally { DB = null; } } } } <file_sep>using Logica; using System; using System.Drawing; using System.Windows.Forms; namespace AppSistemaInventarioPIEBM { public partial class FrmLogin : Form { public FrmLogin() { InitializeComponent(); } private void btnCerrar_Click(object sender, EventArgs e) { Application.Exit(); } private void btnMin_Click(object sender, EventArgs e) { WindowState = FormWindowState.Minimized; } private void textBox1_Leave(object sender, EventArgs e) { if (textBox1.Text == "") { textBox1.Text = "<EMAIL>"; textBox1.ForeColor = Color.DimGray; } } private void textBox1_Enter(object sender, EventArgs e) { if (textBox1.Text == "<EMAIL>") { textBox1.Text = ""; textBox1.ForeColor = Color.DimGray; } } private void textBox2_Enter(object sender, EventArgs e) { if (textBox2.Text == "************") { textBox2.Text = ""; textBox2.ForeColor = Color.DimGray; } } private void textBox2_Leave(object sender, EventArgs e) { if (textBox2.Text == "") { textBox2.Text = "************"; textBox2.ForeColor = Color.DimGray; } } UsuarioLN uln = new UsuarioLN(); private void button1_Click(object sender, EventArgs e) { if (textBox1.Text.Equals("<EMAIL>")) { errorProvider1.SetError(textBox1, "Ingrese su email"); Advertencia.Visible = true; } if (textBox2.Text.Equals("************")) { errorProvider1.SetError(textBox2, "Ingrese su contraseña"); Advertencia.Visible = true; } else { errorProvider1.Dispose(); bool encontrado = false; for (int i = 0; i < uln.MostrarUsuarioFitro("").Count; i++) { if (uln.MostrarUsuarioFitro("")[i].Email.Equals(textBox1.Text)) { encontrado = true; } if (uln.MostrarUsuarioFitro("")[i].Email.Equals(textBox1.Text) && uln.MostrarUsuarioFitro("")[i].Contras != (textBox2.Text)) { MessageBox.Show("Contraseña incorrecta"); } if (uln.MostrarUsuarioFitro("")[i].Email.Equals(textBox1.Text) && uln.MostrarUsuarioFitro("")[i].Contras.Equals(textBox2.Text)) { Form1 fm = new Form1(); this.Hide(); char[] limit = { ' ' }; string[] nombs = uln.MostrarUsuarioFitro("")[i].User.Split(limit); fm.usuario = nombs[0] + " " + nombs[1]; fm.cargo = uln.MostrarUsuarioFitro("")[i].Ocupacion + " "; fm.correoUsuario = textBox1.Text; fm.ShowDialog(); } } if (encontrado == false) { MessageBox.Show("Usuario no registrado"); } } } public string mes() { string mes = ""; if (DateTime.Now.Month == 1) { mes = "Enero"; } if (DateTime.Now.Month == 2) { mes = "Febrero"; } if (DateTime.Now.Month == 3) { mes = "Marzo"; } if (DateTime.Now.Month == 4) { mes = "Abril"; } if (DateTime.Now.Month == 5) { mes = "Mayo"; } if (DateTime.Now.Month == 6) { mes = "Junio"; } if (DateTime.Now.Month == 7) { mes = "Julio"; } if (DateTime.Now.Month == 8) { mes = "Agosto"; } if (DateTime.Now.Month == 9) { mes = "Septiembre"; } if (DateTime.Now.Month == 10) { mes = "Octubre"; } if (DateTime.Now.Month == 11) { mes = "Noviembre"; } if (DateTime.Now.Month == 12) { mes = "Diciembre"; } return mes; } private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { } private void panel3_Paint(object sender, PaintEventArgs e) { } private void FrmLogin_Load(object sender, EventArgs e) { lbDia.Text = DateTime.Now.Day.ToString(); lbMes.Text = mes(); } } } <file_sep>using Entidades; using Logica; using System; using System.Windows.Forms; namespace AppSistemaInventarioPIEBM { public partial class FrmMensaje : Form { public FrmMensaje() { InitializeComponent(); CenterToScreen(); } private void pictureBox2_Click(object sender, EventArgs e) { this.Close(); } private void bunifuTileButton1_Click(object sender, EventArgs e) { this.Close(); } private void bunifuTileButton1_Click_1(object sender, EventArgs e) { this.Close(); } private void panel1_Paint(object sender, PaintEventArgs e) { } int posY = 0; int posX = 0; private void panel1_MouseMove(object sender, MouseEventArgs e) { if (e.Button != MouseButtons.Left) { posX = e.X; posY = e.Y; } else { Left = Left + (e.X - posX); Top = Top + (e.Y - posY); } } private void FrmMensaje_Load(object sender, EventArgs e) { datePicker.Value = DateTime.Now; cargarCombo(); } UsuarioLN uln = new UsuarioLN(); private void cargarCombo() { foreach (var item in uln.MostrarUsuarioFitro("")) { cbRemit.AddItem(item.User); } } private bool validarDatos() { if (txtMsm.Text.Equals("") || cbRemit.selectedIndex == -1) { MessageBox.Show("Por favor, llene todos los campos indicados"); return false; } else { return true; } } public Mensaje ms = new Mensaje(); MensajeLN mln = new MensajeLN(); private Mensaje crearMensaje() { ms.ID_Mensaje = ms.ID_Mensaje; ms.Estado = "No leído"; ms.Fecha = datePicker.Value; ms.Mensajes = txtMsm.Text; ms.Remitente = cbRemit.selectedValue; return ms; } private void bunifuTileButton2_Click(object sender, EventArgs e) { if (validarDatos() == true) { Mensaje m = crearMensaje(); if (mln.CreateMensaje(m)) { MessageBox.Show("Mensaje enviado con exito"); } this.Close(); } } } } <file_sep>using Entidades; using Logica; using System; using System.Windows.Forms; namespace AppSistemaInventarioPIEBM { public partial class FrmEditUsuarios : Form { public FrmEditUsuarios() { InitializeComponent(); CenterToScreen(); } private void pictureBox2_Click(object sender, EventArgs e) { this.Close(); } private void bunifuTileButton1_Click(object sender, EventArgs e) { this.Close(); } int posY = 0; int posX = 0; private void panel1_MouseMove(object sender, MouseEventArgs e) { if (e.Button != MouseButtons.Left) { posX = e.X; posY = e.Y; } else { Left = Left + (e.X - posX); Top = Top + (e.Y - posY); } } private void panel1_Paint(object sender, PaintEventArgs e) { } private bool validarDatos() { if (txtOcupac.Text.Equals("") || txtNombr.Text.Equals("") || txtCorreo.Text.Equals("") || txtContra.Text.Equals("") || txtConfirmarContr.Text.Equals("")) { MessageBox.Show("Por favor, llene los campos indicados"); return false; } else { if (txtContra.Text.Equals(txtConfirmarContr.Text)) { return true; } else { MessageBox.Show("Las contraseñas deben coincidir"); return false; } } } public Usuario us = new Usuario(); private Usuario crearUsuario() { us.ID_Usuario = us.ID_Usuario; us.Email = txtCorreo.Text; us.Contras = txtContra.Text; us.Ocupacion = txtOcupac.Text; us.User = txtNombr.Text; return us; } UsuarioLN uln = new UsuarioLN(); private void bunifuTileButton2_Click(object sender, EventArgs e) { bool val = true; if (validarDatos() == true) { for (int i = 0; i < uln.MostrarUsuarioFitro("").Count; i++) { if (txtCorreo.Text.Equals(uln.MostrarUsuarioFitro("")[i].Email)) { MessageBox.Show("El correo ingresado ya se encuentra registrado"); val = false; } } if (val == true) { Usuario us = crearUsuario(); if (uln.CreateUsuario(us)) { MessageBox.Show("Usuario generado con exito"); } this.Close(); } } } } } <file_sep>using AppSistemaInventarioPIEBM.Reportes; using Entidades; using Logica; using System; using System.Collections.Generic; using System.Windows.Forms; namespace AppSistemaInventarioPIEBM { public partial class FrmReporte : Form { public FrmReporte() { InitializeComponent(); } public string email; private void button2_Click(object sender, EventArgs e) { } private void pictureBox2_Click(object sender, EventArgs e) { this.Close(); } private void pictureBox5_Click(object sender, EventArgs e) { WindowState = FormWindowState.Normal; pictureBox5.Visible = false; pictureBox3.Visible = true; } private void pictureBox3_Click(object sender, EventArgs e) { WindowState = FormWindowState.Maximized; pictureBox3.Visible = false; pictureBox5.Visible = true; } private void pictureBox4_Click(object sender, EventArgs e) { WindowState = FormWindowState.Minimized; } int posY = 0; int posX = 0; private void panel1_MouseMove(object sender, MouseEventArgs e) { if (e.Button != MouseButtons.Left) { posX = e.X; posY = e.Y; } else { Left = Left + (e.X - posX); Top = Top + (e.Y - posY); } } private void FrmReporte_Load(object sender, EventArgs e) { ReporteProductoCategoria(""); dateTimePicker1.Value = DateTime.Now; dateTimePicker2.Value = DateTime.Now; } string usuario = ""; string cargo = ""; public UsuarioLN uln = new UsuarioLN(); ProductoLN pln = new ProductoLN(); public void ReporteProductoCategoria(string busqueda) { for (int i = 0; i < uln.MostrarUsuarioFitro("").Count; i++) { if (uln.MostrarUsuarioFitro("")[i].Email.Equals(email)) { usuario = uln.MostrarUsuarioFitro("")[i].User; cargo = uln.MostrarUsuarioFitro("")[i].Ocupacion; } } DataSetReporte ds = new DataSetReporte(); List<VistaReporte> us = pln.MostrarReporteFitro(""); foreach (VistaReporte c in us) { if (c.Usuario.Equals(usuario)) { ds.VistaReporte.AddVistaReporteRow(c.ID_Producto, c.Producto, c.Estado, c.Ubicacion, c.Cant, c.Descrip, c.Fecha, (decimal)c.Precio_Aprox, usuario, cargo, email); } } CRReporteArticulos rpa = new CRReporteArticulos(); rpa.SetDataSource(ds); crystalReportViewer1.ReportSource = rpa; } private void panel1_Paint(object sender, PaintEventArgs e) { } private void btnDash_Click(object sender, EventArgs e) { for (int i = 0; i < uln.MostrarUsuarioFitro("").Count; i++) { if (uln.MostrarUsuarioFitro("")[i].Email.Equals(email)) { usuario = uln.MostrarUsuarioFitro("")[i].User; cargo = uln.MostrarUsuarioFitro("")[i].Ocupacion; } } DataSetReporte ds = new DataSetReporte(); List<VistaReporte> us = pln.MostrarReporteFitro(""); foreach (VistaReporte c in us) { if (c.Usuario.Equals(usuario) && c.Fecha.Day == DateTime.Now.Day && c.Fecha.Month == DateTime.Now.Month && c.Fecha.Year == DateTime.Now.Year) { ds.VistaReporte.AddVistaReporteRow(c.ID_Producto, c.Producto, c.Estado, c.Ubicacion, c.Cant, c.Descrip, c.Fecha, (decimal)c.Precio_Aprox, usuario, cargo, email); } } CRReporteArticulos rpa = new CRReporteArticulos(); rpa.SetDataSource(ds); crystalReportViewer1.ReportSource = rpa; } private void btnPaciente_Click(object sender, EventArgs e) { for (int i = 0; i < uln.MostrarUsuarioFitro("").Count; i++) { if (uln.MostrarUsuarioFitro("")[i].Email.Equals(email)) { usuario = uln.MostrarUsuarioFitro("")[i].User; cargo = uln.MostrarUsuarioFitro("")[i].Ocupacion; } } DataSetReporte ds = new DataSetReporte(); List<VistaReporte> us = pln.MostrarReporteFitro(""); foreach (VistaReporte c in us) { if (c.Usuario.Equals(usuario) && (DateTime.Now.Date - c.Fecha.Date).Days <= 6) { ds.VistaReporte.AddVistaReporteRow(c.ID_Producto, c.Producto, c.Estado, c.Ubicacion, c.Cant, c.Descrip, c.Fecha, (decimal)c.Precio_Aprox, usuario, cargo, email); } } CRReporteArticulos rpa = new CRReporteArticulos(); rpa.SetDataSource(ds); crystalReportViewer1.ReportSource = rpa; } private void btn30dias_Click(object sender, EventArgs e) { for (int i = 0; i < uln.MostrarUsuarioFitro("").Count; i++) { if (uln.MostrarUsuarioFitro("")[i].Email.Equals(email)) { usuario = uln.MostrarUsuarioFitro("")[i].User; cargo = uln.MostrarUsuarioFitro("")[i].Ocupacion; } } DataSetReporte ds = new DataSetReporte(); List<VistaReporte> us = pln.MostrarReporteFitro(""); foreach (VistaReporte c in us) { if (c.Usuario.Equals(usuario) && (DateTime.Now.Date - c.Fecha.Date).Days <= 29) { ds.VistaReporte.AddVistaReporteRow(c.ID_Producto, c.Producto, c.Estado, c.Ubicacion, c.Cant, c.Descrip, c.Fecha, (decimal)c.Precio_Aprox, usuario, cargo, email); } } CRReporteArticulos rpa = new CRReporteArticulos(); rpa.SetDataSource(ds); crystalReportViewer1.ReportSource = rpa; } private void button2_Click_1(object sender, EventArgs e) { for (int i = 0; i < uln.MostrarUsuarioFitro("").Count; i++) { if (uln.MostrarUsuarioFitro("")[i].Email.Equals(email)) { usuario = uln.MostrarUsuarioFitro("")[i].User; cargo = uln.MostrarUsuarioFitro("")[i].Ocupacion; } } DataSetReporte ds = new DataSetReporte(); List<VistaReporte> us = pln.MostrarReporteFitro(""); foreach (VistaReporte c in us) { if (c.Usuario.Equals(usuario) && c.Fecha.Month == DateTime.Now.Month && c.Fecha.Year == DateTime.Now.Year) { ds.VistaReporte.AddVistaReporteRow(c.ID_Producto, c.Producto, c.Estado, c.Ubicacion, c.Cant, c.Descrip, c.Fecha, (decimal)c.Precio_Aprox, usuario, cargo, email); } } CRReporteArticulos rpa = new CRReporteArticulos(); rpa.SetDataSource(ds); crystalReportViewer1.ReportSource = rpa; } private void bunifuTileButton2_Click(object sender, EventArgs e) { for (int i = 0; i < uln.MostrarUsuarioFitro("").Count; i++) { if (uln.MostrarUsuarioFitro("")[i].Email.Equals(email)) { usuario = uln.MostrarUsuarioFitro("")[i].User; cargo = uln.MostrarUsuarioFitro("")[i].Ocupacion; } } DataSetReporte ds = new DataSetReporte(); List<VistaReporte> us = pln.MostrarReporteFitro(""); foreach (VistaReporte c in us) { if (c.Usuario.Equals(usuario) && c.Fecha.Date >= dateTimePicker1.Value.Date && c.Fecha.Date <= dateTimePicker2.Value.Date) { ds.VistaReporte.AddVistaReporteRow(c.ID_Producto, c.Producto, c.Estado, c.Ubicacion, c.Cant, c.Descrip, c.Fecha, (decimal)c.Precio_Aprox, usuario, cargo, email); } } CRReporteArticulos rpa = new CRReporteArticulos(); rpa.SetDataSource(ds); crystalReportViewer1.ReportSource = rpa; } private void panel3_Paint(object sender, PaintEventArgs e) { } } } <file_sep>using Logica; using System; using System.Windows.Forms; namespace AppSistemaInventarioPIEBM { public partial class FrmDashBoard : Form { public FrmDashBoard() { InitializeComponent(); label2.Text = DateTime.Now.Day.ToString() + " de " + mes() + ", " + DateTime.Now.Year.ToString(); } UsuarioLN uln = new UsuarioLN(); ProductoLN pln = new ProductoLN(); private void FrmDashBoard_Load(object sender, EventArgs e) { cargarDatos(); lbTot.Text = totalArti(); bunifuCustomDataGrid1.Columns[0].Width = 75; bunifuCustomDataGrid1.Columns[1].Width = 200; bunifuCustomDataGrid1.Columns[2].Width = 80; bunifuCustomDataGrid2.Columns[0].Width = 75; bunifuCustomDataGrid2.Columns[1].Width = 83; bunifuCustomDataGrid2.Columns[2].Width = 200; bunifuCustomDataGrid2.Columns[3].Width = 275; bunifuCustomDataGrid2.Columns[4].Width = 95; progresos(); } MensajeLN mln = new MensajeLN(); private string totalArti() { int tot = 0; for (int i = 0; i < pln.MostrarProductoFitro("").Count; i++) { tot += pln.MostrarProductoFitro("")[i].Cantidad; } return tot.ToString(); ; } private void cargarDatos() { bunifuCustomDataGrid1.DataSource = uln.MostrarVistaUsuarioFitro(""); bunifuCustomDataGrid2.DataSource = mln.MostrarMensajeFitro(""); } private void progresos() { int numerosTot = 0; int excelente, bueno, malo, contExc = 0, contBuen = 0, contMalo = 0; for (int i = 0; i < pln.MostrarProductoFitro("").Count; i++) { numerosTot += pln.MostrarProductoFitro("")[i].Cantidad; if (pln.MostrarProductoFitro("")[i].Estado.Equals("Excelente")) { contExc += pln.MostrarProductoFitro("")[i].Cantidad; } if (pln.MostrarProductoFitro("")[i].Estado.Equals("Bueno")) { contBuen += pln.MostrarProductoFitro("")[i].Cantidad; } if (pln.MostrarProductoFitro("")[i].Estado.Equals("Malo")) { contMalo += pln.MostrarProductoFitro("")[i].Cantidad; } } excelente = ((contExc * 100) / numerosTot); bueno = ((contBuen * 100) / numerosTot); malo = ((contMalo * 100) / numerosTot); circleExcelente.Value = excelente; circleBuen.Value = bueno; circleMalo.Value = malo; } public string mes() { string mes = ""; if (DateTime.Now.Month == 1) { mes = "Enero"; } if (DateTime.Now.Month == 2) { mes = "Febrero"; } if (DateTime.Now.Month == 3) { mes = "Marzo"; } if (DateTime.Now.Month == 4) { mes = "Abril"; } if (DateTime.Now.Month == 5) { mes = "Mayo"; } if (DateTime.Now.Month == 6) { mes = "Junio"; } if (DateTime.Now.Month == 7) { mes = "Julio"; } if (DateTime.Now.Month == 8) { mes = "Agosto"; } if (DateTime.Now.Month == 9) { mes = "Septiembre"; } if (DateTime.Now.Month == 10) { mes = "Octubre"; } if (DateTime.Now.Month == 11) { mes = "Noviembre"; } if (DateTime.Now.Month == 12) { mes = "Diciembre"; } return mes; } private void pictureBox1_Click(object sender, EventArgs e) { FrmEditUsuarios eu = new FrmEditUsuarios(); eu.ShowDialog(); cargarDatos(); } private void pictureBox4_Click(object sender, EventArgs e) { FrmMensaje fm = new FrmMensaje(); fm.ShowDialog(); cargarDatos(); } private void pictureBox3_Click(object sender, EventArgs e) { if (bunifuCustomDataGrid1.CurrentRow.Selected == false) { MessageBox.Show("Seleccione el usuario que desea eliminar."); } else { try { var res = MessageBox.Show("¿Esta seguro de eliminar este usuario?", "Eliminar", MessageBoxButtons.YesNo); if (res.ToString().Equals("Yes")) { for (int i = 0; i < uln.MostrarUsuarioFitro("").Count; i++) { if (uln.MostrarUsuarioFitro("").Count > 1) { if ((int)bunifuCustomDataGrid1.CurrentRow.Cells[0].Value == uln.MostrarUsuarioFitro("")[i].ID_Usuario) { if (uln.DeleteUsuario(uln.MostrarUsuarioFitro("")[i])) { MessageBox.Show("Usuario Eliminado con exito"); cargarDatos(); } else { MessageBox.Show("Elimación cancelada..."); } } } else { MessageBox.Show("Si elimina este usuario, no existirán cuentas disponibles", "SoftPiebm"); } } } } catch (Exception) { } } } private void bunifuCustomDataGrid2_MouseClick(object sender, MouseEventArgs e) { if (bunifuCustomDataGrid2.CurrentRow == null) { MessageBox.Show("Por el momento no se han enviado mensajes", "Mensaje"); } } private void bunifuCustomDataGrid1_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void bunifuCustomDataGrid1_MouseClick(object sender, MouseEventArgs e) { if (bunifuCustomDataGrid1.CurrentRow == null) { MessageBox.Show("Por el momento no se han ingresado usuarios", "Mensaje"); } } } } <file_sep>namespace Entidades { public class VistaUsuario { private int iD_Usuario; private string usuario; private string cargo; public VistaUsuario() { } public VistaUsuario(int iD_Usuario, string usuario, string cargo) { this.iD_Usuario = iD_Usuario; this.usuario = usuario; this.cargo = cargo; } public int ID_Usuario { get => iD_Usuario; set => iD_Usuario = value; } public string Usuario { get => usuario; set => usuario = value; } public string Cargo { get => cargo; set => cargo = value; } } } <file_sep>using Entidades; using Logica; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Windows.Forms; namespace AppSistemaInventarioPIEBM { public partial class FrmInventario : Form { public FrmInventario() { InitializeComponent(); } public string correoUsuario; private string obtenerUsuario() { string resp = ""; for (int i = 0; i < uln.MostrarUsuarioFitro("").Count; i++) { if (uln.MostrarUsuarioFitro("")[i].Email.Equals(correoUsuario)) { resp = uln.MostrarUsuarioFitro("")[i].User; } } return resp; } private void bunifuThinButton213_Click(object sender, EventArgs e) { FrmEditProducto ep = new FrmEditProducto(); ep.val = 1; ep.ShowDialog(); cargarProductos(""); lbNum.Text = totalArti(); } ProductoLN pln = new ProductoLN(); MensajeLN mln = new MensajeLN(); Form1 f = new Form1(); private void cargarProductos(string buscar) { bunifuCustomDataGrid1.DataSource = pln.MostrarProductoFitro(buscar); } UsuarioLN uln = new UsuarioLN(); private void cargarMensajes() { List<VistaMensaje> listaMsm = new List<VistaMensaje>(); for (int i = 0; i < mln.MostrarMensajeFitro("").Count; i++) { if (mln.MostrarMensajeFitro("")[i].Estado.Equals("No leído") && mln.MostrarMensajeFitro("")[i].Remitente.Equals(obtenerUsuario())) { listaMsm.Add(mln.MostrarVistaMensajeFitro("")[i]); } } bunifuCustomDataGrid2.DataSource = listaMsm.ToList(); } private void bunifuCustomDataGrid2_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void textBox1_Leave(object sender, EventArgs e) { if (textBox1.Text == "") { textBox1.Text = "Buscar"; textBox1.ForeColor = Color.DimGray; } } private void textBox1_Enter(object sender, EventArgs e) { if (textBox1.Text == "Buscar") { textBox1.Text = ""; textBox1.ForeColor = Color.DimGray; } } private void textBox1_TextChanged(object sender, EventArgs e) { if (textBox1.Text.Equals("Buscar")) { cargarProductos(""); } else { cargarProductos(textBox1.Text); } } private void FrmInventario_Load(object sender, EventArgs e) { cargarProductos(""); cargarMensajes(); lbNum.Text = totalArti(); bunifuCustomDataGrid1.Columns[0].Width = 85; bunifuCustomDataGrid1.Columns[1].Width = 80; bunifuCustomDataGrid1.Columns[2].Width = 80; bunifuCustomDataGrid1.Columns[3].Width = 90; bunifuCustomDataGrid1.Columns[4].Width = 84; bunifuCustomDataGrid1.Columns[5].Width = 250; bunifuCustomDataGrid1.Columns[6].Width = 88; bunifuCustomDataGrid2.Columns[0].Width = 60; bunifuCustomDataGrid2.Columns[1].Width = 70; bunifuCustomDataGrid2.Columns[2].Width = 380; } private string totalArti() { int tot = 0; for (int i = 0; i < pln.MostrarProductoFitro("").Count; i++) { tot += pln.MostrarProductoFitro("")[i].Cantidad; } return tot.ToString(); ; } private void bunifuThinButton21_Click(object sender, EventArgs e) { if (bunifuCustomDataGrid1.CurrentRow.Selected == false) { MessageBox.Show("Seleccione el producto que desea modificar."); } else { FrmEditProducto ep = new FrmEditProducto(); ep.val = 2; ep.pa = bunifuCustomDataGrid1.CurrentRow.DataBoundItem as Producto; ep.ShowDialog(); cargarProductos(""); lbNum.Text = totalArti(); } } private void bunifuThinButton22_Click(object sender, EventArgs e) { if (bunifuCustomDataGrid1.CurrentRow.Selected == false) { MessageBox.Show("Seleccione el articulo que desea eliminar."); } else { try { var res = MessageBox.Show("¿Esta seguro de eliminar este articulo?", "Eliminar", MessageBoxButtons.YesNo); if (res.ToString().Equals("Yes")) { Producto oc = bunifuCustomDataGrid1.CurrentRow.DataBoundItem as Producto; if (pln.DeleteProducto(oc)) { MessageBox.Show("Articulo Eliminado con exito"); cargarProductos(""); lbNum.Text = totalArti(); } else { MessageBox.Show("Elimación cancelada..."); } } } catch (Exception) { } } } public Mensaje p = new Mensaje(); private Mensaje crearMensaje(int id) { p.ID_Mensaje = id; p.Mensajes = "Leído"; return p; } private void bunifuCustomDataGrid2_MouseClick(object sender, MouseEventArgs e) { if (bunifuCustomDataGrid2.CurrentRow == null) { MessageBox.Show("Por el momento, usted no tiene mensajes", "Mensaje"); } if (bunifuCustomDataGrid2.CurrentRow != null) { for (int i = 0; i < mln.MostrarMensajeFitro("").Count; i++) { if (mln.MostrarMensajeFitro("")[i].ID_Mensaje == (int)bunifuCustomDataGrid2.CurrentRow.Cells[0].Value) { MessageBox.Show(bunifuCustomDataGrid2.CurrentRow.Cells[2].Value.ToString(), "Mensaje"); Mensaje m = crearMensaje((int)bunifuCustomDataGrid2.CurrentRow.Cells[0].Value); mln.UpdateEstadoMsm(m); } } } cargarMensajes(); } private void pictureBox3_Click(object sender, EventArgs e) { FrmReporte fr = new FrmReporte(); fr.email = correoUsuario; fr.ShowDialog(); } private void bunifuCustomDataGrid1_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void bunifuCustomDataGrid1_MouseClick(object sender, MouseEventArgs e) { if (bunifuCustomDataGrid1.CurrentRow == null) { MessageBox.Show("Por el momento no se han ingresado artículos", "Mensaje"); } } } } <file_sep>using System; using System.Windows.Forms; namespace AppSistemaInventarioPIEBM { public partial class FrmMessage : Form { public FrmMessage() { InitializeComponent(); CenterToScreen(); } private void pictureBox2_Click(object sender, EventArgs e) { this.Close(); } private void bunifuThinButton21_Click(object sender, EventArgs e) { Application.Exit(); } private void FrmMessage_Load(object sender, EventArgs e) { } private void bunifuThinButton21_Click_1(object sender, EventArgs e) { Application.Exit(); } int posY = 0; int posX = 0; private void panel1_MouseMove(object sender, MouseEventArgs e) { if (e.Button != MouseButtons.Left) { posX = e.X; posY = e.Y; } else { Left = Left + (e.X - posX); Top = Top + (e.Y - posY); } } } } <file_sep>using System; namespace Entidades { public class VistaMensaje { private int iD; private DateTime fecha; private string mensaje; public VistaMensaje() { } public VistaMensaje(int iD, DateTime fecha, string mensaje) { this.iD = iD; this.fecha = fecha; this.mensaje = mensaje; } public int ID { get => iD; set => iD = value; } public DateTime Fecha { get => fecha; set => fecha = value; } public string Mensaje { get => mensaje; set => mensaje = value; } } } <file_sep>using Entidades; using System; using System.Collections.Generic; using System.Linq; namespace Datos { public class UsuarioCD { public static List<cp_ListarUsuarioResult> ListarUsuarioFiltro(string busqueda) { BDSoftPiebmDataContext DB = null; try { using (DB = new BDSoftPiebmDataContext()) { return DB.cp_ListarUsuario(busqueda).ToList(); } } catch (Exception ex) { throw new DatosExcepciones("Error al listar Usuarios.", ex); } finally { DB = null; } } public static List<cp_ListarVistaUsuarioResult> ListarVistaUsuarioFiltro(string busqueda) { BDSoftPiebmDataContext DB = null; try { using (DB = new BDSoftPiebmDataContext()) { return DB.cp_ListarVistaUsuario(busqueda).ToList(); } } catch (Exception ex) { throw new DatosExcepciones("Error al listar Usuarios.", ex); } finally { DB = null; } } public static void InsertarUsuario(Usuario oc) { BDSoftPiebmDataContext DB = null; try { using (DB = new BDSoftPiebmDataContext()) { DB.cp_InsertarUsuario(oc.User, oc.Ocupacion, oc.Email, oc.Contras); DB.SubmitChanges(); } } catch (Exception ex) { throw new DatosExcepciones("Error al insertar el usuario.", ex); } finally { DB = null; } } public static void EliminarUsuario(Usuario oc) { BDSoftPiebmDataContext DB = null; try { using (DB = new BDSoftPiebmDataContext()) { DB.cp_EliminarUsuario(oc.ID_Usuario); DB.SubmitChanges(); } } catch (Exception ex) { throw new DatosExcepciones("Error al eliminar el usuario.", ex); } finally { DB = null; } } } } <file_sep>using Entidades; using Logica; using System; using System.Linq; using System.Windows.Forms; namespace AppSistemaInventarioPIEBM { public partial class FrmEditProducto : Form { public FrmEditProducto() { InitializeComponent(); CenterToScreen(); } public int val; public Producto pa = new Producto(); private void bunifuThinButton24_Click(object sender, EventArgs e) { this.Close(); } public Producto crearObjeto() { pa.ID_Producto = pa.ID_Producto; pa.Cantidad = (int)txtCant.Value; pa.Descripcion = txtDescrp.Text; pa.Estado = cbEstado.selectedValue; pa.Fecha = dateGrid.Value; pa.Articulos = txtProdu.Text; pa.Ubicacion = txtUbicac.Text; pa.Precio_Aproximado = Convert.ToDouble(txtPrecio.Text); return pa; } private void pictureBox2_Click(object sender, EventArgs e) { this.Close(); } int posY = 0; int posX = 0; private void panel1_MouseMove(object sender, MouseEventArgs e) { if (e.Button != MouseButtons.Left) { posX = e.X; posY = e.Y; } else { Left = Left + (e.X - posX); Top = Top + (e.Y - posY); } } private void llenarCampos() { txtCant.Value = pa.Cantidad; txtDescrp.Text = pa.Descripcion; txtProdu.Text = pa.Articulos; txtUbicac.Text = pa.Ubicacion; for (int i = 0; i < cbEstado.Items.Length; i++) { if (pa.Estado.Equals(cbEstado.Items[i])) { cbEstado.selectedIndex = i; } } dateGrid.Value = pa.Fecha; txtPrecio.Text = pa.Precio_Aproximado.ToString(); } private void panel1_Paint(object sender, PaintEventArgs e) { } private void FrmEditProducto_Load(object sender, EventArgs e) { if (val == 2) { llenarCampos(); } if (val == 1) { dateGrid.Value = DateTime.Now; } } private bool validarDatos() { if (txtCant.Value == 0 || txtDescrp.Text.Equals("") || txtProdu.Text.Equals("") || txtUbicac.Text.Equals("") || cbEstado.selectedIndex == -1 || txtPrecio.Text.Equals("")) { MessageBox.Show("Por favor, complete todos los campos"); return false; } else { if (txtPrecio.Text.Contains('.') == true) { MessageBox.Show("Separe los decimales con una coma(,)"); return false; } else { return true; } } } ProductoLN pln = new ProductoLN(); private void bunifuThinButton25_Click(object sender, EventArgs e) { if (val == 1) { if (validarDatos() == true) { Producto pr = crearObjeto(); if (pln.CreateProducto(pr)) { MessageBox.Show("Articulo Ingresado con exito"); } this.Close(); } } if (val == 2) { if (validarDatos() == true) { Producto pr = crearObjeto(); if (pln.UpdateProducto(pr)) { MessageBox.Show("Articulo Modificado con exito"); } this.Close(); } } } private void txtPrecio_TextChanged(object sender, EventArgs e) { } private void txtPrecio_KeyPress(object sender, KeyPressEventArgs e) { if (char.IsLetter(e.KeyChar)) { e.Handled = true; MessageBox.Show("No se permiten letras"); } } } } <file_sep># Softpiebm Software de inventario para la Primera Iglesia Evangélica Bautista de Machala <file_sep>using Datos; using Entidades; using System; using System.Collections.Generic; namespace Logica { public class UsuarioLN { public List<Usuario> MostrarUsuarioFitro(string busqueda) { List<Usuario> Lista = new List<Usuario>(); Usuario oc; try { List<cp_ListarUsuarioResult> auxLista = UsuarioCD.ListarUsuarioFiltro(busqueda); foreach (cp_ListarUsuarioResult aux in auxLista) { oc = new Usuario(aux.ID_Usuario, aux.Usuario, aux.Ocupación, aux.Email, aux.Contraseña); Lista.Add(oc); } } catch (Exception ex) { throw new LogicaExcepciones("Error al listar los usuario.", ex); } return Lista; } public List<VistaUsuario> MostrarVistaUsuarioFitro(string busqueda) { List<VistaUsuario> Lista = new List<VistaUsuario>(); VistaUsuario oc; try { List<cp_ListarVistaUsuarioResult> auxLista = UsuarioCD.ListarVistaUsuarioFiltro(busqueda); foreach (cp_ListarVistaUsuarioResult aux in auxLista) { oc = new VistaUsuario(aux.ID_Usuario, aux.Usuario, aux.Ocupación); Lista.Add(oc); } } catch (Exception ex) { throw new LogicaExcepciones("Error al listar los usuario.", ex); } return Lista; } public bool CreateUsuario(Usuario oc) { try { UsuarioCD.InsertarUsuario(oc); return true; } catch (Exception ex) { throw new LogicaExcepciones("Error al crear el usuario.", ex); } } public bool DeleteUsuario(Usuario oc) { try { UsuarioCD.EliminarUsuario(oc); return true; } catch (Exception ex) { throw new LogicaExcepciones("Error al eliminar el usuario.", ex); } } } }
b8903bb2b65b314f16950ca654739cfcc24d9d06
[ "Markdown", "C#" ]
22
C#
GustavitoH/Softpiebm
e704adfed4664ce8f5fa4b89cba0fe108ade1f83
cccb70c578cda8d21f9014d5fab440aed4709ab0
refs/heads/master
<repo_name>M2odrigo/keras_metrics<file_sep>/Keras_sonar_dataset/perceptron_sonar.py import numpy as np import csv from matplotlib import pyplot as plt dataset = np.loadtxt('hidden_0_activations.csv', delimiter=",") cant_input=30 # split into input (X) and output (Y) variables X = dataset[:,0:cant_input] #add the bias term -1 X = np.insert(X, cant_input,-1, axis=1) y = dataset[:,cant_input] y[y == 0] = -1 def perceptron_sgd_plot(X, Y): ''' train perceptron and plot the total loss in each epoch. :param X: data samples :param Y: data labels :return: weight vector as a numpy array ''' w = np.zeros(len(X[0])) eta = 0.5 #n = 11 n = 500 errors = [] mala_clasif = [] for t in range(n): total_error = 0 cont_error = 0 cont_total_input=0 for i, x in enumerate(X): cont_total_input=cont_total_input+1 if (np.dot(X[i], w)*Y[i]) <= 0.0: total_error += (np.dot(X[i], w)*Y[i]) w = w + eta*X[i]*Y[i] cont_error = cont_error +1 errors.append(total_error*-1) mala_clasif.append(cont_error) #mn,idx = min((mala_clasif[i],i) for i in range(len(mala_clasif))) mala_clasif.sort() print(mala_clasif) mn = mala_clasif[2] error_minimo = mn/cont_total_input print(" error minimo "+ str(mn) + ' acc. ' +str(100 -(error_minimo*100)) + ' total entradas: ' + str(cont_total_input)) #print(errors) #plt.plot(errors) #plt.xlabel('Epoch') #plt.ylabel('Total Loss') #plt.show() return w def perceptron_plot(filename, layer, e, cant_input): dataset = np.loadtxt(filename, delimiter=",") # split into input (X) and output (Y) variables X = dataset[:,0:int(cant_input)] #add the bias term -1 X = np.insert(X, int(cant_input),-1, axis=1) Y = dataset[:,int(cant_input)] Y[Y == 0] = -1 w = np.zeros(len(X[0])) eta = 1 n = 100 errors = [] mala_clasif = [] for t in range(n): total_error = 0 cont_error = 0 cont_total_input=0 for i, x in enumerate(X): cont_total_input=cont_total_input+1 if (np.dot(X[i], w)*Y[i]) <= 0.0: total_error += (np.dot(X[i], w)*Y[i]) #print(total_error) w = w + eta*X[i]*Y[i] cont_error = cont_error +1 errors.append(total_error*-1) mala_clasif.append(cont_error) #obtenemos el error minimo entre los epoch y su ubicacion-indice #mn,idx = min((mala_clasif[i],i) for i in range(len(mala_clasif))) #ordenamos la lista y agarramos el segundo o tercer valor, el primero no cuenta porque todo es muy proximo a zero debido a la inicializacion de los pesos en zeros. mala_clasif.sort() print(mala_clasif) mn = mala_clasif[2] #vamos a calcular la metrica por el menor valor y por el utlimo valor de error en los epoch error_minimo = mn/cont_total_input error_ultimo_epoch = cont_error/cont_total_input print(mala_clasif) #cargamos los valores a escribir en el CSV #se carga el error minimo del perceptron y el ultimo error en el ultimo epoch #fields=[layer, e, str(cont_total_input),mn, idx, error_minimo,error_ultimo_epoch] #se carga solo el error minimo entre los epochs del percecptron fields=[layer, e, str(cont_total_input),mn, error_minimo,str(100 -(error_minimo*100))] with open('train_hidden_perceptron_error.csv', 'a') as f: writer = csv.writer(f) writer.writerow(fields) return fields plt.plot(errors) plt.xlabel('Epoch') plt.ylabel('Total Loss') #plt.show() #print(perceptron_sgd_plot(X,y)) print(perceptron_plot('hidden_0_activations.csv', 0, 500, 30)) <file_sep>/graph_metric_function.py import numpy as np import matplotlib.pyplot as plt #X --> layers #Y --> valores de las metricas #Epoch --> array con los epoch de cada metrica def graph_metric(x,y, epoch): i = 0 for l in x: #sirve para aumentar el subplot y se vean una sola vista los diferentes graficos #por cada layer, significa una clase diferente clase = i i = i+1 print('layer : ', i, ' values ', l) #se recibiran N conjuntos de metricas, la primera es la clase 0, se accede por el indice i sin el aumento ++ for index, m in enumerate(y[clase]): label_epoch = 'epoch {0}'.format(epoch[index+1]) print(label_epoch) print("x", l) print("y", m) #solamente en una figura, si se tiene que separar las figuras por clase, asignar plt.figure(i) #plt.figure(1) #numRows, numCols, figure (211) --- (212) plt.subplot(210+i) #titulo del graph plt.title('Class {0}'.format(clase)) #titulos de los ejes plt.ylabel('metricas',color='red') plt.xlabel('layers',color='red') #establecer los valores para los ejes plt.axis([xmin,xmax,ymin,ymax]) #plt.axis([0, 3, 0, 60]) plt.plot(l, m, label=label_epoch) plt.legend() plt.show() <file_sep>/mnist_train/mnist_calc.py # imports for array-handling and plotting import numpy as np import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt # let's keep our keras backend tensorflow quiet import os os.environ['TF_CPP_MIN_LOG_LEVEL']='3' import csv # for testing on CPU #os.environ['CUDA_VISIBLE_DEVICES'] = '' # keras imports for the dataset and building our neural network from keras.datasets import mnist from keras.models import Sequential, load_model from keras.layers.core import Dense, Dropout, Activation from keras.utils import np_utils from mnist_varianza import calc_varianza from mnist_varianza import calc_media from mnist_varianza import get_values_classes (X_train, y_train), (X_test, y_test) = mnist.load_data() # let's print the shape before we reshape and normalize print("X_train shape", X_train.shape) print("y_train shape", y_train.shape) print("X_test shape", X_test.shape) print("y_test shape", y_test.shape) # building the input vector from the 28x28 pixels X_train = X_train.reshape(60000, 784) X_test = X_test.reshape(10000, 784) X_train = X_train.astype('float32') X_test = X_test.astype('float32') # normalizing the data to help with the training X_train /= 255 X_test /= 255 # print the final input shape ready for training print("Train matrix shape", X_train.shape) print("Test matrix shape", X_test.shape) print(np.unique(y_train, return_counts=True)) # one-hot encoding using keras' numpy-related utilities n_classes = 10 print("Shape before one-hot encoding: ", y_train.shape) Y_train = np_utils.to_categorical(y_train, n_classes) Y_test = np_utils.to_categorical(y_test, n_classes) print("Shape after one-hot encoding: ", Y_train.shape) # building a linear stack of layers with the sequential model model = Sequential() model.add(Dense(512, input_shape=(784,))) model.add(Activation('relu')) #dropout helps avoid the overfittin by zero-ing some random input in each iteration model.add(Dropout(0.2)) model.add(Dense(512)) model.add(Activation('relu')) model.add(Dropout(0.2)) model.add(Dense(10)) model.add(Activation('softmax')) # compiling the sequential model model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adam') contador_zero = 0 param_epoch= "0,1,2" param_epoch = param_epoch.split(',') param_calses = "0,1,2,3,4,5,6,7,8,9" param_calses = param_calses.split(',') varianza_epoch_zero = np.array([]) varianza_classes = np.array([]) list_varianzas = [] list_metrics = [] for e in param_epoch: # training the model and saving metrics in history history = model.fit(X_train, Y_train, batch_size=128, epochs=int(e), verbose=2, validation_data=(X_test, Y_test)) cont = 0 print('####PREDICTION#####') prediction = model.predict_proba(X_test) for index,p in enumerate(prediction): cont = cont + 1 if cont > 50: break r2 = [format(x, 'f') for x in p] print("r init " , r2) fields=[e,r2,str(Y_test[index]), str(Y_test[index].argmax())] with open('prediction.csv', 'a') as f: writer = csv.writer(f) writer.writerow(fields) for cl in param_calses: cl=str(cl) print("vamos a calcular para la clase ", cl) calculo_tmp = calc_media(prediction, cl, Y_test) media = calculo_tmp [0] contador = calculo_tmp[1] print("media_function", media, ' cont', contador) r = get_values_classes(prediction, cl, Y_test) print('r ', r) varianza = calc_varianza(r, media, cl, contador) print('varianza class ',cl , "equals to: ", varianza) print("epoch : ", e) if(str(e) == '0'): if np.any(varianza_epoch_zero): varianza_epoch_zero= np.append(varianza_epoch_zero, [varianza], axis=0) else: varianza_epoch_zero = [varianza] else: list_varianzas.append([varianza]) #if np.any(varianza_classes): # varianza_classes= np.append(varianza_classes, [varianza], axis=0) #else: # varianza_classes = np.array([varianza]) varianza_classes = np.asarray(list_varianzas) print ('varianza_epoch_zero >>>> ', varianza_epoch_zero) print ('varianza_classes >>>> ', varianza_classes) print("END") print ('varianza_epoch_zero >>>> ', varianza_epoch_zero) print ('varianza_classes >>>> ', varianza_classes) tmpv = np.reshape(varianza_classes, (-1, 10)) print ('varianza_classes >>>> ', tmpv) varianza_classes = tmpv for index, v in enumerate(varianza_classes): print('v : ', varianza_classes[index]) print('varianza_epoch_zero : ', varianza_epoch_zero) metric = np.divide(varianza_classes[index], varianza_epoch_zero) list_metrics.append([metric]) #metrics = np.divide(varianza_classes, varianza_epoch_zero) list_metrics = np.reshape(list_metrics, (-1, 10)) print('list metrics ',list_metrics) <file_sep>/experiment_initial_values/predict_diabetes.py # Create first network with Keras from keras.models import Sequential from keras.layers import Dense import numpy import csv from keras import optimizers import keras loss = 'binary_crossentropy' activation1 = 'sigmoid' activation2 = 'sigmoid' optimizer= 'adam' kernel_initializer = 'uniform' # fix random seed for reproducibility #seed = 7 #numpy.random.seed(seed) # load pima indians dataset dataset = numpy.loadtxt("pima-indians-diabetes.csv", delimiter=",") # split into input (X) and output (Y) variables X = dataset[:,0:8] Y = dataset[:,8] dataset = numpy.loadtxt("pima-indians-diabetes-test.csv", delimiter=",") # split into input (X) and output (Y) variables X_test = dataset[:,0:8] Y_test= dataset[:,8] # create model model = Sequential() model.add(Dense(12, input_dim=8, kernel_initializer= kernel_initializer, activation=activation1)) model.add(Dense(8, kernel_initializer=kernel_initializer, activation=activation1)) model.add(Dense(1, kernel_initializer=kernel_initializer, activation=activation2)) # Compile model model.compile(loss= loss, optimizer=optimizer, metrics=['accuracy']) # Fit the model model.fit(X, Y, epochs=0, batch_size=10, verbose=2) # calculate predictions print('####PREDICTION#####') config = 'loss: '+loss + ' kernel_initializer: '+ str(kernel_initializer) +' activation1: ' + activation1 + ' activation2: ' + activation2 + ' optimizer: '+optimizer predictions = model.predict(X_test) for index,p in enumerate(predictions): fields=[str(p),str(Y_test[index]), config] with open('prediction.csv', 'a') as f: writer = csv.writer(f) writer.writerow(fields) # round predictions rounded = [round(x[0]) for x in predictions] print(rounded) <file_sep>/Keras_sonar_dataset/construct_sonar.py #funcion para construir la red y entrenarla ##X conjunto de entrada ##Y salida esperada ##cant_input cantidad de entradas que recibira el primer hidden, serian las neuronas del input layer ##cant_layers cantidad de capas desde el hidden1 hasta el output ##cant_epoch array con los epochs que realizara ##batch es opcional, establece de a cuantos lotes se leera el conjunto de entrada X from keras.models import Sequential from keras.layers import Dense from sklearn.preprocessing import StandardScaler from keras.wrappers.scikit_learn import KerasClassifier from sklearn.model_selection import cross_val_score from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import StratifiedKFold from sklearn.preprocessing import StandardScaler from sklearn.pipeline import Pipeline import numpy as np import csv import os import pandas def construct_train_nn (X, Y, cant_input, cant_layers, cant_nodos, cant_epoch, batch=0): if os.path.isfile('hidden_perceptron_error.csv'): os.remove('hidden_perceptron_error.csv') indice_capas = np.arange((np.count_nonzero(cant_layers))) print("recibimos capas ", indice_capas) metric_zero=np.array([]) metric_one = np.array([]) initial_desviation_zero=np.array([]) initial_desviation_one = np.array([]) desviation_epoch_zero = np.array([]) desviation_epoch_one = np.array([]) activations = [] for e in cant_epoch: #np.random.seed(14) e=int(e) model = Sequential() for layer in indice_capas: if layer==0: model.add(Dense(int(cant_nodos[layer]), input_dim=int(cant_input),activation='sigmoid')) else: model.add(Dense(int(cant_nodos[layer]), activation='sigmoid')) print("Configuracion de la red: ", model.summary()) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) print("entrenando para ", e, " epochs") model.fit(X, Y, epochs=e, batch_size=int(batch)) print('####PREDICTION#####') prediction = model.predict_proba(X) # evaluate the model scores = model.evaluate(X, Y) print(scores) acc = ("%.2f%%" % (scores[1]*100)) row = str(e)+","+str(acc) fields=[str(e),str(acc)] # 'a' para agregar contenido al CSV # 'wb' para sobre-escribir el archivo CSV with open('epoch_acc.csv', 'a') as f: writer = csv.writer(f) writer.writerow(fields) if(e == 0): #extraer las activaciones for layer in indice_capas: print("###extraer las activaciones y calcular la desviacion por clase") print("layer: ", layer) print("cant_nodos: ", cant_nodos[layer]) print("cant input: ", cant_input) if layer==0: activations = get_activations(int(cant_nodos[layer]), cant_input, model.layers[layer].get_weights(), X) print('###############') print(activations) print("activation> ", activations.shape) print("Y> ", Y.shape) save_activation (e, cant_nodos[layer], activations, Y, layer, indice_capas[-1]) else: print("cant_nodos anterior: ", cant_nodos[layer-1]) activations_layers = get_activations(int(cant_nodos[layer]), int(cant_nodos[layer-1]), model.layers[layer].get_weights(), activations) activations = activations_layers save_activation (e, cant_nodos[layer], activations, Y, layer, indice_capas[-1]) desviation = calc_metric(layer, int(cant_nodos[layer]), activations_layers, Y) else: #extraer las activaciones for layer in indice_capas: print("###extraer las activaciones y calcular la desviacion por clase") print("layer: ", layer) print("cant_nodos: ", cant_nodos[layer]) print("cant input: ", cant_input) if layer==0: activations = get_activations(int(cant_nodos[layer]), cant_input, model.layers[layer].get_weights(), X) save_activation (e, cant_nodos[layer], activations, Y, layer, indice_capas[-1]) else: print("cant_nodos anterior: ", cant_nodos[layer-1]) activations_layers = get_activations(int(cant_nodos[layer]), int(cant_nodos[layer-1]), model.layers[layer].get_weights(), activations) activations = activations_layers save_activation (e, cant_nodos[layer], activations, Y, layer, indice_capas[-1]) def get_activations (cant_nodos, cant_input, weights, activations): model = Sequential() model.add(Dense(cant_nodos, input_dim=cant_input, weights=weights, activation='sigmoid')) activations = model.predict_proba(activations) activations_array = np.asarray(activations) return activations_array def save_activation (e, cant_nodos, activations, Y, layer, last_layer): if(layer != last_layer): print("epoch ", e, "cant nodos: ", cant_nodos, "activation shape: ", activations.shape) #print(activations) if os.path.isfile('hidden_'+str(layer) +'_activations.csv'): os.remove('hidden_'+str(layer) +'_activations.csv') for index, activ in enumerate(Y): r2 = ['{:f}'.format(x) for x in activations[index]] fields=[r2, Y[index]] with open('hidden_'+str(layer) +'_activations.csv', 'a') as f: writer = csv.writer(f) writer.writerow(fields) # Read in the file with open('hidden_'+str(layer) +'_activations.csv', 'r') as file : filedata = file.read() # Replace the target string filedata = filedata.replace('[', '') filedata = filedata.replace(']', '') filedata = filedata.replace('"', '') filedata = filedata.replace('\'', '') # Write the file out again with open('hidden_'+str(layer) +'_activations.csv', 'w') as file: file.write(filedata) split(open('hidden_'+str(layer) +'_activations.csv', 'r')); filename1 = 'output_1.csv' filename2 = 'output_2.csv' perceptron_plot(filename1, layer, e,cant_nodos) perceptron_plot(filename2, layer, e,cant_nodos) #input('continue?') else: print("capa actual " + str(layer)) print("capa final " + str(last_layer)) print("llegamos al output layer") param_layers = 2 param_layers = np.arange(1, (int(param_layers)+1)) param_epoch= "800" print(param_epoch) param_epoch = param_epoch.split(',') #cantidad de nodos del input layer param_input = 60 #cantidad de nodos por cada capa, array de nodos param_nodos = "30,1" param_nodos = param_nodos.split(',') ##variables batch_size = 100 ### # fix random seed for reproducibility seed = 7 np.random.seed(seed) # load dataset dataframe = pandas.read_csv("sonar.csv", header=None) dataset = dataframe.values # split into input (X) and output (Y) variables X = dataset[:,0:60].astype(float) Y = dataset[:,60] # encode class values as integers, convierte el output actual (R/M) en clases binarias (0/1) encoder = LabelEncoder() encoder.fit(Y) encoded_Y = encoder.transform(Y) #normalize the data scaler = StandardScaler() #normalizar los valores del train set #X = scaler.fit_transform(X) construct_train_nn(X, encoded_Y, param_input, param_layers, param_nodos, param_epoch, batch_size) <file_sep>/train_nn_function.py import sys param_epoch = sys.argv[1] train_nn(param_epoch) initial_desviation = [] def train_nn (cant_epoch, batch=0): desviation_epoch = [] #para poder reproducir los resultados, limitamos el "random" de las inicializaciones np.random.seed(7) X = np.array([[0,0],[0,1],[1,0],[1,1]]) y = np.array([[0],[1],[1],[0]]) for e in cant_epoch: model = Sequential() model.add(Dense(2, input_dim=2,activation='sigmoid')) model.add(Dense(2, activation='sigmoid')) model.add(Dense(1, activation='sigmoid')) sgd = SGD(lr=0.5) model.compile(loss='binary_crossentropy', optimizer=sgd) print("entrenando para ", e, " epochs") model.fit(X, y, epochs=e) print(' ') print('####PREDICTION#####') print(model.predict_proba(X)) #extraer las activaciones ##hidden 1 model2 = Sequential() model2.add(Dense(2, input_dim=2, weights=model.layers[0].get_weights(), activation='sigmoid')) activations = model2.predict_proba(X) a = np.asarray(activations) desviation_one = calc_metric(1, 2, a, y) ##hidden 2 model3 = Sequential() model3.add(Dense(2, input_dim=2, weights=model.layers[1].get_weights(), activation='sigmoid')) activations2 = model3.predict_proba(activations) c = np.asarray(activations2) desviation_two = calc_metric(2, 2, c, y) ##output model4 = Sequential() model4.add(Dense(1, input_dim=2, weights=model.layers[2].get_weights(), activation='sigmoid')) activations3 = model4.predict_proba(activations2) b = np.asarray(activations3) desviation_three = calc_metric(3, 1, b, y) if(e == 0): initial_desviation = np.array([desviation_one, desviation_two, desviation_three]) print(initial_desviation) else: desviation_epoch = np.array([desviation_one, desviation_two, desviation_three]) print(desviation_epoch) input('enter para continuar') <file_sep>/construc_train_nn_function.py #funcion para construir la red y entrenarla ##X conjunto de entrada ##Y salida esperada ##cant_input cantidad de entradas que recibira el primer hidden, serian las neuronas del input layer ##cant_layers cantidad de capas desde el hidden1 hasta el output ##cant_epoch array con los epochs que realizara ##batch es opcional, establece de a cuantos lotes se leera el conjunto de entrada X from desviation_function import calc_metric from graph_metric_function import graph_metric from keras.models import Sequential from keras.layers import Dense from sklearn.preprocessing import StandardScaler import numpy as np import csv def construct_train_nn (X, Y, cant_input, cant_layers, cant_nodos, cant_epoch, batch=0): indice_capas = np.arange((np.count_nonzero(cant_layers))) print("recibimos capas ", indice_capas) metric_zero=np.array([]) metric_one = np.array([]) initial_desviation_zero=np.array([]) initial_desviation_one = np.array([]) desviation_epoch_zero = np.array([]) desviation_epoch_one = np.array([]) activations = [] for e in cant_epoch: #np.random.seed(14) e=int(e) model = Sequential() for layer in indice_capas: if layer==0: model.add(Dense(int(cant_nodos[layer]), input_dim=int(cant_input),activation='sigmoid')) else: model.add(Dense(int(cant_nodos[layer]), activation='sigmoid')) print("Configuracion de la red: ", model.summary()) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) print("entrenando para ", e, " epochs") model.fit(X, Y, epochs=e, batch_size=int(batch)) print('####PREDICTION#####') prediction = model.predict_proba(X_test) for index,p in enumerate(prediction): fields=[str(e),str(p),str(Y_test[index])] with open('prediction.csv', 'a') as f: writer = csv.writer(f) writer.writerow(fields) # evaluate the model scores = model.evaluate(X, Y) acc = ("%.2f%%" % (scores[1]*100)) row = str(e)+","+str(acc) fields=[str(e),str(acc)] # 'a' para agregar contenido al CSV # 'wb' para sobre-escribir el archivo CSV with open('epoch_acc.csv', 'a') as f: writer = csv.writer(f) writer.writerow(fields) if(e == 0): #extraer las activaciones for layer in indice_capas: print("###extraer las activaciones y calcular la desviacion por clase") print("layer: ", layer) print("cant_nodos: ", cant_nodos[layer]) print("cant input: ", cant_input) if layer==0: activations = get_activations(int(cant_nodos[layer]), cant_input, model.layers[layer].get_weights(), X) desviation = calc_metric(layer, int(cant_nodos[layer]), activations, Y) initial_desviation_zero = desviation[0] initial_desviation_one = desviation[1] else: print("cant_nodos anterior: ", cant_nodos[layer-1]) activations_layers = get_activations(int(cant_nodos[layer]), int(cant_nodos[layer-1]), model.layers[layer].get_weights(), activations) activations = activations_layers desviation = calc_metric(layer, int(cant_nodos[layer]), activations_layers, Y) initial_desviation_zero = np.concatenate((initial_desviation_zero, desviation[0])) initial_desviation_one = np.concatenate((initial_desviation_one, desviation[1])) print("initial_desviation_zero", initial_desviation_zero) print("initial_desviation_one", initial_desviation_one) else: #extraer las activaciones for layer in indice_capas: print("###extraer las activaciones y calcular la desviacion por clase") print("layer: ", layer) print("cant_nodos: ", cant_nodos[layer]) print("cant input: ", cant_input) if layer==0: activations = get_activations(int(cant_nodos[layer]), cant_input, model.layers[layer].get_weights(), X) desviation = calc_metric(layer, int(cant_nodos[layer]), activations, Y) desviation_epoch_zero = desviation[0] desviation_epoch_one = desviation[1] else: print("cant_nodos anterior: ", cant_nodos[layer-1]) activations_layers = get_activations(int(cant_nodos[layer]), int(cant_nodos[layer-1]), model.layers[layer].get_weights(), activations) activations = activations_layers desviation = calc_metric(layer, int(cant_nodos[layer]), activations_layers, Y) desviation_epoch_zero = np.concatenate((desviation_epoch_zero, desviation[0])) desviation_epoch_one = np.concatenate((desviation_epoch_one, desviation[1])) print("desviation_epoch_zero", desviation_epoch_zero) print("desviation_epoch_one", desviation_epoch_one) print("metricas para epoch ---->", e) result_zero = np.divide(desviation_epoch_zero,initial_desviation_zero) result_one = np.divide(desviation_epoch_one,initial_desviation_one) print(result_zero) print(result_one) ##ir agregando las metricas por cada epoch para la clase 0 if np.any(metric_zero): metric_zero= np.append(metric_zero, [result_zero], axis=0) else: metric_zero = [result_zero] print("metricas zero ", metric_zero) ##ir agregando las metricas por cada epoch para la clase 1 if np.any(metric_one): metric_one= np.append(metric_one, [result_one], axis=0) else: metric_one = [result_one] print("metricas one ", metric_one) if np.any(metric_zero): print ('vamos a graficar') print ([metric_zero,metric_one]) #existe metrica one --> hay otra clase, duplicar el parametro "layers" asi su metrica se puede graph if np.any(metric_one): graph_metric([param_layers, param_layers], [metric_zero,metric_one], param_epoch) else: graph_metric(param_layers, metric_zero, param_epoch) def get_activations (cant_nodos, cant_input, weights, activations): model = Sequential() model.add(Dense(cant_nodos, input_dim=cant_input, weights=weights, activation='sigmoid')) activations = model.predict_proba(activations) activations_array = np.asarray(activations) return activations_array param_layers = 4 param_layers = np.arange(1, (int(param_layers)+1)) #param_epoch = input('cantidad epochs ') param_epoch= "0,100" #for i in np.arange(0,201,100): # if(param_epoch==""): # param_epoch = str(i) # else: # param_epoch = param_epoch + "," + str(i) print(param_epoch) param_epoch = param_epoch.split(',') #cantidad de nodos del input layer param_input = 8 #cantidad de nodos por cada capa, array de nodos param_nodos = "12,8,8,1" param_nodos = param_nodos.split(',') ##variables batch_size = 100 ### # load pima indians dataset dataset = np.loadtxt("pima-indians-diabetes.csv", delimiter=",") #normalize the data scaler = StandardScaler() # split into input (X) and output (Y) variables X = dataset[:,0:8] Y = dataset[:,8] # load TEST pima indians dataset dataset = np.loadtxt("pima-indians-diabetes-test.csv", delimiter=",") X_test = dataset[:,0:8] Y_test = dataset[:,8] #normalizar los valores del train set #X = scaler.fit_transform(X) construct_train_nn(X, Y, param_input, param_layers, param_nodos, param_epoch, batch_size) <file_sep>/mnist_train/mnist_train_keras.py # imports for array-handling and plotting import numpy as np import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt # let's keep our keras backend tensorflow quiet import os os.environ['TF_CPP_MIN_LOG_LEVEL']='3' import csv # for testing on CPU #os.environ['CUDA_VISIBLE_DEVICES'] = '' # keras imports for the dataset and building our neural network from keras.datasets import mnist from keras.models import Sequential, load_model from keras.layers.core import Dense, Dropout, Activation from keras.utils import np_utils (X_train, y_train), (X_test, y_test) = mnist.load_data() # let's print the shape before we reshape and normalize print("X_train shape", X_train.shape) print("y_train shape", y_train.shape) print("X_test shape", X_test.shape) print("y_test shape", y_test.shape) # building the input vector from the 28x28 pixels X_train = X_train.reshape(60000, 784) X_test = X_test.reshape(10000, 784) X_train = X_train.astype('float32') X_test = X_test.astype('float32') # normalizing the data to help with the training X_train /= 255 X_test /= 255 # print the final input shape ready for training print("Train matrix shape", X_train.shape) print("Test matrix shape", X_test.shape) print(np.unique(y_train, return_counts=True)) # one-hot encoding using keras' numpy-related utilities n_classes = 10 print("Shape before one-hot encoding: ", y_train.shape) Y_train = np_utils.to_categorical(y_train, n_classes) Y_test = np_utils.to_categorical(y_test, n_classes) print("Shape after one-hot encoding: ", Y_train.shape) # building a linear stack of layers with the sequential model model = Sequential() model.add(Dense(512, input_shape=(784,))) model.add(Activation('relu')) #dropout helps avoid the overfittin by zero-ing some random input in each iteration model.add(Dropout(0.2)) model.add(Dense(512)) model.add(Activation('relu')) model.add(Dropout(0.2)) model.add(Dense(10)) model.add(Activation('softmax')) # compiling the sequential model model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adam') param_epoch= "0,1,2,3" param_epoch = param_epoch.split(',') for e in param_epoch: # training the model and saving metrics in history history = model.fit(X_train, Y_train, batch_size=128, epochs=int(e), verbose=2, validation_data=(X_test, Y_test)) print(model.summary()) cont = 0 print('####PREDICTION#####') prediction = model.predict_proba(X_test) for index,p in enumerate(prediction): cont = cont + 1 if cont > 50: break r = [format(x, 'f') for x in p] fields=[e,r,str(Y_test[index]), str(Y_test[index].argmax())] with open('prediction.csv', 'a') as f: writer = csv.writer(f) writer.writerow(fields) #print("#########outputs of input layer with 512 nodes#################") #model2 = Sequential() #model2.add(Dense(512, input_shape=(784,), weights=model.layers[0].get_weights(), activation='relu')) #model2.add(Dropout(0.2)) #activations = model2.predict(X_test) #print(activations) #a = np.asarray(activations) #roundnumpy = np.round(activations, 5) #arra = np.asarray(activations) #a = np.array_str(arra, precision=4) #np.savetxt("512nodes_batch_100_epoch_5_round.csv", a, fmt = '%.5f', delimiter=",") <file_sep>/train_normalize_data_old.py # Create your first MLP in Keras from desviation_function import calc_metric from keras.models import Sequential from keras.layers import Dense from sklearn.preprocessing import StandardScaler import numpy as np # fix random seed for reproducibility np.random.seed(7) ##variables cant_epoch = 0 batch_size = 100 ### # load pima indians dataset dataset = np.loadtxt("pima-indians-diabetes.csv", delimiter=",") #normalize the data scaler = StandardScaler() # split into input (X) and output (Y) variables X = dataset[:,0:8] Y = dataset[:,8] #normalizar los valores del train set X = scaler.fit_transform(X) # create model model = Sequential() model.add(Dense(12, input_dim=8, activation='sigmoid')) model.add(Dense(8, activation='sigmoid')) model.add(Dense(1, activation='sigmoid')) # Compile model model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # Fit the model model.fit(X, Y, epochs=cant_epoch, batch_size=batch_size) # evaluate the model scores = model.evaluate(X, Y) print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100)) print(model.summary()) print("#########outputs of hidden layer 1 with 12 nodes#################") model2 = Sequential() model2.add(Dense(12, input_dim=8, weights=model.layers[0].get_weights(), activation='sigmoid')) activations2 = model2.predict_proba(X) #print(activations2) a2 = np.asarray(activations2) desviation_one = calc_metric(1, 12, a2, Y) print("desviation_one",desviation_one) print("desviation_class0e",desviation_one[0]) print("desviation_class1e",desviation_one[1]) #np.savetxt(str(cant_epoch) + "_epoch_hidden1.csv", h2, fmt = '%.5f', delimiter=",") print("#########outputs of hidden layer 2 with 8 nodes#################") model3 = Sequential() model3.add(Dense(8, input_dim=12, weights=model.layers[1].get_weights(), activation='sigmoid')) activations3 = model3.predict_proba(activations2) #print(activations3) a3 = np.asarray(activations3) desviation_two = calc_metric(2, 8, a3, Y) print("desviation_two",desviation_two) print("desviation_class0e",desviation_two[0]) print("desviation_class1e",desviation_two[1]) #h3 = [] #for index, w in enumerate(a3): # h3.append(np.append([a3[index]], [Y[index]])) #np.savetxt(str(cant_epoch) + "_epoch_hidden2.csv", h3, fmt = '%.5f', delimiter=",") print("#########outputs of output layer with 1 node#################") model4 = Sequential() model4.add(Dense(1, input_dim=8, weights=model.layers[2].get_weights(), activation='sigmoid')) activations4 = model4.predict_proba(activations3) #print(activations4) a4 = np.asarray(activations4) desviation_three = calc_metric(3, 1, a4, Y) print("desviation_three",desviation_three) print("desviation_class0e",desviation_three[0]) print("desviation_class1e",desviation_three[1]) #h4 = [] #for index, w in enumerate(a4): # h4.append(np.append([a4[index]], [Y[index]])) #np.savetxt(str(cant_epoch) + "_epoch_output.csv", h4, fmt = '%.5f', delimiter=",") <file_sep>/train_normalize_data.py # Create your first MLP in Keras from desviation_function import calc_metric from graph_metric_function import graph_metric from keras.models import Sequential from keras.layers import Dense from sklearn.preprocessing import StandardScaler import numpy as np #funcion para entrenar la red en N epoch y un batch size def train_nn (X, Y, cant_epoch=[], batch=0): metric_zero=np.array([]) metric_one = np.array([]) for e in cant_epoch: #para poder reproducir los resultados, limitamos el "random" de las inicializaciones np.random.seed(7) e=int(e) model = Sequential() model.add(Dense(12, input_dim=8, activation='sigmoid')) model.add(Dense(8, activation='sigmoid')) model.add(Dense(1, activation='sigmoid')) #w_layer_one = model.layers[0].get_weights() #print('weights layer 0: ', w_layer_one) #print('weights layer 1') #print(model.layers[1].get_weights()) # Compile model model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # Fit the model model.fit(X, Y, epochs=e, batch_size=batch) # evaluate the model scores = model.evaluate(X, Y) print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100)) print(' ') #print('####PREDICTION#####') #print(model.predict_proba(X)) #extraer las activaciones ##hidden 1 model2 = Sequential() model2.add(Dense(12, input_dim=8, weights=model.layers[0].get_weights(), activation='sigmoid')) activations2 = model2.predict_proba(X) a2 = np.asarray(activations2) desviation_one = calc_metric(1, 12, a2, Y) print("desviation_one",desviation_one) print("desviation_class0e",desviation_one[0]) print("desviation_class1e",desviation_one[1]) ##hidden 2 model3 = Sequential() model3.add(Dense(8, input_dim=12, weights=model.layers[1].get_weights(), activation='sigmoid')) activations3 = model3.predict_proba(activations2) #print(activations3) a3 = np.asarray(activations3) desviation_two = calc_metric(2, 8, a3, Y) print("desviation_two",desviation_two) print("desviation_class0e",desviation_two[0]) print("desviation_class1e",desviation_two[1]) ##output model4 = Sequential() model4.add(Dense(1, input_dim=8, weights=model.layers[2].get_weights(), activation='sigmoid')) activations4 = model4.predict_proba(activations3) #print(activations4) a4 = np.asarray(activations4) desviation_three = calc_metric(3, 1, a4, Y) print("desviation_three",desviation_three) print("desviation_class0e",desviation_three[0]) print("desviation_class1e",desviation_three[1]) if(e == 0): initial_desviation_zero = np.concatenate((desviation_one[0], desviation_two[0], desviation_three[0])) initial_desviation_one = np.concatenate((desviation_one[1], desviation_two[1], desviation_three[1])) print("initial_desviation_zero", initial_desviation_zero) print("initial_desviation_one", initial_desviation_one) else: desviation_epoch_zero = np.concatenate((desviation_one[0], desviation_two[0], desviation_three[0])) desviation_epoch_one = np.concatenate((desviation_one[1], desviation_two[1], desviation_three[1])) print("desviation_epoch_zero", desviation_epoch_zero) print("desviation_epoch_one", desviation_epoch_one) print("metricas para epoch ---->", e) result_zero = np.divide(desviation_epoch_zero,initial_desviation_zero) result_one = np.divide(desviation_epoch_one,initial_desviation_one) print(result_zero) print(result_one) ##ir agregando las metricas por cada epoch if np.any(metric_zero): metric_zero= np.append(metric_zero, [result_zero], axis=0) else: metric_zero = [result_zero] print("metricas zero ", metric_zero) if np.any(metric_one): metric_one= np.append(metric_one, [result_one], axis=0) else: metric_one = [result_one] print("metricas one ", metric_one) if np.any(metric_zero): print ('vamos a graficar') print ([metric_zero,metric_one]) #existe metrica one --> hay otra clase, duplicar el parametro "layers" asi su metrica se puede graph if np.any(metric_one): graph_metric([param_layers, param_layers], [metric_zero,metric_one], param_epoch) else: graph_metric(param_layers, metric_zero, param_epoch) #param_layers = input('cantidad capas ') param_layers = 3 param_layers = np.arange(1, (int(param_layers)+1)) #param_epoch = input('cantidad epochs ') param_epoch = "0,10,20" param_epoch = param_epoch.split(',') ##variables batch_size = 100 ### # load pima indians dataset dataset = np.loadtxt("pima-indians-diabetes.csv", delimiter=",") #normalize the data scaler = StandardScaler() # split into input (X) and output (Y) variables X = dataset[:,0:8] Y = dataset[:,8] #normalizar los valores del train set X = scaler.fit_transform(X) initial_desviation=[] train_nn(X, Y, param_epoch, batch_size) <file_sep>/desviation_function.py import numpy as np ##funcion para calcular la desviacion def calc_metric(capa, nodos, activaciones, y): print("capa ", capa) print("nodos", nodos) print("y ", y.shape) print("activaciones ", activaciones.shape) desviation = [] h2 = [] sum_zero = [np.zeros(nodos,)] sum_one = [np.zeros(nodos,)] cont_zero = 0 cont_one = 0 class_zero = 0 class_one = 0 for index, w in enumerate(activaciones): h2.append(np.append([activaciones[index]], [y[index]])) if(y[index] == 1): cont_one = cont_one + 1 sum_one = np.sum([sum_one, activaciones[index]], axis=0) #class_one = np.append else: cont_zero = cont_zero + 1 sum_zero = np.sum([sum_zero, activaciones[index]], axis=0) print("cant zeros", cont_zero) print("cant ones", cont_one) #dividimos para hallar el promedio sum_zero[:] = [x / cont_zero for x in sum_zero] sum_one[:] = [x / cont_one for x in sum_one] #restar cada output con su media y elevar al cuadrado for index, w in enumerate(activaciones): h2.append(np.append([activaciones[index]], [y[index]])) if(y[index] == 1): #print("a2[index]",activaciones[index]) #print("sum_one ", sum_one) calc = activaciones[index] - sum_one #print("se ha restado el promedio", calc) calc = np.power(calc,2) #print("se ha elevado al cuadrado", calc) partial_sum = np.sum(calc) #print("partial sum", partial_sum) class_one = class_one + partial_sum #print("class one content", class_one) #input('') else: #print("a2[index]",activaciones[index]) #print("sum_one ", sum_zero) calc = activaciones[index] - sum_zero #print("se ha restado el promedio", calc) calc = np.power(calc,2) #print("se ha elevado al cuadrado", calc) partial_sum = np.sum(calc) #print("partial sum", partial_sum) class_zero = class_zero + partial_sum #print("class one content", class_zero) #input('') class_one = float(class_one / cont_one) class_zero = float(class_zero / cont_zero) print(capa, " Layer - Desviation class one: ", class_one) print(capa, " Layer - Desviation class zero: ", class_zero) desviation = np.array([[class_zero], [class_one]]) #se devuelven las desviaciones por clase desviation_zero = np.array([class_zero]) desviation_one = np.array([class_one]) return desviation_zero, desviation_one <file_sep>/mnist_train/mnist_varianza.py # imports for array-handling and plotting import numpy as np def calc_varianza (r, media, clase, contador): sum_tmp = 0 for num in r: print('r : ', num ) #input('') #print('vamos a restar cada array en R con la media') #print(" ") tmp = np.subtract(media, num) #print(tmp) #print('vamos a elevar al cuadrado cada diferencia') #print(" ") tmp = np.square(tmp) #print(tmp) #print('vamos a sumar todos los elementos del array') #print(" ") tmp = np.sum(tmp) #print(tmp) #print('vamos a sacar la raiz cuadrada a partir de la suma') #print(" ") tmp = np.sqrt(tmp) #print(tmp) #print('vamos a acumular para el siguiente conjunto de array') #print(" ") sum_tmp = sum_tmp + tmp varianza = 0 #print('sum_tmp', sum_tmp) if (sum_tmp == 0): return varianza varianza = sum_tmp / contador return varianza def calc_media (prediction, clase, Y_test): cont = 0 sum_class_zero = np.array([]) contador_zero=0 r=np.array([]) #print('recibimos') #print('pred ', prediction) #print('ytest', Y_test) #input('') for index,p in enumerate(prediction): cont = cont + 1 if cont > 5000: break r1 = [format(x, 'f') for x in p] r1 = [float(x) for x in p] #print(np.asarray(r)) fields=[r1,str(Y_test[index]), str(Y_test[index].argmax())] y = str(Y_test[index].argmax()) if(str(y)==str(clase)): if np.any(r): r= np.append(r, [r1], axis=0) else: r = [r1] contador_zero = contador_zero +1 if np.any(sum_class_zero): sum_class_zero = np.sum([sum_class_zero, np.asarray(r1)], axis=0) else: sum_class_zero = np.asarray(r1) #print ("sum", sum_class_zero) print ("sum class ", clase, " == ", sum_class_zero) print ("cont class",clase, " == ", contador_zero) media = np.divide(sum_class_zero, contador_zero) return media, contador_zero def get_values_classes (prediction, clase, Y_test): r=np.array([]) cont = 0 for index,p in enumerate(prediction): cont = cont + 1 if cont > 5000: break r1 = [format(x, 'f') for x in p] r1 = [float(x) for x in p] #print(np.asarray(r)) fields=[r1,str(Y_test[index]), str(Y_test[index].argmax())] y = str(Y_test[index].argmax()) if(str(y)==str(clase)): if np.any(r): r= np.append(r, [r1], axis=0) else: r = [r1] return r
61d15b613846ca3b55cc7a837114d133cc7fabe7
[ "Python" ]
12
Python
M2odrigo/keras_metrics
8457d8ef96cf5e12efbbadc40f26fbf5b4c77904
129ec56de3ec35d8a3f2a520f62b9cd918533a86
refs/heads/master
<repo_name>jjjohncedeno/ExCedenoJohnSum<file_sep>/src/test/java/SumadoraTest.java import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.junit.Test; public class SumadoraTest { Convertidor c = mock(Convertidor.class); @Test public void test() throws Exception { int[] a = {2,3}; when(c.convertir("2,3")).thenReturn(a); Sumadora s = new Sumadora(c.convertir("2,3")); assertEquals(5, s.sumar()); } @Test public void cuandoUnSoloNumeroEsUsadoSeRetornaEseValor() throws Exception { int[] a = {3}; when(c.convertir("3")).thenReturn(a); Sumadora s = new Sumadora(c.convertir("3")); assertEquals(3, s.sumar()); } @Test public void cuandoDosNumerosSonUsadosEntoncesRetornamosSuSuma() throws Exception { int[] a = {3,6}; when(c.convertir("3,6")).thenReturn(a); Sumadora s = new Sumadora(c.convertir("3,6")); assertEquals(9, s.sumar()); } @Test public void sumarMasDeDosNumeros() throws Exception { int[] a = {3,6,15,18,46,33}; when(c.convertir("3,6,15,18,46,33")).thenReturn(a); Sumadora s = new Sumadora(c.convertir("3,6,15,18,46,33")); assertEquals(121, s.sumar()); } @Test public void sumarMenosDeMil() throws Exception { int[] a = {3,1000,1001,6,1234}; when(c.convertir("3,1000,1001,6,1234")).thenReturn(a); Sumadora s = new Sumadora(c.convertir("3,1000,1001,6,1234")); assertEquals(1009, s.sumar()); } @Test public final void cuandoSeRecibenNumerosNegativosSeProduceRuntimeException() { RuntimeException exception = null; int[] a = {3,-6,15,-18,46,33}; when(c.convertir("3,-6,15,-18,46,33")).thenReturn(a); Sumadora s = new Sumadora(c.convertir("3,-6,15,-18,46,33")); try { assertEquals(1009, s.sumar()); } catch (RuntimeException e) { // TODO Auto-generated catch block exception = e; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } assertNotNull("No hubo excepcion", exception); assertEquals("Numeros negativos no permitidos: [-6, -18]", exception.getMessage()); } } <file_sep>/src/main/java/Sumadora.java public class Sumadora { private int[] nums; public Sumadora(int[] nums) { super(); this.nums = nums; } public int sumar() throws Exception{ int suma=0; int[] numneg; for ( int num : this.nums ) { if (num >= 0){ if (num <= 1000){ suma = suma + num; } }else{ throw new RuntimeException("Numeros negativos no permitidos: [-6, -18]"); } } return suma; } } <file_sep>/src/main/java/Convertidor.java public interface Convertidor { public int[] convertir(String s); }
f64396d63ef91033fef478da06a07e29d49b75d5
[ "Java" ]
3
Java
jjjohncedeno/ExCedenoJohnSum
060350f0fa710fd1733db65775a76052448cb506
e121b9e6348ece4065114eb531c92ef505490e1e
refs/heads/master
<file_sep># Layer Names When fetching recipe content, the selected text layers must be named according to the Spoonacular API response fields, *case sensitive.* Here's a listing of common and not-so-common recipe fields. ### Common fields |Layer name |Description | |:--------------------|:--------------------------------------------| |`title` |Title of the recipe | |`instructions` |Full text of recipe preparation instructions | |`extendedIngredients`|Collected list of recipe ingredients | |`creditText` |Name of recipe source | |`sourceUrl` |URL of recipe source | |`image` |URL of image | |`servings` |Number of servings | |`readyInMinutes` |Time required for recipe | ### Not-so-common fields |Layer name |Description | |:--------------------|:--------------------------------------------| |~~`dishTypes`~~ |WIP | |~~`diets`~~ |WIP | |~~`occasions`~~ |WIP | |`vegetarian` |true/false | |`vegan` |true/false | |`glutenFree` |true/false | |`dairyFree` |true/false | |`veryHealthy` |true/false | |`cheap` |true/false | |`veryPopular` |true/false | |`sustainable` |true/false | |`lowFodmap` |true/false | |`ketogenic` |true/false | |`whole30` |true/false | |`weightWatcherSmartPoints`|Weight Watcher points | |`pricePerServing` |Usually ridiculously wrong | |`gaps` |"yes"/"no" | |`healthScore` |3 | |`id` |Spoonacular recipe ID | <file_sep>const sketch = require('sketch') const { DataSupplier, UI, Settings } = sketch const os = require('os') const path = require('path') const util = require('util') const fs = require('@skpm/fs') const FOLDER = path.join(os.tmpdir(), 'com.maxdavid.sketch.foodreau-plugin') const API_ENDPOINT = 'https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/' const API_KEYS = ['title','creditText','sourceUrl','image','instructions','servings','readyInMinutes','extendedIngredients','vegetarian','vegan','glutenFree','dairyFree','veryHealthy','cheap','veryPopular','sustainable','lowFodmap','ketogenic','whole30','weightWatcherSmartPoints','pricePerServing','gaps','healthScore','id'] const API_RANDOM_PARAM = 'random?number=1' const API_NUM_RESULTS = 20 const API_QUERY_PARAM = 'search?number=' + API_NUM_RESULTS + '&query=' let API_KEY = getAPIKey() let API_OPTIONS = { 'headers': { 'X-RapidAPI-Key': API_KEY } } const BACKUP_RECIPES = JSON.parse(fs.readFileSync(context.plugin.urlForResourceNamed('backup/recipes.js').path(), 'utf8')) export function onStartup () { DataSupplier.registerDataSupplier('public.text', 'Random Recipe Title', 'SupplyRandomTitle') DataSupplier.registerDataSupplier('public.text', 'Random Recipe Source', 'SupplyRandomSource') DataSupplier.registerDataSupplier('public.text', 'Random Recipe Content from Layer Names', 'SupplyRandomContent') DataSupplier.registerDataSupplier('public.text', 'Search Recipe...', 'SearchRecipe') DataSupplier.registerDataSupplier('public.image', 'Random Recipe Image', 'SupplyRandomImage') DataSupplier.registerDataSupplier('public.image', 'Search Recipe Image...', 'SearchImage') } export function onShutdown () { DataSupplier.deregisterDataSuppliers() try { if (fs.existsSync(FOLDER)) { fs.rmdirSync(FOLDER) } } catch (err) { console.error(err) } } export function getAPIKey () { // return api key if exists, return false if not if (Settings.settingForKey('foodreau.apikey')) { return Settings.settingForKey('foodreau.apikey') } try { // if not set in plugin settings, maybe it's stored in a file? let api = '' api = require('./.secret.js') return api.spoonacular.apikey } catch (err) { return false } } export default function onSetAPIKey () { let previousKey = '' || Settings.settingForKey('foodreau.apikey') if (sketch.version.sketch < 53) { const newKey = UI.getStringFromUser("Enter your spoonacular API Key\n\nDon't have one? Register for free:\nhttps://spoonacular.com/food-api", previousKey).trim() if (newKey !== 'null') { Settings.setSettingForKey('foodreau.apikey', newKey) UI.message('API Key successfully set!') } } else { UI.getInputFromUser("Enter your spoonacular API Key\n\nDon't have one? Register for free:\nhttps://spoonacular.com/food-api", { initialValue: previousKey }, (err, newKey) => { if (err) { UI.message('No API key set! Using backup recipes...') return } else { Settings.setSettingForKey('foodreau.apikey', newKey.trim()) UI.message('API Key successfully set!') } } ) } } export function onSupplyRandomTitle (context) { const dataKey = context.data.key const items = util.toArray(context.data.items).map(sketch.fromNative) items.forEach((item, index) => { getRecipe(item, index, dataKey, 'title') }) } export function onSupplyRandomSource (context) { const dataKey = context.data.key const items = util.toArray(context.data.items).map(sketch.fromNative) items.forEach((item, index) => { getRecipe(item, index, dataKey, 'creditText') }) } export function onSupplyRandomContent (context) { const dataKey = context.data.key const items = util.toArray(context.data.items).map(sketch.fromNative) items.forEach((item, index) => { if (!API_KEYS.includes(item.name) && item.type === 'Text') { UI.message('"' + item.name + '" ' + 'is not a valid recipe field name') } else { getRecipe(item, index, dataKey, item.name) } }) } export function onSearchRecipe (context) { // retrieve previous search term. If multiple layers are selected, find the first search term in group // (thanks https://github.com/BohemianCoding/unsplash-sketchplugin/commit/2e763b049fb34cb4b072fab7147bd05b4c84faa1) let selectedLayers = sketch.getSelectedDocument().selectedLayers.layers let previousTerms = selectedLayers.map(layer => Settings.layerSettingForKey(layer, 'foodreau.search.term')) let firstPreviousTerm = previousTerms.find(term => term !== undefined) let previousTerm = firstPreviousTerm || 'Dinner' if (sketch.version.sketch < 53) { const searchTerm = UI.getStringFromUser('Enter a recipe search term...', previousTerm).trim() if (searchTerm !== 'null') { selectedLayers.forEach(layer => { Settings.setLayerSettingForKey(layer, 'foodreau.search.term', searchTerm) }) const dataKey = context.data.key const items = util.toArray(context.data.items).map(sketch.fromNative) items.forEach((item, index) => { if (!API_KEYS.includes(item.name) && item.type === 'Text') { UI.message('"' + item.name + '" ' + 'is not a valid recipe field name') } else { getRecipe(item, index, dataKey, item.name, searchTerm) } }) } } else { UI.getInputFromUser('Enter a recipe search term...', { initialValue: previousTerm }, (err, searchTerm) => { if (err) { return } else { if ((searchTerm = searchTerm.trim()) !== 'null') { selectedLayers.forEach(layer => { Settings.setLayerSettingForKey(layer, 'foodreau.search.term', searchTerm) }) } const dataKey = context.data.key const items = util.toArray(context.data.items).map(sketch.fromNative) items.forEach((item, index) => { if (!API_KEYS.includes(item.name) && item.type === 'Text') { UI.message('"' + item.name + '" ' + 'is not a valid recipe field name') } else { getRecipe(item, index, dataKey, item.name, searchTerm) } }) } } ) } } function getRecipe (item, index, dataKey, section, searchTerm) { // section must be in API_KEYS or item be an image UI.message('Fetching recipe...') if (item.type != 'Text') { section = 'image' } let url = API_ENDPOINT if (API_KEY) { if (searchTerm) { url += API_QUERY_PARAM + searchTerm } else { url += API_RANDOM_PARAM } fetch(url, API_OPTIONS) .then(res => res.json()) .then(json => { if (json.message) { return Promise.reject(json.message) } else if (typeof json.recipes !== 'undefined') { loadData(json.recipes[0][section], dataKey, index, item) } else if (typeof json.results !== 'undefined') { fetchRecipeInfo(json, dataKey, index, item, section) } else { UI.message('Invalid API key, using backup recipes...') loadData(BACKUP_RECIPES[section][Math.floor(Math.random() * BACKUP_RECIPES[section].length)], dataKey, index, item) } }) .catch(err => { console.log(err) UI.message('Invalid API key, using backup recipes...') loadData(BACKUP_RECIPES[section][Math.floor(Math.random() * BACKUP_RECIPES[section].length)], dataKey, index, item) }) } else { loadData(BACKUP_RECIPES[section][Math.floor(Math.random() * BACKUP_RECIPES[section].length)], dataKey, index, item) } function fetchRecipeInfo (response, dataKey, index, item, section) { let rand = Math.floor(Math.random() * API_NUM_RESULTS) if (section === 'image') { let imageUrl = response['baseUri'] + response.results[rand]['image'] loadData(imageUrl, dataKey, index, item) return } let url = API_ENDPOINT + response.results[rand].id + '/information' fetch(url, API_OPTIONS) .then(res => res.json()) .then(json => { if (json.message) { return Promise.reject(json.message) } else { loadData(json[section], dataKey, index, item) return json } }) .catch(err => console.log(err)) } function loadData (data, dataKey, index, item) { if (item.type === 'Text') { if (typeof data === 'object') { data = convertIngredientsArray(data) } DataSupplier.supplyDataAtIndex(dataKey, data, index) } else { return getImageFromURL(data).then(imagePath => { if (!imagePath) { return } DataSupplier.supplyDataAtIndex(dataKey, imagePath, index) }) } function convertIngredientsArray (data) { let text = '' for (var ingredient in data) { text += data[ingredient]['original'] + '\n' } return text } function getImageFromURL (url) { return fetch(url) .then(res => res.blob()) .then(saveTempFileFromImageData) .catch((err) => { console.error(err) return context.plugin.urlForResourceNamed('placeholder.png').path() }) } function saveTempFileFromImageData (imageData) { const guid = NSProcessInfo.processInfo().globallyUniqueString() const imagePath = path.join(FOLDER, `${guid}.jpg`) try { fs.mkdirSync(FOLDER) } catch (err) { // probably because the folder already exists } try { fs.writeFileSync(imagePath, imageData, 'NSData') return imagePath } catch (err) { console.error(err) return undefined } } } } <file_sep>const fs = require('fs'); const fetch = require('node-fetch'); const API_KEY = 'XXX'; const API_OPTIONS = { 'headers': { 'X-RapidAPI-Key': API_KEY } }; const JSON_KEYS = ['title','creditText','sourceUrl','image','instructions','extendedIngredients']; const BACKUP_FILE = 'recipes.js' const NUM_BACKUPS = 200; const API_ENDPOINT = 'https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/random?number=' + NUM_BACKUPS; let JSON_OBJS = createObjs(); function createBackupRecipes () { fetch(API_ENDPOINT, API_OPTIONS) .then(res =>res.json()) .then(json => { if (json.message) { return Promise.reject(json.message) } else if (typeof json.recipes !== 'undefined') { return json } else { return json } }) .then(json => processResponse(json)) .catch(err => console.log(err)) } function processResponse(json) { json['recipes'].forEach(function(recipe) { JSON_KEYS.forEach(function(entry) { let data = recipe[entry]; if (typeof data === 'object') { data = convertIngredientsArray(data) } JSON_OBJS[entry].push(data); //console.log(JSON.stringify(JSON_OBJS, null, 4)); }); }); writeField(BACKUP_FILE, JSON.stringify(JSON_OBJS, null, 4)); } function createObjs () { let OBJS = {} JSON_KEYS.forEach(function(entry) { OBJS[entry] = []; }); return OBJS } function writeField(file, entry) { fs.writeFile(file, entry, (err) => { if (err) throw err; }) } function convertIngredientsArray (data) { let text = '' for (var ingredient in data) { text += data[ingredient]['original'] + '\n' } return text } createBackupRecipes(); <file_sep>![Foodreau logo](https://github.com/maxdavid/sketch-foodreau/blob/master/assets/icon-rounded-wide.png) # Foodreau A simple Sketch plugin to fill text and image layers with recipe-related content. Useful for designing food-related layouts without resorting to Lorem Ipsum. ## Installation ### Sketch plugin manager In the 'Catalog' tab of [Sketch Plugin Manager,](https://mludowise.github.io/Sketch-Plugin-Manager/) search for 'Foodreau' ### Runner In the Runner prompt, type `install`, then hit the Tab key, then type `foodreau` ### Manual 1. Download zip and extract 2. In Sketch `Plugins > Manage Plugins...` 3. Click the cog-wheel icon in lower right, and select `Reveal Plugins Folder` 4. Move extracted zip to the Plugins directory ## Usage Can be used like other DataSupplier plugins. Right-click a layer to fill with recipe information, or use the toolbar Data dropdown. ![Usage example GIF](https://github.com/maxdavid/sketch-foodreau/raw/master/assets/foodreau-example-usage.gif) To fill text layers with the appropriate information, the text layer must be named accordingly. ![Layer naming example](https://github.com/maxdavid/sketch-foodreau/raw/master/assets/foodreau-example-layers.png) Below is a short list of the most commonly used fields: |Layer name |Description | |:--------------------|:--------------------------------------------| |`title` |Title of the recipe | |`instructions` |Full text of recipe preparation instructions | |`extendedIngredients`|Collected list of recipe ingredients | |`creditText` |Name of recipe source | |`sourceUrl` |URL of recipe source | Additional fields are [listed in the docs.](https://github.com/maxdavid/sketch-foodreau/blob/master/docs/layer-names.md) Image layer names can be anything. ## API This plugin comes bundled with a number of offline recipes that be used without restriction. They can be found [here.](https://github.com/maxdavid/sketch-foodreau/blob/master/assets/backup/recipes.js) If the offline recipes are not enough, this plugin can also connect to [Spoonacular's recipe API.](https://spoonacular.com/food-api) Register for a freemium API key through [RapidAPI.](https://rapidapi.com/spoonacular/api/recipe-food-nutrition/pricing) In the plugin menu within Sketch, navigate to the Foodreau options and click `Set API key...`. Your key will persist between sessions. #### Advanced Wanna store your API key on disk? Clone this repo, then create the file `srv/.secret.js` and store your key like so: ```javascript export const spoonacular = { 'apikey' : 'API_KEY_GOES_HERE' }; ``` Run `npm install` to rebuild the plugin, and you should be good to go.
8dee0dec2da8fcf9f1fbe8898cca48fde876bc2e
[ "Markdown", "JavaScript" ]
4
Markdown
ktomasso/sketch-foodreau
a3f3fcb00550d24ee197ec4dfb675887351e0f7a
8d9d46f404767bb4a02edb0b54399ec587c538a8
refs/heads/develop
<file_sep>import { makeStyles, Theme } from '@material-ui/core/styles'; export const useStyles = makeStyles((theme: Theme) => ({ root: { ...theme.mixins.gutters(), paddingTop: theme.spacing(2), paddingBottom: theme.spacing(2), }, footer: { backgroundColor: '#100774', marginTop: theme.spacing(8), padding: theme.spacing(4, 0), }, teamContent: { display: 'flex', flexDirection: 'column', alignItems: 'center', '& a': { margin: theme.spacing(2, 1, 0, 1), }, }, team: { display: 'flex', }, small: { width: theme.spacing(6), height: theme.spacing(6), }, large: { width: theme.spacing(7), height: theme.spacing(7), }, circle: { color: '#fff', backgroundColor: '#FF7C72', textTransform: 'uppercase', fontFamily: 'inherit', }, toolbar: { display: 'flex', justifyContent: 'space-between', [theme.breakpoints.down('xs')]: { flexDirection: 'column', alignItems: 'center', '& > *': { margin: theme.spacing(2, 1, 2, 1), }, } }, footerText: { color: '#fff', fontFamily: 'inherit', fontSize: 20, fontWeight: 600, }, copyright: { marginTop: '24px', fontSize: 16, [theme.breakpoints.down('xs')]: { textAlign: 'center' } }, logo: { [theme.breakpoints.down('xs')]: { width: 'auto', order: 2 } } })); <file_sep>import * as React from 'react'; import { makeStyles, Theme } from '@material-ui/core/styles'; export const useStyles = makeStyles((theme: Theme) => ({ root: { maxWidth: 380, borderRadius: theme.spacing(2), }, image: { borderRadius: theme.spacing(2), }, cards: { marginTop: '1rem' }, title: { fontSize: '3em', fontFamily: 'inherit', fontWeight: 600, textAlign: 'center', marginTop: '3rem', [theme.breakpoints.down('xs')]: { marginRight: '1rem', marginTop: '2rem', marginBottom: '1rem', fontSize: '2em', }, } })); <file_sep>import { fade, makeStyles, Theme } from '@material-ui/core/styles'; export const useStyles = makeStyles((theme: Theme) => ({ introText: { marginRight: '2rem', marginBottom: '2rem', marginTop: '3rem', fontSize: '3em', width: '100%', [theme.breakpoints.up('sm')]: { marginRight: 0, }, [theme.breakpoints.down('xs')]: { marginRight: '1rem', marginBottom: '1rem', fontSize: '2em', }, [theme.breakpoints.down('md')]: { textAlign: 'center' }, }, introGrid: { [theme.breakpoints.down('md')]: { flexDirection: 'column-reverse', }, }, introImg: { '& img': { width: '100%', }, }, search: { position: 'relative', borderRadius: theme.shape.borderRadius, backgroundColor: fade(theme.palette.common.white, 0.15), '&:hover': { backgroundColor: fade(theme.palette.common.white, 0.25), }, marginLeft: 0, width: '100%', [theme.breakpoints.down('md')]: { display: 'flex', justifyContent: 'center', } }, searchIcon: { padding: '0px 6px 0 7px', height: '100%', position: 'absolute', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', backgroundColor: '#91B3FA', borderRadius: '5px', }, inputRoot: { color: 'inherit', fontFamily: 'inherit', paddingLeft: 0, '&:focus': { border: '1px solid #91B3FA', outlineColor: '#91B3FA', }, }, inputInput: { padding: theme.spacing(1, 1, 1, 0), paddingLeft: `calc(1em + ${theme.spacing(4)}px)`, transition: theme.transitions.create('width'), width: '120px', color: '#100774', '&:focus': { width: '20ch', }, [theme.breakpoints.down('xs')]: { fontSize: '14px', }, }, })); <file_sep>import MapComponent from './map'; export default MapComponent; <file_sep>import UserAvatar from "./Avatar"; export default UserAvatar; <file_sep>import { makeStyles, Theme } from '@material-ui/core/styles'; export const useStyles = makeStyles((theme: Theme) => ({ '@global': { body: { margin: '0 auto', fontFamily: 'Montserrat, sans-serif', fontWeight: 600, color: '#100774', }, }, weather: { backgroundColor: '#91B3FA', boxShadow: 'none', color: 'white', padding: '20px 15px', fontSize: '20px', width: '25%', }, content: { display:'flex', justifyContent: 'center', }, item: { padding: '0 20px', textAlign: 'center', }, temp: { fontSize: '48px', }, image: { width: 'auto', }, descr: { fontSize: '15px', } }))<file_sep>import i18n from 'i18next'; import * as translationEN from './en/translation.json'; import * as translationRU from './ru/translation.json'; import * as translationES from './es/translation.json'; import LanguageDetector from 'i18next-browser-languagedetector'; const resources = { en: { translation: translationEN }, ru: { translation: translationRU }, es: { translation: translationES } }; i18n.use(LanguageDetector).init({ fallbackLng: 'en', resources }); export default i18n; <file_sep>const mapLayouts = [ { name: 'MapInk', url: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', attributes: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors', }, { name: 'Black And White', url: 'https://tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png', attributes: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors', }, { name: 'Voyager', url: 'https://{s}.basemaps.cartocdn.com/rastertiles/voyager_labels_under/{z}/{x}/{y}.png', attributes: '©OpenStreetMap, ©CartoDB', checked: true, }, { name: 'Voyager W/O Labels', url: 'https://{s}.basemaps.cartocdn.com/rastertiles/voyager_nolabels/{z}/{x}/{y}.png', attributes: '©OpenStreetMap, ©CartoDB', }, { name: 'Dark Matter', url: 'https://{s}.basemaps.cartocdn.com/rastertiles/dark_all/{z}/{x}/{y}.png', attributes: '©OpenStreetMap, ©CartoDB', }, { name: 'Dark Matter W/O Labels', url: 'https://{s}.basemaps.cartocdn.com/rastertiles/dark_nolabels/{z}/{x}/{y}.png', attributes: '©OpenStreetMap, ©CartoDB', }, { name: 'Positron', url: 'https://{s}.basemaps.cartocdn.com/rastertiles/light_all/{z}/{x}/{y}.png', attributes: '©OpenStreetMap, ©CartoDB', }, { name: 'Positron W/O Labels', url: 'https://{s}.basemaps.cartocdn.com/rastertiles/light_nolabels/{z}/{x}/{y}.png', attributes: '©OpenStreetMap, ©CartoDB', }, ]; export { mapLayouts }; <file_sep>import CountryCardsContainer from './CountryCardsContainer'; export default CountryCardsContainer; <file_sep>import styled from 'styled-components'; const Polaroid = styled.div` margin: 25px auto; width: 50%; background-color: #525ae9; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2); border-radius: 20px; `; const CountryLogo = styled.img` max-width: 100%; width: 100%; min-height: auto; border-radius: 20px; `; const Container = styled.div` text-align: center; padding: 10px 20px; `; const CountryName = styled.p` color: white; `; export { Polaroid, CountryLogo, Container, CountryName }; <file_sep>import axios from 'axios'; const URL: string = 'http://api.openweathermap.org/data/2.5/weather'; const APIKEY: string = '<KEY>'; export const fetchWeather = async(query: string) => { const {data} = await axios.get(URL, { params: { q: query, units: 'metric', APPID: APIKEY } }); return data; } <file_sep>interface ICountryApiService { getCountryData: Function, } export default class CountryApiService implements ICountryApiService { private baseUrl = 'https://restcountries.eu/rest/v2/name'; private returnedFields = 'fields=name;flag;alpha3Code;latlng;capital;timezones;currencies;region'; private getResource = async (countryName: string) => { const url = `${this.baseUrl}/${countryName}?${this.returnedFields}`; const response = await fetch(url); if (!response.ok) { throw new Error(`Could not fetch ${url}, received code is ${response.status}`); } return response.json(); }; public getCountryData = async (countryName: string) => { const result = await this.getResource(countryName); return result[0]; }; } <file_sep>import { makeStyles, Theme } from '@material-ui/core/styles'; export const useStyles = makeStyles((theme: Theme) => ({ title: { fontSize: '2em', fontFamily: 'inherit', fontWeight: 600, [theme.breakpoints.down('xs')]: { display: 'none', }, }, header: { backgroundColor: '#91B3FA', boxShadow: 'none', }, grow: { flexGrow: 1, }, inputRoot: { color: 'inherit', }, inputInput: { padding: theme.spacing(1, 1, 1, 0), paddingLeft: `calc(1em + ${theme.spacing(4)}px)`, transition: theme.transitions.create('width'), width: '100%', [theme.breakpoints.up('md')]: { width: '20ch', }, }, sectionDesktop: { display: 'flex', [theme.breakpoints.down('xs')]: { width: '100%', }, }, formControl: { margin: theme.spacing(1), justifyContent: 'center', [theme.breakpoints.down('xs')]: { flexGrow: 3, } }, selectEmpty: { marginTop: theme.spacing(2), }, menuItem: { fontFamily: 'inherit', color: '#100774', }, select: { padding: '8px', borderColor: '#fff', color: '#fff', '&:focus': { borderColor: '#fff', }, }, selectInput: { width: '60px', }, selectIcon: { fill: '#fff', }, circle: { width: 40, height: 40, margin: 8, marginRight: 0 } })); <file_sep>import spain from '../../../assets/img/resized/spain.jpg'; import minsk from '../../../assets/img/resized/minsk.jpg'; import paris from '../../../assets/img/resized/paris2.jpg'; import italy from '../../../assets/img/resized/rome.jpg'; import germany from '../../../assets/img/resized/germany.jpg'; import sweden from '../../../assets/img/resized/sweden.jpg'; import russia from '../../../assets/img/resized/moscow.jpg'; import ukraine from '../../../assets/img/resized/kiev.jpg'; import poland from '../../../assets/img/resized/warsaw.jpg'; const country1 = { id: 1, name: 'Spain', capital: 'Madrid', image: spain, preview: 'https://ratatum.com/wp-content/uploads/2018/03/1i.jpg', }; const country2 = { id: 2, name: 'Belarus', capital: 'Minsk', image: minsk, preview: 'https://d39raawggeifpx.cloudfront.net/styles/16_9_desktop/s3/articleimages/bneGeneric_Belarus_minsk_cityscape_Cropped.jpg', }; const country8 = { id: 8, name: 'France', capital: 'Paris', image: paris, preview: 'https://opentheoryproject.files.wordpress.com/2014/04/paris.jpg', }; const country4 = { id: 4, name: 'Russia', capital: 'Moscow', image: russia, preview: 'https://brand-mag.com/wp-content/uploads/Reyting-gorodov-Rossii-po-urovnyu-zhizni-2017-..jpg', }; const country9 = { id: 9, name: 'Italy', capital: 'Rome', image: italy, preview: 'https://www.roadaffair.com/wp-content/uploads/2017/09/colosseum-rome-italy-shutterstock_433413835.jpg', }; const country6 = { id: 6, name: 'Germany', capital: 'Berlin', image: germany, preview: 'https://www.kurortbest.ru/assets/images/4/germaniyu.jpg', }; const country7 = { id: 7, name: 'Sweden', capital: 'Stockholm', image: sweden, preview: 'https://avatars.mds.yandex.net/get-zen_doc/53963/pub_5e74876ef2eeaa232df9a9aa_5e748c9a45ca804afa832ad2/scale_1200', }; const country5 = { id: 5, name: 'Ukraine', capital: 'Kiev', image: ukraine, preview: 'https://next.odnaminyta.com/app/uploads/2020/08/image-66.jpg', }; const country3 = { id: 3, name: 'Poland', capital: 'Warsaw', image: poland, preview: 'https://all.accor.com/magazine/imagerie/poland_warsaw3-89bf.jpg', }; const countries = [ country1, country2, country3, country4, country5, country6, country7, country8, country9, ]; export { countries }; <file_sep>import CapitalTime from './capital-time-widget'; export default CapitalTime;
293e3fe15fae52d68c59c84e26f536de27f17179
[ "TypeScript" ]
15
TypeScript
magerrrr/Travel-App-FE
ce85bc353ba6f1841dbd89954075cbe2bd8bc14e
57dcc398b0bf018c3de3e9dfd1cddba37e04b685
refs/heads/master
<repo_name>DonatoClun/symbolicautomata-for-learning<file_sep>/SVPAlib/src/mysvpalearning/MySvpaPlayground.java package mysvpalearning; import automata.sfa.SFA; import automata.sfa.SFAInputMove; import automata.sfa.SFAMove; import automata.svpa.Internal; import automata.svpa.Return; import automata.svpa.SVPA; import automata.svpa.SVPAMove; import automata.svpa.Call; import automata.svpa.TaggedSymbol; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Random; import java.util.Set; import org.sat4j.specs.TimeoutException; import theory.characters.CharPred; import theory.intervals.UnaryCharIntervalSolver; public class MySvpaPlayground { public static void test() throws Exception { UnaryCharIntervalSolver ba = new UnaryCharIntervalSolver(); List<SFAMove<CharPred, Character>> transitions = new LinkedList<>(); transitions.add(new SFAInputMove<>(0,1, new CharPred('a'))); transitions.add(new SFAInputMove<>(0,2, new CharPred('('))); transitions.add(new SFAInputMove<>(1,0, new CharPred('+'))); transitions.add(new SFAInputMove<>(2,4, new CharPred('['))); transitions.add(new SFAInputMove<>(2,3, new CharPred('a'))); transitions.add(new SFAInputMove<>(3,2, new CharPred('+'))); transitions.add(new SFAInputMove<>(3,1, new CharPred(')'))); transitions.add(new SFAInputMove<>(3,7, new CharPred(')'))); transitions.add(new SFAInputMove<>(4,5, new CharPred('a'))); transitions.add(new SFAInputMove<>(4,6, new CharPred('{'))); transitions.add(new SFAInputMove<>(5,4, new CharPred('+'))); transitions.add(new SFAInputMove<>(5,3, new CharPred(']'))); transitions.add(new SFAInputMove<>(6,7, new CharPred('a'))); transitions.add(new SFAInputMove<>(6,2, new CharPred('('))); transitions.add(new SFAInputMove<>(7,6, new CharPred('+'))); transitions.add(new SFAInputMove<>(7,5, new CharPred('}'))); SFA<CharPred, Character> res = SFA.MkSFA(transitions, 0, Collections.singleton(1), ba); List<Character> witness = res.getWitness(ba); res = res.determinize(ba); res.createDotFile("bla", "/home/denny/Documents/research/grammarlearning/"); } public static void main(String[] args) throws Exception { test(); // UnaryCharIntervalSolver ba = new UnaryCharIntervalSolver(); // for (int n = 1; n < 5000; n++) { // try { // SVPA<CharPred, Character> svpa = getRandomSvpa(20, 2, 60, ba, n); // svpa.createDotFile("svpa", "/home/denny/Documents/research/grammarlearning/"); // // LinkedList<TaggedSymbol<Character>> witness = svpa.getWitness(ba); // if (witness.size() < 5) // continue; // System.out.println(witness.toString()); // } catch (Exception e) { // // } // } } public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; public static SVPA<CharPred, Character> getRandomSvpa(int genStates, int genFinalStates, int genTransitions, UnaryCharIntervalSolver ba, int seed) throws Exception { HashMap<Integer, List<SVPAMove<CharPred, Character>>> transitionMap = new HashMap<>(); Set<Integer> initialStates = Collections.singleton(0); List<Integer> finalStates = new LinkedList<>(); Random rnd = new Random(seed); while (--genTransitions >= 0) { int from = rnd.nextInt(genStates); List<SVPAMove<CharPred, Character>> otherTransitionsFromThisState; if (transitionMap.containsKey(from)) { otherTransitionsFromThisState = transitionMap.get(from); } else { otherTransitionsFromThisState = new LinkedList<>(); transitionMap.put(from, otherTransitionsFromThisState); } boolean toFound; int to; int maxcnt = genStates; do { toFound = true; to = rnd.nextInt(genStates); for (SVPAMove<CharPred, Character> otherTr : otherTransitionsFromThisState) { if (otherTr.to == to) { toFound = false; } } } while (!toFound && --maxcnt > 0); SVPAMove<CharPred, Character> generatedTransition; CharPred guard = new CharPred(ALPHABET.charAt(rnd.nextInt(ALPHABET.length()))); int stackState = rnd.nextInt(2); switch (rnd.nextInt(5)) { case 0: //CALL case 1: case 2: generatedTransition = new Call<>(from, to, stackState, guard); break; case 3: //INTERNAL //generatedTransition = new Internal<>(from, to, guard); //break; case 4: //RETURN case 5: case 6: generatedTransition = new Return<>(from, to, stackState, guard); break; default: throw new Exception(); } List<SVPAMove<CharPred, Character>> l; if (!transitionMap.containsKey(from)) { l = new LinkedList<>(); transitionMap.put(from, l); } else { l = transitionMap.get(from); } l.add(generatedTransition); } while (--genFinalStates >= 0) { int f = 1+rnd.nextInt(genStates-1); finalStates.add(f); } List<SVPAMove<CharPred, Character>> transitions = new ArrayList<>(); transitionMap.forEach((k,v)-> transitions.addAll(v)); SVPA<CharPred, Character> result = SVPA.MkSVPA(transitions, initialStates, finalStates, ba); return result; } } <file_sep>/SVPAlib/src/algebralearning/oracles/EquivalenceOracle.java /** * Equivalence oracle abstract class implementation * @author <NAME> */ package algebralearning.oracles; import static java.util.Objects.requireNonNull; import org.sat4j.specs.TimeoutException; public interface EquivalenceOracle <P,D> { /** * Return a counterexample between the model and the target * or null if the two models are equivalent. * * @param model The model to compare the target function against * @return A counterexample of type D or null if the two models are equivalent */ public abstract D getCounterexample(P model) throws TimeoutException; /** * Return a counterexample between the model and the target * or null if the two models are equivalent. * * @param model The model to compare the target function against * @return A counterexample of type D or null if the two models are equivalent */ public abstract Counterexample<D> getCounterexample(P model, long deadline) throws TimeoutException; class Counterexample<D> { private final D counterexample; public final boolean timeoutExceeded; public final boolean hypothesisIsCorrect; public Counterexample(D counterexample) { requireNonNull(counterexample); this.counterexample = counterexample; timeoutExceeded = false; hypothesisIsCorrect = false; } public Counterexample(boolean timeoutExceeded, boolean hypothesisIsCorrect) { if ((timeoutExceeded && hypothesisIsCorrect) || (!timeoutExceeded && !hypothesisIsCorrect)) { throw new RuntimeException("one of the two flags must be true"); } this.timeoutExceeded = timeoutExceeded; this.hypothesisIsCorrect = hypothesisIsCorrect; counterexample = null; } public D getCounterexample() { if (counterexample == null) { throw new RuntimeException("No counterexample present"); } return counterexample; } } }
99f9666b2f4d525187caccefbe3d1402cca33f6b
[ "Java" ]
2
Java
DonatoClun/symbolicautomata-for-learning
2b3e2fd9fef54b1337373efd0ee26b076c22c793
df7853bfa70f9ae8155f01ed51be1cc3cf1c356f
refs/heads/master
<file_sep>let button = document.getElementById("send"); let textInput = document.getElementById("textInput"); let list = document.getElementById("list"); button.addEventListener("click", () => { if (checkLength()) addItem(textInput.value); }) function checkLength() { if (textInput.value.length > 0) return true else return false } function addItem(item) { let row = list.insertRow(-1); let newItem = row.insertCell(0); let deleteCell = row.insertCell(1); let trashIcon = document.createElement("i"); trashIcon.setAttribute("class","fas fa-trash"); deleteCell.setAttribute("class","hide"); deleteCell.appendChild(trashIcon); let shoppingItemNode = document.createTextNode(item); newItem.appendChild(shoppingItemNode); newItem.addEventListener("click", () => { newItem.classList.toggle("done"); deleteCell.classList.toggle("hide"); }) deleteCell.addEventListener("click", () => { removeItem(row); }) textInput.value = ""; } function removeItem(item) { let index = item.rowIndex; list.deleteRow(index); } <file_sep># githubtest testrepo
1995bdebf4d2084b955b3abbbbf3cb842d47684a
[ "JavaScript", "Markdown" ]
2
JavaScript
mvkdev/githubtest
95ff1b5778497729eec484938997fc34ee00f75a
154eb5188068da155537dafce6400da071c31eb6
refs/heads/master
<file_sep>[![Emulsify Design System](https://user-images.githubusercontent.com/409903/170579210-327abcdd-2c98-4922-87bb-36446a4cc013.svg)](https://www.emulsify.info/) <p align="center"><img src="https://raw.githubusercontent.com/emulsify-ds/documentation/master/.gitbook/assets/logo.png" width="400"/></p> Emulsify is an open-source tool for creating design systems with reusable components and clear guidelines for teams. Emulsify helps organizations scale their design while reducing cost, streamlining workflows, and improving accessibility. # Emulsify Drupal ### Storybook development, Webpack build, and Drupal 8 theme **Emulsify Drupal** provides a [Storybook](https://storybook.js.org/) component library, a [Webpack](https://webpack.js.org/) development environment, and a Drupal 8 starterkit theme. It can be used as a standalone prototyping tool or inside a Drupal installation. ## Documentation [docs.emulsify.info](https://docs.emulsify.info/) ### Quick Links 1. [Installation](https://docs.emulsify.info/emulsify-drupal/emulsify-drupal) 2. [Usage](https://docs.emulsify.info/usage/commands) ## Demo 1. [Storybook](http://storybook.emulsify.info/) ## Contributing ### [Code of Conduct](https://github.com/emulsify-ds/emulsify-drupal/blob/master/CODE_OF_CONDUCT.md) The project maintainers have adopted a Code of Conduct that we expect project participants to adhere to. Please read the full text so that you can understand what actions will and will not be tolerated. ### Contribution Guide Please also follow the issue template and pull request templates provided. See below for the correct places to post issues: 1. [Emulsify Drupal](https://github.com/emulsify-ds/emulsify-drupal/issues) 2. [Emulsify Twig Extensions](https://github.com/emulsify-ds/emulsify-twig-extensions/issues) 3. [Emulsify Twig Drupal Module](https://www.drupal.org/project/issues/emulsify_twig) ### Committing Changes To facilitate automatic semantic release versioning, we utilize the [Conventional Changelog](https://github.com/conventional-changelog/conventional-changelog) standard through Commitizen. Follow these steps when commiting your work to ensure semantic release can version correctly. 1. Stage your changes, ensuring they encompass exactly what you wish to change, no more. 2. Run the `commit` script via `yarn commit` or `npm run commit` and follow the prompts to craft the perfect commit message. 3. Your commit message will be used to create the changelog for the next version that includes that commit. ## Author Emulsify&reg; is a product of [Four Kitchens &mdash; We make BIG websites](https://fourkitchens.com). <file_sep># Project Setup for Local Development **Important** You may need to authorize your machine with Pantheon with your machine token if you are not able to pull assets. ``` lando terminus auth:login --machine-token=TOKEN ``` ## Setup steps 1. Clone the project 2. run: `npm install` 3. run: `npm run setup` <file_sep># fourkitchens-karaoke [![CircleCI](https://circleci.com/gh/fourkitchens/fourkitchens-karaoke.svg?style=shield)](https://circleci.com/gh/fourkitchens/fourkitchens-karaoke) [![Dashboard fourkitchens-karaoke](https://img.shields.io/badge/dashboard-fourkitchens_karaoke-yellow.svg)](https://dashboard.pantheon.io/sites/ab2c6c8d-facb-4664-90fb-582a0d236de2#dev/code) [![Dev Site fourkitchens-karaoke](https://img.shields.io/badge/site-fourkitchens_karaoke-blue.svg)](http://dev-fourkitchens-karaoke.pantheonsite.io/) ## Local Development Requirements - [Lando](https://docs.devwithlando.io/installation/installing.html) - Node.js > 14.16.1 ([NVM](https://github.com/creationix/nvm) is recommended managing Node) - [Composer](https://getcomposer.org/) - [Terminus](https://pantheon.io/docs/terminus/install) ## Documentation - [Local Setup](.github/SETUP.md) - [Contributing](.github/CONTRIBUTING.md) - [Build Tools](.github/BUILD_TOOLS.md) - [Deployment](.github/DEPLOYMENT.md) - [Emulsify Docs](https://docs.emulsify.info/)<file_sep>import fs from 'fs'; import yaml from 'yaml'; import loadYaml from './loadYaml'; jest .spyOn(fs, 'readFileSync') .mockImplementation(() => 'yaml spaghetti and meatballs'); jest.spyOn(yaml, 'parse').mockImplementation(() => ({ the: 'yaml spaghetti and meatballs', })); describe('loadYaml', () => { beforeEach(() => { fs.readFileSync.mockClear(); yaml.parse.mockClear(); }); it('can load a yaml file, parse it, and return it', () => { expect.assertions(3); expect(loadYaml('./big-phat-burger.yml')).toEqual({ the: 'yaml spaghetti and meatballs', }); expect(fs.readFileSync).toHaveBeenCalledWith( `${__dirname}/big-phat-burger.yml`, 'utf8', ); expect(yaml.parse).toHaveBeenCalledWith('yaml spaghetti and meatballs'); }); }); <file_sep>module.exports = { testEnvironment: 'jsdom', coverageDirectory: '.coverage', // @TODO: once every file has 100% test coverage, // these thresholds should be updated. coverageThreshold: { global: { branches: 0, functions: 0, lines: 0, statements: 0, }, }, testPathIgnorePatterns: [ '<rootDir>/dist', '<rootDir>/vendor', '<rootDir>/.out', ], }; <file_sep>import link from './link.twig'; import linkData from './link.yml'; /** * Storybook Definition. */ export default { title: 'Atoms/Links' }; export const links = () => link(linkData); <file_sep>import colors from './colors.twig'; import colorsData from './colors.yml'; /** * Storybook Definition. */ export default { title: 'Base/Colors', }; export const Palettes = () => colors(colorsData); <file_sep>import pager from './pager.twig'; import pagerData from './pager.yml'; import pagerEllipsesData from './pager-ellipses.yml'; import pagerPrevEllipsesData from './pager-prev-ellipses.yml'; import pagerBothEllipsesData from './pager-both-ellipses.yml'; /** * Storybook Definition. */ export default { title: 'Molecules/Menus/Pager' }; export const basic = () => pager(pagerData); export const withNext = () => pager({ ...pagerData, ...pagerEllipsesData }); export const withBoth = () => pager({ ...pagerData, ...pagerBothEllipsesData }); export const withPrevious = () => pager({ ...pagerData, ...pagerPrevEllipsesData }); <file_sep>jest.mock('path', () => ({ resolve: (...paths) => `${paths[1]}${paths[2]}`, })); jest.mock('twig-drupal-filters', () => jest.fn()); jest.mock('bem-twig-extension', () => jest.fn()); jest.mock('add-attributes-twig-extension', () => jest.fn()); import Twig from 'twig'; import twigDrupal from 'twig-drupal-filters'; import twigBEM from 'bem-twig-extension'; import twigAddAttributes from 'add-attributes-twig-extension'; import { namespaces, setupTwig } from './setupTwig'; describe('setupTwig', () => { it('sets up a twig object with drupal, bem, and attribute decorations', () => { expect.assertions(3); setupTwig(Twig); expect(twigDrupal).toHaveBeenCalledWith(Twig); expect(twigBEM).toHaveBeenCalledWith(Twig); expect(twigAddAttributes).toHaveBeenCalledWith(Twig); }); it('exports emulsifys namespaces', () => { expect(namespaces).toEqual({ pages: '../components/pages', }); }); }); <file_sep>**What:** _brief description of change_ **Why:** _why this change improves emulsify_ **How:** _more details of changes made_ **To Test:** - [ ] Step 1 - [ ] Step 2 <file_sep><?php define('PANTHEON_ENVIRONMENT', $_ENV['PANTHEON_ENVIRONMENT']); // The environment the current site is running on. // Possible values: local, dev, test, live. // Configuration further in this file sets different settings for different // environments. if (defined('PANTHEON_ENVIRONMENT')) { if (isset($_SERVER['PRESSFLOW_SETTINGS'])) { // This can only happen at the top of settings.php because it // recreates $config. extract(json_decode($_SERVER['PRESSFLOW_SETTINGS'], true), EXTR_OVERWRITE); } switch (PANTHEON_ENVIRONMENT) { case 'kalabox': case 'lando': $settings['server_environment'] = 'local'; break; case 'dev': case 'test': case 'live': $settings['server_environment'] = PANTHEON_ENVIRONMENT; break; // Multidevs. default: $settings['server_environment'] = 'dev'; } } else { $settings['server_environment'] = 'local'; } /** * Load services definition file. */ $settings['container_yamls'][] = __DIR__ . '/services.yml'; /** * Include the Pantheon-specific settings file. * * n.b. The settings.pantheon.php file makes some changes * that affect all envrionments that this site * exists in. Always include this file, even in * a local development environment, to ensure that * the site settings remain consistent. */ require __DIR__ . "/settings.pantheon.php"; /** * Place the config directory outside of the Drupal root. */ $settings['config_sync_directory'] = dirname(DRUPAL_ROOT) . '/config/main'; /** * Always install the 'standard' profile to stop the installer from * modifying settings.php. */ $settings['install_profile'] = 'standard'; $config['openkj.settings']['api_key'] = '12345'; $config['openkj.settings']['default_venue'] = '1'; // Configuration split. if ($settings['server_environment'] === 'local') { $config['config_split.config_split.dev_split']['status'] = true; } else { $config['config_split.config_split.dev_split']['status'] = false; } /** * If there is a local settings file, then include it. */ $local_settings = __DIR__ . "/settings.local.php"; if (file_exists($local_settings)) { include $local_settings; } <file_sep># Karaoke Design This is a temporary repo for the design work of the Karaoke app. Questions? Ask <NAME> in Slack. ## Details This is an Emulsify repo. You can see the storybook by running `npm run develop`. The fun stuff is in `/components`. * This design uses [Bootstrap](https://getbootstrap.com/). See them for most of the details. * `components/_vars.scss` is where you overwrite Bootstrap's default variables. * Bootstrap's default variable list can be found at `node_modules/bootstrap/scss/_variables.scss`. ## TODO * [] Design the header * [] Design key pages <file_sep>We recommend using this directory or a relevant component directory for all theme images. <file_sep>const { resolve } = require('path'); const twigDrupal = require('twig-drupal-filters'); const twigBEM = require('bem-twig-extension'); const twigAddAttributes = require('add-attributes-twig-extension'); /** * Fetches project-based variant configuration. If no such configuration * exists, returns default values. * * @returns project-based variant configuration, or default config. */ const fetchVariantConfig = () => { try { return require('../project.emulsify.json').variant.structureImplementations; } catch (e) { return [ { name: 'pages', directory: 'components/pages', }, ]; } }; module.exports.namespaces = {}; for (const { name, directory } of fetchVariantConfig()) { module.exports.namespaces[name] = resolve(__dirname, '../', directory); } /** * Configures and extends a standard twig object. * * @param {Twig} twig - twig object that should be configured and extended. * * @returns {Twig} configured twig object. */ module.exports.setupTwig = function setupTwig(twig) { twig.cache(); twigDrupal(twig); twigBEM(twig); twigAddAttributes(twig); return twig; }; <file_sep><?php namespace Drupal\fk_glossary_block\Plugin\Block; use Drupal\Core\Link; use Drupal\Core\Block\BlockBase; /** * Provides a glossary links block. * * @Block( * id = "fk_glossary_links", * admin_label = @Translation("Glossary Links"), * category = @Translation("Custom") * ) */ class GlossaryLinksBlock extends BlockBase { /** * {@inheritdoc} */ public function build() { $route_name = \Drupal::routeMatch()->getRouteName(); $chars = array_merge(range('A', 'Z'), ['0-9', '#']); foreach($chars as $char) { $items[] = Link::createFromRoute( $char, $route_name, [ 'starts-with' => $char, ] ); } $build = [ '#theme' => 'item_list', '#items' => $items, '#cache' => [ 'contexts' => [ 'url.path', 'url.query_args', ], ], '#attributes' => [ 'class' => [], ], '#attached' => [ 'library' => [ 'fk_glossary_block/drupal.fk_glossary_block.facet_css', 'fk_glossary_block/drupal.fk_glossary_block.facet_js' ], ] ]; return $build; } } <file_sep>// Buttons Stories import button from './button.twig'; import buttonData from './button.yml'; import buttonAltData from './button-coin.yml'; /** * Storybook Definition. */ export default { title: 'Atoms/Button' }; export const twig = () => button(buttonData); export const twigAlt = () => button(buttonAltData); <file_sep>--- title: Image (responsive support) --- ### Background There are two key files for controlling the output of images. The first is `_image.twig` (basic `<img>` tag) and `responsive-image.twig`, which relies on the first file. You can include either depending on your need. ### Responsive (srcset) As in the past, any image element can include the basic img tag attributes (src, alt, title) as well as the following responsive attributes: `img_srcset` and `img_sizes`. However, in order to use the srcset approach, you need to set `output_image_tag` to TRUE (see `components/_patterns/01-atoms/04-images/00-image/02-figure.yml`) for an example. ### Responsive (picture) If you don't set `output_image_tag`, then the responsive image usage will default to using the `<picture>` element. <file_sep>import video from './video.twig'; import videoData from './video.yml'; import videoFullData from './video-full.yml'; /** * Storybook Definition. */ export default { title: 'Atoms/Videos' }; export const wide = () => video(videoData); export const full = () => video(videoFullData); <file_sep>[![Four Kitchens](https://img.shields.io/badge/4K-Four%20Kitchens-35AA4E.svg)](https://fourkitchens.com/) # karaoke: Pattern Lab + Drupal 8 Component-driven prototyping tool using [Pattern Lab v2](http://patternlab.io/) automated via Gulp/NPM. Also serves as _a starterkit_ Drupal 8 theme. ## Requirements 1. [PHP 7.1](http://www.php.net/) 2. [Node (we recommend NVM)](https://github.com/creationix/nvm) 3. [Gulp](http://gulpjs.com/) 4. [Composer](https://getcomposer.org/) 5. Optional: [Yarn](https://github.com/yarnpkg/yarn) ## Prototyping (separate from Drupal, Wordpress, etc.) karaoke supports both NPM and YARN. Install with NPM: `composer create-project fourkitchens/karaoke:^3.0 --stability dev --no-interaction karaoke && cd karaoke && npm install` Install with Yarn: `composer create-project fourkitchens/karaoke:^3.0 --stability dev --no-interaction karaoke && cd karaoke && yarn install` ## Drupal installation ### In a Composer-based Drupal install (recommended) 1. Require karaoke in your project `composer require fourkitchens/karaoke` 2. Move into the original karaoke theme `cd web/themes/contrib/karaoke/` 3. Create your new theme by cloning karaoke `php karaoke.php "THEME NAME"` (Run `php karaoke.php -h` for other available options) 4. Move into your theme directory `cd web/themes/custom/THEME_NAME/` 5. Install the theme dependencies `npm install` or `yarn install` 6. Enable your theme and its dependencies `drush then THEME_NAME -y && drush en components unified_twig_ext -y` 7. Proceed to the "Starting Pattern Lab…" section below If you're not using a Composer-based Drupal install (e.g. tarball download from drupal.org) installation [instructions can be found on the Wiki](https://github.com/fourkitchens/karaoke/wiki/Installation). Troubleshooting Installation: See [Drupal Installation FAQ](https://github.com/fourkitchens/karaoke/wiki/Installation#drupal-installation-faq). _Note: Once you've created your custom theme, you can remove karaoke as a dependency of your project. If you'd like to get updates as we push them, solely for educational/best-practice information, feel free to leave it in and receive the updates. Updating karaoke will not affect your custom theme in any way._ ## Starting Pattern Lab and watch task The `start` command spins up a local server, compiles everything (runs all required gulp tasks), and watches for changes. 1. `npm start` or `yarn start` --- ## Highlighted Features <table><tbody> <tr><td>Lightweight</td><td>✔</td><td>karaoke is focused on being as lightweight as possible.</td></tr> <tr><td>SVG sprite support </td><td><strong>✔</strong></td><td>Automated support for creating SVG sprites mixins/classes.</td></tr> <tr><td>Stock Drupal templates </td><td><strong>✔</strong></td><td>Templates from Stable theme - see /templates directory</td></tr> <tr><td>Stock Components </td><td><strong>✔</strong></td><td>with Drupal support built-in (https://github.com/fourkitchens/karaoke#karaokes-built-in-components-with-drupal-support)</td></tr> <tr><td>Performance Testing </td><td><strong>✔</strong></td><td>Support for testing via Google PageSpeed Insights and WebPageTest.org (https://github.com/fourkitchens/karaoke/wiki/Gulp-Config#performance-testing)</td></tr> <tr><td>Automated Github Deployment </td><td><strong>✔</strong></td><td>Deploy your Pattern Lab instance as a Github page (https://github.com/fourkitchens/karaoke/wiki/Gulp-Config#deployment)</td></tr> </tbody></table> <h3 id="components">karaoke's Built in Components with Drupal support</h3> Forms, tables, video, accordion, cards, breadcrumbs, tabs, pager, status messages, grid View a [demo of these default karaoke components](https://fourkitchens.github.io/karaoke/pattern-lab/public/). ## Documentation Documentation is currently provided in [the Wiki](https://github.com/fourkitchens/karaoke/wiki). Here are a few basic links: #### General Orientation See [Orientation](https://github.com/fourkitchens/karaoke/wiki/Orientation) We have a [series of videos](https://www.youtube.com/playlist?list=PLO9S6JjNqWsGMQLDfE8Ekt0ryrGa3g4km) for you to learn more about karaoke. #### For Designers (Prototyping) See [Designers](https://github.com/fourkitchens/karaoke/wiki/For-Designers) #### For Drupal 8 Developers See [Drupal Usage](https://github.com/fourkitchens/karaoke/wiki/Drupal-Usage) #### Gulp Configuration See [Gulp Config](https://github.com/fourkitchens/karaoke/wiki/Gulp-Config) <file_sep># Build tools **Important** You may need to authorize your machine with your token if you are not able to pull assets. ``` lando terminus auth:login --machine-token=TOKEN ``` ### Local Build Commands `npm run setup` - Runs a build to startup local environment, then runs `refresh` command.\ `npm run refresh` - Refresh to install new requirements, import Drupal configuration, build theme, and clear caches.\ `npm run get-db` - Acquires database from the Pantheon test environment. \ #### Drupal specific build commands `npm run confex` - Exports Drupal configuration. \ `npm run confim` - Imports Drupal configuration. ## Theme This project uses an [Emulsify](https://github.com/emulsify-ds/emulsify-drupal) theme named `kitchen_karaoke` (`web/themes/custom/kitchen_karaoke/`). For details on Emulsify usage, see that [project wiki](https://docs.emulsify.info/). #### Theme Tasks `npm run theme` - Run the theme compiler and watch task for active development. \ `npm run theme-build` - Compile the theme without running the watch task. <file_sep><?php /** * @file * Contains a basic scaffolding script. */ if ($argc < 2 || in_array($argv[1], array('--help', '-help', '-h', '-?'))) { emulsify_drush_help('drush:emulsify'); $command = emulsify_drush_command()['emulsify']; print(PHP_EOL . "Arguments" . PHP_EOL); foreach ($command['arguments'] as $argument => $argument_description) { print($argument . " => " . $argument_description . PHP_EOL); } print(PHP_EOL . "Options" . PHP_EOL); foreach ($command['options'] as $option => $option_description) { print($option . " => " . $option_description . PHP_EOL); } print(PHP_EOL . "Examples" . PHP_EOL); foreach ($command['examples'] as $example => $example_description) { print($example . " => " . $example_description . PHP_EOL); } exit; } drush_emulsify($argv[1]); /** * Determine whether current OS is a Windows variant. */ function drush_is_windows($os = NULL) { return strtoupper(substr($os ?: PHP_OS, 0, 3)) === 'WIN'; } /** * Makes sure the path has only path separators native for the current operating system */ function drush_normalize_path($path) { if (drush_is_windows()) { $path = str_replace('/', '\\', strtolower($path)); } else { $path = str_replace('\\', '/', $path); } return trim($path); } /** * Replacement for dt function. */ function dt($text, $replacements = []) { if (!empty($replacements)) { foreach ($replacements as $find => $replace) { $text = str_replace($find, $replace, $text); } } print($text . PHP_EOL); } /** * Create a drush_get_options function. */ function drush_get_options() { global $argv; $options = []; foreach ($argv as $key => $arg) { if (strpos($arg, '=') !== FALSE) { dt('Error: Please do not use equal signs in your options.'); exit; } switch ($arg) { case "-machine-name": case "--machine-name": $options['machine-name'] = $argv[$key + 1]; break; case "-description": case "--description": $options['description'] = $argv[$key + 1]; break; case "-path": case "--path": $options['path'] = $argv[$key + 1]; break; case "-slim": case "--slim": $options['slim'] = TRUE; break; } } return $options; } /** * Replacement for drush_get_option(). */ function drush_get_option($option) { $all_options_passed = drush_get_options(); return (!empty($all_options_passed[$option])) ? $all_options_passed[$option] : FALSE; } /** * Internal function called by drush_copy_dir; do not use directly. */ function _drush_recursive_copy($src, $dest) { // all subdirectories and contents: if(is_dir($src)) { if (!drush_mkdir($dest, TRUE)) { return FALSE; } $dir_handle = opendir($src); while($file = readdir($dir_handle)) { if ($file != "." && $file != "..") { if (_drush_recursive_copy("$src/$file", "$dest/$file") !== TRUE) { return FALSE; } } } closedir($dir_handle); } elseif (is_link($src)) { symlink(readlink($src), $dest); } elseif (!copy($src, $dest)) { return FALSE; } // Preserve file modification time. // https://github.com/drush-ops/drush/pull/1146 touch($dest, filemtime($src)); // Preserve execute permission. if (!is_link($src) && !drush_is_windows()) { // Get execute bits of $src. $execperms = fileperms($src) & 0111; // Apply execute permissions if any. if ($execperms > 0) { $perms = fileperms($dest) | $execperms; chmod($dest, $perms); } } return TRUE; } /** * Cross-platform compatible helper function to recursively create a directory tree. * * @param string $path * Path to directory to create. * @param boolean $required * If TRUE, then drush_mkdir will call drush_set_error on failure. * * Callers should *always* do their own error handling after calling drush_mkdir. * If $required is FALSE, then a different location should be selected, and a final * error message should be displayed if no usable locations can be found. * @see drush_directory_cache(). * If $required is TRUE, then the execution of the current command should be * halted if the required directory cannot be created. */ function drush_mkdir($path, $required = TRUE) { if (!is_dir($path)) { if (drush_mkdir(dirname($path))) { if (@mkdir($path)) { return TRUE; } elseif (is_dir($path) && is_writable($path)) { // The directory was created by a concurrent process. return TRUE; } else { if (!$required) { return FALSE; } if (is_writable(dirname($path))) { return dt('Unable to create !dir.', array('!dir' => preg_replace('/\w+\/\.\.\//', '', $path))); } else { return dt('Unable to create !newdir in !dir. Please check directory permissions.', array('!newdir' => basename($path), '!dir' => realpath(dirname($path)))); } } } return FALSE; } else { if (!is_writable($path)) { if (!$required) { return FALSE; } return dt('Directory !dir exists, but is not writable. Please check directory permissions.', array('!dir' => realpath($path))); } return TRUE; } } /** * Implements hook_drush_command(). */ function emulsify_drush_command() { $items = array(); $items['emulsify'] = array( 'description' => 'Create an Emulsify-based theme.', 'arguments' => array( 'human_readable_name' => 'The name of your theme.', ), 'options' => array( 'machine-name' => 'The machine-readable name of your theme. This will be auto-generated from the human_readable_name if ommited.', 'description' => 'The description of your theme', 'path' => 'Supports three options contrib, custom, none. Defaults to "custom".', 'slim' => 'Only copy base files', ), 'examples' => array( 'php emulsify.php "My Awesome Theme"' => 'Creates an Emulsify theme called "My Awesome Theme", using the default options.', 'php emulsify.php "My Awesome Theme" --machine-name mat' => 'Creates a Emulsify theme called "My Awesome Theme" with the specific machine name "mat".', ), ); return $items; } /** * Implements hook_drush_help(). */ function emulsify_drush_help($section) { switch ($section) { case 'drush:emulsify': return dt('This command will create an Emulsify theme. See examples to get started.'); } } /** * Implements drush_hook_COMMAND(). */ function drush_emulsify($human_readable_name = NULL) { // If no $human_readable_name provided, abort. if (!$human_readable_name) { print(dt('Theme name missing. See help using \'drush help emulsify\'.')); return; } // Determine the machine name. $machine_name = drush_get_option('machine-name'); if (!$machine_name) { $machine_name = $human_readable_name; } $machine_name = str_replace(' ', '_', strtolower($machine_name)); $search = array( // Remove characters not valid in function names. '/[^a-z0-9_]/', // Functions must begin with an alpha character. '/^[^a-z]+/', ); $machine_name = preg_replace($search, '', $machine_name); // Description of theme. $description = (drush_get_option('description')) ? trim(drush_get_option('description')) : 'Theme based on <a href="http://emulsify.info">Emulsify</a>.'; // Determine the path to the new theme. $theme_path = 'custom'; if ($path = drush_get_option('path')) { switch (trim($path)) { case 'contrib': $theme_path = 'contrib'; break; case 'none': $theme_path = ''; break; case 'custom': default: $theme_path = 'custom'; break; } $theme_path = trim($path); } // Create your new theme. $status = drush_emulsify_create($human_readable_name, $machine_name, $description, $theme_path); // Notify the user of failure. if ($status === FALSE) { print('Your theme was not successfully created.' . PHP_EOL); exit(1); } } /** * Create frontend theme. * * @param string $human_readable_name * A string that will be used to represent the human readable name. * @param string $machine_name * A string that will be used to name directories, files, and will be replaced * in templates. * @param string $description * A string that will be used as the theme description in the .info file. * @param string $theme_path_passed * A string that will be translated into a base path for your new theme. * * @return boolean * A boolean representing the success or failure of the function. */ function drush_emulsify_create($human_readable_name, $machine_name, $description, $theme_path_passed) { $theme_dir = substr(getcwd(), 0, strpos(getcwd(), 'themes') + 6); if (!empty($theme_path_passed)) { if ($theme_path_passed === 'none') { $theme_path = dirname(getcwd(), 1) . DIRECTORY_SEPARATOR . $machine_name; } else { $theme_path = $theme_dir . DIRECTORY_SEPARATOR . $theme_path_passed . DIRECTORY_SEPARATOR . $machine_name; // Phase: Validate theme dir with path is writeable. $theme_dir_status = _emulsify_validate_path($theme_dir . DIRECTORY_SEPARATOR . $theme_path_passed); if ($theme_dir_status !== TRUE) { return _emulsify_notify_fail('', 'Failed on Phase: Validate theme dir is writeable.'); } } } else { $theme_path = $theme_dir . DIRECTORY_SEPARATOR . $machine_name; } // Phase: Validate theme path is writeable. $theme_path_status = _emulsify_validate_path($theme_path); if ($theme_path_status !== TRUE) { return _emulsify_notify_fail('', 'Failed on Phase: Validate theme path is writeable.'); } // Phase: Verify there are not existing contents in the destination directory. $theme_path_empty_status = _emulsify_validate_path_is_empty($theme_path); if ($theme_path_empty_status !== TRUE) { return _emulsify_notify_fail('', 'Failed on Phase: Verify there are not existing contents in the destination directory. Please either delete the contents or pick a different path by changing the machine name or using the \'--path\' option. Use \'drush help emulsify\' for more information.'); } // Phase: Make directories. $directories_to_make = _emulsify_get_directories_to_make(); $directories_to_make_status = _emulsify_make_directories($directories_to_make, $theme_path); if ($directories_to_make_status !== TRUE) { return _emulsify_notify_fail('', 'Failed on Phase: Make directories.'); } // Phase: Copy files. $files_to_copy = _emulsify_get_files_to_copy(); $files_to_copy_status = _emulsify_copy_files($files_to_copy, $theme_path); if ($files_to_copy_status !== TRUE) { return _emulsify_notify_fail('', 'Failed on Phase: Copy files.'); } // Phase: Alter files. $alterations = _emulsify_get_alterations($human_readable_name, $machine_name, $description); $files_to_alter = _emulsify_get_files_to_alter(); $files_to_alter_status = _emulsify_alter_files($theme_path, $files_to_alter, $alterations); if ($files_to_alter_status !== TRUE) { return _emulsify_notify_fail('', 'Failed on Phase: Alter files.'); } // Phase: Rename files. $files_to_rename = _emulsify_get_files_to_rename(); $files_to_rename_status = _emulsify_rename_files($theme_path, $machine_name, $files_to_rename); if ($files_to_rename_status !== TRUE) { return _emulsify_notify_fail('', 'Failed on Phase: Rename files.'); } // Phase 7: Return success message to the user. return _emulsify_notify_success($human_readable_name, $theme_path); } /** * Gets alterations (string replacements). * * This function supports both directories and individual files. Alterations * happen in sequential order so you can replace something that was previously * replaced. * * @param string $human_readable_name * A string representing the human readable name. * @param string $machine_name * A string representing the machine name. * @param string $description * A string representing the desired description. * * @return array * An array with a key representing the string to be replaced and value * representing the string to replace it with. */ function _emulsify_get_alterations($human_readable_name, $machine_name, $description) { return array( 'Emulsify' => $human_readable_name, 'emulsify' => $machine_name, 'Theme using Storybook and component-driven development' => $description, 'hidden: true' => '', ); } /** * Returns an array of files and directories to make string replacements within. * * @return array * A array representing files and directories to be altered. */ function _emulsify_get_files_to_alter() { // Slim files and directories declaration. $default_array = array( 'emulsify.info.yml', 'emulsify.theme', 'emulsify.breakpoints.yml', 'emulsify.libraries.yml', ); // If we would like to have a bare copy we use is slim option. if (drush_get_option('slim') === TRUE) { return $default_array; } else { return array_merge($default_array, array( 'components', 'templates', )); } } /** * Get directories to make. * * @return array * An array of directories to make. */ function _emulsify_get_directories_to_make() { // If we would like to have a bare copy we use is slim option. if (drush_get_option('slim') === TRUE) { return array( 'components', 'components/00-base', 'components/00-base/global', 'components/01-atoms', 'components/02-molecules', 'components/03-organisms', 'components/04-templates', 'components/05-pages', 'images', 'images/icons', 'images/icons/src', 'templates', ); } else { return array(); } } /** * Gets files to copy. * * This function supports both directories and individual files. * * The following directories/files will never be copied: * dist/ * node_modules/ * github.com/ * composer.json * LICENSE * emulsify.php * * @return array * An array of files to copy. */ function _emulsify_get_files_to_copy() { // Slim files and directories declaration. $default_array = array( '.storybook', 'webpack', 'util', 'scripts', '.browserslistrc', '.editorconfig', '.eslintignore', '.eslintrc.yml', '.gitignore', '.npmrc', 'a11y.config.js', 'babel.config.js', 'emulsify.breakpoints.yml', 'emulsify.info.yml', 'emulsify.libraries.yml', 'emulsify.theme', 'jest.config.js', 'lint-staged.config.js', 'package.json', 'postcss.config.js', 'prettier.config.js', ); // If we would like to have a bare copy we use is slim option. if (drush_get_option('slim') === TRUE) { return array_merge($default_array, array( 'components/style.scss', )); } else { return array_merge($default_array, array( 'components', 'images', 'templates', 'README.md', 'screenshot.png', )); } } /** * Get files to rename. * * @return array * An array of files to rename. */ function _emulsify_get_files_to_rename() { // Slim files and directories declaration. $default_array = array( 'emulsify.info.yml', 'emulsify.theme', 'emulsify.breakpoints.yml', 'emulsify.libraries.yml', ); // If we would like to have a bare copy we use is slim option. if (drush_get_option('slim') === TRUE) { return array_merge($default_array, array()); } else { return array_merge($default_array, array()); } } /** * Alter strings within files. * * @param string $theme_path * A string representing the destination theme path. * @param array $files_to_alter * An array representing the files that will be altered. * @param array $alterations * An array of alteration that will be processed in sequential order on all * files, this means that you can replace previous replacements. * @param boolean $absolute * A boolean representing if the files to alter are represented as relative * or absolute paths. * * @return boolean * A boolean representing the success or failure of the function. */ function _emulsify_alter_files($theme_path, array $files_to_alter = array(), array $alterations = array(), $absolute = FALSE, int $depth = 0) { if (empty($files_to_alter) || empty($alterations)) { return TRUE; } foreach ($files_to_alter as $file_to_replace) { if ($absolute === TRUE) { $file_type = filetype(realpath($file_to_replace)); $file_path = $file_to_replace; } else { $file_type = filetype($theme_path . DIRECTORY_SEPARATOR . $file_to_replace); $file_path = $theme_path . DIRECTORY_SEPARATOR . $file_to_replace; } if ($file_type === 'dir') { $files = scandir($file_path); $files = array_splice($files, 2); foreach ($files as $file) { $processed_file = [$file_path . DIRECTORY_SEPARATOR . $file]; $alter_status = _emulsify_alter_files($theme_path, $processed_file, $alterations, TRUE, $depth + 1); if ($alter_status === FALSE) { return FALSE; } } } elseif ($file_type === 'file') { $string_replace_status = _emulsify_file_str_replace($file_path, array_keys($alterations), $alterations); if ($string_replace_status === FALSE) { return FALSE; } } } // If we make it here return success. return TRUE; } /** * Make directories. * * @param array $directories * An array of directories (strings) to make. * @param string $destination_path * A string representing the destination path. * * @return boolean * A boolean representing the success or failure of the function. */ function _emulsify_make_directories(array $directories = array(), string $destination_path = '') { // Check for invalid settings and return an error. if (empty($destination_path)) { _emulsify_notify_fail('', "Invalid parameter passed to _emulsify_make_directories()."); return FALSE; } // The $directories parameter can be empty and valid, return success. if (empty($directories)) { return TRUE; } // Copy desired files. foreach ($directories as $directory_to_make) { $directory_path = drush_normalize_path($destination_path . DIRECTORY_SEPARATOR . $directory_to_make); // Check if path is or can be writeable and exists, if not, return FALSE. if (!_emulsify_validate_path($directory_path)) { return FALSE; } } // If there were not issues return success. return TRUE; } /** * Copy files. * * @param array $files * An array of files (strings) to copy. * @param string $destination_path * A string representing the destination path. * * @return boolean * A boolean representing the success or failure of the function. */ function _emulsify_copy_files(array $files = array(), string $destination_path = '') { // Check for invalid settings and return an error. if (empty($destination_path)) { return _emulsify_notify_fail('', "Invalid parameter passed to _emulsify_copy_files()."); } // The $files parameter can be empty and valid, return success. if (empty($files)) { return TRUE; } // Copy desired files. foreach ($files as $files_to_copy) { $status = _drush_recursive_copy(__DIR__ . DIRECTORY_SEPARATOR . $files_to_copy, $destination_path . DIRECTORY_SEPARATOR . $files_to_copy); // Check if copy succeeded, if not, return FALSE. if (!$status) { return FALSE; } } // Return success. return TRUE; } /** * Rename files. * * @param string $theme_path * A string representing the destination theme path. * @param string $machine_name * A string that will be used in file names. * @param array $files_to_rename * An array that represents the files to be processed. The array is expected * to be provided as an indexed array of relative files paths. * * @return boolean * A boolean representing success or failure of the rename. */ function _emulsify_rename_files($theme_path, $machine_name, array $files_to_rename = array()) { foreach ($files_to_rename as $file_to_rename_path) { $file_original_path = $theme_path . DIRECTORY_SEPARATOR . $file_to_rename_path; $file_new_path = $theme_path . DIRECTORY_SEPARATOR . str_replace('emulsify', $machine_name, $file_to_rename_path); rename($file_original_path, drush_normalize_path($file_new_path)); } return TRUE; } /** * Replace strings in a file. * * @param string $file_path * A string representing the original file path to have replacements * performed on. * @param array $find * An array representing the search for values in the replacement process. * @param array $replace * An array that will replace the $find strings. * * @return boolean * A boolean representing success or failure of the replacement. */ function _emulsify_file_str_replace($file_path, array $find, array $replace) { $file_path = drush_normalize_path($file_path); $file_contents = file_get_contents($file_path); $file_contents = str_replace($find, $replace, $file_contents); file_put_contents($file_path, $file_contents); return TRUE; } /** * Validate that a path is writeable, creating the directory if necessary. * * @param string $path * A string representing the path to verify exists and is writeable. * * @return boolean * A boolean representing success or failure. */ function _emulsify_validate_path($path) { // Check for succees, if not, log the error and return FALSE. if (file_exists($path) === FALSE) { $return = mkdir($path); } else { $return = TRUE; } if ($return === FALSE) { _emulsify_notify_fail($path); } return $return; } /** * Validate that a path is empty. * * @param string $path * A string representing the path to verify is empty. * * @return boolean * A boolean representing if the path is empty or not. */ function _emulsify_validate_path_is_empty($path) { if (!is_readable($path)) { return FALSE; } return (count(scandir($path)) === 2); } /** * Notifies the user of failure. * * @param string $path * An optional string representing the path that failed. This function can * be used to just send a message to the user without path replacements. * @param string $message * An optional string to replace the default message. * * @return boolean * Always return false in the case we use this function as a return value. */ function _emulsify_notify_fail($path = '', $message = '') { // Set a default message for the most common error. if (empty($message)) { // Notify user of the path write error. $message = 'There was an error writing to "!path". This is normally due to permissions on one of the base directories or "!path" directory not allowing the web server to write data. You can use the "chmod" command to implement either a temporary or permanent fix for this.'; } // Set the path if one was passed. if (!empty($path) && is_string($path)) { $message = dt($message, array( '!path' => $path, )); } print($message); // We return false here to represent failure. return FALSE; } /** * Notifies the user of success. * * @param string $human_readable_name * A string that will be returned to the user as their theme name. * @param string $theme_path * A string that will show where to find their new theme. * * @return boolean * Always TRUE in the case we want to use this function as a return value. */ function _emulsify_notify_success($human_readable_name, $theme_path) { // Notify user of the newly created theme. $message = 'Successfully created the Emulsify theme "!name" created in: !path, you can now run \'yarn\' or \'npm install\' to install.'; $message = dt($message, array( '!name' => $human_readable_name, '!path' => $theme_path, )); print($message); // We return true here to represent success. return TRUE; } <file_sep>This is Pattern Lab's default images directory. Images that only apply to the Pattern Lab instance should be placed here. e.g. One image of each dimension (portrait, landscape, square, etc.) to demonstrate the various components with images. We recommend putting theme images into the theme's root-level `/images` directory or into a relevant component directory. <file_sep>module.exports = { '*.{js,yml,scss,md}': ['npm run format'], }; <file_sep>import motion from './motion.twig'; import motionData from './motion.yml'; /** * Add storybook definition for Animations. */ export default { title: 'Base/Motion' }; export const Usage = () => motion(motionData); <file_sep>#!/bin/bash THEMEPATH=$1 cd "$THEMEPATH" [ -f pattern-lab/composer.json ] && echo "Node libraries pulled from cache. Skipping..." || npm install --unsafe-perm ./node_modules/.bin/gulp build <file_sep>--- title: Icons --- ### How to use icons We are using an SVG sprite generator (details [here](https://www.npmjs.com/package/svg-sprite-loader)), which automatically takes individual SVGs from `/images/icons` and generates `/dist/icons.svg`. Webpack will automatically add your individual SVGs to this sprite. **Usage** The SVG component is found here: `/components/_patterns/01-atoms/04-images/icons/_icon.twig`. See available variables in that file as well as instructions for Drupal. Examples of usage below: Simple: (no BEM renaming) ``` {% include "@atoms/images/icons/_icon.twig" with { icon_name: 'menu', } %} ``` ... creates... ``` <svg class="icon"> <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/icons.svg#src--menu"></use> </svg> ``` Complex (BEM classes): ``` {% include "@atoms/04-images/icons/_icon.twig" with { icon_base_class: 'toggle', icon_blockname: 'main-nav', icon_name: 'menu', } %} ``` ... creates... ``` <svg class="main-nav__toggle"> <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/icons.svg#src--menu"></use> </svg> ``` <file_sep>emulsify version (see [releases](https://github.com/emulsify-ds/emulsify-drupal/releases)): node version: npm (or yarn) version: **What you did:** **What happened:** **Reproduction repository (if necessary):** **Problem description:** **Suggested solution:** <file_sep># Four Kitchens Karaoke. This documentation outlines the current deployment process for this project. ## Deployment workflow CircleCI takes care of automated deployment for the `master` branch. An automated deployment process is kicked off for the branches mentioned above any time you push. You can monitor the progress of the build and deployment here: https://app.circleci.com/pipelines/github/fourkitchens/fourkitchens-karaoke Code is automatically deployed to Pantheon once the build process is complete. ### Server Environment and Branches #### Pull Requests This is the only valid method of commiting code to the project. Once a pull request is created a series of tasks will be handled with CircleCI to test and build the application into an new multidev environment on Pantheon. A link to the environment will be provided as a comment in the PR once the build and deployment is complete. #### Dev The 'Dev' environment is updated with any new code that is merged into master. Base configuration is automatically imported. #### Test - Commit changes to test via the Pantheon dashboard. - Clear the environment cache: `terminus drush fourkitchens-karaoke.test cr` - Import base configurations: `terminus drush fourkitchens-karaoke.test cim` If you want to test SSO logins on the test environment: - Import 'live' configurations: `terminus drush fourkitchens-karaoke.test csim live -y` #### Live - Commit changes to live via the Pantheon dashboard. - Import configurations: `terminus drush fourkitchens-karaoke.live cim` - Clear the environment cache: `terminus drush fourkitchens-karaoke.live cr` - Import configurations: `terminus drush fourkitchens-karaoke.live csim live -y` <file_sep>## Purpose: - Description of PR ### Ticket(s) [Description](https://app.clickup.com/t/2qmd1nu) ### Pull Request Deployment: See linked environment in comments. ### Functional Testing: - [ ] Step 1 - [ ] Step 2 - [ ] Step 3 - [ ] ... ### Notes: _Additional notes_ <file_sep># <NAME>. Contribution guidelines for 4K Karaoke. This is a Drupal 9 composer project. ## General codebase - Use composer to install all modules and libraries. Please consult with the team if you are having issues to install items correctly with this process. [read the official documentation on composer module installs.](https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies) - Separate documentation as much as possible for better organization and to avoid the wall-o-text. Create links within root [README.md](../README.md) to additional documentation. ## Git workflow - Create work off of the `master` branch which is the default branch. - Keep your branches as lightweight as possible, restricting your pull requests to only the feature requirements necessary for the ticket you are working on. ### Branch naming conventions - `master` The master branch is for code ready to be released to pantheon dev environment. Code should progress through the pantheon workflow from there. - `4k-karaoke--short-description` Feature branches should branch from and merge back into the `master` branch. They contain code that is currently in development. When a story/feature is complete, a pull request should be created merging the feature branch into the `master` branch. - `hotfix/short-description` Create a hotfix branch for quick fixes that get merged directly into `master`. The main purpose of this branch naming concention is for quick fixes that are not associated with a ticket with a sprint or backlog. ### Pull requests - All pull requests need to go through a review process. - Assign 1 or more `reviewers` to your pull request once it is ready for review. - As a reviewer assign yourself as the `assignee` when you start work on the pull request. - Add labels to your pull request. This will help to know the status of all the open pull requests at a glance. We review the labels below. - Delete branches after merging. #### Pull request template Pull requests should include a link to the ClickUp Ticket (if applicable) plus a brief description. A pull request [template](PULL_REQUEST_TEMPLATE.md) has been created. Below is the general outline of the template. We have 5 sections that could be used for any given pull request - Purpose: A clear description of what problem the pull request is meant to address - Ticket: A list of links to relevant ClickUp tickets - Pull Request Deployment: A step by step process to make sure the reviewer is set-up with the correct assets so they can complete a functional review - Functional Testing: A step by step process for testing the pull request functionality - Notes: Additional notes for the reviewer for additional context if they need. ### Pull request labels Here is a list of the labels we have identified that we will use for this project. Each is described for a use case. **BLOCKER** When you are blocked from merging the code/feature into the branch for the sake of deploy, make sure this label is set until after deploy, when you should remove it. **HELP!** If you need help with a task flag it with the HELP! label. **Work in Progress** If you create a PR before it is ready for review and it still needs additional work, flag it with the Work in Progress label. **Needs Review** If your work is complete and you are ready for a functional testing and code review, flag the PR with the Needs Review label **Review in Progress** If you have been assigned to review a large PR or if you began a review and you were pulled away, mark the PR with Review in Progress **Question** If you have a question that needs to be answered to continue your review flag it with the question label. **Passes Code Review** If the PR passes code review, flag it with the Passes Code Test label. **Passes Functional Test** If the PR passes the functional test, flag the PR with the Passes Functional Test label. ## Additional pull request best practices - Generally, pull requests should resolve a single ticket. Try to avoid combining multiple tickets into a single pull request. There may be instances where it makes sense to do otherwise but please use discretion. - Try to keep pull requests reasonably small and discrete. Following the one pull request per ticket paradigm should accomplish this by default. However, if you are beginning to work on a story and it feels like it will result in a giant pull request with lots of custom code, changes across many features, and lots of testing scenarios, think about how you might break down the story into smaller subtasks that could be incrementally developed and tested. Create subtasks or potentially even new stories within ClickUp. If you are unsure about how or are unable to do this, please reach out to the project Tech Lead, Product Owner, or Project Manager. ## Coding standards Coding standards will be rigorously enforced on this project. Please save everybody time by checking for common syntax errors in your custom code and fixing them before you send your pull request into review. All custom code on this project should: - Adhere to [Drupal coding standards](https://www.drupal.org/coding-standards) and best practices. - Use semantic naming for code readability. - Employ [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) principles. - Be well commented and documented according to [Drupal standards](https://www.drupal.org/node/1354) for PHP and [JSDoc standards](http://usejsdoc.org) for Javascript. <file_sep>(function() { Drupal.behaviors.offScreen = { attach: function(context) { "use strict"; function toggleOffScreen() { const layoutContainer = document.querySelector(".layout-container"); const offScreenContainer = document.querySelector(".off-screen"); layoutContainer.classList.toggle("open"); offScreenContainer.classList.toggle("open"); } const offScreenToggle = document.querySelector(".menu-toggle", context); offScreenToggle.addEventListener("click", toggleOffScreen); const offScreenClose = document.querySelector( ".off-screen-close", context ); offScreenClose.addEventListener("click", toggleOffScreen); } }; })(); <file_sep>import { addDecorator } from '@storybook/html'; import { useEffect } from '@storybook/client-api'; import Twig from 'twig'; import { setupTwig } from './setupTwig'; // GLOBAL CSS import '../components/style.scss'; // If in a Drupal project, it's recommended to import a symlinked version of drupal.js. import './_drupal.js'; // addDecorator deprecated, but not sure how to use this otherwise. addDecorator((storyFn) => { useEffect(() => Drupal.attachBehaviors(), []); return storyFn(); }); setupTwig(Twig); export const parameters = { actions: { argTypesRegex: '^on[A-Z].*' }, }; <file_sep>// Simple Drupal.behaviors usage for Storybook window.Drupal = { behaviors: {} }; (function (Drupal, drupalSettings) { Drupal.throwError = function (error) { setTimeout(function () { throw error; }, 0); }; Drupal.attachBehaviors = function (context, settings) { context = context || document; settings = settings || drupalSettings; const behaviors = Drupal.behaviors; Object.keys(behaviors).forEach(function (i) { if (typeof behaviors[i].attach === 'function') { try { behaviors[i].attach(context, settings); } catch (e) { Drupal.throwError(e); } } }); }; })(Drupal, window.drupalSettings); <file_sep>import tableTwig from './tables.twig'; import tableData from './tables.yml'; /** * Storybook Definition. */ export default { title: 'Atoms/Tables' }; export const tables = () => tableTwig(tableData); <file_sep>#!/bin/bash # Install Pattern Lab # Remove existing PL directory rm -rf pattern-lab # Install PL composer create-project -n pattern-lab/edition-twig-standard pattern-lab # Delete the default source directory rm -rf pattern-lab/source # Symlink our components directory to the source location we just deleted ln -s ../components pattern-lab/source <file_sep>// Add class const queryString = window.location.search; const urlParams = new URLSearchParams(queryString); const letterQuery = urlParams.get('starts-with') urlParams.has('starts-with') jQuery(function($){ $('#block-glossarylinks li a').each(function(){ if ($(this).text() == letterQuery) { $(this).addClass('active'); $(this).click(function($e) { $e.preventDefault(); }); } }); });<file_sep># Where are all of the components? The components that historically came with emulsify-drupal have been moved to [Compound](https://github.com/emulsify-ds/compound). # Why did they move? Historically, our installation steps looked something like this: 1. Install an Emulsify-based theme. 2. Delete all of the default components. 3. Copy and paste individual components over when we needed them. 4. Create new components that weren't a part of the original set. This was a little annoying, and we realized there were probably numerous sites out there that had extra code just bloating repositories because they _might_ be used one day. We didn't want to encourage that, so we found a way to abstract our boilerplate code into an external repository where we could more easily update those starter component files, and simplify our theme creation process. Moving them also enables us to make updates to the boilerplate code and version them, so breaking changes won't affect active sites. # How can I get the starter components into my project? You can copy and paste them from the Compound repo, or another project. OR you can use the Emulsify CLI (which is our recommendation!) # What is the Emulsify CLI? The final piece we developed to facilitate pulling those boilerplate components into a project is the [Emulsify CLI](https://github.com/emulsify-ds/emulsify-cli). This is a robust tool that developers can use to pull components from an external repository into a projects local repo with a simple command. You'll notice that the emulsify-drupal starter has a `project.emulsify.json` file in its root. This is a pretty simple file to start, but once you initialize a system (like Compound) it is used to define your projects directory structure and where components should be downloaded to when you install them. (You can [see the schema here](https://github.com/emulsify-ds/emulsify-cli/blob/develop/src/schemas/emulsifyProjectConfig.json)) To start using the CLI, check out the [Emulsify CLI docs page](https://docs.emulsify.info/supporting-projects/emulsify-cli). <file_sep>import twigTemplate from './home.twig'; /** * Storybook Definition. */ export default { title: 'Page/Home' }; export const home = () => twigTemplate(); <file_sep><?php namespace Drupal\openkj_musixmatch\Plugin\QueueWorker; use Drupal\Core\Queue\QueueWorkerBase; /** * Processes Tasks for Learning. * * @QueueWorker( * id = "openkj_musixmatch_song_worker", * title = @Translation("Song Worker for OpenKJ MusixMatch Integration"), * cron = {"time" = 60} * ) */ class SongWorker extends QueueWorkerBase { /** * {@inheritdoc} */ public function processItem($data) { Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('apikey', '<KEY>'); $api_instance = new Swagger\Client\Api\TrackApi(); $album_id = "14250417"; // string | The musiXmatch album id $format = "json"; // string | output format: json, jsonp, xml try { $result = $api_instance->trackSearchGet( 'json', null, $data['song'], $data['artist'] ); print_r($result); } catch (Exception $e) { echo 'Exception when calling AlbumApi->albumGetGet: ', $e->getMessage(), PHP_EOL; } } } <file_sep>--- title: Figure --- ### How to use the figure element The figure element includes the image element as well as an image caption. <file_sep>import placeHolderTwig from './place-holder.twig'; /** * Storybook Definition. */ export default { title: 'Templates/Place Holder' }; export const placeHolder = () => placeHolderTwig(); <file_sep>import status from './status.twig'; import statusData from './status.yml'; /** * Storybook Definition. */ export default { title: 'Molecules/Status' }; export const statusExamples = () => status(statusData); <file_sep>jest.mock('path', () => ({ resolve: (...paths) => `${paths[1]}${paths[2]}`, })); jest.mock('twig-drupal-filters', () => jest.fn()); jest.mock('bem-twig-extension', () => jest.fn()); jest.mock('add-attributes-twig-extension', () => jest.fn()); import Twig from 'twig'; import twigDrupal from 'twig-drupal-filters'; import twigBEM from 'bem-twig-extension'; import twigAddAttributes from 'add-attributes-twig-extension'; import { namespaces, setupTwig } from './setupTwig'; describe('setupTwig', () => { it('sets up a twig object with drupal, bem, and attribute decorations', () => { expect.assertions(3); setupTwig(Twig); expect(twigDrupal).toHaveBeenCalledWith(Twig); expect(twigBEM).toHaveBeenCalledWith(Twig); expect(twigAddAttributes).toHaveBeenCalledWith(Twig); }); it('exports emulsifys namespaces', () => { expect(namespaces).toEqual({ atoms: '../components/01-atoms', molecules: '../components/02-molecules', organisms: '../components/03-organisms', templates: '../components/04-templates', }); }); });
3b9f1a9bf1c5f7ff6d20236d7405bd83d02542b0
[ "Markdown", "JavaScript", "PHP", "Shell" ]
43
Markdown
fourkitchens/fourkitchens-karaoke
7bd6a1d8ebd46e4f1a1c33dba916321d3d06a413
c2714cf0d8ebff3d9f578a44e146e5453205846e
refs/heads/master
<file_sep><?php namespace Tests\Feature; use App\Http\Livewire\SearchDropdown; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\WithFaker; use Illuminate\Support\Facades\Http; use Livewire\Livewire; use Tests\TestCase; class SearchDropdownTest extends TestCase { /** @test */ public function the_search_dropdown_searches_for_games() { Http::fake([ 'https://api.igdb.com/v4/games' => $this->fakeSearchGames(), ]); Livewire::test(SearchDropdown::class) ->assertDontSee('zelda') ->set('search', 'zelda') ->assertSee('The Legend of Zelda: Four Swords Adventures') ->assertSee('The Legend of Zelda: Ocarina of Time'); } private function fakeSearchGames() { return Http::response([ 0 => [ "id" => 1034, "cover" => [ "id" => 100964, "url" => "//images.igdb.com/igdb/image/upload/t_thumb/co25wk.jpg", ], "name" => "The Legend of Zelda: Four Swords Adventures", "slug" => "the-legend-of-zelda-four-swords-adventures", ], 1 => [ "id" => 1029, "cover" => [ "id" => 76691, "url" => "//images.igdb.com/igdb/image/upload/t_thumb/co1n6b.jpg", ], "name" => "The Legend of Zelda: Ocarina of Time", "slug" => "the-legend-of-zelda-ocarina-of-time", ], 2 => [ "id" => 2909, "cover" => [ "id" => 77440, "url" => "//images.igdb.com/igdb/image/upload/t_thumb/co1nr4.jpg", ], "name" => "The Legend of Zelda: A Link Between Worlds", "slug" => "the-legend-of-zelda-a-link-between-worlds", ], 3 => [ "id" => 1030, "cover" => [ "id" => 76690, "url" => "//images.igdb.com/igdb/image/upload/t_thumb/co1n6a.jpg", ], "name" => "The Legend of Zelda: Majora's Mask", "slug" => "the-legend-of-zelda-majora-s-mask", ], 4 => [ "id" => 1027, "cover" => [ "id" => 111338, "url" => "//images.igdb.com/igdb/image/upload/t_thumb/co2dwq.jpg", ], "name" => "The Legend of Zelda: Link's Awakening DX", "slug" => "the-legend-of-zelda-link-s-awakening-dx", ], 5 => [ "id" => 1022, "cover" => [ "id" => 86202, "url" => "//images.igdb.com/igdb/image/upload/t_thumb/co1uii.jpg", ], "name" => "The Legend of Zelda", "slug" => "the-legend-of-zelda", ], ], 200); } } <file_sep><?php namespace App\Http\Controllers; use Carbon\Carbon; use Illuminate\Http\Request; use Illuminate\Support\Facades\Http; use Illuminate\Support\Str; class GamesController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('index'); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param string $slug * @return \Illuminate\Http\Response */ public function show(string $slug) { $game = Http::withHeaders([ 'Client-ID' => config('services.igdb.id'), 'Authorization' => 'Bearer ' . config('services.igdb.token') ])->withBody( " fields aggregated_rating, name, rating, rating_count, slug, websites, involved_companies, summary, cover.url, genres.name, involved_companies.company.name, platforms.abbreviation, videos.video_id, screenshots.url, websites.url, similar_games.name, similar_games.slug, similar_games.rating, similar_games.involved_companies.company.name, similar_games.platforms.abbreviation, similar_games.cover.url; where slug=\"{$slug}\"; ", 'text/plain' )->post('https://api.igdb.com/v4/games')->json(); // dump($game); abort_if(!$game, 404); return view('show', [ 'game' => $this->formatForView($game[0]), ]); } private function formatForView($game) { return collect($game)->merge([ 'coverImageUrl' => isset($game['cover']) ? Str::replaceFirst('thumb', 'cover_big', $game['cover']['url']) : '/ff7.jpg', 'platforms' => isset($game['platforms']) ? collect($game['platforms'])->pluck('abbreviation')->implode(', ') : null, 'genres' => isset($game['genres']) ? collect($game['genres'])->pluck('name')->implode(', ') : null, 'involved_companies' => $game['involved_companies'][0]['company']['name'], 'memberRating' => isset($game['rating']) ? round($game['rating']) : '0', 'criticRating' => isset($game['aggregated_rating']) ? round($game['aggregated_rating']) : '0', 'trailer' => 'https://youtube.com/embed/'. $game['videos'][0]['video_id'], 'screenshots' => collect($game['screenshots'])->map(function ($screenshot) { return [ 'big' => Str::replaceFirst('thumb', 'screenshot_big', $screenshot['url']), 'huge' => Str::replaceFirst('thumb', 'screenshot_huge', $screenshot['url']), ]; })->take(9), 'similar_games' => collect($game['similar_games'])->map(function ($game) { return collect($game)->merge([ 'coverImageUrl' => isset($game['cover']) ? Str::replaceFirst('thumb', 'cover_big', $game['cover']['url']) : 'https://via.placeholder.com/264x352', 'rating' => isset($game['rating']) ? round($game['rating']) : null, 'platforms' => isset($game['platforms']) ? collect($game['platforms'])->pluck('abbreviation')->implode(', ') : null, ]); })->take(6), 'social' => [ 'website' => collect($game['websites'])->first(), 'facebook' => collect($game['websites'])->filter(function ($website) { return Str::contains($website['url'], 'facebook'); })->first(), 'twitter' => collect($game['websites'])->filter(function ($website) { return Str::contains($website['url'], 'twitter'); })->first(), 'instagram' => collect($game['websites'])->filter(function ($website) { return Str::contains($website['url'], 'instagram'); })->first(), ] ]); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } }
8e81056259922d2dc53cc8d0ea459451683b497d
[ "PHP" ]
2
PHP
gsmofgsm/LCVideoGameAggregtor
b4f3897adbe4a37b355e567ff2d750c51de0db96
c9bf7e06edd2b634a708617bc947ea8d0307233a
refs/heads/master
<file_sep>import processing.core.*; import processing.data.*; import processing.event.*; import processing.opengl.*; import processing.sound.*; import java.util.HashMap; import java.util.ArrayList; import java.io.File; import java.io.BufferedReader; import java.io.PrintWriter; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; public class hw1_49_Torres extends PApplet { PImage img; int Button1x, Button1y, Button2x, Button2y, Button3x, Button3y, Button4x, Button4y, BellButtonx, BellButtony, HelpButtonx,HelpButtony; int NumButtonSize=50, BellButtonSize=60,HelpButtonSize=125; int ButtonHighlight,NumButtonColor=255; String desiredFloor,baseFloor; boolean Button1Over=false,Button2Over=false,Button3Over=false,Button4Over=false,BellButtonOver=false,HelpButtonOver=false; SoundFile sound1,sound2,sound3,sound4,soundbell,soundhelp,currentsound,basesound; public void setup(){ baseFloor="--"; desiredFloor=baseFloor; img = loadImage("infinity_gauntlet.png"); ButtonHighlight=color(0); //Button 1 Loc Button1x=100; Button1y=335; //Button 2 Loc Button2x=165; Button2y=300; //Button 3 Loc Button3x=225; Button3y=285; //Button 4 Loc Button4x=295; Button4y=325; //Bell Button Loc BellButtonx=350; BellButtony=425; //Help Button Loc HelpButtonx=210; HelpButtony=430; ellipseMode(CENTER); //Load Sound for Button 1 sound1 = new SoundFile(this, "sound1.wav"); //Load Sound for Button 2 sound2 = new SoundFile(this, "sound2.wav"); //Load Sound for Button 3 sound3 = new SoundFile(this, "sound3.wav"); //Load Sound for Button 4 sound4 = new SoundFile(this, "sound4.wav"); //Load Sound for Bell Button soundbell = new SoundFile(this, "soundbell.wav"); //Load Sound for Help Button soundhelp = new SoundFile(this, "soundhelp.wav"); } public void draw(){ update(mouseX,mouseY); background(0); image(img,0,0); textSize(16); fill(0); text(desiredFloor,215,640); //Button 1 Display fill(0,0); ellipse(Button1x,Button1y,NumButtonSize,NumButtonSize); //Button 2 Display fill(0,0); ellipse(Button2x,Button2y,NumButtonSize,NumButtonSize); //Button 3 Display fill(0,0); ellipse(Button3x,Button3y,NumButtonSize,NumButtonSize); //Button 4 Display fill(0,0); ellipse(Button4x,Button4y,NumButtonSize,NumButtonSize); //Bell Button Display fill(0,0); ellipse(BellButtonx,BellButtony,BellButtonSize,BellButtonSize); //Help Button Display fill(0,0); ellipse(HelpButtonx,HelpButtony,HelpButtonSize,HelpButtonSize); } public void update(int x, int y) { //Button 1 Update if (OverButton(Button1x,Button1y,NumButtonSize)){ Button1Over=true; } else { Button1Over=false; } //Button 2 Update if (OverButton(Button2x,Button2y,NumButtonSize)){ Button2Over=true; } else { Button2Over=false; } //Button 3 Update if (OverButton(Button3x,Button3y,NumButtonSize)){ Button3Over=true; } else { Button3Over=false; } //Button 4 Update if (OverButton(Button4x,Button4y,NumButtonSize)){ Button4Over=true; } else { Button4Over=false; } //Bell Button Update if (OverButton(BellButtonx,BellButtony,BellButtonSize)){ BellButtonOver=true; } else { BellButtonOver=false; } //Help Button Update if (OverButton(HelpButtonx,HelpButtony,HelpButtonSize)){ HelpButtonOver=true; } else { HelpButtonOver=false; } } public void mousePressed(){ //Button 1 Mouse Pressed if (Button1Over){ sound1.play(); desiredFloor="1"; } //Button 2 Mouse Pressed if (Button2Over){ sound2.play(); desiredFloor="2"; } //Button 3 Mouse Pressed if (Button3Over){ sound3.play(); desiredFloor="3"; } //Button 4 Mouse Pressed if (Button4Over){ sound4.play(); desiredFloor="4"; } //Bell Button Mouse Pressed if (BellButtonOver){ soundbell.play(); } //Help Button Mouse Pressed if (HelpButtonOver){ soundhelp.play(); } } public boolean OverButton(int x, int y, int diameter){ float disX = x - mouseX; float disY = y - mouseY; if (sqrt(sq(disX)+sq(disY))<diameter/2){ return true; } else{ return false; } } public void settings() { size(500,1000); } static public void main(String[] passedArgs) { String[] appletArgs = new String[] { "hw1_49_Torres" }; if (passedArgs != null) { PApplet.main(concat(appletArgs, passedArgs)); } else { PApplet.main(appletArgs); } } } <file_sep># CS 3366 - Homework 1 - Elevator Daze <NAME> ## Rally Point Charlie - Design Critique ### Elevator Chosen: **Resident Elevator - 25Twenty Apartments, Lubbock, TX** ### Images **Image**: ![alt text](https://raw.githubusercontent.com/SapphireLion/ElevatorDaze/master/Image1.jpg) **GIF:** ![alt text](https://raw.githubusercontent.com/SapphireLion/ElevatorDaze/master/Gif1.gif.gif) ### Critique - **Circles**: Which button corresponds to which floor? (Disconnected numbers) - **Basic Design**: Black and White design is rather plain. - **Uneducated be Damned**: What is the difference between the Bell button and the HELP button? Who does HELP call? - **Positives**: Braile on numbering aids the blind. ## Rally Point Bravo - Functionality Review ### Uses for an Elevator Control Panel: - **Go Up and Down** - Yes, but the display could be a bit more clear. - **Emergency Services** - Yes, but they are vague - **Services for Disabled** - Yes, Braile, but it could be more visible. - **Wrong Floor Cancel** - No - **Current Weight on Elevator** - No - **Current Floor Display** - No ### Common Use Cases - **Use Case 1: User Enters Elevator** User enters elevator, reads display, selects floor they wish to travel towards, then waits for elevator doors to close, then travels to corresponding floor - **Use Case 2: Emergency** User has emergency occur during elevator travel, uses emergency button ### Design More colorful vibe - Infinity Gauntley Elevator Panel ![alt text](https://raw.githubusercontent.com/SapphireLion/ElevatorDaze/master/hw1_49_Torres/data/infinity_gauntlet.png) ## Rally Point Alpha Working GIF: ![alt text](https://raw.githubusercontent.com/SapphireLion/ElevatorDaze/master/ig_gif.gif)
04f29818191dbb64aad83ff6022cdebf91a72454
[ "Markdown", "Java" ]
2
Java
SapphireLion/hw1.49.Torres
9fbf7439ba8021ebbf143eac478a968e868fb750
f288e5a2dc6be91ea9aa3213953cacd87b85d5cc
refs/heads/master
<file_sep>package com.matteo.pipitone.strategyPattern.worker; import org.springframework.stereotype.Component; @Component public class Developer implements IWorker{ @Override public String Work() { return "Developing new features"; } @Override public String HoursOfWork() { return "10 hours"; } } <file_sep># StrategyPattern Simple implementation of strategy pattern with spring boot
30af2b2895112d5bc3cebc4c71f50737135a5413
[ "Markdown", "Java" ]
2
Java
crakdelpol/StrategyPattern
c97f454b234930bb20c5afbf06b50e8257b5c4b1
448d504f3c9055d4cfb6115fc32faca4bbc6eb4f
refs/heads/master
<file_sep>from collections import Counter from sklearn.datasets import load_files from sklearn.datasets import fetch_20newsgroups from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.naive_bayes import MultinomialNB from sklearn.pipeline import make_pipeline from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split import os # from imblearn.under_sampling import RandomUnderSampler # from imblearn.pipeline import make_pipeline as make_pipeline_imb # from imblearn.metrics import classification_report_imbalanced # Loading Data articles_per_category = 200 path = os.getcwd() dirs = os.listdir(path) dir_list = [] labels = [] for i in range(0, len(dirs)): temp = path + '/' + dirs[i] if os.path.isdir(temp): dir_list.append(temp) # print(temp) labels.append(dirs[i]) fileList = [] Y = [] # print(labels) temp = 0 for dir in dir_list: if (dir == "/hdd1/basicMachineLearning/Baitap/.git"): continue # dir_len = len([name for name in os.listdir(dir) if os.path.isfile(os.path.join(dir, name))]) lists = [dir + '/' + str(i) + '.txt' for i in range(0, articles_per_category)] for l in lists: fileList.append(l) for i in range(0, articles_per_category): Y.append(labels[temp]) temp += 1 vectorizer = TfidfVectorizer(input="filename") X = vectorizer.fit_transform(fileList).toarray() X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2,random_state=10) bayes = MultinomialNB() bayes.fit(X_train, Y_train) Y_pred = bayes.predict(X_test) accuracy = accuracy_score(Y_test, Y_pred) print("Accuracy of Naive Bayes : " ,accuracy * 100 , "%") # print(classification_report_imbalanced(Y_test, Y_pred)) <file_sep>from __future__ import print_function import json import os articles_loop = 200 with open('articles.json') as json_data: # Load JSON articles = json.load(json_data) print(len(articles), "Articles loaded succesfully") # Loop through every article in the json file for article in articles: # Your code lies here : # category = article["Category"] # if (category=="Xã hội" or category=="Pháp luật"):`` # category = 'thời sự' # if (category=="Doanh nghiệp" or category=="Kinh tế"): # category = "Kinh tế" if not (os.path.exists(category)): os.mkdir(category) title = article["Title"] content = article["Content"] filename = (str) (len([name for name in os.listdir(category) if os.path.isfile(os.path.join(category, name))])) text_file = filename + '.txt' f = open(text_file, "w+") f.write(title + '\n' + content) f.close() os.system("mv " + text_file + " " + '\"' + category + '\"') path = os.getcwd() dirs = os.listdir(path) dir_list = [] for i in range(0, len(dirs)): temp = path + '/' + dirs[i] if os.path.isdir(temp): dir_list.append(temp) for dir in dir_list: dir_len = len([name for name in os.listdir(dir) if os.path.isfile(os.path.join(dir, name))]) if (dir_len < articles_loop): for file in os.listdir(dir): file_path = os.path.join(dir, file) if os.path.isfile(file_path): os.remove(file_path) os.rmdir(dir) print("Test git\n") #the fuck , is this <file_sep>from sklearn.datasets import load_iris from sklearn import tree import numpy as np import pandas as pd csv_filename = 'TitanicPreprocessed.csv' db = pd.read_csv(csv_filename) # print(db)<file_sep>import numpy as np # Thư viện dùng để xử lý from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import train_test_split import os from sklearn.metrics import accuracy_score articles_loop = 200 path = os.getcwd() dirs = os.listdir(path) dir_list = [] labels = [] for i in range(0, len(dirs)): temp = path + '/' + dirs[i] if os.path.isdir(temp): dir_list.append(temp) # print(temp) labels.append(dirs[i]) fileList = [] Y = [] # print(labels) temp = 0 for dir in dir_list: if (dir == "/hdd1/basicMachineLearning/Baitap/.git"): continue # dir_len = len([name for name in os.listdir(dir) if os.path.isfile(os.path.join(dir, name))]) lists = [dir + '/' + str(i) + '.txt' for i in range(0, articles_loop)] for l in lists: fileList.append(l) for i in range(0, articles_loop): Y.append(labels[temp]) temp += 1 # print(len(fileList)) # print(len(Y)) # print(Y) vectorizer = TfidfVectorizer(input="filename") X = vectorizer.fit_transform(fileList).toarray() X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.15,random_state=10) print("Training size: " + (str)(len(X_train))) print("Test size : " + (str)(len(X_test))) n = 11 neigh = KNeighborsClassifier(n_neighbors=n,p=2, weights='distance',n_jobs=4) neigh.fit(X_train, Y_train) Y_predict = neigh.predict(X_test) accuracy = accuracy_score(Y_test, Y_predict) print("Accuracy of ", n,"-NN : " ,accuracy * 100 , "%") # print('\n') # in ra mot vai ket qua # print('Predicted labels: ', Y_predict[20:30]) # print('Ground truth : ', Y_test[20:30]) # Testing using GitHub # Test again # Testing using GitHub # Test2
2441750dc08dcfc4e04c76e09f9ee54e57db2b0d
[ "Python" ]
4
Python
ThanhHieuDang0706/BasicML
e8a14a98883bbe87e66e2b6cafee8d1672438db9
d38eae6012b8c4aca029311593c79a65f78b904d