diff --git a/code/IndexedDBShim.min.js b/code/IndexedDBShim.min.js new file mode 100644 index 0000000..29a317e --- /dev/null +++ b/code/IndexedDBShim.min.js @@ -0,0 +1,3 @@ +/*! IndexedDBShim - v0.1.2 - 2014-06-14 */ +"use strict";var idbModules={},cleanInterface=!1;(function(){var e={test:!0};if(Object.defineProperty)try{Object.defineProperty(e,"test",{enumerable:!1}),e.test&&(cleanInterface=!0)}catch(t){}})(),function(e){function t(e,t,n,o){n.target=t,"function"==typeof t[e]&&t[e].apply(t,[n]),"function"==typeof o&&o()}function n(t,n,o){var r=new DOMException.prototype.constructor(0,n);throw r.name=t,r.message=n,e.DEBUG&&(console.log(t,n,o,r),console.trace&&console.trace()),r}var o=function(){this.length=0,this._items=[],cleanInterface&&Object.defineProperty(this,"_items",{enumerable:!1})};if(o.prototype={contains:function(e){return-1!==this._items.indexOf(e)},item:function(e){return this._items[e]},indexOf:function(e){return this._items.indexOf(e)},push:function(e){this._items.push(e),this.length+=1;for(var t=0;this._items.length>t;t++)this[t]=this._items[t]},splice:function(){this._items.splice.apply(this._items,arguments),this.length=this._items.length;for(var e in this)e===parseInt(e,10)+""&&delete this[e];for(e=0;this._items.length>e;e++)this[e]=this._items[e]}},cleanInterface)for(var r in{indexOf:!1,push:!1,splice:!1})Object.defineProperty(o.prototype,r,{enumerable:!1});e.util={throwDOMException:n,callback:t,quote:function(e){return"'"+e+"'"},StringList:o}}(idbModules),function(idbModules){var Sca=function(){return{decycle:function(object,callback){function checkForCompletion(){0===queuedObjects.length&&returnCallback(derezObj)}function readBlobAsDataURL(e,t){var n=new FileReader;n.onloadend=function(e){var n=e.target.result,o="blob";updateEncodedBlob(n,t,o)},n.readAsDataURL(e)}function updateEncodedBlob(dataURL,path,blobtype){var encoded=queuedObjects.indexOf(path);path=path.replace("$","derezObj"),eval(path+'.$enc="'+dataURL+'"'),eval(path+'.$type="'+blobtype+'"'),queuedObjects.splice(encoded,1),checkForCompletion()}function derez(e,t){var n,o,r;if(!("object"!=typeof e||null===e||e instanceof Boolean||e instanceof Date||e instanceof Number||e instanceof RegExp||e instanceof Blob||e instanceof String)){for(n=0;objects.length>n;n+=1)if(objects[n]===e)return{$ref:paths[n]};if(objects.push(e),paths.push(t),"[object Array]"===Object.prototype.toString.apply(e))for(r=[],n=0;e.length>n;n+=1)r[n]=derez(e[n],t+"["+n+"]");else{r={};for(o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=derez(e[o],t+"["+JSON.stringify(o)+"]"))}return r}return e instanceof Blob?(queuedObjects.push(t),readBlobAsDataURL(e,t)):e instanceof Boolean?e={$type:"bool",$enc:""+e}:e instanceof Date?e={$type:"date",$enc:e.getTime()}:e instanceof Number?e={$type:"num",$enc:""+e}:e instanceof RegExp&&(e={$type:"regex",$enc:""+e}),e}var objects=[],paths=[],queuedObjects=[],returnCallback=callback,derezObj=derez(object,"$");checkForCompletion()},retrocycle:function retrocycle($){function dataURLToBlob(e){var t,n,o,r=";base64,";if(-1===e.indexOf(r))return n=e.split(","),t=n[0].split(":")[1],o=n[1],new Blob([o],{type:t});n=e.split(r),t=n[0].split(":")[1],o=window.atob(n[1]);for(var i=o.length,a=new Uint8Array(i),s=0;i>s;++s)a[s]=o.charCodeAt(s);return new Blob([a.buffer],{type:t})}function rez(value){var i,item,name,path;if(value&&"object"==typeof value)if("[object Array]"===Object.prototype.toString.apply(value))for(i=0;value.length>i;i+=1)item=value[i],item&&"object"==typeof item&&(path=item.$ref,value[i]="string"==typeof path&&px.test(path)?eval(path):rez(item));else if(void 0!==value.$type)switch(value.$type){case"blob":case"file":value=dataURLToBlob(value.$enc);break;case"bool":value=Boolean("true"===value.$enc);break;case"date":value=new Date(value.$enc);break;case"num":value=Number(value.$enc);break;case"regex":value=eval(value.$enc)}else for(name in value)"object"==typeof value[name]&&(item=value[name],item&&(path=item.$ref,value[name]="string"==typeof path&&px.test(path)?eval(path):rez(item)));return value}var px=/^\$(?:\[(?:\d+|\"(?:[^\\\"\u0000-\u001f]|\\([\\\"\/bfnrt]|u[0-9a-zA-Z]{4}))*\")\])*$/;return rez($),$},encode:function(e,t){function n(e){t(JSON.stringify(e))}this.decycle(e,n)},decode:function(e){return this.retrocycle(JSON.parse(e))}}}();idbModules.Sca=Sca}(idbModules),function(e){var t=["","number","string","boolean","object","undefined"],n=function(){return{encode:function(e){return t.indexOf(typeof e)+"-"+JSON.stringify(e)},decode:function(e){return e===void 0?void 0:JSON.parse(e.substring(2))}}},o={number:n("number"),"boolean":n(),object:n(),string:{encode:function(e){return t.indexOf("string")+"-"+e},decode:function(e){return""+e.substring(2)}},undefined:{encode:function(){return t.indexOf("undefined")+"-undefined"},decode:function(){return void 0}}},r=function(){return{encode:function(e){return o[typeof e].encode(e)},decode:function(e){return o[t[e.substring(0,1)]].decode(e)}}}();e.Key=r}(idbModules),function(e){var t=function(e,t){return{type:e,debug:t,bubbles:!1,cancelable:!1,eventPhase:0,timeStamp:new Date}};e.Event=t}(idbModules),function(e){var t=function(){this.onsuccess=this.onerror=this.result=this.error=this.source=this.transaction=null,this.readyState="pending"},n=function(){this.onblocked=this.onupgradeneeded=null};n.prototype=t,e.IDBRequest=t,e.IDBOpenRequest=n}(idbModules),function(e,t){var n=function(e,t,n,o){this.lower=e,this.upper=t,this.lowerOpen=n,this.upperOpen=o};n.only=function(e){return new n(e,e,!1,!1)},n.lowerBound=function(e,o){return new n(e,t,o,t)},n.upperBound=function(e){return new n(t,e,t,open)},n.bound=function(e,t,o,r){return new n(e,t,o,r)},e.IDBKeyRange=n}(idbModules),function(e,t){function n(n,o,r,i,a,s){this.__range=n,this.source=this.__idbObjectStore=r,this.__req=i,this.key=t,this.direction=o,this.__keyColumnName=a,this.__valueColumnName=s,this.__valueDecoder="value"===s?e.Sca:e.Key,this.source.transaction.__active||e.util.throwDOMException("TransactionInactiveError - The transaction this IDBObjectStore belongs to is not active."),this.__offset=-1,this.__lastKeyContinued=t,this["continue"]()}n.prototype.__find=function(n,o,r,i,a){a=a||1;var s=this,c=["SELECT * FROM ",e.util.quote(s.__idbObjectStore.name)],u=[];c.push("WHERE ",s.__keyColumnName," NOT NULL"),s.__range&&(s.__range.lower||s.__range.upper)&&(c.push("AND"),s.__range.lower&&(c.push(s.__keyColumnName+(s.__range.lowerOpen?" >":" >= ")+" ?"),u.push(e.Key.encode(s.__range.lower))),s.__range.lower&&s.__range.upper&&c.push("AND"),s.__range.upper&&(c.push(s.__keyColumnName+(s.__range.upperOpen?" < ":" <= ")+" ?"),u.push(e.Key.encode(s.__range.upper)))),n!==t&&(s.__lastKeyContinued=n,s.__offset=0),s.__lastKeyContinued!==t&&(c.push("AND "+s.__keyColumnName+" >= ?"),u.push(e.Key.encode(s.__lastKeyContinued))),c.push("ORDER BY ",s.__keyColumnName),c.push("LIMIT "+a+" OFFSET "+s.__offset),e.DEBUG&&console.log(c.join(" "),u),s.__prefetchedData=null,o.executeSql(c.join(" "),u,function(n,o){o.rows.length>1?(s.__prefetchedData=o.rows,s.__prefetchedIndex=0,e.DEBUG&&console.log("Preloaded "+s.__prefetchedData.length+" records for cursor"),s.__decode(o.rows.item(0),r)):1===o.rows.length?s.__decode(o.rows.item(0),r):(e.DEBUG&&console.log("Reached end of cursors"),r(t,t))},function(t,n){e.DEBUG&&console.log("Could not execute Cursor.continue"),i(n)})},n.prototype.__decode=function(t,n){var o=e.Key.decode(t[this.__keyColumnName]),r=this.__valueDecoder.decode(t[this.__valueColumnName]),i=e.Key.decode(t.key);n(o,r,i)},n.prototype["continue"]=function(n){var o=e.cursorPreloadPackSize||100,r=this;this.__idbObjectStore.transaction.__addToTransactionQueue(function(e,i,a,s){r.__offset++;var c=function(e,n,o){r.key=e,r.value=n,r.primaryKey=o,a(r.key!==t?r:t,r.__req)};return r.__prefetchedData&&(r.__prefetchedIndex++,r.__prefetchedIndex=n&&e.util.throwDOMException("Type Error - Count is invalid - 0 or negative",n);var o=this;this.__idbObjectStore.transaction.__addToTransactionQueue(function(e,r,i,a){o.__offset+=n,o.__find(t,e,function(e,n){o.key=e,o.value=n,i(o.key!==t?o:t,o.__req)},a)})},n.prototype.update=function(n){var o=this,r=this.__idbObjectStore.transaction.__createRequest(function(){});return e.Sca.encode(n,function(n){o.__idbObjectStore.transaction.__pushToQueue(r,function(r,i,a,s){o.__find(t,r,function(t,i,c){var u="UPDATE "+e.util.quote(o.__idbObjectStore.name)+" SET value = ? WHERE key = ?";e.DEBUG&&console.log(u,n,t,c),r.executeSql(u,[n,e.Key.encode(c)],function(e,n){1===n.rowsAffected?a(t):s("No rows with key found"+t)},function(e,t){s(t)})},s)})}),r},n.prototype["delete"]=function(){var n=this;return this.__idbObjectStore.transaction.__addToTransactionQueue(function(o,r,i,a){n.__find(t,o,function(r,s,c){var u="DELETE FROM "+e.util.quote(n.__idbObjectStore.name)+" WHERE key = ?";e.DEBUG&&console.log(u,r,c),o.executeSql(u,[e.Key.encode(c)],function(e,o){1===o.rowsAffected?(n.__offset--,i(t)):a("No rows with key found"+r)},function(e,t){a(t)})},a)})},e.IDBCursor=n}(idbModules),function(idbModules,undefined){function IDBIndex(e,t){this.indexName=this.name=e,this.__idbObjectStore=this.objectStore=this.source=t;var n=t.__storeProps&&t.__storeProps.indexList;n&&(n=JSON.parse(n)),this.keyPath=n&&n[e]&&n[e].keyPath||e,["multiEntry","unique"].forEach(function(t){this[t]=!!(n&&n[e]&&n[e].optionalParams&&n[e].optionalParams[t])},this)}IDBIndex.prototype.__createIndex=function(indexName,keyPath,optionalParameters){var me=this,transaction=me.__idbObjectStore.transaction;transaction.__addToTransactionQueue(function(tx,args,success,failure){me.__idbObjectStore.__getStoreProps(tx,function(){function error(){idbModules.util.throwDOMException(0,"Could not create new index",arguments)}2!==transaction.mode&&idbModules.util.throwDOMException(0,"Invalid State error, not a version transaction",me.transaction);var idxList=JSON.parse(me.__idbObjectStore.__storeProps.indexList);idxList[indexName]!==undefined&&idbModules.util.throwDOMException(0,"Index already exists on store",idxList);var columnName=indexName;idxList[indexName]={columnName:columnName,keyPath:keyPath,optionalParams:optionalParameters},me.__idbObjectStore.__storeProps.indexList=JSON.stringify(idxList);var sql=["ALTER TABLE",idbModules.util.quote(me.__idbObjectStore.name),"ADD",columnName,"BLOB"].join(" ");idbModules.DEBUG&&console.log(sql),tx.executeSql(sql,[],function(tx,data){tx.executeSql("SELECT * FROM "+idbModules.util.quote(me.__idbObjectStore.name),[],function(tx,data){(function initIndexForRow(i){if(data.rows.length>i)try{var value=idbModules.Sca.decode(data.rows.item(i).value),indexKey=eval("value['"+keyPath+"']");tx.executeSql("UPDATE "+idbModules.util.quote(me.__idbObjectStore.name)+" set "+columnName+" = ? where key = ?",[idbModules.Key.encode(indexKey),data.rows.item(i).key],function(){initIndexForRow(i+1)},error)}catch(e){initIndexForRow(i+1)}else idbModules.DEBUG&&console.log("Updating the indexes in table",me.__idbObjectStore.__storeProps),tx.executeSql("UPDATE __sys__ set indexList = ? where name = ?",[me.__idbObjectStore.__storeProps.indexList,me.__idbObjectStore.name],function(){me.__idbObjectStore.__setReadyState("createIndex",!0),success(me)},error)})(0)},error)},error)},"createObjectStore")})},IDBIndex.prototype.openCursor=function(e,t){var n=new idbModules.IDBRequest;return new idbModules.IDBCursor(e,t,this.source,n,this.indexName,"value"),n},IDBIndex.prototype.openKeyCursor=function(e,t){var n=new idbModules.IDBRequest;return new idbModules.IDBCursor(e,t,this.source,n,this.indexName,"key"),n},IDBIndex.prototype.__fetchIndexData=function(e,t){var n=this;return n.__idbObjectStore.transaction.__addToTransactionQueue(function(o,r,i,a){var s=["SELECT * FROM ",idbModules.util.quote(n.__idbObjectStore.name)," WHERE",n.indexName,"NOT NULL"],c=[];e!==undefined&&(s.push("AND",n.indexName," = ?"),c.push(idbModules.Key.encode(e))),idbModules.DEBUG&&console.log("Trying to fetch data for Index",s.join(" "),c),o.executeSql(s.join(" "),c,function(e,n){var o;o="count"===t?n.rows.length:0===n.rows.length?undefined:"key"===t?idbModules.Key.decode(n.rows.item(0).key):idbModules.Sca.decode(n.rows.item(0).value),i(o)},a)})},IDBIndex.prototype.get=function(e){return this.__fetchIndexData(e,"value")},IDBIndex.prototype.getKey=function(e){return this.__fetchIndexData(e,"key")},IDBIndex.prototype.count=function(e){return this.__fetchIndexData(e,"count")},idbModules.IDBIndex=IDBIndex}(idbModules),function(idbModules){var IDBObjectStore=function(e,t,n){this.name=e,this.transaction=t,this.__ready={},this.__setReadyState("createObjectStore",n===void 0?!0:n),this.indexNames=new idbModules.util.StringList};IDBObjectStore.prototype.__setReadyState=function(e,t){this.__ready[e]=t},IDBObjectStore.prototype.__waitForReady=function(e,t){var n=!0;if(t!==void 0)n=this.__ready[t]===void 0?!0:this.__ready[t];else for(var o in this.__ready)this.__ready[o]||(n=!1);if(n)e();else{idbModules.DEBUG&&console.log("Waiting for to be ready",t);var r=this;window.setTimeout(function(){r.__waitForReady(e,t)},100)}},IDBObjectStore.prototype.__getStoreProps=function(e,t,n){var o=this;this.__waitForReady(function(){o.__storeProps?(idbModules.DEBUG&&console.log("Store properties - cached",o.__storeProps),t(o.__storeProps)):e.executeSql("SELECT * FROM __sys__ where name = ?",[o.name],function(e,n){1!==n.rows.length?t():(o.__storeProps={name:n.rows.item(0).name,indexList:n.rows.item(0).indexList,autoInc:n.rows.item(0).autoInc,keyPath:n.rows.item(0).keyPath},idbModules.DEBUG&&console.log("Store properties",o.__storeProps),t(o.__storeProps))},function(){t()})},n)},IDBObjectStore.prototype.__deriveKey=function(tx,value,key,callback){function getNextAutoIncKey(){tx.executeSql("SELECT * FROM sqlite_sequence where name like ?",[me.name],function(e,t){1!==t.rows.length?callback(0):callback(t.rows.item(0).seq)},function(e,t){idbModules.util.throwDOMException(0,"Data Error - Could not get the auto increment value for key",t)})}var me=this;me.__getStoreProps(tx,function(props){if(props||idbModules.util.throwDOMException(0,"Data Error - Could not locate defination for this table",props),props.keyPath)if(key!==void 0&&idbModules.util.throwDOMException(0,"Data Error - The object store uses in-line keys and the key parameter was provided",props),value)try{var primaryKey=eval("value['"+props.keyPath+"']");primaryKey?callback(primaryKey):"true"===props.autoInc?getNextAutoIncKey():idbModules.util.throwDOMException(0,"Data Error - Could not eval key from keyPath")}catch(e){idbModules.util.throwDOMException(0,"Data Error - Could not eval key from keyPath",e)}else idbModules.util.throwDOMException(0,"Data Error - KeyPath was specified, but value was not");else key!==void 0?callback(key):"false"===props.autoInc?idbModules.util.throwDOMException(0,"Data Error - The object store uses out-of-line keys and has no key generator and the key parameter was not provided. ",props):getNextAutoIncKey()})},IDBObjectStore.prototype.__insertData=function(tx,encoded,value,primaryKey,success,error){var paramMap={};primaryKey!==void 0&&(paramMap.key=idbModules.Key.encode(primaryKey));var indexes=JSON.parse(this.__storeProps.indexList);for(var key in indexes)try{paramMap[indexes[key].columnName]=idbModules.Key.encode(eval("value['"+indexes[key].keyPath+"']"))}catch(e){error(e)}var sqlStart=["INSERT INTO ",idbModules.util.quote(this.name),"("],sqlEnd=[" VALUES ("],sqlValues=[];for(key in paramMap)sqlStart.push(key+","),sqlEnd.push("?,"),sqlValues.push(paramMap[key]);sqlStart.push("value )"),sqlEnd.push("?)"),sqlValues.push(encoded);var sql=sqlStart.join(" ")+sqlEnd.join(" ");idbModules.DEBUG&&console.log("SQL for adding",sql,sqlValues),tx.executeSql(sql,sqlValues,function(){success(primaryKey)},function(e,t){error(t)})},IDBObjectStore.prototype.add=function(e,t){var n=this,o=n.transaction.__createRequest(function(){});return idbModules.Sca.encode(e,function(r){n.transaction.__pushToQueue(o,function(o,i,a,s){n.__deriveKey(o,e,t,function(t){n.__insertData(o,r,e,t,a,s)})})}),o},IDBObjectStore.prototype.put=function(e,t){var n=this,o=n.transaction.__createRequest(function(){});return idbModules.Sca.encode(e,function(r){n.transaction.__pushToQueue(o,function(o,i,a,s){n.__deriveKey(o,e,t,function(t){var i="DELETE FROM "+idbModules.util.quote(n.name)+" where key = ?";o.executeSql(i,[idbModules.Key.encode(t)],function(o,i){idbModules.DEBUG&&console.log("Did the row with the",t,"exist? ",i.rowsAffected),n.__insertData(o,r,e,t,a,s)},function(e,t){s(t)})})})}),o},IDBObjectStore.prototype.get=function(e){var t=this;return t.transaction.__addToTransactionQueue(function(n,o,r,i){t.__waitForReady(function(){var o=idbModules.Key.encode(e);idbModules.DEBUG&&console.log("Fetching",t.name,o),n.executeSql("SELECT * FROM "+idbModules.util.quote(t.name)+" where key = ?",[o],function(e,t){idbModules.DEBUG&&console.log("Fetched data",t);try{if(0===t.rows.length)return r();r(idbModules.Sca.decode(t.rows.item(0).value))}catch(n){idbModules.DEBUG&&console.log(n),r(void 0)}},function(e,t){i(t)})})})},IDBObjectStore.prototype["delete"]=function(e){var t=this;return t.transaction.__addToTransactionQueue(function(n,o,r,i){t.__waitForReady(function(){var o=idbModules.Key.encode(e);idbModules.DEBUG&&console.log("Fetching",t.name,o),n.executeSql("DELETE FROM "+idbModules.util.quote(t.name)+" where key = ?",[o],function(e,t){idbModules.DEBUG&&console.log("Deleted from database",t.rowsAffected),r()},function(e,t){i(t)})})})},IDBObjectStore.prototype.clear=function(){var e=this;return e.transaction.__addToTransactionQueue(function(t,n,o,r){e.__waitForReady(function(){t.executeSql("DELETE FROM "+idbModules.util.quote(e.name),[],function(e,t){idbModules.DEBUG&&console.log("Cleared all records from database",t.rowsAffected),o()},function(e,t){r(t)})})})},IDBObjectStore.prototype.count=function(e){var t=this;return t.transaction.__addToTransactionQueue(function(n,o,r,i){t.__waitForReady(function(){var o="SELECT * FROM "+idbModules.util.quote(t.name)+(e!==void 0?" WHERE key = ?":""),a=[];e!==void 0&&a.push(idbModules.Key.encode(e)),n.executeSql(o,a,function(e,t){r(t.rows.length)},function(e,t){i(t)})})})},IDBObjectStore.prototype.openCursor=function(e,t){var n=new idbModules.IDBRequest;return new idbModules.IDBCursor(e,t,this,n,"key","value"),n},IDBObjectStore.prototype.index=function(e){var t=new idbModules.IDBIndex(e,this);return t},IDBObjectStore.prototype.createIndex=function(e,t,n){var o=this;n=n||{},o.__setReadyState("createIndex",!1);var r=new idbModules.IDBIndex(e,o);return o.__waitForReady(function(){r.__createIndex(e,t,n)},"createObjectStore"),o.indexNames.push(e),r},IDBObjectStore.prototype.deleteIndex=function(e){var t=new idbModules.IDBIndex(e,this,!1);return t.__deleteIndex(e),t},idbModules.IDBObjectStore=IDBObjectStore}(idbModules),function(e){var t=0,n=1,o=2,r=function(o,r,i){if("number"==typeof r)this.mode=r,2!==r&&e.DEBUG&&console.log("Mode should be a string, but was specified as ",r);else if("string"==typeof r)switch(r){case"readwrite":this.mode=n;break;case"readonly":this.mode=t;break;default:this.mode=t}this.storeNames="string"==typeof o?[o]:o;for(var a=0;this.storeNames.length>a;a++)i.objectStoreNames.contains(this.storeNames[a])||e.util.throwDOMException(0,"The operation failed because the requested database object could not be found. For example, an object store did not exist but was being opened.",this.storeNames[a]);this.__active=!0,this.__running=!1,this.__requests=[],this.__aborted=!1,this.db=i,this.error=null,this.onabort=this.onerror=this.oncomplete=null};r.prototype.__executeRequests=function(){if(this.__running&&this.mode!==o)return e.DEBUG&&console.log("Looks like the request set is already running",this.mode),void 0;this.__running=!0;var t=this;window.setTimeout(function(){2===t.mode||t.__active||e.util.throwDOMException(0,"A request was placed against a transaction which is currently not active, or which is finished",t.__active),t.db.__db.transaction(function(n){function o(t,n){n&&(a.req=n),a.req.readyState="done",a.req.result=t,delete a.req.error;var o=e.Event("success");e.util.callback("onsuccess",a.req,o),s++,i()}function r(){a.req.readyState="done",a.req.error="DOMError";var t=e.Event("error",arguments);e.util.callback("onerror",a.req,t),s++,i()}function i(){return s>=t.__requests.length?(t.__active=!1,t.__requests=[],void 0):(a=t.__requests[s],a.op(n,a.args,o,r),void 0)}t.__tx=n;var a=null,s=0;try{i()}catch(c){e.DEBUG&&console.log("An exception occured in transaction",arguments),"function"==typeof t.onerror&&t.onerror()}},function(){e.DEBUG&&console.log("An error in transaction",arguments),"function"==typeof t.onerror&&t.onerror()},function(){e.DEBUG&&console.log("Transaction completed",arguments),"function"==typeof t.oncomplete&&t.oncomplete()})},1)},r.prototype.__addToTransactionQueue=function(t,n){this.__active||this.mode===o||e.util.throwDOMException(0,"A request was placed against a transaction which is currently not active, or which is finished.",this.__mode);var r=this.__createRequest();return this.__pushToQueue(r,t,n),r},r.prototype.__createRequest=function(){var t=new e.IDBRequest;return t.source=this.db,t.transaction=this,t},r.prototype.__pushToQueue=function(e,t,n){this.__requests.push({op:t,args:n,req:e}),this.__executeRequests()},r.prototype.objectStore=function(t){return new e.IDBObjectStore(t,this)},r.prototype.abort=function(){!this.__active&&e.util.throwDOMException(0,"A request was placed against a transaction which is currently not active, or which is finished",this.__active)},r.prototype.READ_ONLY=0,r.prototype.READ_WRITE=1,r.prototype.VERSION_CHANGE=2,e.IDBTransaction=r}(idbModules),function(e){var t=function(t,n,o,r){this.__db=t,this.version=o,this.__storeProperties=r,this.objectStoreNames=new e.util.StringList;for(var i=0;r.rows.length>i;i++)this.objectStoreNames.push(r.rows.item(i).name);this.name=n,this.onabort=this.onerror=this.onversionchange=null};t.prototype.createObjectStore=function(t,n){var o=this;n=n||{},n.keyPath=n.keyPath||null;var r=new e.IDBObjectStore(t,o.__versionTransaction,!1),i=o.__versionTransaction;return i.__addToTransactionQueue(function(i,a,s){function c(){e.util.throwDOMException(0,"Could not create new object store",arguments)}o.__versionTransaction||e.util.throwDOMException(0,"Invalid State error",o.transaction);var u=["CREATE TABLE",e.util.quote(t),"(key BLOB",n.autoIncrement?", inc INTEGER PRIMARY KEY AUTOINCREMENT":"PRIMARY KEY",", value BLOB)"].join(" ");e.DEBUG&&console.log(u),i.executeSql(u,[],function(e){e.executeSql("INSERT INTO __sys__ VALUES (?,?,?,?)",[t,n.keyPath,n.autoIncrement?!0:!1,"{}"],function(){r.__setReadyState("createObjectStore",!0),s(r)},c)},c)}),o.objectStoreNames.push(t),r},t.prototype.deleteObjectStore=function(t){var n=function(){e.util.throwDOMException(0,"Could not delete ObjectStore",arguments)},o=this;!o.objectStoreNames.contains(t)&&n("Object Store does not exist"),o.objectStoreNames.splice(o.objectStoreNames.indexOf(t),1);var r=o.__versionTransaction;r.__addToTransactionQueue(function(){o.__versionTransaction||e.util.throwDOMException(0,"Invalid State error",o.transaction),o.__db.transaction(function(o){o.executeSql("SELECT * FROM __sys__ where name = ?",[t],function(o,r){r.rows.length>0&&o.executeSql("DROP TABLE "+e.util.quote(t),[],function(){o.executeSql("DELETE FROM __sys__ WHERE name = ?",[t],function(){},n)},n)})})})},t.prototype.close=function(){},t.prototype.transaction=function(t,n){var o=new e.IDBTransaction(t,n||1,this);return o},e.IDBDatabase=t}(idbModules),function(e){var t=4194304;if(window.openDatabase){var n=window.openDatabase("__sysdb__",1,"System Database",t);n.transaction(function(t){t.executeSql("SELECT * FROM dbVersions",[],function(){},function(){n.transaction(function(t){t.executeSql("CREATE TABLE IF NOT EXISTS dbVersions (name VARCHAR(255), version INT);",[],function(){},function(){e.util.throwDOMException("Could not create table __sysdb__ to save DB versions")})})})},function(){e.DEBUG&&console.log("Error in sysdb transaction - when selecting from dbVersions",arguments)});var o={open:function(o,r){function i(){if(!c){var t=e.Event("error",arguments);s.readyState="done",s.error="DOMError",e.util.callback("onerror",s,t),c=!0}}function a(a){var c=window.openDatabase(o,1,o,t);s.readyState="done",r===void 0&&(r=a||1),(0>=r||a>r)&&e.util.throwDOMException(0,"An attempt was made to open a database using a lower version than the existing version.",r),c.transaction(function(t){t.executeSql("CREATE TABLE IF NOT EXISTS __sys__ (name VARCHAR(255), keyPath VARCHAR(255), autoInc BOOLEAN, indexList BLOB)",[],function(){t.executeSql("SELECT * FROM __sys__",[],function(t,u){var d=e.Event("success");s.source=s.result=new e.IDBDatabase(c,o,r,u),r>a?n.transaction(function(t){t.executeSql("UPDATE dbVersions set version = ? where name = ?",[r,o],function(){var t=e.Event("upgradeneeded");t.oldVersion=a,t.newVersion=r,s.transaction=s.result.__versionTransaction=new e.IDBTransaction([],2,s.source),e.util.callback("onupgradeneeded",s,t,function(){var t=e.Event("success");e.util.callback("onsuccess",s,t)})},i)},i):e.util.callback("onsuccess",s,d)},i)},i)},i)}var s=new e.IDBOpenRequest,c=!1;return n.transaction(function(e){e.executeSql("SELECT * FROM dbVersions where name = ?",[o],function(e,t){0===t.rows.length?e.executeSql("INSERT INTO dbVersions VALUES (?,?)",[o,r||1],function(){a(0)},i):a(t.rows.item(0).version)},i)},i),s},deleteDatabase:function(o){function r(t){if(!s){a.readyState="done",a.error="DOMError";var n=e.Event("error");n.message=t,n.debug=arguments,e.util.callback("onerror",a,n),s=!0}}function i(){n.transaction(function(t){t.executeSql("DELETE FROM dbVersions where name = ? ",[o],function(){a.result=void 0;var t=e.Event("success");t.newVersion=null,t.oldVersion=c,e.util.callback("onsuccess",a,t)},r)},r)}var a=new e.IDBOpenRequest,s=!1,c=null;return n.transaction(function(n){n.executeSql("SELECT * FROM dbVersions where name = ?",[o],function(n,s){if(0===s.rows.length){a.result=void 0;var u=e.Event("success");return u.newVersion=null,u.oldVersion=c,e.util.callback("onsuccess",a,u),void 0}c=s.rows.item(0).version;var d=window.openDatabase(o,1,o,t);d.transaction(function(t){t.executeSql("SELECT * FROM __sys__",[],function(t,n){var o=n.rows;(function a(n){n>=o.length?t.executeSql("DROP TABLE __sys__",[],function(){i()},r):t.executeSql("DROP TABLE "+e.util.quote(o.item(n).name),[],function(){a(n+1)},function(){a(n+1)})})(0)},function(){i()})},r)})},r),a},cmp:function(t,n){return e.Key.encode(t)>e.Key.encode(n)?1:t===n?0:-1}};e.shimIndexedDB=o}}(idbModules),function(e,t){e.openDatabase!==void 0&&(e.shimIndexedDB=t.shimIndexedDB,e.shimIndexedDB&&(e.shimIndexedDB.__useShim=function(){e.indexedDB=t.shimIndexedDB,e.IDBDatabase=t.IDBDatabase,e.IDBTransaction=t.IDBTransaction,e.IDBCursor=t.IDBCursor,e.IDBKeyRange=t.IDBKeyRange,e.indexedDB!==t.shimIndexedDB&&Object.defineProperty&&Object.defineProperty(e,"indexedDB",{value:t.shimIndexedDB})},e.shimIndexedDB.__debug=function(e){t.DEBUG=e})),"indexedDB"in e||(e.indexedDB=e.indexedDB||e.webkitIndexedDB||e.mozIndexedDB||e.oIndexedDB||e.msIndexedDB);var n=!1;if((navigator.userAgent.match(/Android 2/)||navigator.userAgent.match(/Android 3/)||navigator.userAgent.match(/Android 4\.[0-3]/))&&(navigator.userAgent.match(/Chrome/)||(n=!0)),void 0!==e.indexedDB&&!n||void 0===e.openDatabase){e.IDBDatabase=e.IDBDatabase||e.webkitIDBDatabase,e.IDBTransaction=e.IDBTransaction||e.webkitIDBTransaction,e.IDBCursor=e.IDBCursor||e.webkitIDBCursor,e.IDBKeyRange=e.IDBKeyRange||e.webkitIDBKeyRange,e.IDBTransaction||(e.IDBTransaction={});try{e.IDBTransaction.READ_ONLY=e.IDBTransaction.READ_ONLY||"readonly",e.IDBTransaction.READ_WRITE=e.IDBTransaction.READ_WRITE||"readwrite"}catch(o){}}else e.shimIndexedDB.__useShim()}(window,idbModules); +//@ sourceMappingURL=http://nparashuram.com/IndexedDBShim/dist/IndexedDBShim.min.map \ No newline at end of file diff --git a/code/audio/nitroAudio.js b/code/audio/nitroAudio.js new file mode 100644 index 0000000..44fe294 --- /dev/null +++ b/code/audio/nitroAudio.js @@ -0,0 +1,113 @@ +// +// nitroAudio.js +//-------------------- +// Provides an interface for playing nds music and sound effects. +// by RHY3756547 +// + +window.AudioContext = window.AudioContext || window.webkitAudioContext; + +window.nitroAudio = new (function() { + var t = this; + var ctx; + + t.sounds = []; + + t.tick = tick; + t.playSound = playSound; + t.kill = kill; + t.init = init; + t.instaKill = instaKill; + + t.sdat = null; + + function init(sdat) { + ctx = new AudioContext(); + t.ctx = ctx; + + var listener = ctx.listener; + listener.dopplerFactor = 1; + listener.speedOfSound = 100/1024; //343.3 + + SSEQWaveCache.init(sdat, ctx); + t.sdat = sdat; + } + + function tick() { + for (var i=0; i0) { + t.threads.splice(threadsToKill.pop(), 1); + } + + if (t.threads.length == 0 && ctx.currentTime > t.lastNoteEnd) t.dead = true; + } + + function startThread(pc) { + var thread = new SSEQThread(sseqHead.seq.data, pc, t); + t.threads.push(thread); + } + + function terminateThread(thread) { + threadsToKill.push(t.threads.indexOf(thread)); + } + + function setTempo(bpm) { + //sets tempo of threads and alters their wait times to adjust + t.bpm = bpm*t.bpmMultiplier; + } + + function loadBank(bn) { + t.bank = sdat.sections["$INFO"][2][bn]; + if (t.bank == null) {return;} + for (var i=0; i<4; i++) { + if (t.bank.waveArcs[i] != 0xFFFF) SSEQWaveCache.cacheWaveArc(t.bank.waveArcs[i]); + } + } + + function cutNoteShort(thread, note) { + try { //can throw exception if note has already ended. + if (note.ended) return; + var time = thread.calculateCurrentTime(); + var baseTime = (time == Infinity)?ctx.currentTime:time; + if (baseTime > note.noteEndsAt) return; + var releaseTime = note.relTime; + note.note.gain.cancelScheduledValues(baseTime); + note.note.gain.linearRampToValueAtTime(0, baseTime+releaseTime); //then release + note.src.stop(baseTime+releaseTime); + if (baseTime+releaseTime > t.lastNoteEnd) t.lastNoteEnd = baseTime+releaseTime; + } catch (e) {} + } + + function setTranspose(newT) { + t.transpose = newT; + for (var i=0; i>11)/1000; + source.playbackRate.exponentialRampToValueAtTime(targetFreq, baseTime+time); + } + } + + //sequence the note + + var atk = (thread.attack != null)?thread.attack:inst.attack; + var dec = (thread.decay != null)?thread.decay:inst.decay; + var sus = (thread.sustain != null)?thread.sustain:inst.sustainLvl; + var rel = (thread.release != null)?thread.release:inst.release; + + var attackTime = calculateRequiredAttackCycles(convertAttToRate(atk))*CYCLE_TIME;//(255/convertAttToRate(inst.attack))*0.016; //0.01; + var decayTime = (92544/convertFallToRate(dec))*(1-sus/0x7F)*CYCLE_TIME/2; + var releaseTime = (92544/convertFallToRate(rel))*(sus/0x7F)*CYCLE_TIME/2; + + if ((!thread.tie) || thread.lastNote == null) { + note.gain.value = 0.0; + note.gain.setValueAtTime(0.0, baseTime); //initially 0 + note.gain.linearRampToValueAtTime(velocity, baseTime+attackTime); //attack + note.gain.linearRampToValueAtTime(velocity*sus/0x7F, baseTime+attackTime+decayTime); //decay + + source.start(baseTime); + + source.onended = function(){ + note.ended = true; + source.disconnect(); + } + } + + if (realDur != Infinity) { + if (baseTime+attackTime+decayTime < baseTime+realDur) note.gain.linearRampToValueAtTime(velocity*sus/0x7F, baseTime+realDur); //sustain until + note.gain.linearRampToValueAtTime(0, baseTime+realDur+releaseTime); //then release + source.stop(baseTime+realDur+releaseTime); + + if (baseTime+realDur+releaseTime > t.lastNoteEnd) t.lastNoteEnd = baseTime+realDur+releaseTime; + } + + return {src: source, base: inst.freq, start:num, note: note, relTime: releaseTime, snd: snd, noteEndsAt:baseTime+realDur}; + } + + function calculateRequiredAttackCycles(att) { + var value = 92544; + var ticks = 0; + while (value > 0) { + value = Math.floor((att*value)/255); + ticks++ + } + return ticks; + } + + function convertAttToRate(attack) { + var table = [0x00, 0x01, 0x05, 0x0E, 0x1A, 0x26, 0x33, 0x3F, 0x49, 0x54, + 0x5C, 0x64, 0x6D, 0x74, 0x7B, 0x7F, 0x84, 0x89, 0x8F]; + if (attack & 0x80) return 0; + else if (attack >= 0x6F) return table[0x7F-attack]; + else return 0xFF-attack; + } + + function convertFallToRate(fall) { + if (fall&0x80) return 0; + else if (fall == 0x7F) return 0xFFFF; + else if (fall == 0x7E) return 0x3C00; + else if (fall < 0x32) return ((fall<<1)+1)&0xFFFF; + else return (0x1E00/(0x7E-fall))&0xFFFF; + } + + function noteToFreq(n) { + return Math.pow(2, (n-49)/12)*440; + } + + function getInst(inst, note) { + switch (inst.type) { + case 0: + return null; + case 1: + return inst; + case 2: + return inst.entries[Math.max(inst.lower, Math.min(inst.upper, note))-inst.lower]; + case 3: + for (var i=0; i 10000) { Instructions[0xFF](); console.error("audio thread locked up")}; + } + + if (t.wait == Infinity && t.lastNote != null && t.lastNote.note.ended) Instructions[0xFF](); + } + + function noteOn(num) { + if (num == 0) return; //NOP + var velocity = forcableValue(true); + var length = forcableValueFunc(false, readVariableLength); + if (length == 0) length = Infinity; + t.lastNote = player.playNote(t, velocity, length, num); + if (t.noteWait) t.wait += length; + } + + function ticksToMs(ticks) { + return (ticks/48)*(60000/player.bpm); + } + + function readVariableLength() { + var read = prog[pc++]; + var value = read&0x7F; + while (read & 0x80) { + var read = prog[pc++]; + value = (value<<7) | (read&0x7F); + } + return value; + + } + + function calculateCurrentTime() { + return player.baseAudioTime+ticksToMs(t.wait-player.remainder)/1000; + } + + var InstArgs = [ //starts at 0x80 + [readVariableLength], [readVariableLength], [], [], [], [], [], [], [], [], [], [], [], [], [], [], //0x80-0x8F + [], [], [], [read8, read24], [read24], [read24], [], [], [], [], [], [], [], [], [], [], //0x90-0x9F + [read8, readSpecial, read16, read16], [read8, readSpecial], [], [], [], [], [], [], [], [], [], [], [], [], [], [], + [read8, read8], [read8, read8], [read8, read8], [read8, read8], [read8, read8], [read8, read8], [read8, read8], [], [read8, read8], [read8, read8], [read8, read8], [read8, read8], [read8, read8], [read8, read8], [], [], //0xB0-0xBF + [read8], [read8], [read8], [read8], [read8], [read8], [read8], [read8], [read8], [read8], [read8], [read8], [read8], [read8], [read8], [read8], + [read8], [read8], [read8], [read8], [read8], [read8], [read8], [], [], [], [], [], [], [], [], [], + [read16], [read16], [read16], [], [], [], [], [], [], [], [], [], [], [], [], [], + [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], + ] + + var Instructions = []; + + Instructions[0xFE] = function() { //track definition + player.trackAlloc = read16(); + } + + Instructions[0x93] = function() { //track definition + var trackID = prog[pc++]; + var newPC = prog[pc++]; + newPC |= prog[pc++]<<8; + newPC |= prog[pc++]<<16; + + var bit = 1<>7; + if (bank != 0) player.loadBank(bank); + } + + Instructions[0x94] = function() { //JUMP + var newPC = prog[pc++]; + newPC |= prog[pc++]<<8; + newPC |= prog[pc++]<<16; + pc = newPC; + } + + Instructions[0x95] = function() { //CALL + var newPC = prog[pc++]; + newPC |= prog[pc++]<<8; + newPC |= prog[pc++]<<16; + t.stack.push(pc); + pc = newPC; + } + + Instructions[0xFD] = function() { //RETURN + if (t.stack.length == 0) Instructions[0xFF](); + pc = t.stack.pop(); + } + + //LOGIC INSTRUCTIONS + + Instructions[0xA0] = function() { //random + force = true; //this command forces the input to the next command to be a generated random number + forceCommand = prog[pc++]; + if (forceCommand < 0x80 || (forceCommand >= 0xB0 && forceCommand <= 0xBD)) forceSpecial = prog[pc++]; + var min = reads16(); + var max = reads16(); + forceValue = Math.floor(Math.random()*(max-min+1))+min; + } + + Instructions[0xA1] = function() { //from var + force = true; //this command forces the input to the next command to be from a variable. use with caution probably! + forceCommand = prog[pc++]; + if (forceCommand < 0x80 || (forceCommand >= 0xB0 && forceCommand <= 0xBD)) forceSpecial = prog[pc++]; + forceValue = player.vars[prog[pc++]]; + } + + function varInst(inst){ + var varNum = forcableValue(true); + var arg = forcableValue(); + if (arg & 0x80) arg -= 256; + if (inst == 0xB4 && arg == 0) return; + varFunc[inst-0xB0](varNum, arg) + } + + var varFunc = [ //"=", "+=", "-=", "*=", "/=", "[Shift]", "[Rand]" + function(a, b) { player.vars[a] = b }, + function(a, b) { player.vars[a] += b }, + function(a, b) { player.vars[a] -= b }, + function(a, b) { player.vars[a] *= b }, + function(a, b) { player.vars[a] = Math.floor(player.vars[a]/b) }, + function(a, b) { + if (b < 0) player.vars[a] = player.vars[a]>>(-b); + else player.vars[a] = player.vars[a]<= b }, + function(a, b) { return player.vars[a] > b }, + function(a, b) { return player.vars[a] <= b }, + function(a, b) { return player.vars[a] < b }, + function(a, b) { return player.vars[a] != b }, + ] + + Instructions[0xB8] = boolInst; + Instructions[0xB9] = boolInst; + Instructions[0xBA] = boolInst; + Instructions[0xBB] = boolInst; + Instructions[0xBC] = boolInst; + Instructions[0xBD] = boolInst; + + Instructions[0xA2] = function() { //if# + if (!comparisonResult) { + //skip next + var inst = prog[pc++]; + if (inst < 0x80) { + read8(); + readVariableLength(); + } else { + var cmds = InstArgs[inst-0x80]; + var last = 0; + for (var i=0; i0); } //mono/poly + + Instructions[0xC8] = function() { t.tie = prog[pc++]; if (t.lastNote != null) player.cutNoteShort(t, t.lastNote); t.lastNote = null; } //tie + Instructions[0xC9] = function() { t.portaKey = prog[pc++]; } //portamento control + Instructions[0xCA] = function() { var value = forcableValue(); } //modulation depth + Instructions[0xCB] = function() { var value = forcableValue(); } //modulation speed + Instructions[0xCC] = function() { var value = prog[pc++]; } //modulation type + Instructions[0xCD] = function() { var value = prog[pc++]; } //modulation range + Instructions[0xCE] = function() { t.portaKey = (t.portaKey&0x7F)|((!prog[pc++])<<7); } //portamento on/off + Instructions[0xCF] = function() { t.portaTime = forcableValue(); } //portamento time + Instructions[0xD0] = function() { t.attack = forcableValue(); } //attack rate + Instructions[0xD1] = function() { t.decay = forcableValue(); } //decay rate + Instructions[0xD2] = function() { t.sustain = forcableValue(); } //sustain rate + Instructions[0xD3] = function() { t.release = forcableValue(); } //release rate + + Instructions[0xD4] = function() { t.loopTimes = forcableValue(); t.loopPtr = pc; } //loop start + Instructions[0xFC] = function() { if (t.loopTimes-- > 0) pc = t.loopPtr; } //loop end + + Instructions[0xD5] = function() { var value = forcableValue(); } //expression + Instructions[0xD6] = function() { var value = prog[pc++]; } //print variable + Instructions[0xE0] = function() { var value = prog[pc++]; value |= prog[pc++]<<8 } //modulation delay + + Instructions[0xE1] = function() { + var value = prog[pc++]; + value |= prog[pc++]<<8; + player.setTempo(value); + } //set BPM + + Instructions[0xE3] = function() { t.sweepPitch = forcableValueFunc(false, reads16); } //sweep pitch + + Instructions[0xFF] = function() { + if (t.lastNote != null) player.cutNoteShort(t, t.lastNote); + player.terminateThread(t); + t.dead = true; + } //end of track + + function read16() { + var value = prog[pc++]; + value |= prog[pc++]<<8; + return value; + } + + function reads16() { + var value = read16(); + if (value & 0x8000) value -= 0x10000; + return value; + } + + function read8() { + return prog[pc++]; + } + + function readSpecial(last) { + if (last < 0x80 || (last >= 0xB0 && last < 0xBD)) return prog[pc++]; + else return 0; + } + + function read24() { + var value = prog[pc++]; + value |= prog[pc++]<<8; + value |= prog[pc++]<<16; + return value; + } + + function forcableValueFunc(special, func) { + if (force) return special?forceSpecial:forceValue; + else return func(); + } + + function forcableValue(special) { + if (force) return special?forceSpecial:forceValue; + else return prog[pc++]; + } + + function setPan(value) { + t.pan = value; + if (value > 0) { + gainR.gain.value = 1; + gainL.gain.value = 1-value; + } else { + gainR.gain.value = 1+value; + gainL.gain.value = 1; + } + } + + function noteToFreq(n) { + return Math.pow(2, (n-49)/12)*440; + } +} \ No newline at end of file diff --git a/code/engine/cameras/cameraIngame.js b/code/engine/cameras/cameraIngame.js new file mode 100644 index 0000000..1592ace --- /dev/null +++ b/code/engine/cameras/cameraIngame.js @@ -0,0 +1,98 @@ +// +// cameraIngame.js +//-------------------- +// The ingame camera that follows the kart from behind. +// by RHY3756547 +// +// includes: main.js +// + +window.cameraIngame = function(kart) { + + var thisObj = this; + this.kart = kart; + this.getView = getView; + this.targetShadowPos = [0, 0, 0] + + var mat = mat4.create(); + + var camOffset = [0, 32, -48] + var lookAtOffset = [0, 16, 0] + + var camNormal = [0, 1, 0]; + var camAngle = 0; + var boostOff = 0; + + function getView(scene) { + var basis = buildBasis(); + var camPos = vec3.transformMat4([], camOffset, basis); + var lookAtPos = vec3.transformMat4([], lookAtOffset, basis); + + vec3.scale(camPos, camPos, 1/1024); + vec3.scale(lookAtPos, lookAtPos, 1/1024); + + var mat = mat4.lookAt(mat4.create(), camPos, lookAtPos, [0, 1, 0]); + var kpos = vec3.clone(kart.pos); + if (kart.drifting && !kart.driftLanded && kart.ylock>0) kpos[1] -= kart.ylock; + mat4.translate(mat, mat, vec3.scale([], kpos, -1/1024)); + + //interpolate visual normal roughly to target + camNormal[0] += (kart.kartNormal[0]-camNormal[0])*0.075; + camNormal[1] += (kart.kartNormal[1]-camNormal[1])*0.075; + camNormal[2] += (kart.kartNormal[2]-camNormal[2])*0.075; + vec3.normalize(camNormal, camNormal); + + camAngle += dirDiff(kart.physicalDir+kart.driftOff/2, camAngle)*0.075; + camAngle = fixDir(camAngle); + + boostOff += (((kart.boostNorm+kart.boostMT > 0)?5:0) - boostOff)*0.075 + + var p = mat4.perspective(mat4.create(), ((70+boostOff)/180)*Math.PI, gl.viewportWidth / gl.viewportHeight, 0.01, 10000.0); + + var dist = 192; + this.targetShadowPos = vec3.add([], kart.pos, [Math.sin(kart.angle)*dist, 0, -Math.cos(kart.angle)*dist]) + + thisObj.view = {p:p, mv:mat}; + + return thisObj.view; + } + + function buildBasis() { + //order y, x, z + var basis = gramShmidt(camNormal, [Math.cos(camAngle), 0, Math.sin(camAngle)], [Math.sin(camAngle), 0, -Math.cos(camAngle)]); + var temp = basis[0]; + basis[0] = basis[1]; + basis[1] = temp; //todo: cleanup + return [ + basis[0][0], basis[0][1], basis[0][2], 0, + basis[1][0], basis[1][1], basis[1][2], 0, + basis[2][0], basis[2][1], basis[2][2], 0, + 0, 0, 0, 1 + ] + } + + function gramShmidt(v1, v2, v3) { + var u1 = v1; + var u2 = vec3.sub([0, 0, 0], v2, project(u1, v2)); + var u3 = vec3.sub([0, 0, 0], vec3.sub([0, 0, 0], v3, project(u1, v3)), project(u2, v3)); + return [vec3.normalize(u1, u1), vec3.normalize(u2, u2), vec3.normalize(u3, u3)] + } + + function project(u, v) { + return vec3.scale([], u, (vec3.dot(u, v)/vec3.dot(u, u))) + } + + function fixDir(dir) { + return posMod(dir, Math.PI*2); + } + + function dirDiff(dir1, dir2) { + var d = fixDir(dir1-dir2); + return (d>Math.PI)?(-2*Math.PI+d):d; + } + + function posMod(i, n) { + return (i % n + n) % n; + } + +} \ No newline at end of file diff --git a/code/engine/cameras/cameraIntro.js b/code/engine/cameras/cameraIntro.js new file mode 100644 index 0000000..7081423 --- /dev/null +++ b/code/engine/cameras/cameraIntro.js @@ -0,0 +1,118 @@ +// +// cameraIntro.js +//-------------------- +// Runs the intro camera for a scene. +// by RHY3756547 +// +// includes: main.js +// + +window.cameraIntro = function() { + + var thisObj = this; + this.kart = kart; + this.getView = getView; + this.targetShadowPos = [0, 0, 0] + + var mat = mat4.create(); + + var curCamNum = -1; + var curCam = null; + + var route = null; + var routePos = 0; + var routeSpeed = 0; + var routeProg = 0; + var duration = 0; + var pointInterp = 0; + + var normalFOV = 70; + var zoomLevel = 1; + + var viewW; + var viewH; + + function getView(scene, width, height) { + if (curCam == null) { + restartCam(scene); + } + viewW = width; + viewH = height; + + if (zoomLevel < curCam.zoomMark1) zoomLevel += curCam.zoomSpeedM1; + else if (zoomLevel > curCam.zoomMark2) zoomLevel += curCam.zoomSpeedM2; + else zoomLevel += curCam.zoomSpeed; + + if (zoomLevel > curCam.zoomEnd) zoomLevel = curCam.zoomEnd; + + if (duration-- < 0) { + var cams = scene.nkm.sections["CAME"].entries; + if (curCam.nextCam != -1) { + curCamNum = curCam.nextCam; + curCam = cams[curCamNum]; + zoomLevel = curCam.zoomStart; + + initCam(scene, curCam) + } else { + restartCam(scene); + } + } + + + thisObj.view = camFunc(scene, curCam); + } + + function restartCam(scene) { + var cams = scene.nkm.sections["CAME"].entries; + for (var i=0; i 1) { + routePos = (routePos+1)%route.length; + routeProg = 0; + recalcRouteSpeed(); + } + + pointInterp += (curCam.pointSpeed/100)/60; + if (pointInterp > 1) pointInterp = 1; + + var lookAtPos = vec3.lerp([], curCam.pos2, curCam.pos3, pointInterp) + + vec3.scale(camPos, camPos, 1/1024); + vec3.scale(lookAtPos, lookAtPos, 1/1024); + + var mat = mat4.lookAt(mat4.create(), camPos, lookAtPos, [0, 1, 0]); + var p = mat4.perspective(mat4.create(), (zoomLevel*normalFOV/180)*Math.PI, viewW / viewH, 0.01, 10000.0); + + thisObj.targetShadowPos = lookAtPos; + + return {p:p, mv:mat} + } + + var initCam = function(scene, came) { + var routes = scene.paths; + route = routes[came.camRoute]; + routePos = 0; + routeProg = 0; + duration = came.duration; + recalcRouteSpeed(); + + } + +} \ No newline at end of file diff --git a/code/engine/cameras/cameraSpectator.js b/code/engine/cameras/cameraSpectator.js new file mode 100644 index 0000000..a89cf49 --- /dev/null +++ b/code/engine/cameras/cameraSpectator.js @@ -0,0 +1,216 @@ +// +// cameraSpectator.js +//-------------------- +// Spectates a specific kart. Requires NKM AREA and CAME to be set up correctly. +// by RHY3756547 +// +// includes: main.js +// + +window.cameraSpectator = function(kart) { + + var thisObj = this; + this.kart = kart; + this.getView = getView; + this.targetShadowPos = [0, 0, 0] + + var mat = mat4.create(); + + var curCamNum = -1; + var curCam = null; + + var route = null; + var routePos = 0; + var routeSpeed = 0; + var routeProg = 0; + + var relPos = []; + var posOff = []; + + var normalFOV = 70; + var zoomLevel = 1; + + var viewW; + var viewH; + + function getView(scene, width, height) { + viewW = width; + viewH = height; + + var cams = scene.nkm.sections["CAME"].entries; + var tArea = getNearestArea(scene.nkm.sections["AREA"].entries, kart.pos) + if (tArea.came != curCamNum) { + //restart camera. + curCamNum = tArea.came; + curCam = cams[curCamNum]; + zoomLevel = curCam.zoomStart; + + initCam[curCam.camType](scene, curCam) + } + + if (zoomLevel < curCam.zoomMark1) zoomLevel += curCam.zoomSpeedM1; + else if (zoomLevel > curCam.zoomMark2) zoomLevel += curCam.zoomSpeedM2; + else zoomLevel += curCam.zoomSpeed; + + if (zoomLevel > curCam.zoomEnd) zoomLevel = curCam.zoomEnd; + + thisObj.view = camFunc[curCam.camType](scene, curCam); + return thisObj.view; + } + + var camFunc = []; + + camFunc[1] = function(scene, came) { + var camPos = vec3.lerp([], route[routePos].pos, route[(routePos+1)%route.length].pos, routeProg); + routeProg += routeSpeed; + if (routeProg > 1) { + routePos = (routePos+1)%route.length; + routeProg = 0; + recalcRouteSpeed(); + } + + var lookAtPos = vec3.transformMat4([], [0, 4, 0], kart.mat); + + vec3.scale(camPos, camPos, 1/1024); + vec3.scale(lookAtPos, lookAtPos, 1/1024); + + var mat = mat4.lookAt(mat4.create(), camPos, lookAtPos, [0, 1, 0]); + var p = mat4.perspective(mat4.create(), (zoomLevel*normalFOV/180)*Math.PI, viewW / viewH, 0.01, 10000.0); + + thisObj.targetShadowPos = kart.pos; + + return {p:p, mv:mat} + } + + camFunc[0] = function(scene, came) { //point cam + var camPos = vec3.clone(came.pos1); + + var lookAtPos = vec3.transformMat4([], [0, 4, 0], kart.mat); + + vec3.scale(camPos, camPos, 1/1024); + vec3.scale(lookAtPos, lookAtPos, 1/1024); + + var mat = mat4.lookAt(mat4.create(), camPos, lookAtPos, [0, 1, 0]); + var p = mat4.perspective(mat4.create(), (zoomLevel*normalFOV/180)*Math.PI, viewW / viewH, 0.01, 10000.0); + + thisObj.targetShadowPos = kart.pos; + + return {p:p, mv:mat} + } + + camFunc[5] = function(scene, came) { //dash cam + var basis = kart.basis; + var camPos = vec3.transformMat4([], relPos, basis); + var lookAtPos = vec3.transformMat4([], [0, 0, 0], basis); + + vec3.scale(camPos, camPos, 1/1024); + vec3.scale(lookAtPos, lookAtPos, 1/1024); + + var mat = mat4.lookAt(mat4.create(), camPos, lookAtPos, [0, 1, 0]); + + var off = mat4.create(); + mat4.translate(off, off, [-came.pos3[0]/1024, came.pos3[1]/1024, -came.pos3[2]/1024]); + mat4.mul(mat, off, mat); + + var kpos = vec3.clone(kart.pos); + if (kart.drifting && !kart.driftLanded && kart.ylock>0) kpos[1] -= kart.ylock; + mat4.translate(mat, mat, vec3.scale([], kpos, -1/1024)); + + var p = mat4.perspective(mat4.create(), (zoomLevel*normalFOV/180)*Math.PI, viewW / viewH, 0.01, 10000.0); + + thisObj.targetShadowPos = kart.pos; + + return {p:p, mv:mat} + } + + camFunc[2] = camFunc[0]; + + var initCam = []; + + initCam[1] = function(scene, came) { + var routes = scene.paths; + route = routes[came.camRoute]; + routePos = 0; + routeProg = 0; + recalcRouteSpeed(); + + } + + initCam[2] = function(scene, came) { + } + + function recalcRouteSpeed() { + routeSpeed = (curCam.routeSpeed/100)/60; + //(curCam.routeSpeed/20)/vec3.dist(route[routePos].pos, route[(routePos+1)%route.length].pos); + } + + initCam[5] = function(scene, came) { + var mat = mat4.create(); + mat4.rotateY(mat, mat, (180-came.pos2[0])*(Math.PI/180)); + mat4.rotateX(mat, mat, -came.pos2[1]*(Math.PI/180)); + + + relPos = vec3.transformMat4([], [0, 0, -came.pos2[2]], mat); + /*var basis = kart.basis; + relPos = vec3.sub(relPos, came.pos1, kart.pos); + vec3.transformMat4(relPos, relPos, mat4.invert([], basis));*/ + } + + initCam[0] = initCam[2]; + + + function getNearestArea(areas, pos) { + var smallestDist = Infinity; + var closestArea = null; + for (var i=0; iMath.PI)?(-2*Math.PI+d):d; + } + + function posMod(i, n) { + return (i % n + n) % n; + } + +} \ No newline at end of file diff --git a/code/engine/collisionTypes.js b/code/engine/collisionTypes.js new file mode 100644 index 0000000..be9cd5e --- /dev/null +++ b/code/engine/collisionTypes.js @@ -0,0 +1,336 @@ +// +// collisionTypes.js +//-------------------- +// Includes enums for collision types. +// by RHY3756547 +// +// includes: gl-matrix.js (glMatrix 2.0) +// /formats/kcl.js +// + + +window.MKDS_COLSOUNDS = new function() { + this.DRIFT_ASPHALT = 84; + this.DRIFT_CONCRETE = 85; + this.DRIFT_EDGE = 86; //happens when you hit an edge while drifting? + this.DRIFT_DIRT = 87; + this.DRIFT_ROAD = 88; + this.DRIFT_STONE = 89; + this.DRIFT_SAND = 90; + this.DRIFT_ICE = 91; + this.DRIFT_GLASS = 92; + this.DRIFT_WATER = 93; + this.DRIFT_BOARD = 94; //boardwalk! + this.DRIFT_CARPET = 95; //like luigis mansion + this.DRIFT_METALGAUZE = 96; + this.DRIFT_PLASTIC = 97; + this.DRIFT_RAINBOW = 99; + this.DRIFT_MARSH = 100; //luigis mansion + + this.LAND_ASPHALT = 103; + this.LAND_SAND = 104; + this.LAND_DIRT = 105; + this.LAND_ICE = 106; + this.LAND_GRASS = 107; + this.LAND_SNOW = 108; + this.LAND_METALGAUZE = 109; + this.LAND_MARSH = 110; + this.LAND_WATER = 111; + this.LAND_WATERDEEP = 112; + this.LAND_CARPET = 113; + + this.DRIVE_DIRT = 114; + this.DRIVE_GRASS = 115; + this.DRIVE_WATER = 116; + this.DRIVE_STONE = 117; + this.DRIVE_SAND = 118; + this.DRIVE_MARSH = 119; + this.DRIVE_CARPET = 120; + + this.HIT_CAR = 128; + this.HIT_CONCRETE = 129; + this.HIT_FENCE = 130; + this.HIT_WOOD = 131; + this.HIT_TREE = 132; + this.HIT_BUSH = 133; + this.HIT_CLIFF = 134; + this.HIT_SIGN = 135; + this.HIT_ICE = 136; + this.HIT_SNOW = 137; + this.HIT_TABLE = 138; + this.HIT_BOUNCY = 139; + this.HIT_JELLY = 140; + this.HIT_METALGAUZE = 141; + this.HIT_METAL = 142; + + this.BRAKE = 143; + this.BRAKE_CONCRETE = 144; + this.BRAKE_DIRT = 145; + this.BRAKE_STONE = 146; + this.BRAKE_ICE = 147; + this.BRAKE_GLASS = 148; + this.BRAKE_WATER = 149; + this.BRAKE_BOARD = 150; //boardwalk + this.BRAKE_CARPET = 151; + this.BRAKE_METALGAUZE = 152; + this.BRAKE_PLASTIC = 153; + this.BRAKE_METAL = 154; + this.BRAKE_RAINBOW = 155; + this.BRAKE_MARSH = 156; + + this.BRAKE_BOOST = 158; + +} + +window.MKDS_COLTYPE = new (function(){ + this.ROAD = 0x00; + this.OFFROADMAIN = 0x01; + this.OFFROAD3 = 0x02; + this.OFFROAD2 = 0x03; + this.RAINBOWFALL = 0x04; + this.OFFROAD1 = 0x05; + this.SLIPPERY = 0x06; + this.BOOST = 0x07; + this.WALL = 0x08; + this.WALL2 = 0x09; + this.OOB = 0x0A; //voids out the player, returns to lakitu checkpoint. + this.FALL = 0x0B; //like out of bounds, but you fall through it. + this.JUMP_PAD = 0x0C; //jump pads on GBA levels + this.STICKY = 0x0D; //sets gravity to negative this plane's normal until the object hasn't collided for a few frames. + this.SMALLJUMP = 0x0E; //choco island 2's disaster ramps + this.CANNON = 0x0F; //activates cannon. basic effect id is the cannon to use. + this.UNKNOWN = 0x10; //it is a mystery... + this.FALLSWATER = 0x11; //points to falls object in nkm, gets motion parameters from there. + this.BOOST2 = 0x12; + this.LOOP = 0x13; //like sticky but with boost applied. see rainbow road ds + this.SOUNDROAD = 0x14; + this.RR_SPECIAL_WALL = 0x15; + + this.GROUP_ROAD = [ + this.ROAD, this.OFFROAD1, this.OFFROAD2, this.OFFROAD3, this.OFFROAD4, this.SLIPPERY, this.BOOST, + this.JUMP_PAD, this.STICKY, this.SMALLJUMP, this.FALLSWATER, this.BOOST2, this.LOOP, this.SOUNDROAD, + this.OOB, this.OFFROADMAIN + ] + + this.GROUP_SOLID = [ + this.ROAD, this.OFFROAD1, this.OFFROAD2, this.OFFROAD3, this.OFFROAD4, this.SLIPPERY, this.BOOST, + this.JUMP_PAD, this.STICKY, this.SMALLJUMP, this.FALLSWATER, this.BOOST2, this.LOOP, this.SOUNDROAD, + this.OOB, this.OFFROADMAIN, + + this.WALL, this.WALL2, this.RR_SPECIAL_WALL + ] + + this.GROUP_WALL = [ + this.WALL, this.WALL2, this.RR_SPECIAL_WALL + ] + + this.GROUP_BOOST = [ + this.BOOST, this.BOOST2, this.LOOP + ] + + this.PHYS_MAP = new Array(31); + this.PHYS_MAP[this.ROAD] = 0; + this.PHYS_MAP[this.OFFROAD3] = 2; + this.PHYS_MAP[this.OFFROAD2] = 3; + this.PHYS_MAP[this.OFFROAD1] = 4; + this.PHYS_MAP[this.OFFROADMAIN] = 5; + this.PHYS_MAP[this.SLIPPERY] = 6; + this.PHYS_MAP[this.BOOST] = 8; + this.PHYS_MAP[this.BOOST2] = 8; + this.PHYS_MAP[this.FALLSWATER] = 10; + this.PHYS_MAP[this.LOOP] = 11; + + //collision sound handlers + + var waterRoad = {drift: MKDS_COLSOUNDS.DRIFT_WATER, brake: MKDS_COLSOUNDS.BRAKE_WATER, land: MKDS_COLSOUNDS.LAND_WATER, drive: MKDS_COLSOUNDS.DRIVE_WATER}; + + this.SOUNDMAP = { + 0x00: //road + [ + {drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_ASPHALT}, + {drift: MKDS_COLSOUNDS.DRIFT_SAND, brake: MKDS_COLSOUNDS.BRAKE_SAND, land: MKDS_COLSOUNDS.LAND_SAND, drive: MKDS_COLSOUNDS.DRIVE_SAND}, + {drift: MKDS_COLSOUNDS.DRIFT_STONE, brake: MKDS_COLSOUNDS.BRAKE_STONE, land: MKDS_COLSOUNDS.LAND_ASPHALT, drive: MKDS_COLSOUNDS.DRIVE_STONE}, + {drift: MKDS_COLSOUNDS.DRIFT_CONCRETE, brake: MKDS_COLSOUNDS.BRAKE_CONCRETE, land: MKDS_COLSOUNDS.LAND_ASPHALT}, + {drift: MKDS_COLSOUNDS.DRIFT_BOARD, brake: MKDS_COLSOUNDS.BRAKE_BOARD, land: MKDS_COLSOUNDS.LAND_ASPHALT}, + + {drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_SNOW}, //snow? + + {drift: MKDS_COLSOUNDS.DRIFT_METALGAUZE, brake: MKDS_COLSOUNDS.BRAKE_METALGAUZE, land: MKDS_COLSOUNDS.LAND_METALGAUZE}, + {drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_ASPHALT}, + ], + + 0x01: //road 2 the roadening + [ + {drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_ASPHALT}, + {drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_ASPHALT}, + {drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_ASPHALT}, + {drift: MKDS_COLSOUNDS.DRIFT_WATER, brake: MKDS_COLSOUNDS.BRAKE_WATER, land: MKDS_COLSOUNDS.LAND_WATERDEEP, drive: MKDS_COLSOUNDS.DRIVE_WATER}, + {drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_ASPHALT}, + {}, + {}, + {} + ], + + 0x02: //road 3 + [ + {drift: MKDS_COLSOUNDS.DRIFT_SAND, brake: MKDS_COLSOUNDS.BRAKE_SAND , land: MKDS_COLSOUNDS.LAND_SAND, drive: MKDS_COLSOUNDS.DRIVE_SAND}, + waterRoad, + + {drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_SNOW}, //snow + + {drift: MKDS_COLSOUNDS.DRIFT_SAND, brake: MKDS_COLSOUNDS.BRAKE_SAND, land: MKDS_COLSOUNDS.LAND_SAND, drive: MKDS_COLSOUNDS.DRIVE_SAND}, + {}, + {}, + {}, + {} + ], + + 0x03: //road 4 + [ + {drift: MKDS_COLSOUNDS.DRIFT_SAND, brake: MKDS_COLSOUNDS.BRAKE_SAND , land: MKDS_COLSOUNDS.LAND_SAND, drive: MKDS_COLSOUNDS.DRIVE_SAND}, + {drift: MKDS_COLSOUNDS.DRIFT_DIRT, brake: MKDS_COLSOUNDS.BRAKE_DIRT, land: MKDS_COLSOUNDS.LAND_DIRT, drive: MKDS_COLSOUNDS.DRIVE_DIRT}, + + {drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_GRASS, drive: MKDS_COLSOUNDS.DRIVE_GRASS}, + + {drift: MKDS_COLSOUNDS.DRIFT_SAND, brake: MKDS_COLSOUNDS.BRAKE_SAND, land: MKDS_COLSOUNDS.LAND_SAND, drive: MKDS_COLSOUNDS.DRIVE_SAND}, + {drift: MKDS_COLSOUNDS.DRIFT_SAND, brake: MKDS_COLSOUNDS.BRAKE_SAND, land: MKDS_COLSOUNDS.LAND_SAND, drive: MKDS_COLSOUNDS.DRIVE_SAND}, + {drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_SNOW}, //snow + {}, + {} + ], + + 0x05: //road 5 + [ + {drift: MKDS_COLSOUNDS.DRIFT_SAND, brake: MKDS_COLSOUNDS.BRAKE_SAND , land: MKDS_COLSOUNDS.LAND_SAND, drive: MKDS_COLSOUNDS.DRIVE_SAND}, + {drift: MKDS_COLSOUNDS.DRIFT_DIRT, brake: MKDS_COLSOUNDS.BRAKE_DIRT, land: MKDS_COLSOUNDS.LAND_DIRT, drive: MKDS_COLSOUNDS.DRIVE_DIRT}, + + {drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_GRASS, drive: MKDS_COLSOUNDS.DRIVE_GRASS}, + + {drift: MKDS_COLSOUNDS.DRIFT_SAND, brake: MKDS_COLSOUNDS.BRAKE_SAND, land: MKDS_COLSOUNDS.LAND_SAND, drive: MKDS_COLSOUNDS.DRIVE_SAND}, + {drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_GRASS, drive: MKDS_COLSOUNDS.DRIVE_GRASS}, + {}, + {}, + {} + ], + + 0x06: //slippery + [ + {drift: MKDS_COLSOUNDS.DRIFT_ICE, brake: MKDS_COLSOUNDS.BRAKE_ICE, land:MKDS_COLSOUNDS.LAND_ICE}, + {drift: MKDS_COLSOUNDS.DRIFT_MARSH, brake: MKDS_COLSOUNDS.BRAKE_MARSH, land:MKDS_COLSOUNDS.LAND_MARSH, drive: MKDS_COLSOUNDS.DRIVE_MARSH}, + {}, + {}, + {}, + {}, + {}, + {} + ], + + 0x07: //bo0st + [ + {drift: MKDS_COLSOUNDS.BRAKE_PLASTIC, brake: MKDS_COLSOUNDS.BRAKE_PLASTIC, land:MKDS_COLSOUNDS.LAND_ASPHALT}, + {drift: MKDS_COLSOUNDS.BRAKE_PLASTIC, brake: MKDS_COLSOUNDS.BRAKE_PLASTIC, land:MKDS_COLSOUNDS.LAND_ASPHALT}, + {}, + {}, + {}, + {}, + {}, + {} + ], + + 0x08: //wall + [//placeholders + {hit: MKDS_COLSOUNDS.HIT_CONCRETE}, + {hit: MKDS_COLSOUNDS.HIT_CLIFF}, + {hit: MKDS_COLSOUNDS.HIT_SIGN}, //cliff + {hit: MKDS_COLSOUNDS.HIT_WOOD}, + {hit: MKDS_COLSOUNDS.HIT_BUSH}, + {}, + {hit: MKDS_COLSOUNDS.HIT_JELLY}, + {hit: MKDS_COLSOUNDS.HIT_ICE}, + ], + + 0x09: //wall 2 + [ + {hit: MKDS_COLSOUNDS.HIT_CONCRETE}, + {hit: MKDS_COLSOUNDS.HIT_STONE}, + {hit: MKDS_COLSOUNDS.HIT_METAL}, + {hit: MKDS_COLSOUNDS.HIT_WOOD}, + {hit: MKDS_COLSOUNDS.HIT_BUSH}, + {}, + {hit: MKDS_COLSOUNDS.HIT_JELLY}, + {hit: MKDS_COLSOUNDS.HIT_ICE}, + ], + + 0x10: //wall 3 + [ + {hit: MKDS_COLSOUNDS.HIT_CONCRETE}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + ], + + 0x15: //wall with sound effect + [ + {hit: MKDS_COLSOUNDS.HIT_CONCRETE}, + {hit: MKDS_COLSOUNDS.HIT_STONE}, + {hit: MKDS_COLSOUNDS.HIT_RAINBOW}, //only diff i think + {hit: MKDS_COLSOUNDS.HIT_WOOD}, + {hit: MKDS_COLSOUNDS.HIT_BUSH}, + {}, + {hit: MKDS_COLSOUNDS.HIT_JELLY}, + {hit: MKDS_COLSOUNDS.HIT_ICE}, + ], + + 0x11: [ //yoshi falls water + waterRoad, + waterRoad, + waterRoad, + waterRoad, + waterRoad, + waterRoad, + waterRoad, + waterRoad + ], + + 0x12: //boost + [ + {drift: MKDS_COLSOUNDS.BRAKE_PLASTIC, brake: MKDS_COLSOUNDS.BRAKE_PLASTIC, land:MKDS_COLSOUNDS.LAND_ASPHALT}, + {}, + {}, + {}, + {}, + {}, + {}, + {} + ], + + 0x13: //looping + [ + {drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land:MKDS_COLSOUNDS.LAND_ASPHALT}, + {drift: MKDS_COLSOUNDS.DRIFT_RAINBOW, brake: MKDS_COLSOUNDS.BRAKE_RAINBOW, land:MKDS_COLSOUNDS.LAND_ASPHALT}, + {}, + {}, + {}, + {}, + {}, + {} + ], + + 0x14: //road with sfx + [ + {}, + {drift: MKDS_COLSOUNDS.DRIFT_CARPET, brake: MKDS_COLSOUNDS.BRAKE_CARPET, land:MKDS_COLSOUNDS.LAND_CARPET, drive: MKDS_COLSOUNDS.DRIVE_CARPET}, + {drift: MKDS_COLSOUNDS.DRIFT_RAINBOW, brake: MKDS_COLSOUNDS.BRAKE_RAINBOW, land:MKDS_COLSOUNDS.LAND_ASPHALT}, + {}, + {}, //stairs + {}, + {}, + {} + ] + } + +})() \ No newline at end of file diff --git a/code/engine/controls/controlDefault.js b/code/engine/controls/controlDefault.js new file mode 100644 index 0000000..9afc54d --- /dev/null +++ b/code/engine/controls/controlDefault.js @@ -0,0 +1,35 @@ +// +// controlDefault.js +//-------------------- +// Provides default (keyboard) controls for kart. In future there will be an AI controller and default will support gamepad. +// by RHY3756547 +// +// includes: main.js +// + +window.controlDefault = function() { + + var thisObj = this; + this.local = true; + var kart; + + this.setKart = function(k) { + kart = k; + thisObj.kart = k; + } + this.fetchInput = fetchInput; + + function fetchInput() { + return { + accel: keysArray[88], //x + decel: keysArray[90], //z + drift: keysArray[83], //s + item: keysArray[65], //a + + //-1 to 1, intensity. + turn: (keysArray[37]?-1:0)+(keysArray[39]?1:0), + airTurn: (keysArray[40]?-1:0)+(keysArray[38]?1:0) //air excitebike turn, doesn't really have much function + }; + } + +} \ No newline at end of file diff --git a/code/engine/controls/controlNetwork.js b/code/engine/controls/controlNetwork.js new file mode 100644 index 0000000..fa60bdc --- /dev/null +++ b/code/engine/controls/controlNetwork.js @@ -0,0 +1,41 @@ +// +// controlDefault.js +//-------------------- +// Provides default (keyboard) controls for kart. In future there will be an AI controller and default will support gamepad. +// by RHY3756547 +// +// includes: main.js +// + +window.controlNetwork = function() { + + var t = this; + var kart; + + this.local = false; + this.turn = 0; + this.airTurn = 0; + this.binput = 0; + + this.setKart = function(k) { + kart = k; + t.kart = k; + } + this.fetchInput = fetchInput; + + function fetchInput() { + //local controllers generally just return input and handle items - the network controller restores kart data from the stream sent from the server. Obviously this data needs to be verified by the server... + + return { + accel: t.binput&1, //x + decel: t.binput&2, //z + drift: t.binput&4, //s + item: false,//keysArray[65], //a + + //-1 to 1, intensity. + turn: t.turn,//(keysArray[37]?-1:0)+(keysArray[39]?1:0), + airTurn: t.airTurn//(keysArray[40]?-1:0)+(keysArray[38]?1:0) //air excitebike turn, doesn't really have much function + }; + } + +} \ No newline at end of file diff --git a/code/engine/controls/controlRaceCPU.js b/code/engine/controls/controlRaceCPU.js new file mode 100644 index 0000000..e43741b --- /dev/null +++ b/code/engine/controls/controlRaceCPU.js @@ -0,0 +1,141 @@ +// +// controlRaceCPU.js +//-------------------- +// Provides AI control for default races +// by RHY3756547 +// +// includes: main.js +// + +window.controlRaceCPU = function(nkm) { + + var thisObj = this; + var kart; + + this.setKart = function(k) { + kart = k; + thisObj.kart = k; + calcDestNorm(); + } + + this.fetchInput = fetchInput; + + var battleMode = (nkm.sections["EPAT"] == null); + + var paths, points; + if (battleMode) { //MEEPO!! + var paths = nkm.sections["MEPA"].entries; + var points = nkm.sections["MEPO"].entries; + } else { + var paths = nkm.sections["EPAT"].entries; + var points = nkm.sections["EPOI"].entries; + } + + var ePath = paths[0]; + var ePoiInd = ePath.startInd; + var ePoi = points[ePath.startInd]; + + var posOffset = [0, 0, 0]; + var destOff = [0, 0, 0]; + var offTrans = 0; + chooseNewOff(); + + var destNorm; + var destConst; + var destPoint; + + function fetchInput() { + //basically as a cpu, we're really dumb and need a constant supply of points to drive to. + //battle mode AI is a lot more complex, but since we're only going in one direction it can be kept simple. + + var accel = true; //currently always driving forward. should change for sharp turns and when we get stuck on a wall + //(drive in direction of wall? we may need to reverse, "if stuck for too long we can just call lakitu and the players won't even notice" - Nintendo) + + var dist = vec3.dot(destNorm, kart.pos) + destConst; + if (dist < ePoi.pointSize) advancePoint(); + + destPoint = vec3.add([], ePoi.pos, vec3.scale([], vec3.lerp([], posOffset, destOff, offTrans), ePoi.pointSize)); + var dirToPt = Math.atan2(destPoint[0]-kart.pos[0], kart.pos[2]-destPoint[2]); + + var diff = dirDiff(dirToPt, kart.physicalDir); + var turn = Math.min(Math.max(-1, (diff*3)), 1); + + offTrans += 1/240; + + if (offTrans >= 1) chooseNewOff(); + + return { + accel: accel, //x + decel: false, //z + drift: false, //s + item: false, //a + + //-1 to 1, intensity. + turn: turn, + airTurn: 0 //air excitebike turn, doesn't really have much function + }; + } + + function chooseNewOff() { + posOffset = destOff; + var ang = Math.random()*Math.PI*2; + var strength = Math.random(); + destOff = [Math.sin(ang)*strength, 0, Math.cos(ang)*strength]; + offTrans = 0; + } + + + function calcDestNorm() { + var norm = vec3.sub([], kart.pos, ePoi.pos); + vec3.normalize(norm, norm); + + destNorm = norm; + destConst = -vec3.dot(ePoi.pos, norm) + + } + + function advancePoint() { + if (++ePoiInd < ePath.startInd+ePath.pathLen) { + //next within this path + ePoi = points[ePoiInd]; + } else { + //advance to one of next possible paths + + if (battleMode) { + var pathInd = ((Math.random()>0.5 && ePath.source.length>0)?ePath.source:ePath.dest)[Math.floor(Math.random()*ePath.dest.length)]; + ePoiInd = pathInd; + ePoi = points[ePoiInd]; + recomputePath(); + } else { + var pathInd = ePath.dest[Math.floor(Math.random()*ePath.dest.length)]; + ePath = paths[pathInd]; + ePoi = points[ePath.startInd]; + ePoiInd = ePath.startInd; + } + } + calcDestNorm(); + } + + function recomputePath() { //use if point is set by anything but the path system, eg. respawn + for (var i=0; i= 0 && rel < paths[i].pathLen) { + ePath = paths[i]; + } + } + } + + function fixDir(dir) { + return posMod(dir, Math.PI*2); + } + + function dirDiff(dir1, dir2) { + var d = fixDir(dir1-dir2); + return (d>Math.PI)?(-2*Math.PI+d):d; + } + + function posMod(i, n) { + return (i % n + n) % n; + } + +} \ No newline at end of file diff --git a/code/engine/ingameRes.js b/code/engine/ingameRes.js new file mode 100644 index 0000000..1269aea --- /dev/null +++ b/code/engine/ingameRes.js @@ -0,0 +1,100 @@ +// +// ingameRes.js +//-------------------- +// Provides access to general ingame resources. +// by RHY3756547 +// + +window.IngameRes = function(rom) { + var r = this; + this.kartPhys = new kartphysicalparam(rom.getFile("/data/KartModelMenu/kartphysicalparam.bin")); + this.kartOff = new kartoffsetdata(rom.getFile("/data/KartModelMenu/kartoffsetdata.bin")); + this.MapObj = new narc(lz77.decompress(rom.getFile("/data/Main/MapObj.carc"))); //contains generic map obj, look in here when mapobj res is missing from course. (itembox etc) + this.MainRace = new narc(lz77.decompress(rom.getFile("/data/MainRace.carc"))); //contains item models. + this.MainEffect = new narc(lz77.decompress(rom.getFile("/data/MainEffect.carc"))); //contains particles. + this.Main2D = new narc(lz77.decompress(rom.getFile("/data/Main2D.carc"))); + + this.KartModelSub = new narc(lz77.decompress(rom.getFile("/data/KartModelSub.carc"))); //contains characters + animations + + this.Race = new narc(lz77.decompress(rom.getFile("/data/Scene/Race.carc"))); //contains lakitu, count, various graphics + this.RaceLoc = new narc(lz77.decompress(rom.getFile("/data/Scene/Race_us.carc"))); //contains lakitu lap signs, START, YOU WIN etc. some of these will be replaced by hi res graphics by default. + + this.MainFont = new nftr(r.Main2D.getFile("marioFont.NFTR")); + //debugger; + + this.getChar = getChar; + this.getKart = getKart; + + var itemNames = [ + "banana", "bomb", "gesso" /*squid*/, "kinoko" /*mushroom*/, "kinoko_p" /*queen shroom*/, "koura_g" /*green shell*/, "koura_r" /*red shell*/, "star", "teresa" /*boo*/, "thunder", + "koura_w" /*blue shell item rep*/, "f_box", "killer" /*bullet bill*/ + ] + + var charNames = [ + "mario", "donkey", "kinopio", "koopa", "peach", "wario", "yoshi", "luigi", "karon", "daisy", "waluigi", "robo", "heyho" + ] + + var charAbbrv = [ + "MR", "DK", "KO", "KP", "PC", "WR", "YS", "LG", "KA", "DS", "WL", "RB", "HH" + ] + + var tireName = ["kart_tire_L", "kart_tire_M", "kart_tire_S"]; + + var characters = []; + var karts = []; + + loadItems(); + loadTires(); + + function loadItems() { //loads physical representations of items + var t = {} + for (var i=0; i0 && newT t1) { //make sure t0 is smallest value + var temp = t1; + t1 = t0; + t0 = temp; + } + + if (!(t0>1 || t1<0)) { + //we will intersect this triangle's plane within this frame. + // + // Three things can happen for the earliest intersection: + // - sphere intersects plane of triangle (pt on plane projected from new position is inside triangle) + // - sphere intersects edge of triangle + // - sphere intersects point of triangle + + if (t0 < 0) { embedded = true; t0 = 0; } + if (t1 > 1) t1 = 1; + + var newT = t0; + + //sphere intersects plane of triangle + var pt = []; + if (embedded) { + vec3.sub(pt, pos, vec3.scale([], tri.Normal, dist)); + } else { + vec3.add(pt, pos, vec3.scale([], dir, newT)) + vec3.sub(pt, pt, tri.Normal); //project new position onto plane along normal + } + if (pointInTriangle(tri, pt, 0) && newT= 0 && edgePos <= 1) { + t = root; + colPlane = oTri; + colO = targ; + colPoint = vec3.add([], vert, vec3.scale(distLine, distLine, edgePos)); //result! + planeNormal = tri.Normal; + edge = true; + } + } + } + + } + } + } + + function getSmallestRoot(a, b, c, upperLimit) { + var det = (b*b) - 4*(a*c); + if (det<0) return null; //no result :'( + else { + det = Math.sqrt(det); + var root1 = ((-b)-det)/(2*a) + var root2 = ((-b)+det)/(2*a) + + if (root1 > root2) { //ensure root1 is smallest + var temp = root1; + root1 = root2; + root2 = temp; + } + + if (root1>0 && root10 && root2=-error && v>=-error && (u+v)<1+error); + } + + function getTriList(pos, diff, kclO) { //gets tris from kcl around a line. currently only fetches from middle point of line, but should include multiple samples for large differences in future. + var sample = vec3.add([], pos, vec3.scale([], diff, 0.5)) + return kclO.getPlanesAt(sample[0], sample[1], sample[2]); + } + +})(); \ No newline at end of file diff --git a/code/engine/mkdsConst.js b/code/engine/mkdsConst.js new file mode 100644 index 0000000..fe66624 --- /dev/null +++ b/code/engine/mkdsConst.js @@ -0,0 +1,113 @@ +// +// mkdsConst.js +//-------------------- +// Provides various game constants. +// by RHY3756547 +// + +window.MKDSCONST = new (function() { + + this.COURSEDIR = "/data/Course/"; + + this.COURSES = [ //in order of course id, nitro through retro + "cross_course", + "bank_course", + "beach_course", + "mansion_course", + + "desert_course", + "town_course", + "pinball_course", + "ridge_course", + + "snow_course", + "clock_course", + "mario_course", + "airship_course", + + "stadium_course", + "garden_course", + "koopa_course", + "rainbow_course", + + + "old_mario_sfc", + "old_momo_64", + "old_peach_agb", + "old_luigi_gc", + + "old_donut_sfc", + "old_frappe_64", + "old_koopa_agb", + "old_baby_gc", + + "old_noko_sfc", + "old_choco_64", + "old_luigi_agb", + "old_kinoko_gc", + + "old_choco_sfc", + "old_hyudoro_64", + "old_sky_agb", + "old_yoshi_gc", + + "mini_stage1", + "mini_stage2", + "mini_stage3", + "mini_stage4", + "mini_block_64", + "mini_dokan_gc" + + ] + + this.COURSE_MUSIC = [ + 74, + 16, + 15, + 21, + + 38, + 17, + 19, + 36, + + 37, + 39, + 74, + 18, + + 19, + 20, + 40, + 41, + + + 22, + 30, + 26, + 33, + + 24, + 31, + 27, + 34, + + 23, + 29, + 26, + 35, + + 25, + 32, + 28, + 33, + + 43, + 43, + 43, + 43, + 43, + 43 + ] + +})(); \ No newline at end of file diff --git a/code/engine/scenes/clientScene.js b/code/engine/scenes/clientScene.js new file mode 100644 index 0000000..3f46158 --- /dev/null +++ b/code/engine/scenes/clientScene.js @@ -0,0 +1,156 @@ +// +// clientScene.js +//-------------------- +// Manages the game state when connected to a server. Drives the course scene and track picker. +// by RHY3756547 +// + +window.clientScene = function(wsUrl, wsInstance, res) { + var res = res; //gameRes + var t = this; + + var WebSocket = window.WebSocket || window.MozWebSocket; + var ws = new WebSocket(wsUrl); + ws.binaryType = "arraybuffer"; + + t.ws = ws; + t.mode = -1; + t.activeScene = null; + t.myKart = null; + + ws.onopen = function() { + console.log("initial connection") + //first we need to establish connection to the instance. + var obj = { + t:"*", + i:wsInstance, + c:{ + name:"TestUser"+Math.round(Math.random()*10000), + char:Math.floor(Math.random()*12), + kart:Math.floor(Math.random()*0x24) + } + } + sendJSONMessage(obj); + }; + + ws.onmessage = function(evt) { + var d = evt.data; + if (typeof d != "string") { + //binary data + var view = new DataView(d); + var handler = binH[view.getUint8(0)]; + if (handler != null) handler(view); + } else { + //JSON string + var obj; + try { + obj = JSON.parse(d); + } catch (err) { + debugger; //packet recieved from server is bullshit + return; + } + var handler = wsH["$"+obj.t]; + if (handler != null) handler(obj); + } + } + + this.update = function() { + if (t.activeScene != null) t.activeScene.update(); + if (t.myKart != null) sendKartInfo(t.myKart); + } + + this.render = function() { + if (t.activeScene != null) sceneDrawer.drawTest(gl, t.activeScene, 0, 0, gl.viewportWidth, gl.viewportHeight) + } + + function abFromBlob(blob, callback) { + var fileReader = new FileReader(); + fileReader.onload = function() { + callback(this.result); + }; + fileReader.readAsArrayBuffer(blob); + } + + function sendKartInfo(kart) { + var dat = new ArrayBuffer(0x61); + var view = new DataView(dat); + view.setUint8(0, 32); + netKart.saveKart(view, 1, kart, kart.lastInput); + ws.send(dat); + } + + var wsH = {}; + wsH["$*"] = function(obj) { //initiate scene. + t.myKart = null; + if (obj.m == 1) { //race + t.mode = 1; + + var mainNarc, texNarc + if (obj.c.substr(0, 5) == "mkds/") { + var cnum = Number(obj.c.substr(5)); + var music = MKDSCONST.COURSE_MUSIC[cnum]; + var cDir = MKDSCONST.COURSEDIR+MKDSCONST.COURSES[cnum]; + var mainNarc = new narc(lz77.decompress(gameROM.getFile(cDir+".carc"))); + var texNarc = new narc(lz77.decompress(gameROM.getFile(cDir+"Tex.carc"))); + setUpCourse(mainNarc, texNarc, music, obj) + } + else throw "custom tracks are not implemented yet!" + } + } + + wsH["$+"] = function(obj) { //add kart. only used in debug circumstances. (people can't join normal gamemodes midgame) + console.log("kart added"); + if (t.mode != 1) return; + var kart = new Kart([0, -2000, 0], 0, 0, obj.k.kart, obj.k.char, new ((obj.p)?((window.prompt("press y for cpu controlled") == "y")?controlRaceCPU:controlDefault):controlNetwork)(t.activeScene.nkm, {}), t.activeScene); + t.activeScene.karts.push(kart); + } + + wsH["$-"] = function(obj) { //kart disconnect. + t.activeScene.karts[obj.k].active = false; + } + + var binH = []; + binH[32] = function(view) { + //if we are in a race, update kart positions in main scene. we should trust the server on this, however if anything goes wrong it will be caught earlier. + if (t.mode != 1) return; + + var n = view.getUint16(0x01, true); + var off = 0x03; + for (var i=0; i -1) { + musicRestartTimer++; + if (musicRestartTimer > musicRestart) { + scn.musicPlayer = nitroAudio.playSound(music, {volume:2, bpmMultiplier:(musicRestartType==0)?1.25:1}, null); + musicRestartTimer = -1; + } + } + + for (var i=0; i winPercent) continue; + finishTuple = finishPercents[i]; + } + + kart.controller = new controlRaceCPU(scn.nkm, {}); + kart.controller.setKart(kart); + + kart.anim.setAnim(winPercent>0.5?kart.charRes.LoseA:kart.charRes.winA); + kart.animMode = "raceEnd"; + + scn.camera = (new cameraSpectator(kart, scn)); + nitroAudio.playSound(finishTuple[1], {volume:2}, 0); + nitroAudio.playSound(finishTuple[2], {volume:2}, null); + nitroAudio.instaKill(scn.musicPlayer); + musicRestartTimer = 0; + musicRestart = 7.5*60; + musicRestartType = 1; + music = finishTuple[3]; + scn.entities.push(new Race3DUI(scn, "goal")); + } + else if (kart.lapNumber < 4) nitroAudio.playSound(65, {volume:2}, 0); + } + + if (kart.lapNumber == 4) finishers.push(kart); + } + + function startPosition(toAline, xspacing, yspacing, liney, angle, i) { + var horizN = i%toAline; + var vertN = Math.floor(i/toAline); + var staggered = (vertN%2); //second line moves 1/2 x spacing to the right + var relPos = [(horizN-(toAline/2)-0.25)*xspacing+staggered*0.5, 8, -(horizN*yspacing + vertN*liney)]; + var mat = mat4.rotateY([], mat4.create(), angle*(Math.PI/180)); + vec3.transformMat4(relPos, relPos, mat); + return relPos; + } + + function loadRes(res, id) { + var models = []; + + for (var i=0; i 0) { + //beeps for countdown + nitroAudio.playSound(39, {bpmMultiplier:16}, 0); + } + break; + case 2: + //show ui and play music at certain time after go + + if (mode.time == 1) { + scn.musicPlayer = nitroAudio.playSound(music, {volume:2}, null); + } + // + break; + } + } + + //win sting: 46 + //ok sting: 47 + //lose sting: 48 + //battle lose sting: 49 + //battle win sting: 50 + //ok sting??: 51 + //mission mode win sting: 52 + //mission mode win2 sting: 53 + //mission mode superwin sting: 54 + //boss win sting: 55 + //ok music: 56 + //lose music: 57 + //win music: 58 + //racelose : 61 + //ok music: 58 + //good time trials music: 59 + //ok time trials: 60 + + //final lap: 62 + + //full results win: 63 + //results draw: 64 + //full results lose: 65 + //gp results cutscene music: 66 + //gp results win music: 67 + //??? : 68 + //credits: 69-70 + // star: 73 + + scn.mode = mode; + } +} diff --git a/code/engine/scenes/sceneDrawer.js b/code/engine/scenes/sceneDrawer.js new file mode 100644 index 0000000..b010166 --- /dev/null +++ b/code/engine/scenes/sceneDrawer.js @@ -0,0 +1,132 @@ +// +// sceneDrawer.js +//-------------------- +// Provides functions to draw scenes in various ways. +// by RHY3756547 +// + +window.sceneDrawer = new function() { + var gl, shadowTarg; + + var shadowRes = 2048; + + this.init = function(gl) { + gl = gl; + shadowTarg = createRenderTarget(gl, shadowRes, shadowRes, true); + } + + this.drawWithShadow = function(gl, scn, x, y, width, height) { + if (scn.lastWidth != width || scn.lastHeight != height) { + scn.lastWidth = width; + scn.lastHeight = height; + scn.renderTarg = createRenderTarget(gl, width, height, true); + } + + var view = scn.camera.getView(scn, width, height); + var viewProj = mat4.mul(view.p, view.p, view.mv); + + var shadMat = scn.shadMat; + + if (scn.farShad == null) { + scn.farShad = createRenderTarget(gl, shadowRes*2, shadowRes*2, true); + gl.viewport(0, 0, shadowRes*2, shadowRes*2); + gl.bindFramebuffer(gl.FRAMEBUFFER, scn.farShad.fb); + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT); + gl.colorMask(false, false, false, false); + scn.draw(gl, scn.farShadMat, true); + } + + gl.viewport(0, 0, shadowRes, shadowRes); + gl.bindFramebuffer(gl.FRAMEBUFFER, shadowTarg.fb); + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT); + gl.colorMask(false, false, false, false); + scn.draw(gl, shadMat, true); + + gl.viewport(0, 0, width, height); + gl.bindFramebuffer(gl.FRAMEBUFFER, scn.renderTarg.fb); + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT); + gl.colorMask(true, true, true, true); + scn.draw(gl, viewProj, false); + + scn.sndUpdate(view.mv); + + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + + gl.viewport(x, y, width, height); + shadowRender.drawShadowed(scn.renderTarg.color, scn.renderTarg.depth, shadowTarg.depth, scn.farShad.depth, viewProj, shadMat, scn.farShadMat) + } + + this.drawTest = function(gl, scn, x, y, width, height) { + + var view = scn.camera.view; //scn.camera.getView(scn, width, height); + + var viewProj = mat4.mul(mat4.create(), view.p, view.mv); + view = {p: viewProj, mv: view.mv}; + + var shadMat = scn.shadMat; + + nitroRender.unsetShadowMode(); + nitroRender.flagShadow = true; + nitroRender.updateBillboards(scn.lightMat); + + if (scn.farShad == null) { + scn.farShad = createRenderTarget(gl, shadowRes*2, shadowRes*2, true); + gl.viewport(0, 0, shadowRes*2, shadowRes*2); + gl.bindFramebuffer(gl.FRAMEBUFFER, scn.farShad.fb); + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT); + gl.colorMask(false, false, false, false); + scn.draw(gl, scn.farShadMat, true); + } + + gl.viewport(0, 0, shadowRes, shadowRes); + gl.bindFramebuffer(gl.FRAMEBUFFER, shadowTarg.fb); + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT); + gl.colorMask(false, false, false, false); + scn.draw(gl, shadMat, true); + + nitroRender.setShadowMode(shadowTarg.depth, scn.farShad.depth, shadMat, scn.farShadMat); + nitroRender.flagShadow = false; + + nitroRender.updateBillboards(view.mv); + gl.viewport(x, y, width, height); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT); + gl.colorMask(true, true, true, true); + scn.draw(gl, viewProj, false); + + scn.sndUpdate(view.mv); + + } + + function createRenderTarget(gl, xsize, ysize, depth) { + var depthTextureExt = gl.getExtension("WEBGL_depth_texture"); + if (!depthTextureExt) alert("depth texture not supported! we're DOOMED! jk we'll just have to add a fallback for people with potato gfx"); + + var colorTexture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, colorTexture); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, xsize, ysize, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + + var depthTexture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, depthTexture); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, xsize, ysize, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null); + + var framebuffer = gl.createFramebuffer(); + gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, colorTexture, 0); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture, 0); + + return { + color: colorTexture, + depth: depthTexture, + fb: framebuffer + } + } +} \ No newline at end of file diff --git a/code/engine/scenes/singleScene.js b/code/engine/scenes/singleScene.js new file mode 100644 index 0000000..8e23ed1 --- /dev/null +++ b/code/engine/scenes/singleScene.js @@ -0,0 +1,86 @@ +// +// singleScene.js +//-------------------- +// Drives the course scene when not connected to a server. Simulates responses expected from a server. +// by RHY3756547 +// + +window.singleScene = function(course, wsInstance, res) { + var res = res; //gameRes + var t = this; + + t.mode = -1; + t.activeScene = null; + t.myKart = null; + + var mchar = Math.floor(Math.random()*12); + var mkart = Math.floor(Math.random()*0x24); + + this.update = function() { + if (t.activeScene != null) { + t.activeScene.update(); + //simulate what a server would do + updateServer(); + } + } + + var advanceTimes = [3,4,-1,-1] + + function updateServer() { + var m = t.mode; + m.frameDiv++; + if (m.frameDiv == 60) { + m.frameDiv -= 60; + m.time++; + var timeAd = advanceTimes[m.id]; + if (timeAd != -1 && m.time >= timeAd) { + m.id++; + m.time = 0; + } + } + + t.activeScene.updateMode(JSON.parse(JSON.stringify(t.mode))); + } + + this.render = function() { + if (t.activeScene != null) sceneDrawer.drawTest(gl, t.activeScene, 0, 0, gl.viewportWidth, gl.viewportHeight) + } + + begin(course); + + function begin(course) { + var mainNarc, texNarc + if (course.substr(0, 5) == "mkds/") { + var cnum = Number(course.substr(5)); + var music = MKDSCONST.COURSE_MUSIC[cnum]; + var cDir = MKDSCONST.COURSEDIR+MKDSCONST.COURSES[cnum]; + var mainNarc = new narc(lz77.decompress(gameROM.getFile(cDir+".carc"))); + var texNarc = new narc(lz77.decompress(gameROM.getFile(cDir+"Tex.carc"))); + setUpCourse(mainNarc, texNarc, music) + } else throw "custom tracks are not implemented yet!" + } + + + function setUpCourse(mainNarc, texNarc, music) { + var chars = []; + chars.push({charN:mchar, kartN:mkart, controller:((window.prompt("press y for cpu controlled") == "y")?controlRaceCPU:controlDefault), raceCam:true, extraParams:[{k:"name", v:"single"}, {k:"active", v:true}]}); + + for (var i=0; i<7; i++) { + var tchar = Math.floor(Math.random()*12); + var tkart = Math.floor(Math.random()*0x24); + + chars.push({charN:tchar, kartN:tkart, controller:controlRaceCPU, raceCam:false, extraParams:[{k:"name", v:"no"}, {k:"active", v:true}]}); + } + + t.activeScene = new courseScene(mainNarc, texNarc, music, chars, {}, res); + + t.myKart = t.activeScene.karts[0]; + t.mode = { + id:0, + time:0, + frameDiv:0, + } + t.activeScene.updateMode(t.mode); + } + +} \ No newline at end of file diff --git a/code/engine/storage/fileStore.js b/code/engine/storage/fileStore.js new file mode 100644 index 0000000..dc737bf --- /dev/null +++ b/code/engine/storage/fileStore.js @@ -0,0 +1,83 @@ +window.fileStore = new (function(){ + var db; + var indexedDB; + + this.requestGameFiles = requestGameFiles; + + function requestGameFiles(callback) { + indexedDB = window.indexedDB + || window.webkitIndexedDB + || window.mozIndexedDB + || window.shimIndexedDB; + + var request = indexedDB.open("MKJS_DB", 1); + request.onerror = window.onerror; + + request.onsuccess = function(event) { + db = event.target.result; + loadGameFiles(callback); + } + + request.onupgradeneeded = function(event) { + db = event.target.result; + var objectStore = db.createObjectStore("files", { keyPath: "filename" }); + objectStore.transaction.oncomplete = function(event) { + loadGameFiles(callback); + } + } + } + + function loadGameFiles(callback) { + var transaction = db.transaction(["files"]); + var objectStore = transaction.objectStore("files"); + var request = objectStore.get("mkds.nds"); + request.onerror = function(event) { + alert("Fatal database error!"); + }; + request.onsuccess = function(event) { + if (request.result == null) downloadGame("Mario Kart DS.nds", callback); + else callback(request.result.data); + }; + } + + function downloadGame(url, callback) { + if (typeof url == "string") { + var xml = new XMLHttpRequest(); + xml.open("GET", url, true); + xml.responseType = "arraybuffer"; + xml.onload = function() { + storeGame(xml.response, callback); + } + xml.send(); + } else { + alert("You need to supply MKJS with a Mario Kart DS ROM to function. Click anywhere on the page to load a file.") + fileCallback = callback; + document.getElementById("fileIn").onchange = fileInChange; + waitForROM = true; + } + } + + function fileInChange(e) { + var bFile = e.target.files[0]; + var bReader = new FileReader(); + bReader.onload = function(e) { + waitForROM = false; //todo: verify + storeGame(e.target.result, fileCallback); + }; + bReader.readAsArrayBuffer(bFile); + } + + function storeGame(dat, callback) { + var transaction = db.transaction(["files"], "readwrite"); + var objectStore = transaction.objectStore("files"); + var request = objectStore.put({filename:"mkds.nds", data:dat}); + + request.onerror = function(event) { + alert("Failed to store game locally!"); + callback(dat); + }; + request.onsuccess = function(event) { + callback(dat); + }; + } +})(); \ No newline at end of file diff --git a/code/entities/bowserPlatforms.js b/code/entities/bowserPlatforms.js new file mode 100644 index 0000000..972f45d --- /dev/null +++ b/code/entities/bowserPlatforms.js @@ -0,0 +1,196 @@ +// +// bowserPlatforms.js +//-------------------- +// Provides platforms for Bowser's Castle +// by RHY3756547 +// +// includes: +// render stuff idk +// + +window.ObjRotaryRoom = function(obji, scene) { + var obji = obji; + var res = []; + + var t = this; + + t.collidable = true; + t.colMode = 0; + t.colRad = 512; + t.getCollision = getCollision; + t.moveWith = moveWith; + + t.pos = vec3.clone(obji.pos); + //t.angle = vec3.clone(obji.angle); + t.scale = vec3.clone(obji.scale); + + t.requireRes = requireRes; + t.provideRes = provideRes; + t.update = update; + t.draw = draw; + + t.speed = (obji.setting1&0xFFFF)/8192; + t.angle = 0; + + var dirVel = 0; + + function update(scene) { + dirVel = t.speed; + t.angle += dirVel; + } + + function draw(view, pMatrix) { + var mat = mat4.translate(mat4.create(), view, t.pos); + + mat4.scale(mat, mat, vec3.scale([], t.scale, 16)); + + mat4.rotateY(mat, mat, t.angle); + res.mdl[0].draw(mat, pMatrix); + } + + function requireRes() { //scene asks what resources to load + return {mdl:[{nsbmd:"rotary_room.nsbmd"}]}; + } + + function provideRes(r) { + res = r; //...and gives them to us. :) + } + + function getCollision() { + var obj = {}; + var inf = res.mdl[0].getCollisionModel(0, 0); + obj.tris = inf.dat; + + var mat = mat4.translate([], mat4.create(), t.pos); + mat4.scale(mat, mat, vec3.mul([], [16*inf.scale, 16*inf.scale, 16*inf.scale], t.scale)); + mat4.rotateY(mat, mat, t.angle); + + obj.mat = mat; + return obj; + } + + function moveWith(obj) { //used for collidable objects that move. + var p = vec3.sub([], obj.pos, t.pos); + vec3.transformMat4(p, p, mat4.rotateY([], mat4.create(), dirVel)); + vec3.add(obj.pos, t.pos, p); + obj.physicalDir -= dirVel; + } + +} + +window.ObjRoutePlatform = function(obji, scene) { + var obji = obji; + var res = []; + var genCol; + + var t = this; + + t.collidable = true; + t.colMode = 0; + t.colRad = 512; + t.getCollision = getCollision; + t.moveWith = moveWith; + + t.pos = vec3.clone(obji.pos); + //t.angle = vec3.clone(obji.angle); + t.scale = vec3.clone(obji.scale); + + t.requireRes = requireRes; + t.provideRes = provideRes; + t.update = update; + t.draw = draw; + + generateCol(); + + t.statDur = (obji.setting1&0xFFFF); + t.route = scene.paths[obji.routeID]; + t.routeSpeed = 1/6; + t.routePos = 0; + t.nextNode = t.route[t.routePos]; + t.prevPos = t.pos; + t.elapsedTime = 0; + + t.mode = 0; + + var movVel; + + //t.speed = (obji.setting1&0xFFFF)/8192; + + function update(scene) { + if (t.mode == 0) { + t.elapsedTime += t.routeSpeed; + movVel = vec3.sub([], t.nextNode.pos, t.prevPos); + //vec3.normalize(movVel, movVel); + vec3.scale(movVel, movVel, t.routeSpeed/t.nextNode.duration); + vec3.add(t.pos, t.pos, movVel); + if (t.elapsedTime >= t.nextNode.duration) { + t.elapsedTime = 0; + t.prevPos = t.nextNode.pos; + t.routePos = (t.routePos+1)%t.route.length; + t.nextNode = t.route[t.routePos]; + t.mode = 1; + } + } else { + t.elapsedTime += 1; + movVel = [0, 0, 0]; + if (t.elapsedTime > t.statDur) { + t.mode = 0; + t.elapsedTime = 0; + } + } + } + + function draw(view, pMatrix) { + var mat = mat4.translate(mat4.create(), view, t.pos); + + mat4.scale(mat, mat, vec3.scale([], t.scale, 16)); + + res.mdl[0].draw(mat, pMatrix); + } + + function requireRes() { //scene asks what resources to load + return {mdl:[{nsbmd:"koopa_block.nsbmd"}]}; //25x, 11y + } + + function provideRes(r) { + res = r; //...and gives them to us. :) + } + + function generateCol() { + genCol = {dat: [ + { + Vertex1: [25, 0, 11], + Vertex2: [25, 0, -11], + Vertex3: [-25, 0, -11], + Normal: [0, 1, 0] + }, + { + Vertex1: [-25, 0, -11], + Vertex2: [-25, 0, 11], + Vertex3: [25, 0, 11], + Normal: [0, 1, 0] + }, + ], scale: 1}; + } + + function getCollision() { + var obj = {}; + var inf = genCol;//res.mdl[0].getCollisionModel(0, 0); + obj.tris = inf.dat; + + var mat = mat4.translate([], mat4.create(), t.pos); + mat4.scale(mat, mat, vec3.mul([], [16*inf.scale, 16*inf.scale, 16*inf.scale], t.scale)); + + obj.mat = mat; + return obj; + } + + function moveWith(obj) { //used for collidable objects that move. + /*var p = vec3.sub([], obj.pos, t.pos); + vec3.transformMat4(p, p, mat4.rotateY([], mat4.create(), dirVel)); + vec3.add(obj.pos, t.pos, p); + obj.physicalDir -= dirVel;*/ + vec3.add(obj.pos, obj.pos, movVel); + } + +} \ No newline at end of file diff --git a/code/entities/decorations.js b/code/entities/decorations.js new file mode 100644 index 0000000..d4706f8 --- /dev/null +++ b/code/entities/decorations.js @@ -0,0 +1,273 @@ +// +// decorations.js +//-------------------- +// Provides decoration objects. +// by RHY3756547 +// +// includes: +// render stuff idk +// + +window.ObjDecor = function(obji, scene) { + var forceBill; + var obji = obji; + var res = []; + + var t = this; + + t.pos = vec3.clone(obji.pos); + t.angle = vec3.clone(obji.angle); + t.scale = vec3.clone(obji.scale); + + t.requireRes = requireRes; + t.provideRes = provideRes; + t.update = update; + t.draw = draw; + + var mat = mat4.create(); + var frame = 0; + var anim = null; + var animFrame = 0; + var animMat = null; + + function draw(view, pMatrix) { + mat4.translate(mat, view, t.pos); + + if (t.angle[2] != 0) mat4.rotateZ(mat, mat, t.angle[2]*(Math.PI/180)); + if (t.angle[1] != 0) mat4.rotateY(mat, mat, t.angle[1]*(Math.PI/180)); + if (t.angle[0] != 0) mat4.rotateX(mat, mat, t.angle[0]*(Math.PI/180)); + + if (anim != null) { + animMat = anim.setFrame(0, 0, animFrame++); + } + + mat4.scale(mat, mat, vec3.scale([], t.scale, 16)); + res.mdl[0].draw(mat, pMatrix, animMat); + } + + function update() { + + } + + function requireRes() { //scene asks what resources to load + forceBill = true; + switch (obji.ID) { + case 0x012D: + return {mdl:[{nsbmd:"BeachTree1.nsbmd"}]}; //non solid + case 0x012E: + return {mdl:[{nsbmd:"BeachTree1.nsbmd"}]}; + case 0x012F: + return {mdl:[{nsbmd:"earthen_pipe1.nsbmd"}]}; //why is there an earthen pipe 2 + + case 0x0130: + return {mdl:[{nsbmd:"opa_tree1.nsbmd"}]}; + case 0x0131: + return {mdl:[{nsbmd:"OlgPipe1.nsbmd"}]}; + case 0x0132: + return {mdl:[{nsbmd:"OlgMush1.nsbmd"}]}; + case 0x0133: + return {mdl:[{nsbmd:"of6yoshi1.nsbmd"}]}; + case 0x0134: + return {mdl:[{nsbmd:"cow.nsbmd"}], other:[null, null, "cow.nsbtp"]}; //has animation, cow.nsbtp + case 0x0135: + forceBill = false; + return {mdl:[{nsbmd:"NsKiller1.nsbmd"}, {nsbmd:"NsKiller2.nsbmd"}, {nsbmd:"NsKiller2_s.nsbmd"}]}; //probably animates + case 0x0138: + return {mdl:[{nsbmd:"GardenTree1.nsbmd"}]}; + case 0x0139: + return {mdl:[{nsbmd:"kamome.nsbmd"}], other:[null, null, "kamone.nsbtp"]}; //animates using nsbtp, and uses route to move + + case 0x013A: + return {mdl:[{nsbmd:"CrossTree1.nsbmd"}]}; + + //0x013C is big cheep cheep + case 0x013C: + forceBill = false; + return {mdl:[{nsbmd:"bakubaku.nsbmd"}]}; + + //0x013D is spooky ghost + case 0x013D: + forceBill = false; + return {mdl:[{nsbmd:"teresa.nsbmd"}], other:[null, null, "teresa.nsbtp"]}; + + case 0x013E: + return {mdl:[{nsbmd:"Bank_Tree1.nsbmd"}]}; + case 0x013F: + return {mdl:[{nsbmd:"GardenTree1.nsbmd"}]}; //non solid + + case 0x0140: + return {mdl:[{nsbmd:"chandelier.nsbmd"}], other:[null, "chandelier.nsbca"]}; + case 0x0142: + return {mdl:[{nsbmd:"MarioTree3.nsbmd"}]}; + case 0x0145: + return {mdl:[{nsbmd:"TownTree1.nsbmd"}]}; + case 0x0146: + //solid + return {mdl:[{nsbmd:"Snow_Tree1.nsbmd"}]}; + case 0x0148: + return {mdl:[{nsbmd:"DeTree1.nsbmd"}]}; + case 0x0149: + return {mdl:[{nsbmd:"BankEgg1.nsbmd"}]}; + + case 0x014B: + return {mdl:[{nsbmd:"KinoHouse1.nsbmd"}]}; + case 0x014C: + return {mdl:[{nsbmd:"KinoHouse2.nsbmd"}]}; + case 0x014D: + return {mdl:[{nsbmd:"KinoMount1.nsbmd"}]}; + case 0x014E: + return {mdl:[{nsbmd:"KinoMount2.nsbmd"}]}; + + + case 0x014F: + return {mdl:[{nsbmd:"olaTree1c.nsbmd"}]}; + + case 0x0150: + return {mdl:[{nsbmd:"osaTree1c.nsbmd"}]}; + case 0x0151: + forceBill = false; + return {mdl:[{nsbmd:"picture1.nsbmd"}], other:[null, "picture1.nsbca"]}; + case 0x0152: + forceBill = false; + return {mdl:[{nsbmd:"picture2.nsbmd"}], other:[null, "picture2.nsbca"]}; + case 0x0153: + return {mdl:[{nsbmd:"om6Tree1.nsbmd"}]}; + + //0x0154 is rainbow road rotating star + case 0x0154: + forceBill = false; + return {mdl:[{nsbmd:"RainStar.nsbmd"}], other:["RainStar.nsbta"]}; + + case 0x0155: + return {mdl:[{nsbmd:"Of6Tree1.nsbmd"}]}; + case 0x0156: + return {mdl:[{nsbmd:"Of6Tree1.nsbmd"}]}; + case 0x0157: + return {mdl:[{nsbmd:"TownMonte.nsbmd"}], other:[null, null, "TownMonte.nsbtp"]}; //pianta! + + //debug pianta bridge + case 0x00CC: + forceBill = false; + return {mdl:[{nsbmd:"bridge.nsbmd"}], other:[null, "bridge.nsbca"]}; + //debug puddle + case 0x000D: + forceBill = false; + return {mdl:[{nsbmd:"puddle.nsbmd"}]}; + //debug airship + case 0x0158: + forceBill = false; + return {mdl:[{nsbmd:"airship.nsbmd"}]}; + + //need version for 3d objects? + + //DEBUG ENEMIES - remove here when implemented. + + case 0x0191: //goomba + return {mdl:[{nsbmd:"kuribo.nsbmd"}], other:[null, null, "kuribo.nsbtp"]}; //has nsbtp, route + case 0x0192: //rock + forceBill = false; + return {mdl:[{nsbmd:"rock.nsbmd"}, {nsbmd:"rock_shadow.nsbmd"}]}; //has route + case 0x0193: //thwomp + forceBill = false; + return {mdl:[{nsbmd:"dossun.nsbmd"}, {nsbmd:"dossun_shadow.nsbmd"}]}; //has route + case 0x0196: //chain chomp + forceBill = false; + return {mdl:[{nsbmd:"wanwan.nsbmd"}, {nsbmd:"wanwan_chain.nsbmd"}, {nsbmd:"wanwan_kui.nsbmd"}, {nsbmd:"rock_shadow.nsbmd"}]}; + case 0x0198: //bowser castle GBA fireball + return {mdl:[{nsbmd:"mkd_ef_bubble.nsbmd"}]}; + case 0x0199: //peach gardens monty + forceBill = false; + return {mdl:[{nsbmd:"choropu.nsbmd"}], other:[null, null, "choropu.nsbtp"]}; //has nsbtp + case 0x019B: //cheep cheep (bouncing) + return {mdl:[{nsbmd:"pukupuku.nsbmd"}], other:[null, null, "pukupuku.nsbtp"]}; //has nsbtp + case 0x019D: //snowman + return {mdl:[{nsbmd:"sman_top.nsbmd"}, {nsbmd:"sman_bottom.nsbmd"}]}; + case 0x019E: //trunk with bats + forceBill = false; + return {mdl:[{nsbmd:"kanoke_64.nsbmd"}, {nsbmd:"basabasa.nsbmd"}], other:[null, "kanoke_64.nsbca"]}; //basa has nsbtp + case 0x01A0: //bat + return {mdl:[{nsbmd:"basabasa.nsbmd"}], other:[null, null, "basabasa.nsbtp"]}; //has nsbtp + case 0x01A1: //as fortress cannon + forceBill = false; + return {mdl:[{nsbmd:"NsCannon1.nsbmd"}]}; + case 0x01A3: //mansion moving tree + forceBill = false; + return {mdl:[{nsbmd:"move_tree.nsbmd"}], other:[null, "move_tree.nsbca"]}; //has route + case 0x01A4: //flame + forceBill = false; + return {mdl:[{nsbmd:"mkd_ef_burner.nsbmd"}], other:["mkd_ef_burner.nsbta", null]}; + case 0x01A5: //chain chomp no base + forceBill = false; + return {mdl:[{nsbmd:"wanwan.nsbmd"}, {nsbmd:"wanwan_chain.nsbmd"}, {nsbmd:"rock_shadow.nsbmd"}]}; + + case 0x01A6: //plant + return {mdl:[{nsbmd:"ob_pakkun_sf.nsbmd"}], other:[null, null, "ob_pakkun_sf.nsbtp"]}; //has nsbtp + + case 0x01A7: //monty airship + forceBill = false; + return {mdl:[{nsbmd:"poo.nsbmd"}, {nsbmd:"cover.nsbmd"}, {nsbmd:"hole.nsbmd"}], other:[null, null, "poo.nsbtp"]}; //poo has nsbtp + + case 0x01A8: //bound + forceBill = false; + return {mdl:[{nsbmd:"bound.nsbmd"}], other:[null, null, "bound.nsbtp"]}; //has nsbtp + case 0x01A9: //flipper + forceBill = false; + return {mdl:[{nsbmd:"flipper.nsbmd"}], other:["flipper.nsbta", null, "flipper.nsbtp"]}; //has nsbtp + + case 0x01AA: //3d fire plant + forceBill = false; + //note... what exactly is PakkunZHead... + return {mdl:[{nsbmd:"PakkunMouth.nsbmd"}, {nsbmd:"PakkunBody.nsbmd"}, {nsbmd:"FireBall.nsbmd"}], other:[null, "PakkunMouth.nsbca"]}; + case 0x01AC: //crab + forceBill = false; + return {mdl:[{nsbmd:"crab.nsbmd"}, {nsbmd:"crab_hand.nsbmd"}], other:[null, null, "crab.nsbtp"]}; //both have nsbtp + + case 0x01AD: //desert hills sun + forceBill = false; + return {mdl:[{nsbmd:"sun.nsbmd"}, {nsbmd:"sun_LOD.nsbmd"}]/*, other:[null, "sun.nsbca"]*/}; //exesun animation does not load + + case 0x01B0: //routed iron ball + return {mdl:[{nsbmd:"IronBall.nsbmd"}]}; + case 0x01B1: //routed choco mountain rock + forceBill = false; + return {mdl:[{nsbmd:"rock2.nsbmd"}]}; + case 0x01B2: //sanbo... whatever that is (pokey?) routed + return {mdl:[{nsbmd:"sanbo_h.nsbmd"}, {nsbmd:"sanbo_b.nsbmd"}]}; + case 0x01B3: //iron ball + return {mdl:[{nsbmd:"IronBall.nsbmd"}]}; + + case 0x01B4: //cream + forceBill = false; + return {mdl:[{nsbmd:"cream.nsbmd"}, {nsbmd:"cream_effect.nsbmd"}]}; + case 0x01B5: //berry + forceBill = false; + return {mdl:[{nsbmd:"berry.nsbmd"}, {nsbmd:"cream_effect.nsbmd"}]}; + } + } + + function provideRes(r) { + res = r; //...and gives them to us. :) + + if (forceBill) { + t.angle[1] = 0; + var bmd = r.mdl[0].bmd; + bmd.hasBillboards = true; + var models = bmd.modelData.objectData; + for (var i=0; i 0 && r.other[0] != null) { + res.mdl[0].loadTexAnim(r.other[0]); + } + if (r.other.length > 1 && r.other[1] != null) + anim = new nitroAnimator(r.mdl[0].bmd, r.other[1]); + } + } + +} \ No newline at end of file diff --git a/code/entities/itembox.js b/code/entities/itembox.js new file mode 100644 index 0000000..fc64640 --- /dev/null +++ b/code/entities/itembox.js @@ -0,0 +1,120 @@ +// +// itembox.js +//-------------------- +// Drives and animates itembox entity. +// by RHY3756547 +// + +window.ItemBox = function(obji, scene) { + var obji = obji; + var res = []; + + var t = this; + + var anim = 0; + var animFrame = 0; + var animMat; + var frames = 0; + + t.soundProps = {}; + t.pos = vec3.clone(obji.pos); + //t.angle = vec3.clone(obji.angle); + t.scale = vec3.clone(obji.scale); + + t.sndUpdate = sndUpdate; + t.requireRes = requireRes; + t.provideRes = provideRes; + t.update = update; + t.draw = draw; + + t.mode = 0; + t.time = 0; + + var test = 0; + + + function update(scene) { + switch (t.mode) { + case 0: //alive + for (var i=0; i 30) { + t.mode = 2; + t.time = 0; + } + break; + case 2: //respawning + if (t.time++ > 30) { + t.mode = 0; + t.time = 0; + } + break; + } + + animMat = anim.setFrame(0, 0, animFrame); + animFrame = (animFrame+1)%frames; + } + + function draw(view, pMatrix, gl) { + if (t.mode == 0 || t.mode == 2) { + if (t.mode == 2) nitroRender.setColMult([1, 1, 1, t.time/30]); + var mat = mat4.translate(mat4.create(), view, t.pos); + + mat4.scale(mat, mat, vec3.scale([], t.scale, 16)); + + //res.mdl[2].draw(mat, pMatrix); + + mat4.translate(mat, mat, [0, 1, 0]) + + gl.enable(gl.CULL_FACE); //box part + //gl.depthMask(false); + res.mdl[0].drawPoly(mat, pMatrix, 0, 1, animMat); + //gl.depthMask(true); + gl.disable(gl.CULL_FACE); + + //question mark part + gl.depthRange(0, 0.99); //hack to push question mark forward in z buffer, causes a few issues with far away boxes though + res.mdl[0].drawPoly(mat, pMatrix, 0, 0, animMat); + gl.depthRange(0, 1); + + if (t.mode == 2) nitroRender.setColMult([1, 1, 1, 1]); + } + } + + function sndUpdate(view) { + t.soundProps.pos = vec3.transformMat4([], t.pos, view); + if (t.soundProps.lastPos != null) t.soundProps.vel = vec3.sub([], t.soundProps.pos, t.soundProps.lastPos); + else t.soundProps.vel = [0, 0, 0]; + t.soundProps.lastPos = t.soundProps.pos; + + t.soundProps.refDistance = 192/1024; + t.soundProps.rolloffFactor = 1; + } + + function requireRes() { //scene asks what resources to load + return {mdl:[{nsbmd:"itembox.nsbmd"}, {nsbmd:"obj_shadow.nsbmd"}, {nsbmd:"itembox_hahen.nsbmd"}], other:["itembox.nsbca"]}; + } + + function provideRes(r) { + res = r; //...and gives them to us. :) + anim = new nitroAnimator(r.mdl[0].bmd, r.other[0]); + frames = r.other[0].animData.objectData[0].frames; + animFrame = Math.floor(Math.random()*frames); + animMat = anim.setFrame(0, 0, animFrame); + } + +} \ No newline at end of file diff --git a/code/entities/kart.js b/code/entities/kart.js new file mode 100644 index 0000000..495d853 --- /dev/null +++ b/code/entities/kart.js @@ -0,0 +1,890 @@ +// +// kart.js +//-------------------- +// Entity type for karts. +// by RHY3756547 +// +// includes: gl-matrix.js (glMatrix 2.0) +// /formats/kcl.js +// + +window.Kart = function(pos, angle, speed, kartN, charN, controller, scene) { + var k = this; + var minimumMove = 0.05; + var MAXSPEED = 24; + var BOOSTTIME = 90; + + var kartSoundBase = 170; + + var COLBOUNCE_TIME = 20; + var COLBOUNCE_STRENGTH = 1; + + var params = scene.gameRes.kartPhys.karts[kartN]; + var offsets = scene.gameRes.kartOff.karts[kartN]; + + this.local = controller.local; + this.active = true; + this.preboost = true; + + this.soundProps = {}; + this.pos = pos; + this.angle = angle; + this.vel = vec3.create(); + this.weight = params.weight; + this.params = params; + this.kartBounce = kartBounce; + + this.speed = speed; + this.drifting = false; + this.driftMode = 0; //1 left, 2 right, 0 undecided + this.driftLanded = false; //if we haven't landed then apply a constant turn. + + //powerslide info: to advance to the next mode you need to hold the same button for 10 or more frames. Mode 0 starts facing drift direction, 1 is other way, 2 is returning (mini spark), 3 is other way, 4 is returning (turbo spark) + this.driftPSTick = 0; + this.driftPSMode = 0; + + this.kartTargetNormal = [0, 1, 0]; + this.kartNormal = [0, 1, 0]; + this.airTime = 0; + this.controller = controller; + + this.driftOff = 0; + this.physicalDir = angle; + this.mat = mat4.create(); + this.basis = mat4.create(); + this.ylock = 0; + + this.cannon = null; + + this.gravity = [0, -0.17, 0]; //100% confirmed by me messing around with the gravity value in mkds. for sticky surface and loop should modify to face plane until in air + + this.update = update; + this.sndUpdate = sndUpdate; + this.draw = draw; + + this.drawKart = drawKart; + this.drawWheels = drawWheels; + this.drawChar = drawChar; + + this.trackAttach = null; //a normal for the kart to attach to (loop) + this.boostMT = 0; + this.boostNorm = 0; + + this.kartColVel = vec3.create(); + this.kartColTimer = 0; + + var charRes = scene.gameRes.getChar(charN); + var kartRes = scene.gameRes.getKart(kartN); + var kartPolys = []; + + var kObj = kartRes.bmd.modelData.objectData[0]; + + for (var i=0; i= hitGroundAnim.length) groundAnim = -1; + } + + onGround = (k.airTime < 5); + + kartAnim = (kartAnim+1)%8; + var input = k.controller.fetchInput(); + k.lastInput = input; + + if (input.turn > 0.3) { + if (k.driveAnimF < 28) k.driveAnimF++; + } else if (input.turn < -0.3) { + if (k.driveAnimF > 0) k.driveAnimF--; + } else { + if (k.driveAnimF > 14) k.driveAnimF--; + else if (k.driveAnimF < 14) k.driveAnimF++; + } + + //update sounds + + var newSoundMode = soundMode; + if (input.accel) { + if (soundMode == 0 || soundMode == 6) newSoundMode = 2; + if (soundMode == 4) newSoundMode = 3; + } else { + if (soundMode != 0) { + if (soundMode == 2 || soundMode == 3) newSoundMode = 4; + if (newSoundMode == 4 && k.speed < 0.5) newSoundMode = 0; + } + } + + if (k.boostMT+k.boostNorm > 0) { + if (k.boostNorm == BOOSTTIME || k.boostMT == params.miniTurbo) { + if (sounds.boostSoundTrig) { + if (sounds.boost != null) nitroAudio.instaKill(sounds.boost); + sounds.boost = nitroAudio.playSound(160, {}, 0, k); + sounds.boost.gainN.gain.value = 2; + sounds.boostSoundTrig = false; + } + } else { + sounds.boostSoundTrig = true; + } + } else if (sounds.boost != null) { + nitroAudio.kill(sounds.boost); + sounds.boost = null; + } + + if (onGround && k.speed > 0.5) { + if (lastCollided != sounds.lastTerrain || lastBE != sounds.lastBE || sounds.drive == null) { + if (sounds.drive != null) nitroAudio.kill(sounds.drive); + if (lastColSounds.drive != null) { + sounds.drive = nitroAudio.playSound(lastColSounds.drive, {}, 0, k); + sounds.drive.gainN.gain.value = 2; + } + } + + if (k.drifting && k.driftLanded) { + if (lastCollided != sounds.lastTerrain || lastBE != sounds.lastBE || sounds.drift == null) { + if (sounds.drift != null) nitroAudio.kill(sounds.drift); + if (lastColSounds.drift != null) { + sounds.drift = nitroAudio.playSound(lastColSounds.drift, {}, 0, k); + } + } + } else if (sounds.drift != null) { nitroAudio.kill(sounds.drift); sounds.drift = null; } + + sounds.lastTerrain = lastCollided; + sounds.lastBE = lastBE; + } else { + if (sounds.drift != null) { nitroAudio.kill(sounds.drift); sounds.drift = null; } + if (sounds.drive != null) { nitroAudio.kill(sounds.drive); sounds.drive = null; } + } + + //end sound update + + if (k.preboost) { + + } else if (k.cannon != null) { //when cannon is active, we fly forward at max move speed until we get to the cannon point. + var c = scene.nkm.sections["KTPC"].entries[k.cannon]; + + var mat = mat4.create(); + mat4.rotateY(mat, mat, c.angle[1]*(Math.PI/180)); + mat4.rotateX(mat, mat, c.angle[0]*(-Math.PI/180)); + + var forward = [0, 0, 1]; + var up = [0, 1, 0]; + + k.vel = vec3.scale([], vec3.transformMat4(forward, forward, mat), MAXSPEED); + k.speed = MAXSPEED; + vec3.add(k.pos, k.pos, k.vel); + k.physicalDir = (180-c.angle[1])*(Math.PI/180); + k.angle = k.physicalDir; + k.kartTargetNormal = vec3.transformMat4(up, up, mat); + + var planeConst = -vec3.dot(c.pos, forward); + var cannonDist = vec3.dot(k.pos, forward) + planeConst; + if (cannonDist > 0) k.cannon = null; + } else { //default kart mode + + var groundEffect = 0; + if (lastCollided != -1) { + groundEffect = MKDS_COLTYPE.PHYS_MAP[lastCollided]; + if (groundEffect == null) groundEffect = 0; + } + + var effect = params.colParam[groundEffect]; + var top = params.topSpeed*effect.topSpeedMul; //if you let go of accel, drift ends anyway, so always accel in drift. + + var boosting = (k.boostNorm + k.boostMT)>0; + + if (boosting) { + var top2 + if (k.boostNorm>0){ + top2 = params.topSpeed*1.3; + k.boostNorm--; + } else { + top2 = params.topSpeed*((effect.topSpeedMul >= 1)?1.3:effect.topSpeedMul); + } + + if (k.boostMT>0) { + k.boostMT--; + } + + if (k.speed <= top2) { + k.speed += 1; + if (k.speed > top2) k.speed = top2; + } else { + k.speed *= 0.95; + } + } + + //kart controls + if (k.drifting) { + if ((onGround) && !(input.accel && input.drift && (k.speed > 2 || !k.driftLanded))) { + //end drift, execute miniturbo + k.drifting = false; + if (sounds.powerslide != null) { + nitroAudio.instaKill(sounds.powerslide); + sounds.powerslide = null; + } + if (k.driftPSMode == 3) { + k.boostMT = params.miniTurbo; + } + k.driftPSMode = 0; + k.driftPSTick = 0; + } + + if (k.driftMode == 0) { + if (input.turn > 0.30) { + k.driftMode = 2; + } else if (input.turn < -0.30) { + k.driftMode = 1; + } + } else { + if (k.driftLanded) { + var change = (((k.driftMode-1.5)*Math.PI/1.5)-k.driftOff)*0.05; + k.driftOff += change; + k.physicalDir -= change; + } + + //if we're above the initial y position, add a constant turn with a period of 180 frames. + if (!k.driftLanded && k.ylock>=0) { + k.physicalDir += (Math.PI*2/180)*(k.driftMode*2-3); + } + } + + if (onGround) { + if (!k.driftLanded) { + if (k.driftMode == 0) k.drifting = false; + else { + k.driftPSMode = 0; + k.driftPSTick = 0; + k.driftLanded = true; + } + } + if (k.drifting) { + + if (!boosting) { + if (k.speed <= top) { + k.speed += (k.speed/top > params.driftAccelSwitch)?params.driftAccel2:params.driftAccel1; + if (k.speed > top) k.speed = top; + } else { + k.speed *= 0.95; + } + } + + var turn = ((k.driftMode == 1)?(input.turn-1):(input.turn+1))/2; + + k.physicalDir += params.driftTurnRate*turn+((k.driftMode == 1)?-1:1)*(50/32768)*Math.PI; //what is this mystery number i hear you ask? well my friend, this is the turn rate for outward drift. + + //miniturbo code + if (input.turn != 0) { + var inward = ((input.turn>0) == k.driftMode-1); //if we're turning + + switch (k.driftPSMode) { + case 0: //dpad away from direction for 10 frames + if (!inward) k.driftPSTick++; + else if (k.driftPSTick > 9) { + k.driftPSMode++; + k.driftPSTick = 1; + + //play blue spark sound + var blue = nitroAudio.playSound(210, {}, 0, k); + blue.gainN.gain.value = 2; + + } else k.driftPSTick = 0; + break; + case 1: //dpad toward direction for 10 frames + if (inward) k.driftPSTick++; + else if (k.driftPSTick > 9) { + k.driftPSMode++; + k.driftPSTick = 1; + + } else k.driftPSTick = 0; + break; + case 2: //dpad away from direction for 10 frames + if (!inward) k.driftPSTick++; + else if (k.driftPSTick > 9) { + k.driftPSMode++; + k.driftPSTick = 1; + //play red sparks sound, full MT! + sounds.powerslide = nitroAudio.playSound(209, {}, 0, k); + sounds.powerslide.gainN.gain.value = 2; + } else k.driftPSTick = 0; + break; + case 3: //turbo charged + break; + } + } + } + } + } + + if (!k.drifting) { + if (onGround) { + var effect = params.colParam[groundEffect]; + if (!boosting) { + if (input.accel) { + if (k.speed <= top) { + k.speed += (k.speed/top > params.accelSwitch)?params.accel2:params.accel1; + if (k.speed > top) k.speed = top; + } else { + k.speed *= 0.95; + } + } else { + k.speed *= params.decel; + } + } + + if ((input.accel && k.speed >= 0) || (k.speed > 0.1)) { + k.physicalDir += params.turnRate*input.turn; + } else if ( k.speed < -0.1) { + k.physicalDir -= params.turnRate*input.turn; + } + + if (input.drift) { + ylvel = 1.25; + k.vel[1] += 1.25; + k.airTime = 4; + k.drifting = true; + k.driftLanded = false; + k.driftMode = 0; + k.ylock = 0; + + var boing = nitroAudio.playSound(207, {transpose: -4}, 0, k); + boing.gainN.gain.value = 2; + } + } else { + if (input.drift) { + ylvel = 0; + k.drifting = true; + k.driftLanded = false; + k.driftMode = 0; + k.ylock = -0.001; + } + } + } + + k.physicalDir = fixDir(k.physicalDir); + + if (k.driftOff != 0 && (!k.drifting || !k.driftLanded)) { + if (k.driftOff > 0) { + k.physicalDir += params.driftOffRestore; + k.driftOff -= params.driftOffRestore; + if (k.driftOff < 0) k.driftOff = 0; + } else { + k.physicalDir -= params.driftOffRestore; + k.driftOff += params.driftOffRestore; + if (k.driftOff > 0) k.driftOff = 0; + } + } + + checkKartCollision(scene); + + if (!onGround) { + this.kartTargetNormal = [0, 1, 0]; + vec3.add(k.vel, k.vel, k.gravity) + if (k.ylock >= 0) { + ylvel += k.gravity[1]; + k.ylock += ylvel; + } + + if (k.kartColTimer == COLBOUNCE_TIME) { + vec3.add(k.vel, k.vel, k.kartColVel); + } + } else { + k.angle += dirDiff(k.physicalDir, k.angle)*effect.handling/2; + k.angle = fixDir(k.physicalDir); + + k.vel[1] += k.gravity[1]; + k.vel = [Math.sin(k.angle)*k.speed, k.vel[1], -Math.cos(k.angle)*k.speed] + + if (k.kartColTimer > 0) { + vec3.add(k.vel, k.vel, vec3.scale([], k.kartColVel, k.kartColTimer/10)) + } + } + + if (k.kartColTimer > 0) k.kartColTimer--; + + wheelTurn += k.speed/16; + wheelTurn = fixDir(wheelTurn); + k.airTime++; + //end kart controls + + //move kart on moving platforms (no collision, will be corrected by next step) + if (stuckTo != null) { + if (stuckTo.moveWith != null) stuckTo.moveWith(k); + stuckTo = null; + } + + //move kart. + + + + var steps = 0; + var remainingT = 1; + var velSeg = vec3.clone(k.vel); + var posSeg = vec3.clone(k.pos); + var ignoreList = []; + while (steps++ < 10 && remainingT > 0.01) { + var result = lsc.sweepEllipse(posSeg, velSeg, scene, [params.colRadius, params.colRadius, params.colRadius], ignoreList); + if (result != null) { + colResponse(posSeg, velSeg, result, ignoreList) + remainingT -= result.t; + if (remainingT > 0.01) { + velSeg = vec3.scale(vec3.create(), k.vel, remainingT); + } + } else { + vec3.add(posSeg, posSeg, velSeg); + remainingT = 0; + } + } + k.pos = posSeg; + } + + //interpolate visual normal roughly to target + var rate = onGround?0.15:0.025; + k.kartNormal[0] += (k.kartTargetNormal[0]-k.kartNormal[0])*rate; + k.kartNormal[1] += (k.kartTargetNormal[1]-k.kartNormal[1])*rate; + k.kartNormal[2] += (k.kartTargetNormal[2]-k.kartNormal[2])*rate; + vec3.normalize(k.kartNormal, k.kartNormal); + + k.basis = buildBasis(); + + var mat = mat4.create(); + mat4.translate(mat, mat, k.pos); + k.mat = mat4.mul(mat, mat, k.basis); + + if (input.item) { + scene.items.addItem(0, scene.karts.indexOf(k), {}) + } + + updateKartSound(newSoundMode, input); + positionChanged(lastPos, k.pos); + } + + function genFutureChecks() { + //all future points that + var chosen = {} + var current = checkpoints[k.checkPointNumber]; + var expectedSection = current.nextSection; + futureChecks = []; + for (var i=k.checkPointNumber+1; i 0 && lineDot < vec2.sqrLen(lineCheck) && dot < 0 && dotOld >= 0) { + k.checkPointNumber = futureChecks[i]; + genFutureChecks(); + break; + } + } + + if (!k.passedKTP2 && forwardCrossedKTP(passLine, oldPos, pos)) k.passedKTP2 = true; + if (k.passedKTP2 && futureChecks.length == 0) { + //we can finish the lap + if (forwardCrossedKTP(startLine, oldPos, pos)) { + k.lapNumber++; + k.checkPointNumber = 0; + k.passedKTP2 = 0; + scene.lapAdvance(k); + } + } + } + + function forwardCrossedKTP(ktp, oldPos, pos) { + var distOld = vec2.sub([], [ktp.pos[0], ktp.pos[2]], [oldPos[0], oldPos[2]]); + var dist = vec2.sub([], [ktp.pos[0], ktp.pos[2]], [pos[0], pos[2]]); + + var ang = (ktp.angle[1]/180)*Math.PI; + + var sinus = Math.sin(ang); + var cosinus = Math.cos(ang); + + var dot = vec2.dot(dist, [sinus, cosinus]); + var dotOld = vec2.dot(distOld, [sinus, cosinus]); + + return (dot < 0 && dotOld >= 0); + } + + function checkKartCollision(scene) { //check collision with other karts. Really simple. + for (var i=0; i0 || ok.boostMT>0)?2:1)*((k.boostNorm>0 || k.boostMT>0)?0.5:1); + + //as well as side bounce also add velocity difference if other vel > mine. + + vec3.sub(k.kartColVel, k.pos, ok.pos); + k.kartColVel[1] = 0; + vec3.normalize(k.kartColVel, k.kartColVel); + vec3.scale(k.kartColVel, k.kartColVel, weightMul); + + if (vec3.length(k.vel) < vec3.length(ok.vel)) vec3.add(k.kartColVel, k.kartColVel, vec3.sub([], ok.vel, k.vel)); + + k.kartColVel[1] = 0; + } + + function fixDir(dir) { + return posMod(dir, Math.PI*2); + } + + function dirDiff(dir1, dir2) { + var d = fixDir(dir1-dir2); + return (d>Math.PI)?(-2*Math.PI+d):d; + } + + function posMod(i, n) { + return (i % n + n) % n; + } + + function updateKartSound(mode, input) { + var turn = (onGround && !k.drifting)?(1-Math.abs(input.turn)/11):1; + var transpose = (mode == 0)?0:(22*turn*k.speed/params.topSpeed); + + sounds.transpose += (transpose-sounds.transpose)/15; + if (mode != soundMode) { + soundMode = mode; + if (sounds.kart != null) nitroAudio.instaKill(sounds.kart); + sounds.kart = nitroAudio.playSound(kartSoundBase+soundMode, {transpose:sounds.transpose, volume:1}, 0, k); + //if (mode == 3) sounds.kart.gainN.gain.value = 0.5; + } else { + sounds.kart.seq.setTranspose(sounds.transpose); + } + } + + function buildBasis() { + //order y, x, z + var dir = k.physicalDir+k.driftOff+(Math.sin((COLBOUNCE_TIME-k.kartColTimer)/3)*(Math.PI/6)*(k.kartColTimer/COLBOUNCE_TIME)); + var basis = gramShmidt(k.kartNormal, [Math.cos(dir), 0, Math.sin(dir)], [Math.sin(dir), 0, -Math.cos(dir)]); + var temp = basis[0]; + basis[0] = basis[1]; + basis[1] = temp; //todo: cleanup + return [ + basis[0][0], basis[0][1], basis[0][2], 0, + basis[1][0], basis[1][1], basis[1][2], 0, + basis[2][0], basis[2][1], basis[2][2], 0, + 0, 0, 0, 1 + ] + + } + + function sndUpdate(view) { + k.soundProps.pos = vec3.transformMat4([], k.pos, view); + if (k.soundProps.lastPos != null) k.soundProps.vel = vec3.sub([], k.soundProps.pos, k.soundProps.lastPos); + else k.soundProps.vel = [0, 0, 0]; + k.soundProps.lastPos = k.soundProps.pos; + + k.soundProps.refDistance = 192/1024; + k.soundProps.rolloffFactor = 1; + + var calcVol = (k.soundProps.refDistance / (k.soundProps.refDistance + k.soundProps.rolloffFactor * (Math.sqrt(vec3.dot(k.soundProps.pos, k.soundProps.pos)) - k.soundProps.refDistance))); + } + + function gramShmidt(v1, v2, v3) { + var u1 = v1; + var u2 = vec3.sub([0, 0, 0], v2, project(u1, v2)); + var u3 = vec3.sub([0, 0, 0], vec3.sub([0, 0, 0], v3, project(u1, v3)), project(u2, v3)); + return [vec3.normalize(u1, u1), vec3.normalize(u2, u2), vec3.normalize(u3, u3)] + } + + function colSound(collision, effect) { + if (MKDS_COLTYPE.SOUNDMAP[collision] == null) return {}; + return MKDS_COLTYPE.SOUNDMAP[collision][effect] || {}; + } + + function project(u, v) { + return vec3.scale([], u, (vec3.dot(u, v)/vec3.dot(u, u))) + } + + function colResponse(pos, pvel, dat, ignoreList) { + + var plane = dat.plane; + var colType = (plane.CollisionType>>8)&31; + var colBE = (plane.CollisionType>>5)&7; + + lastCollided = colType; + lastBE = colBE; + lastColSounds = colSound(lastCollided, colBE); + + var n = vec3.normalize([], dat.normal); + var gravS = Math.sqrt(vec3.dot(k.gravity, k.gravity)); + var angle = Math.acos(vec3.dot(vec3.scale(vec3.create(), k.gravity, -1/gravS), n)); + var adjustPos = true; + + if (MKDS_COLTYPE.GROUP_WALL.indexOf(colType) != -1) { //wall + //sliding plane, except normal is transformed to be entirely on the xz plane (cannot ride on top of wall, treated as vertical) + var xz = Math.sqrt(n[0]*n[0]+n[2]*n[2]) + var adjN = [n[0]/xz, 0, n[2]/xz] + var proj = vec3.dot(k.vel, adjN); + + if (proj < -1) { + if (lastColSounds.hit != null) nitroAudio.playSound(lastColSounds.hit, {volume:1}, 0, k) + } + vec3.sub(k.vel, k.vel, vec3.scale(vec3.create(), adjN, proj)); + + //convert back to angle + speed to keep change to kart vel + + var v = k.vel; + k.speed = Math.sqrt(v[0]*v[0]+v[2]*v[2]); + k.angle = Math.atan2(v[0], -v[2]); + } else if (MKDS_COLTYPE.GROUP_ROAD.indexOf(colType) != -1) { + //sliding plane + if (MKDS_COLTYPE.GROUP_BOOST.indexOf(colType) != -1) { + k.boostNorm = BOOSTTIME; + } + + if (k.vel[1] > 0) k.vel[1] = 0; + var proj = vec3.dot(k.vel, n); + if (proj < -4 && k.vel[1] < -2) { proj -= 1.5; } + vec3.sub(k.vel, k.vel, vec3.scale(vec3.create(), n, proj)); + k.kartTargetNormal = dat.pNormal; + if (!onGround) { + console.log("ground: "+colType+", "+colBE); + groundAnim = 0; + if (lastColSounds.land != null) nitroAudio.playSound(lastColSounds.land, {volume:1}, 0, k) + } + k.airTime = 0; + stuckTo = dat.object; + } else if (colType == MKDS_COLTYPE.CANNON) { + //cannon!! + k.cannon = colBE; + } else { + adjustPos = false; + ignoreList.push(plane); + } + + //vec3.add(pos, pos, vec3.scale(vec3.create(), n, minimumMove)); //move away from plane slightly + + if (adjustPos) { //move back from plane slightly + //vec3.add(pos, pos, vec3.scale(vec3.create(), n, minimumMove)); + vec3.add(pos, pos, vec3.scale(vec3.create(), pvel, dat.t)); + vec3.add(pos, vec3.scale([], n, params.colRadius+minimumMove), dat.colPoint); + /*if (dat.embedded) { + + } else { + var velMag = Math.sqrt(vec3.dot(pvel, pvel)); + if (velMag*dat.t > minimumMove) { + vec3.add(pos, pos, vec3.scale(vec3.create(), pvel, dat.t-(minimumMove/velMag))); + } else { + //do not move, too close + } + }*/ + } else { + vec3.add(pos, pos, vec3.scale(vec3.create(), pvel, dat.t)); + } + + } +} \ No newline at end of file diff --git a/code/entities/objDatabase.js b/code/entities/objDatabase.js new file mode 100644 index 0000000..3a6504a --- /dev/null +++ b/code/entities/objDatabase.js @@ -0,0 +1,119 @@ +// +// objDatabase.js +//-------------------- +// Links object IDs to specific entity types. Must be initialized after all js files are loaded! +// by RHY3756547 +// +// includes: +// entities/* +// + +window.objDatabase = new (function(){ + + this.init = function() { + this.idToType = []; + + var t = this.idToType; + t[0x0001] = ObjWater; + t[0x0003] = ObjWater; + t[0x0006] = ObjWater; + t[0x0008] = ObjSoundMaker; + t[0x0009] = ObjWater; + t[0x000C] = ObjWater; + + t[0x0065] = ItemBox; + + t[0x00CA] = ObjRoutePlatform; + t[0x00CB] = ObjGear; + t[0x00CE] = ObjGear; //test_cylinder, tick tock clock end + t[0x00D0] = ObjRotaryRoom; + t[0x00D1] = ObjGear; //rotary bridge + + t[0x012D] = ObjDecor; + t[0x012E] = ObjDecor; + t[0x012F] = ObjDecor; + + t[0x0130] = ObjDecor; + t[0x0131] = ObjDecor; + t[0x0132] = ObjDecor; + t[0x0133] = ObjDecor; + t[0x0134] = ObjDecor; + t[0x0135] = ObjDecor; + t[0x0138] = ObjDecor; + t[0x0139] = ObjDecor; + t[0x013C] = ObjDecor; //DEBUG: cheep cheep (routed) + t[0x013D] = ObjDecor; //DEBUG: ghost + + t[0x013A] = ObjDecor; //figure 8 tree + t[0x013C] = ObjDecor; + t[0x013F] = ObjDecor; + + t[0x0140] = ObjDecor; + t[0x0142] = ObjDecor; //more trees + t[0x0145] = ObjDecor; + t[0x0146] = ObjDecor; + t[0x0148] = ObjDecor; + t[0x0149] = ObjDecor; //yoshi falls egg + + t[0x014B] = ObjDecor; + t[0x014C] = ObjDecor; + t[0x014D] = ObjDecor; + t[0x014E] = ObjDecor; + t[0x014F] = ObjDecor; + + t[0x0150] = ObjDecor; + t[0x0151] = ObjDecor; + t[0x0152] = ObjDecor; + t[0x0153] = ObjDecor; + t[0x0154] = ObjDecor; //rainbow star + t[0x0155] = ObjDecor; + t[0x0156] = ObjDecor; + t[0x0157] = ObjDecor; + + t[0x019C] = ObjTruck; + t[0x019A] = ObjCar; + t[0x0195] = ObjBus; + + + t[0x00CC] = ObjDecor; //DEBUG: pianta bridge + t[0x000D] = ObjDecor; //DEBUG: puddle + + t[0x0158] = ObjDecor; //DEBUG: airship (routed) + + //DEBUG ENEMIES AS DECOR: switch as implemented: + + t[0x0191] = ObjDecor; + t[0x0192] = ObjDecor; + t[0x0193] = ObjDecor; + t[0x0196] = ObjDecor; + t[0x0198] = ObjDecor; + t[0x0199] = ObjDecor; + //truck + t[0x019B] = ObjDecor; + t[0x019D] = ObjDecor; + t[0x019E] = ObjDecor; + + t[0x01A0] = ObjDecor; + t[0x01A1] = ObjDecor; + t[0x01A3] = ObjDecor; + t[0x01A4] = ObjDecor; + t[0x01A5] = ObjDecor; + t[0x01A6] = ObjDecor; + t[0x01A7] = ObjDecor; + t[0x01A8] = ObjDecor; + t[0x01A9] = ObjDecor; + + t[0x01AA] = ObjDecor; + t[0x01AC] = ObjDecor; + t[0x01AD] = ObjDecor; + //rotating fireballs + + t[0x01B0] = ObjDecor; + t[0x01B1] = ObjDecor; + t[0x01B2] = ObjDecor; + t[0x01B3] = ObjDecor; + t[0x01B4] = ObjDecor; + t[0x01B5] = ObjDecor; + } + +})(); \ No newline at end of file diff --git a/code/entities/rotatingGear.js b/code/entities/rotatingGear.js new file mode 100644 index 0000000..2186d9b --- /dev/null +++ b/code/entities/rotatingGear.js @@ -0,0 +1,161 @@ +// +// rotatingGear.js +//-------------------- +// Provides rotating gear objects for tick tock clock +// by RHY3756547 +// +// includes: +// render stuff idk +// + +window.ObjGear = function(obji, scene) { + var obji = obji; + var res = []; + + var t = this; + + t.collidable = true; + t.colMode = 0; + t.colRad = 512; + t.getCollision = getCollision; + t.moveWith = moveWith; + + t.pos = vec3.clone(obji.pos); + //t.angle = vec3.clone(obji.angle); + t.scale = vec3.clone(obji.scale); + + t.requireRes = requireRes; + t.provideRes = provideRes; + t.update = update; + t.draw = draw; + + t.speed = (obji.setting1&0xFFFF)/8192; + t.duration = obji.setting1>>16; + t.rampDur = obji.setting2&0xFFFF; + t.statDur = obji.setting2>>16; + t.wB1 = obji.setting3&0xFFFF; //ONE of these flips direction, the other makes the gear use the black model. Not sure which is which, but for tick tock clock there is no need to get this right. + t.wB2 = obji.setting3>>16; + + t.time = 0; + t.mode = 0; //0=rampup, 1=normal, 2=rampdown, 3=stationary + t.angle = 0; + t.dir = (t.wB1 == 0) + + var dirVel = 0; + + var prevMat; + var curMat; + setMat(); + prevMat = curMat; + + function setMat() { + prevMat = curMat; + var mat = mat4.create(); + mat4.translate(mat, mat, t.pos); + + mat4.scale(mat, mat, vec3.scale([], t.scale, 16)); + + mat4.rotateY(mat, mat, obji.angle[1]*(Math.PI/180)); + mat4.rotateX(mat, mat, obji.angle[0]*(Math.PI/180)); + + mat4.rotateY(mat, mat, t.angle); + curMat = mat; + } + + function update(scene) { + t.time++; + switch (t.mode) { + case 0: + dirVel = t.speed*(t.time/t.rampDur)*((t.dir)?-1:1); + if (t.time > t.rampDur) { + t.time = 0; t.mode = 1; + } + break; + case 1: + dirVel = t.speed*((t.dir)?-1:1); + if (t.time > t.duration) { + t.time = 0; t.mode = 2; + } + break; + case 2: + dirVel = t.speed*(1-t.time/t.rampDur)*((t.dir)?-1:1); + if (t.time > t.rampDur) { + t.time = 0; t.mode = 3; t.dir = !t.dir; + } + break; + case 3: + dirVel = 0; + if (t.time > t.statDur) { + t.time = 0; t.mode = 0; + } + break; + } + t.angle += dirVel; + setMat(); + } + + function draw(view, pMatrix) { + var mat = mat4.translate(mat4.create(), view, t.pos); + + mat4.scale(mat, mat, vec3.scale([], t.scale, 16)); + + mat4.rotateY(mat, mat, obji.angle[1]*(Math.PI/180)); + mat4.rotateX(mat, mat, obji.angle[0]*(Math.PI/180)); + + mat4.rotateY(mat, mat, t.angle); + + res.mdl[t.wB1].draw(mat, pMatrix); + } + + function requireRes() { //scene asks what resources to load + switch (obji.ID) { + case 0x00CB: + return {mdl:[{nsbmd:"gear_white.nsbmd"}, {nsbmd:"gear_black.nsbmd"}]}; + case 0x00CE: + return {mdl:[{nsbmd:"test_cylinder.nsbmd"}]}; + case 0x00D1: + t.colRad = 4096; + return {mdl:[{nsbmd:"rotary_bridge.nsbmd"}]}; + } + } + + function provideRes(r) { + res = r; //...and gives them to us. :) + } + + function getCollision() { + var obj = {}; + var inf = res.mdl[0].getCollisionModel(0, 0); + obj.tris = inf.dat; + + var mat = mat4.translate([], mat4.create(), t.pos); + mat4.scale(mat, mat, vec3.mul([], [16*inf.scale, 16*inf.scale, 16*inf.scale], t.scale)); + + mat4.rotateY(mat, mat, obji.angle[1]*(Math.PI/180)); + mat4.rotateX(mat, mat, obji.angle[0]*(Math.PI/180)); + mat4.rotateY(mat, mat, t.angle); + + obj.mat = mat; + return obj; + } + + function moveWith(obj) { //used for collidable objects that move. + + //the most general way to move something with an object is to multiply its position by the inverse mv matrix of that object, and then the new mv matrix. + + vec3.transformMat4(obj.pos, obj.pos, mat4.invert([], prevMat)) + vec3.transformMat4(obj.pos, obj.pos, curMat) + + /*var p = vec3.sub([], obj.pos, t.pos); + + if (obji.ID == 0x00D1) { //todo: maybe something more general + vec3.transformMat4(p, p, mat4.rotateX([], mat4.create(), dirVel)); + vec3.add(obj.pos, t.pos, p); + } else { + vec3.transformMat4(p, p, mat4.rotateY([], mat4.create(), dirVel)); + vec3.add(obj.pos, t.pos, p); + obj.physicalDir -= dirVel; + }*/ + } + +} \ No newline at end of file diff --git a/code/entities/shell.js b/code/entities/shell.js new file mode 100644 index 0000000..9dc2238 --- /dev/null +++ b/code/entities/shell.js @@ -0,0 +1,118 @@ +// +// shell.js +//-------------------- +// Entity type for shells. (green) +// by RHY3756547 +// +// includes: gl-matrix.js (glMatrix 2.0) +// /formats/kcl.js +// + +window.GreenShell = function(scene, owner, time, itemID, cliID, params) { + var t = this; + var minimumMove = 0.01; + + this.pos = vec3.transformMat4([], [0, (-owner.params.colRadius)+1, 16], owner.mat); + this.vel = vec3.create(); + this.gravity = [0, -0.17, 0]; //100% confirmed by me messing around with the gravity value in mkds + this.angle = owner.angle; + this.speed = 10; + this.yvel = 0; + + this.update = update; + this.draw = draw; + + function update(scene) { + t.vel = [Math.sin(t.angle)*t.speed, t.yvel, -Math.cos(t.angle)*t.speed] + vec3.add(t.vel, t.vel, t.gravity); + + //simple point move. + + var steps = 0; + var remainingT = 1; + var velSeg = vec3.clone(t.vel); + var posSeg = vec3.clone(t.pos); + var ignoreList = []; + while (steps++ < 10 && remainingT > 0.01) { + var result = lsc.raycast(posSeg, velSeg, scene.kcl, 0.05, ignoreList); + if (result != null) { + colResponse(posSeg, velSeg, result, ignoreList) + remainingT -= result.t; + if (remainingT > 0.01) { + velSeg = vec3.scale(vec3.create(), t.vel, remainingT); + } + } else { + vec3.add(posSeg, posSeg, velSeg); + remainingT = 0; + } + } + t.pos = posSeg; + + t.yvel = t.vel[1]; + } + + function draw(mvMatrix, pMatrix) { + var mat = mat4.translate(mat4.create(), mvMatrix, vec3.add(vec3.create(), t.pos, [0, 3, 0])); + + spritify(mat); + mat4.scale(mat, mat, [16, 16, 16]); + + scene.gameRes.items.koura_g.draw(mat, pMatrix); + } + + var spritify = function(mat, scale) { + var scale = (scale == null)?Math.sqrt(mat[0]*mat[0]+mat[1]*mat[1]+mat[2]*mat[2]):scale; + + mat[0]=scale; mat[1]=0; mat[2]=0; + mat[4]=0; mat[5]=scale; mat[6]=0; + mat[8]=0; mat[9]=0; mat[10]=scale; + } + + function colResponse(pos, pvel, dat, ignoreList) { + + var plane = dat.plane; + var colType = (plane.CollisionType>>8)&31; + vec3.add(pos, pos, vec3.scale(vec3.create(), pvel, dat.t)); + + var n = dat.normal; + vec3.normalize(n, n); + var gravS = Math.sqrt(vec3.dot(t.gravity, t.gravity)); + var angle = Math.acos(vec3.dot(vec3.scale(vec3.create(), t.gravity, -1/gravS), n)); + var adjustPos = true + + if (MKDS_COLTYPE.GROUP_WALL.indexOf(colType) != -1) { //wall + //shell reflection code - slide y vel across plane, bounce on xz + vec3.add(t.vel, vec3.scale(vec3.create(), n, -2*(vec3.dot(t.vel, n)/vec3.dot(n,n))), t.vel); + t.vel[1] = 0; + + var v = t.vel; + t.angle = Math.atan2(v[0], -v[2]); + + } else if (MKDS_COLTYPE.GROUP_ROAD.indexOf(colType) != -1) { + //sliding plane + var proj = vec3.dot(t.vel, n); + vec3.sub(t.vel, t.vel, vec3.scale(vec3.create(), n, proj)); + } else { + adjustPos = false; + ignoreList.push(plane); + } + + var rVelMag = Math.sqrt(vec3.dot(t.vel, t.vel)); + vec3.scale(t.vel, t.vel, t.speed/rVelMag); //force speed to shell speed for green shells. + + //vec3.add(pos, pos, vec3.scale(vec3.create(), n, minimumMove)); //move away from plane slightly + + if (adjustPos) { //move back from plane slightly + vec3.add(pos, pos, vec3.scale(vec3.create(), n, minimumMove)); + /* + var velMag = Math.sqrt(vec3.dot(pvel, pvel)); + if (velMag*dat.t > minimumMove) { + vec3.sub(pos, pos, vec3.scale(vec3.create(), pvel, minimumMove/velMag)); //move back slightly after moving + } else { + vec3.sub(pos, pos, vec3.scale(vec3.create(), pvel, dat.t)); //if we're already too close undo the movement. + } + */ + } + + } +} \ No newline at end of file diff --git a/code/entities/soundMaker.js b/code/entities/soundMaker.js new file mode 100644 index 0000000..5fac83a --- /dev/null +++ b/code/entities/soundMaker.js @@ -0,0 +1,77 @@ +// +// soundMaker.js +//-------------------- +// Provides env sound object, such as crowd for figure 8 +// by RHY3756547 +// + +//0008 + +window.ObjSoundMaker = function(obji, scene) { + var obji = obji; + + var t = this; + + t.pos = vec3.clone(obji.pos); + + t.soundProps = {}; + t.sndUpdate = sndUpdate; + t.requireRes = requireRes; + t.provideRes = provideRes; + t.update = update; + t.draw = draw; + + var mat = mat4.create(); + var frame = 0; + + var sound = null; + var sN = 0; + var threshold = 0.2; + var gain = 1; + switch (obji.ID) { + case 0x0008: + sN = 259; + gain = 2; + threshold = 0.2; + break; + } + + function draw(view, pMatrix) { + + } + + function update() { + } + + function sndUpdate(view) { + t.soundProps.pos = vec3.transformMat4([], t.pos, view); + t.soundProps.pos = [0, 0, Math.sqrt(vec3.dot(t.soundProps.pos, t.soundProps.pos))] + //if (t.soundProps.lastPos != null) t.soundProps.vel = vec3.sub([], t.soundProps.pos, t.soundProps.lastPos); + //else t.soundProps.vel = [0, 0, 0]; + //t.soundProps.lastPos = t.soundProps.pos; + + t.soundProps.refDistance = 1024/1024; + //t.soundProps.rolloffFactor = 1; + + var calcVol = (t.soundProps.refDistance / (t.soundProps.refDistance + t.soundProps.rolloffFactor * (t.soundProps.pos[2] - t.soundProps.refDistance))); + + if (calcVol>16)/100; + t.routePos = (obji.setting1&0xFFFF)%t.route.length; + t.nextNode = t.route[t.routePos]; + t.prevPos = t.pos; + t.elapsedTime = 0; + + var facingNormal = [0, 1, 0]; + var curNormal = [0, 1, 0]; + var floorNormal = [0, 1, 0]; + + function update(scene) { + //simple behaviour, just follow the path! piece of cake. + t.elapsedTime += t.routeSpeed; + t.pos = vec3.lerp([], t.prevPos, t.nextNode.pos, t.elapsedTime/t.nextNode.duration); + if (t.elapsedTime >= t.nextNode.duration) { + t.elapsedTime = 0; + t.prevPos = t.nextNode.pos; + t.routePos = (t.routePos+1)%t.route.length; + t.nextNode = t.route[t.routePos]; + } + + facingNormal = vec3.sub([], t.prevPos, t.nextNode.pos) + vec3.normalize(facingNormal, facingNormal); + + var rate = 0.025 + curNormal[0] += (facingNormal[0]-curNormal[0])*rate; + curNormal[1] += (facingNormal[1]-curNormal[1])*rate; + curNormal[2] += (facingNormal[2]-curNormal[2])*rate; + vec3.normalize(curNormal, curNormal); + + var spos = vec3.clone(t.pos); + spos[1] += 32; + var result = lsc.raycast(spos, [0, -100, 0], scene.kcl, 0.05, []); + if (result != null) { + floorNormal = result.normal; + } else { + floorNormal = [0,1,0]; + } + + } + + function draw(view, pMatrix) { + var mat = mat4.translate(mat4.create(), view, t.pos); + + mat4.scale(mat, mat, vec3.scale([], t.scale, 16)); + + mat4.mul(mat, mat, mat4.invert([], mat4.lookAt([], [0, 0, 0], curNormal, floorNormal))); + res.mdl[0].draw(mat, pMatrix); + } + + function requireRes() { //scene asks what resources to load + switch (obji.ID) { + case 0x019A: + return {mdl:[{nsbmd:"car_a.nsbmd"}]}; //one model, car + case 0x019C: + return {mdl:[{nsbmd:"truck_a.nsbmd"}]}; //one model, truck + case 0x0195: + return {mdl:[{nsbmd:"bus_a.nsbmd"}]}; //one model, bus + } + } + + function provideRes(r) { + res = r; //...and gives them to us. :) + } +} + +window.ObjCar = ObjTruck; +window.ObjBus = ObjTruck; \ No newline at end of file diff --git a/code/entities/water.js b/code/entities/water.js new file mode 100644 index 0000000..523e917 --- /dev/null +++ b/code/entities/water.js @@ -0,0 +1,86 @@ +// +// water.js +//-------------------- +// Provides multiple types of traffic. +// by RHY3756547 +// +// includes: +// render stuff idk +// + +window.ObjWater = function(obji, scene) { + var obji = obji; + var res = []; + + var t = this; + + t.pos = vec3.clone(obji.pos); + //t.angle = vec3.clone(obji.angle); + t.scale = vec3.clone(obji.scale); + + t.requireRes = requireRes; + t.provideRes = provideRes; + t.update = update; + t.draw = draw; + var frame = 0; + + function draw(view, pMatrix) { + if (nitroRender.flagShadow) return; + var waterM = mat4.create(); + + gl.enable(gl.STENCIL_TEST); + gl.stencilMask(0xFF); + + gl.stencilFunc(gl.ALWAYS, 1, 0xFF); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE); //when depth test passes for water lower layer, pixel is already drawn, do not cover it with the white overlay (set stencil bit) + + var height = (t.pos[1])+6.144+Math.sin(frame/150)*12.288 //0.106 + + mat4.translate(waterM, view, [Math.sin(frame/180)*96, height-3.072, Math.cos(frame/146)*96]) + nitroRender.setAlpha(0x0A/31); + res.mdl[0].drawPoly(mat4.scale([], waterM, [16, 16, 16]), pMatrix, 0, 0); //water + + if (res.mdl[1] != null) { + mat4.translate(waterM, view, [-Math.sin((frame+30)/180)*96, height-3, Math.cos((frame+100)/146)*96]) + nitroRender.setAlpha(0x02/31); + res.mdl[1].draw(mat4.scale([], waterM, [16, 16, 16]), pMatrix); //water white detail part. stencil should do nothing here, since it's in the same position as the above. + } + + gl.stencilFunc(gl.EQUAL, 0, 0xFF); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + + if (!obji.ID == 9) { + mat4.translate(waterM, view, [0, height, 0]) + nitroRender.setAlpha(0x10/31); + res.mdl[0].drawPoly(mat4.scale([], waterM, [16, 16, 16]), pMatrix, 0, 1); //white shore wash part, water is stencil masked out + } + + gl.disable(gl.STENCIL_TEST); + + nitroRender.setAlpha(1); + } + + function update() { + frame = (frame+1)%197100; //it's a big number but yolo... we have the technology... + } + + function requireRes() { //scene asks what resources to load + switch (obji.ID) { + case 0x0001: + return {mdl:[{nsbmd:"beach_waterC.nsbmd"}, {nsbmd:"beach_waterA.nsbmd"}]}; + case 0x0003: + return {mdl:[{nsbmd:"town_waterC.nsbmd"}, {nsbmd:"town_waterA.nsbmd"}]}; + case 0x0006: + return {mdl:[{nsbmd:"yoshi_waterC.nsbmd"}]}; + case 0x0009: + return {mdl:[{nsbmd:"hyudoro_waterC.nsbmd"}, {nsbmd:"hyudoro_waterA.nsbmd"}]}; + case 0x000C: + return {mdl:[{nsbmd:"mini_stage3_waterC.nsbmd"}, {nsbmd:"mini_stage3_waterA.nsbmd"}]}; + } + } + + function provideRes(r) { + res = r; //...and gives them to us. :) + } + +} \ No newline at end of file diff --git a/code/formats/.subl29.tmp b/code/formats/.subl29.tmp new file mode 100644 index 0000000..a406902 --- /dev/null +++ b/code/formats/.subl29.tmp @@ -0,0 +1,158 @@ +// +// nsbtx.js +//-------------------- +// Reads NSBTX files (or TEX0 sections) and provides canvases containing decoded texture data. +// by RHY3756547 +// +// includes: gl-matrix.js (glMatrix 2.0) +// /formats/nitro.js +// + +window.nsbtx = function(input, tex0, autogen) { + var texDataSize, texInfoOff, texOffset, compTexSize, compTexInfoOff, + compTexOffset, compTexInfoDataOff /*wtf*/, palSize, palInfoOff, + palOffset, mainOff + + var textureInfo, paletteInfo, palData, texData, colourBuffer + var thisObj = this; + + var bitDepths = [0, 8, 2, 4, 8, 2, 8, 16] + + if (input != null) { + load(input, tex0, autogen); + } + this.load = load; + this.readTexWithPal = readTexWithPal; + + this.scopeEval = function(code) {return eval(code)} //for debug purposes + + function load(input, tex0, autogen) { + var colourBuffer = new Uint32Array(4); + var view = new DataView(input); + var header = null; + var offset = 0; + if (!tex0) { //nitro 3d header + header = nitro.readHeader(view); + if (header.stamp != "BTX0") throw "NSBTX invalid. Expected BTX0, found "+header.stamp; + if (header.numSections > 1) throw "NSBTX invalid. Too many sections - should only have one."; + offset = header.sectionOffsets[0]; + } + + mainOff = offset; + + var stamp = readChar(view, offset+0x0)+readChar(view, offset+0x1)+readChar(view, offset+0x2)+readChar(view, offset+0x3); + if (stamp != "TEX0") throw "NSBTX invalid. Expected TEX0, found "+stamp; + var size = view.getUint32(offset+0x04, true); + var texDataSize = view.getUint16(offset+0x0C, true)<<8; + var texInfoOff = view.getUint16(offset+0x0E, true); + var texOffset = view.getUint16(offset+0x14, true); + + var compTexSize = view.getUint16(offset+0x1C, true)<<8; + var compTexInfoOff = view.getUint16(offset+0x1E, true); + var compTexOffset = view.getUint32(offset+0x24, true); + var compTexInfoDataOff = view.getUint32(offset+0x28, true); + + var palSize = view.getUint32(offset+0x30, true)<<3; + var palInfoOff = view.getUint32(offset+0x34, true); + var palOffset = view.getUint32(offset+0x38, true); + + //read palletes, then textures. + palData = input.slice(mainOff + palOffset, palSize); + texData = input.slice(mainOff + texOffset, texDataSize); + + paletteInfo = nitro.read3dInfo(view, palInfoOff, palInfoHandler); + textureInfo = nitro.read3dInfo(view, texInfoOff, texInfoHandler); + + /*if (f) { + console.log(textureInfo.objectData.length) + for (var i=0; i>((i%4)*2))&3) + if (i%4 == 3) databuf = texView.readUint8(++off); + } else if (bitDepths == 4) { + if (i%2 == 0) { + col = readPalColour(palView, palOff, databuf&15) + } else { + col = readPalColour(palView, palOff, databuf>>4) + databuf = texView.readUint8(++off); + } + } else if (bitDepths == 8) { + col = readPalColour(palView, palOff, texView.readUint8(off)) + off += 1; + } else if (bitDepths == 16) { + col = readPalColour(palView, palOff, texView.readUint16(off, true)) + off += 2; + } + data.data.set(col, i*4); + } + return canvas; + } + + function readPalColour(view, palOff, ind) { + var col = palView.getUint16(palOff+ind*2, true); + colourBuffer[0] = Math.round(((col&31)/31)*255) + colourBuffer[1] = Math.round((((col>>5)&31)/31)*255) + colourBuffer[2] = Math.round((((col>>10)&31)/31)*255) + colourBuffer[3] = Math.round((col>>15)*255) + } + + function palInfoHandler(view, offset) { + var palOffset = view.getUint16(offset, true)<<3; + var unknown = view.getUint16(offset+2, true); + return { + palOffset: palOffset, + nextoff: offset+4 + } + } + + function texInfoHandler(view, offset) { + var texOffset = view.getUint16(offset, true)<<3; + var flags = view.getUint16(offset+2, true); + var width2 = view.getUint8(offset+4, true); + var unknown = view.getUint8(offset+5, true); + var height2 = view.getUint8(offset+6, true); + var unknown2 = view.getUint8(offset+7, true); + return { + texOffset: texOffset, + pal: (flags>>13), + format: ((flags>>10)&7), + height: ((flags>>7)&7)<<3, + width: ((flags>>4)&7)<<3, + + nextoff: offset+8 + } + } + + function readChar(view, offset) { + return String.fromCharCode(view.getUint8(offset)); + } +} \ No newline at end of file diff --git a/code/formats/.subl509.tmp b/code/formats/.subl509.tmp new file mode 100644 index 0000000..a92148c --- /dev/null +++ b/code/formats/.subl509.tmp @@ -0,0 +1,158 @@ +// +// nsbtx.js +//-------------------- +// Reads NSBTX files (or TEX0 sections) and provides canvases containing decoded texture data. +// by RHY3756547 +// +// includes: gl-matrix.js (glMatrix 2.0) +// /formats/nitro.js +// + +window.nsbtx = function(input, tex0, autogen) { + var texDataSize, texInfoOff, texOffset, compTexSize, compTexInfoOff, + compTexOffset, compTexInfoDataOff /*wtf*/, palSize, palInfoOff, + palOffset, mainOff + + var textureInfo, paletteInfo, palData, texData, colourBuffer + var thisObj = this; + + var bitDepths = [0, 8, 2, 4, 8, 2, 8, 16] + + if (input != null) { + load(input, tex0, autogen); + } + this.load = load; + this.readTexWithPal = readTexWithPal; + + this.scopeEval = function(code) {return eval(code)} //for debug purposes + + function load(input, tex0, autogen) { + var colourBuffer = new Uint32Array(4); + var view = new DataView(input); + var header = null; + var offset = 0; + if (!tex0) { //nitro 3d header + header = nitro.readHeader(view); + if (header.stamp != "BTX0") throw "NSBTX invalid. Expected BTX0, found "+header.stamp; + if (header.numSections > 1) throw "NSBTX invalid. Too many sections - should only have one."; + offset = header.sectionOffsets[0]; + } + + mainOff = offset; + + var stamp = readChar(view, offset+0x0)+readChar(view, offset+0x1)+readChar(view, offset+0x2)+readChar(view, offset+0x3); + if (stamp != "TEX0") throw "NSBTX invalid. Expected TEX0, found "+stamp; + var size = view.getUint32(offset+0x04, true); + var texDataSize = view.getUint16(offset+0x0C, true)<<8; + var texInfoOff = view.getUint16(offset+0x0E, true); + var texOffset = view.getUint16(offset+0x14, true); + + var compTexSize = view.getUint16(offset+0x1C, true)<<8; + var compTexInfoOff = view.getUint16(offset+0x1E, true); + var compTexOffset = view.getUint32(offset+0x24, true); + var compTexInfoDataOff = view.getUint32(offset+0x28, true); + + var palSize = view.getUint32(offset+0x30, true)<<3; + var palInfoOff = view.getUint32(offset+0x34, true); + var palOffset = view.getUint32(offset+0x38, true); + + //read palletes, then textures. + palData = input.slice(mainOff + palOffset, palSize); + texData = input.slice(mainOff + texOffset, texDataSize); + + paletteInfo = nitro.read3dInfo(view, palInfoOff, palInfoHandler); + textureInfo = nitro.read3dInfo(view, texInfoOff, texInfoHandler); + + if (autogen) { + console.log(textureInfo.objectData.length) + for (var i=0; i>((i%4)*2))&3) + if (i%4 == 3) databuf = texView.readUint8(++off); + } else if (bitDepths == 4) { + if (i%2 == 0) { + col = readPalColour(palView, palOff, databuf&15) + } else { + col = readPalColour(palView, palOff, databuf>>4) + databuf = texView.readUint8(++off); + } + } else if (bitDepths == 8) { + col = readPalColour(palView, palOff, texView.readUint8(off)) + off += 1; + } else if (bitDepths == 16) { + col = readPalColour(palView, palOff, texView.readUint16(off, true)) + off += 2; + } + data.data.set(col, i*4); + } + return canvas; + } + + function readPalColour(view, palOff, ind) { + var col = palView.getUint16(palOff+ind*2, true); + colourBuffer[0] = Math.round(((col&31)/31)*255) + colourBuffer[1] = Math.round((((col>>5)&31)/31)*255) + colourBuffer[2] = Math.round((((col>>10)&31)/31)*255) + colourBuffer[3] = Math.round((col>>15)*255) + } + + function palInfoHandler(view, offset) { + var palOffset = view.getUint16(offset, true)<<3; + var unknown = view.getUint16(offset+2, true); + return { + palOffset: palOffset, + nextoff: offset+4 + } + } + + function texInfoHandler(view, offset) { + var texOffset = view.getUint16(offset, true)<<3; + var flags = view.getUint16(offset+2, true); + var width2 = view.getUint8(offset+4, true); + var unknown = view.getUint8(offset+5, true); + var height2 = view.getUint8(offset+6, true); + var unknown2 = view.getUint8(offset+7, true); + return { + texOffset: texOffset, + pal: (flags>>13), + format: ((flags>>10)&7), + height: ((flags>>7)&7)<<3, + width: ((flags>>4)&7)<<3, + + nextoff: offset+8 + } + } + + function readChar(view, offset) { + return String.fromCharCode(view.getUint8(offset)); + } +} \ No newline at end of file diff --git a/code/formats/.sublaf1.tmp b/code/formats/.sublaf1.tmp new file mode 100644 index 0000000..0969e34 --- /dev/null +++ b/code/formats/.sublaf1.tmp @@ -0,0 +1,158 @@ +// +// nsbtx.js +//-------------------- +// Reads NSBTX files (or TEX0 sections) and provides canvases containing decoded texture data. +// by RHY3756547 +// +// includes: gl-matrix.js (glMatrix 2.0) +// /formats/nitro.js +// + +window.nsbtx = function(input, tex0, autogen) { + var texDataSize, texInfoOff, texOffset, compTexSize, compTexInfoOff, + compTexOffset, compTexInfoDataOff /*wtf*/, palSize, palInfoOff, + palOffset, mainOff + + var textureInfo, paletteInfo, palData, texData, colourBuffer + var thisObj = this; + + var bitDepths = [0, 8, 2, 4, 8, 2, 8, 16] + + if (input != null) { + load(input, tex0, autogen); + } + this.load = load; + this.readTexWithPal = readTexWithPal; + + this.scopeEval = function(code) {return eval(code)} //for debug purposes + + function load(input, tex0, autogen) { + var colourBuffer = new Uint32Array(4); + var view = new DataView(input); + var header = null; + var offset = 0; + if (!tex0) { //nitro 3d header + header = nitro.readHeader(view); + if (header.stamp != "BTX0") throw "NSBTX invalid. Expected BTX0, found "+header.stamp; + if (header.numSections > 1) throw "NSBTX invalid. Too many sections - should only have one."; + offset = header.sectionOffsets[0]; + } + + mainOff = offset; + + var stamp = readChar(view, offset+0x0)+readChar(view, offset+0x1)+readChar(view, offset+0x2)+readChar(view, offset+0x3); + if (stamp != "TEX0") throw "NSBTX invalid. Expected TEX0, found "+stamp; + var size = view.getUint32(offset+0x04, true); + var texDataSize = view.getUint16(offset+0x0C, true)<<8; + var texInfoOff = view.getUint16(offset+0x0E, true); + var texOffset = view.getUint16(offset+0x14, true); + + var compTexSize = view.getUint16(offset+0x1C, true)<<8; + var compTexInfoOff = view.getUint16(offset+0x1E, true); + var compTexOffset = view.getUint32(offset+0x24, true); + var compTexInfoDataOff = view.getUint32(offset+0x28, true); + + var palSize = view.getUint32(offset+0x30, true)<<3; + var palInfoOff = view.getUint32(offset+0x34, true); + var palOffset = view.getUint32(offset+0x38, true); + + //read palletes, then textures. + palData = input.slice(mainOff + palOffset, palSize); + texData = input.slice(mainOff + texOffset, texDataSize); + + paletteInfo = nitro.read3dInfo(view, palInfoOff, palInfoHandler); + textureInfo = nitro.read3dInfo(view, texInfoOff, texInfoHandler); + + if (false) { + console.log(textureInfo.objectData.length) + for (var i=0; i>((i%4)*2))&3) + if (i%4 == 3) databuf = texView.readUint8(++off); + } else if (bitDepths == 4) { + if (i%2 == 0) { + col = readPalColour(palView, palOff, databuf&15) + } else { + col = readPalColour(palView, palOff, databuf>>4) + databuf = texView.readUint8(++off); + } + } else if (bitDepths == 8) { + col = readPalColour(palView, palOff, texView.readUint8(off)) + off += 1; + } else if (bitDepths == 16) { + col = readPalColour(palView, palOff, texView.readUint16(off, true)) + off += 2; + } + data.data.set(col, i*4); + } + return canvas; + } + + function readPalColour(view, palOff, ind) { + var col = palView.getUint16(palOff+ind*2, true); + colourBuffer[0] = Math.round(((col&31)/31)*255) + colourBuffer[1] = Math.round((((col>>5)&31)/31)*255) + colourBuffer[2] = Math.round((((col>>10)&31)/31)*255) + colourBuffer[3] = Math.round((col>>15)*255) + } + + function palInfoHandler(view, offset) { + var palOffset = view.getUint16(offset, true)<<3; + var unknown = view.getUint16(offset+2, true); + return { + palOffset: palOffset, + nextoff: offset+4 + } + } + + function texInfoHandler(view, offset) { + var texOffset = view.getUint16(offset, true)<<3; + var flags = view.getUint16(offset+2, true); + var width2 = view.getUint8(offset+4, true); + var unknown = view.getUint8(offset+5, true); + var height2 = view.getUint8(offset+6, true); + var unknown2 = view.getUint8(offset+7, true); + return { + texOffset: texOffset, + pal: (flags>>13), + format: ((flags>>10)&7), + height: ((flags>>7)&7)<<3, + width: ((flags>>4)&7)<<3, + + nextoff: offset+8 + } + } + + function readChar(view, offset) { + return String.fromCharCode(view.getUint8(offset)); + } +} \ No newline at end of file diff --git a/code/formats/kartoffsetdata.js b/code/formats/kartoffsetdata.js new file mode 100644 index 0000000..8fb0516 --- /dev/null +++ b/code/formats/kartoffsetdata.js @@ -0,0 +1,71 @@ +// +// kartoffsetdata.js +//-------------------- +// Provides functionality to read mario kart ds kart wheel and character model offsets. +// by RHY3756547 +// +// includes: gl-matrix.js (glMatrix 2.0) +// + +window.kartoffsetdata = function(input) { + + var thisObj = this; + + if (input != null) { + load(input); + } + this.load = load; + + function load(input) { + var view = new DataView(input); + var off = 0; + var karts = [] + for (var i=0; i<37; i++) { + var obj = {}; + obj.name = readString(view, off, 0x10); + off += 0x10; + obj.frontTireSize = view.getInt32(off, true)/4096; + off += 4; + + var wheels = []; + for (var j=0; j<4; j++) { + var pos = vec3.create(); + pos[0] = view.getInt32(off, true)/4096; + pos[1] = view.getInt32(off+4, true)/4096; + pos[2] = view.getInt32(off+8, true)/4096; + off += 12; + wheels.push(pos); + } + + var chars = []; + for (var j=0; j<13; j++) { + var pos = vec3.create(); + pos[0] = view.getInt32(off, true)/4096; + pos[1] = view.getInt32(off+4, true)/4096; + console.log("charPos: "+pos[1]); + pos[2] = view.getInt32(off+8, true)/4096; + off += 12; + chars.push(pos); + } + + obj.wheels = wheels; + obj.chars = chars; + + karts.push(obj); + } + thisObj.karts = karts; + } + + function readChar(view, offset) { + return String.fromCharCode(view.getUint8(offset)); + } + + function readString(view, offset, length) { + var str = ""; + for (var i=0; i maxx) maxx=vert[0]; + if (vert[2] < minz) minz=vert[2]; + if (vert[2] > maxz) maxz=vert[2]; + } + + console.log("minx: "+minx+" maxx: "+maxx+" minz: "+minz+" maxz: "+maxz) + + //var sfx = canvas.width/(maxx-minx); + //var sfy = canvas.height/(maxz-minz); + //offx = -((minx+maxx)/2); + //offz = -((minz+maxz)/2); + //sf = Math.min(sfx, sfy)*0.8; + octree = [] + + var rootNodes = ((~xMask >> coordShift) + 1) * ((~yMask >> coordShift) + 1) * ((~zMask >> coordShift) + 1); + + for (var i=0; i> coordShift) + 1); x++) { + for (var z=0; z<((~zMask >> coordShift) + 1); z++) { + ctx.strokeRect(topLeftVec[0]+size*x, topLeftVec[2]+size*z, size, size); + } + } + } + + function testDrawPlanes(planes) { + for (var i=1; i0 || (y&yMask)>0 || (z&zMask)>0) return []; //no collision + + var index = (x>>coordShift)|((y>>coordShift)<>coordShift)<>shift)&1)|(((y>>shift)&1)<<1)|(((z>>shift)&1)<<2); + return traverseOctree(node.items[index], x, y, z, shift-1); + } + + function decodeCube(baseoff, off, view) { + var data = view.getUint32(off, end); + var off2 = baseoff+(data&0x7FFFFFFF); + if (off2 >= view.byteLength) { + return { + leaf: true, + tris: [], + realTris: [] + } + } + if (data&0x80000000) { //is a leaf. + off2 += 2; + var tris = []; + var realTris = []; + while (true) { + var read = view.getUint16(off2, end); + if (read == 0) break; //zero terminated + tris.push(read); + realTris.push(planes[read]); + trisMapped += 1; + off2 += 2; + } + return { + leaf: true, + tris: tris, + realTris: realTris + } + } else { //contains 8 more cubes + var cubes = []; + var boff = off2; + for (var i=0; i<8; i++) { + cubes.push(decodeCube(boff, off2, view)); + off2 += 4; + } + return { + leaf: false, + items: cubes + } + } + } + + function Plane(view, offset) { + this.Len = readBigDec(view, offset, mkwiiMode); + this.Vertex1 = readVert(view.getUint16(offset+0x4, end), view); + this.Normal = readNormal(view.getUint16(offset+0x6, end), view); + this.NormalA = readNormal(view.getUint16(offset+0x8, end), view); + this.NormalB = readNormal(view.getUint16(offset+0xA, end), view); + this.NormalC = readNormal(view.getUint16(offset+0xC, end), view); + this.CollisionType = view.getUint16(offset+0xE, end); + + var crossA = vec3.cross(vec3.create(), this.NormalA, this.Normal); + var crossB = vec3.cross(vec3.create(), this.NormalB, this.Normal); + + this.Vertex2 = vec3.scaleAndAdd(vec3.create(), this.Vertex1, crossB, (this.Len/vec3.dot(crossB, this.NormalC))); + this.Vertex3 = vec3.scaleAndAdd(vec3.create(), this.Vertex1, crossA, (this.Len/vec3.dot(crossA, this.NormalC))); + } + + function readVert(num, view) { + var vec = vec3.create(); + var loc = vertexOffset+num*0xC; + vec[0] = readBigDec(view, loc, mkwiiMode); + vec[1] = readBigDec(view, loc+0x4, mkwiiMode); + vec[2] = readBigDec(view, loc+0x8, mkwiiMode); + return vec; + } + + function readNormal(num, view) { + var mkwii = mkwiiMode; + var vec = vec3.create(); + if (mkwii) { + var loc = normalOffset+num*0xC; + vec[0] = view.getFloat32(loc); + vec[1] = view.getFloat32(loc+0x4); + vec[2] = view.getFloat32(loc+0x8); + } else { + var loc = normalOffset+num*0x6; + vec[0] = view.getInt16(loc, end)/4096; //fixed point + vec[1] = view.getInt16(loc+0x2, end)/4096; + vec[2] = view.getInt16(loc+0x4, end)/4096; + } + return vec; + } +} \ No newline at end of file diff --git a/code/formats/lz77.js b/code/formats/lz77.js new file mode 100644 index 0000000..b6e5861 --- /dev/null +++ b/code/formats/lz77.js @@ -0,0 +1,41 @@ +// +// lz77.js +//-------------------- +// Reads and decompresses lz77 (mode 0x10 only) files. In future may be able to recompress. +// by RHY3756547 +// + +window.lz77 = new (function() { + this.decompress = function(buffer) { + var view = new DataView(buffer); + var compType = view.getUint8(0); + var size = view.getUint32(0, true)>>8; + + var targ = new ArrayBuffer(size); + var targA = new Uint8Array(targ); + + var off = 4; + var dOff = 0; + var eof = buffer.byteLength; + while (off=0; j--) { + if (off>=eof) break; + if ((flag>>j)&1) { //1=compressed, 2=raw byte + var dat = view.getUint16(off); + off += 2; + var cOff = (dOff-(dat&4095))-1; + var len = (dat>>12)+3; + + for (var k=0; k>1)&3; + k.driftLanded = driftFlags&8; + + k.animMode = animNames[view.getUint8(off+0x56)]; + + k.controller.binput = view.getUint8(off+0x57); + + k.controller.turn = view.getFloat32(off+0x58, true); + k.controller.airTurn = view.getFloat32(off+0x5C, true); + + } catch (err) { + console.err("Kart restore failure:"+err.message); + //failed to restore kart data. may wish to disconnect on this, but it's probably better to not react. + } + } + + function saveVec3(view, off, vec) { + var vec = vec; + if (vec == null) vec = [NaN, NaN, NaN]; + view.setFloat32(off, vec[0], true); + view.setFloat32(off+4, vec[1], true); + view.setFloat32(off+8, vec[2], true); + } + + function readVec3(view, off, vec) { + var first = view.getFloat32(off, true); + if (isNaN(first)) return null; + vec = vec3.create(); + vec[0] = first; + vec[1] = view.getFloat32(off+4, true); + vec[2] = view.getFloat32(off+8, true); + return vec; + } +} \ No newline at end of file diff --git a/code/formats/nftr.js b/code/formats/nftr.js new file mode 100644 index 0000000..e06fb99 --- /dev/null +++ b/code/formats/nftr.js @@ -0,0 +1,37 @@ +// +// nftr.js +//-------------------- +// Reads NFTR fonts and compiles them to a texture and character lookup table. Texture is replaceable. +// by RHY3756547 +// +// includes: gl-matrix.js (glMatrix 2.0) +// /formats/nitro.js +// + +window.nftr = function(input) { + + var mainOff; + var mainObj = this; + + if (input != null) { + load(input); + } + this.load = load; + + + function load(input) { + var view = new DataView(input); + var header = null; + var offset = 0; + var tex; + + //nitro 3d header + header = nitro.readHeader(view); + //debugger; + if (header.stamp != "RTFN") throw "NFTR invalid. Expected RTFN, found "+header.stamp; + offset = header.sectionOffsets[0]; + //end nitro + + mainOff = offset; + } +} \ No newline at end of file diff --git a/code/formats/nitro.js b/code/formats/nitro.js new file mode 100644 index 0000000..1a14f41 --- /dev/null +++ b/code/formats/nitro.js @@ -0,0 +1,85 @@ +// +// nitro.js +//-------------------- +// General purpose functions for nitro formats, eg. NSBTX or NSBMD +// by RHY3756547 +// +// includes: gl-matrix.js (glMatrix 2.0) +// + +window.nitro = new function() { + this.readHeader = function(view) { //input: DataView with base offset at header position + var stamp = readChar(view, 0x0)+readChar(view, 0x1)+readChar(view, 0x2)+readChar(view, 0x3); + var unknown1 = view.getUint32(0x4, true); + var filesize = view.getUint32(0x8, true); + var headsize = view.getUint16(0xC, true); + var numSections = view.getUint16(0xE, true); + var sectionOffsets = []; + for (var i=0; i>5)&31, (dat>>10)&31]; + return col; + } + + function readChar(view, offset) { + return String.fromCharCode(view.getUint8(offset)); + } + + if (input != null) { + if (typeof input == "string") { + var xml = new XMLHttpRequest(); + xml.responseType = "arraybuffer"; + xml.open("GET", input, true); + xml.onload = function() { + load(xml.response); + } + xml.send(); + } else { + load(input, mkwii); + } + } + +} \ No newline at end of file diff --git a/code/formats/nsbca.js b/code/formats/nsbca.js new file mode 100644 index 0000000..3174932 --- /dev/null +++ b/code/formats/nsbca.js @@ -0,0 +1,246 @@ +// +// nsbca.js +//-------------------- +// Reads NSBCA files (bone animations) for use in combination with an NSBMD (model) file +// by RHY3756547 +// +// includes: gl-matrix.js (glMatrix 2.0) +// /formats/nitro.js +// + +// most investigation done by florian for the mkds course modifier. +// I've tried to keep things much simpler than they were in his code. + +window.nsbca = function(input) { + + var mainOff; + var animData; + var speeds = [1.0, 0.5, 1/3]; + var mainObj = this; + + if (input != null) { + load(input); + } + this.load = load; + + function load(input) { + var view = new DataView(input); + var header = null; + var offset = 0; + var tex; + + //nitro 3d header + header = nitro.readHeader(view); + if (header.stamp != "BCA0") throw "NSBCA invalid. Expected BCA0, found "+header.stamp; + if (header.numSections > 1) throw "NSBCA invalid. Too many sections - should have 1 maximum."; + offset = header.sectionOffsets[0]; + //end nitro + + mainOff = offset; + + var stamp = readChar(view, offset+0x0)+readChar(view, offset+0x1)+readChar(view, offset+0x2)+readChar(view, offset+0x3); + if (stamp != "JNT0") throw "NSBCA invalid. Expected JNT0, found "+stamp; + + animData = nitro.read3dInfo(view, mainOff+8, animInfoHandler); + mainObj.animData = animData; + } + + function animInfoHandler(view, off, base) { + var offset = mainOff + view.getUint32(off, true); + var obj = {nextoff: off + 4} + readAnim(view, offset, obj); + return obj; + } + + function readAnim(view, off, obj) { + obj.baseOff = off; + obj.stamp = readChar(view, off+0x0)+readChar(view, off+0x2)+readChar(view, off+0x3); + obj.frames = view.getUint16(off+0x4, true); + obj.numObj = view.getUint16(off+0x6, true); + obj.unknown = view.getUint32(off+0x8, true); //NOTE: this may be a flag. used later to specify extra frames if not = 3 + obj.off1 = view.getUint32(off+0xC, true); + obj.off2 = view.getUint32(off+0x10, true); //offset to rotation data + off += 0x14; + var transforms = []; + for (var i=0; i>1) & 1)) { //T: translation + var translate = [[], [], []]; //store translations in x,y,z arrays + var tlExtra = []; + + for (var i=0; i<3; i++) { //iterate over x y z (for translation) + var f = (flag>>(3+i))&1; + if (f) { //one value + translate[i].push(view.getInt32(off, true)/4096); + off += 4; + } else { //credit to florian for cracking this. + var inf = {}; + inf.startFrame = view.getUint16(off, true) + var dat = view.getUint16(off+2, true) + inf.endFrame = dat&0x0FFF; + inf.halfSize = ((dat>>12)&3); + inf.speed = speeds[((dat>>14)&3)]; + inf.off = view.getUint32(off+4, true); + + var extra = (obj.unknown != 3)?0:(obj.frames-inf.endFrame); + var length = Math.floor((obj.frames+extra)*inf.speed); + var w = (inf.halfSize)?2:4; + + var off2 = obj.baseOff+inf.off; + for (var j=0; j>6) & 1)) { //R: rotation, which is both fun and exciting. + + var rotate = []; + var rotExtra; + + var f = (flag>>8)&1; + if (f) { //one value + rotate.push(readRotation(view, off, obj)); + off += 4; + } else { //credit to florian for cracking this. + var inf = {}; + inf.startFrame = view.getUint16(off, true) + var dat = view.getUint16(off+2, true) //low 12 bits are end frame, high 4 are size flag and speed + inf.endFrame = dat&0x0FFF; + inf.halfSize = ((dat>>12)&3); //not used by rotation? + inf.speed = speeds[((dat>>14)&3)]; + inf.off = view.getUint32(off+4, true); + var extra = (obj.unknown != 3)?0:(obj.frames-inf.endFrame); + //florian's rotate code seems to ignore this extra value. I'll need more examples of nsbca to test this more thoroughly. + var length = Math.floor((obj.frames+extra)*inf.speed); + + var off2 = obj.baseOff+inf.off; + try { + for (var j=0; j>9) & 1)) { //S: scale + var scale = [[], [], []]; //store scales in x,y,z arrays + var scExtra = []; + + for (var i=0; i<3; i++) { //iterate over x y z (for scale) + var f = (flag>>(11+i))&1; + if (f) { //one value + scale[i].push({ + s1: view.getInt32(off, true)/4096, + s2: view.getInt32(off, true)/4096 + }); + off += 8; + } else { //credit to florian for cracking this. + var inf = {}; + inf.startFrame = view.getUint16(off, true) + var dat = view.getUint16(off+2, true) + inf.endFrame = dat&0x0FFF; + inf.halfSize = ((dat>>12)&3); + inf.speed = speeds[((dat>>14)&3)]; + inf.off = view.getUint32(off+4, true); + + var extra = (obj.unknown != 3)?0:(obj.frames-inf.endFrame); + var length = Math.ceil((obj.frames+extra)*inf.speed); + var w = ((inf.halfSize)?2:4); + + var off2 = obj.baseOff+inf.off; + for (var j=0; j>15); + + if (mode) { //rotation is pivot + var off2 = obj.baseOff+obj.off1+ind*6; //jump to rotation data + return { + pivot: true, + param: view.getUint16(off2, true), + a: view.getInt16(off2+2, true)/4096, + b: view.getInt16(off2+4, true)/4096 + }; + } else { + var off2 = obj.baseOff+obj.off2+ind*10; //jump to rotation data + var d1 = view.getInt16(off2, true); + var d2 = view.getInt16(off2+2, true); + var d3 = view.getInt16(off2+4, true); + var d4 = view.getInt16(off2+6, true); + var d5 = view.getInt16(off2+8, true); + + var i6 = ((d5&7)<<12) | ((d1&7)<<9) | ((d2&7)<<6) | ((d3&7)<<3) | ((d4&7)); + if (i6&4096) i6 = (-8192)+i6; + + var v1 = [d1>>3, d2>>3, d3>>3] + var v2 = [d4>>3, d5>>3, i6] + + vec3.scale(v1, v1, 1/4096); + vec3.scale(v2, v2, 1/4096); + var v3 = vec3.cross([], v1, v2) + + var mat = [ + v1[0], v1[1], v1[2], + v2[0], v2[1], v2[2], + v3[0], v3[1], v3[2] + ] + + return { + pivot: false, + mat: mat + }; + } + } + + function readChar(view, offset) { + return String.fromCharCode(view.getUint8(offset)); + } +} \ No newline at end of file diff --git a/code/formats/nsbmd.js b/code/formats/nsbmd.js new file mode 100644 index 0000000..b266e85 --- /dev/null +++ b/code/formats/nsbmd.js @@ -0,0 +1,411 @@ +// +// nsbmd.js +//-------------------- +// Reads NSBMD models and any texture data within them. +// by RHY3756547 +// +// includes: gl-matrix.js (glMatrix 2.0) +// /formats/nitro.js +// /formats/nsbtx.js +// + +window.nsbmd = function(input) { + + var mainOff, modelData, texPalOff, materials; + var mainObj = this; + + if (input != null) { + load(input); + } + this.load = load; + + + function load(input) { + mainObj.hasBillboards = false; + var view = new DataView(input); + var header = null; + var offset = 0; + var tex; + + //nitro 3d header + header = nitro.readHeader(view); + if (header.stamp != "BMD0") throw "NSBMD invalid. Expected BMD0, found "+header.stamp; + if (header.numSections > 2) throw "NSBMD invalid. Too many sections - should have 2 maximum."; + if (header.numSections == 2) tex = new nsbtx(input.slice(header.sectionOffsets[1]), true, true); + offset = header.sectionOffsets[0]; + //end nitro + + mainOff = offset; + + var stamp = readChar(view, offset+0x0)+readChar(view, offset+0x1)+readChar(view, offset+0x2)+readChar(view, offset+0x3); + if (stamp != "MDL0") throw "NSBMD invalid. Expected MDL0, found "+stamp; + + mainObj.tex = tex; + + modelData = nitro.read3dInfo(view, mainOff+8, modelInfoHandler); + mainObj.modelData = modelData; + } + + function modelInfoHandler(view, offset) { + var mdlOff = view.getUint32(offset, true); + + var off = mainOff+mdlOff; + var obj = readModelData(view, off); + obj.nextoff = offset+4; + + return obj; + } + + function readModelData(view, offset) { + var head = {} + head.blockSize = view.getUint32(offset, true); + head.bonesOffset = offset+view.getUint32(offset+4, true); + head.materialsOffset = offset+view.getUint32(offset+8, true); + head.polyStartOffset = offset+view.getUint32(offset+0xC, true); + head.polyEndOffset = offset+view.getUint32(offset+0x10, true); + + head.numObjects = view.getUint8(offset+0x17); + head.numMaterials = view.getUint8(offset+0x18); + head.numPolys = view.getUint8(offset+0x19); + head.maxStack = view.getUint8(offset+0x1A); + + head.scale = view.getInt32(offset+0x1C, true)/4096; + + head.numVerts = view.getUint16(offset+0x24, true); + head.numSurfaces = view.getUint16(offset+0x26, true); + head.numTriangles = view.getUint16(offset+0x28, true); + head.numQuads = view.getUint16(offset+0x2A, true); + + head.bboxX = view.getInt16(offset+0x2C, true)/4096; + head.bboxY = view.getInt16(offset+0x2E, true)/4096; + head.bboxZ = view.getInt16(offset+0x30, true)/4096; + head.bboxWidth = view.getInt16(offset+0x32, true)/4096; + head.bboxHeight = view.getInt16(offset+0x34, true)/4096; + head.bboxDepth = view.getInt16(offset+0x36, true)/4096; + //head.runtimeData = view.getUint64(offset+0x38, true); + texPalOff = head.materialsOffset; //leak into local scope so it can be used by tex and pal bindings + + var objects = nitro.read3dInfo(view, offset+0x40, objInfoHandler); + var polys = nitro.read3dInfo(view, head.polyStartOffset, polyInfoHandler); + + materials = nitro.read3dInfo(view, head.materialsOffset+4, matInfoHandler); + + var tex = nitro.read3dInfo(view, head.materialsOffset+view.getUint16(head.materialsOffset, true), texInfoHandler); + var palt = nitro.read3dInfo(view, head.materialsOffset+view.getUint16(head.materialsOffset+2, true), palInfoHandler); + + var commands = parseBones(head.bonesOffset, view, polys, materials, objects, head.maxStack); + + return {head: head, objects: objects, polys: polys, materials: materials, tex:tex, palt:palt, commands:commands} + } + + function parseBones(offset, view, polys, materials, objects, maxStack) { + var last; + var commands = []; + + var freeStack = maxStack; + var forceID=null; + var lastMat = null; + + while (offset 10) debugger; + break; + case 3: //stack id for poly (wit) + forceID = view.getUint8(offset++); + console.log("stackid is "+forceID); + case 0: + break; + case 5: + //i don't... what?? + //holy shp! + var poly = view.getUint8(offset++); + polys.objectData[poly].stackID = (stackID == null)?(commands[commands.length-1].forceID):forceID; + polys.objectData[poly].mat = lastMat; + + break; + case 7: + //sets object to be billboard + var obj = view.getUint8(offset++); + objects.objectData[obj].billboardMode = 1; + mainObj.hasBillboards = true; + break; + case 8: + //sets object to be billboard around only y axis. (xz remain unchanged) + var obj = view.getUint8(offset++); + objects.objectData[obj].billboardMode = 2; + mainObj.hasBillboards = true; + break; + case 0x0b: + break; //begin, not quite sure what of. doesn't seem to change anything + case 0x2b: + break; //end + default: + console.log("bone transform unknown: "+last); + break; + } + } + //if (window.throwWhatever) debugger; + return commands; + } + + function matInfoHandler(view, off, base) { + var offset = texPalOff + view.getUint32(off, true); + + var rel = 0; + /*while (rel < 40) { + var flags = view.getUint16(offset+rel, true); + if ((flags&15)==15) console.log("rel at "+rel); + rel += 2; + }*/ + + var polyAttrib = view.getUint16(offset+12, true); + console.log(polyAttrib); + + var flags = view.getUint16(offset+22, true); //other info in here is specular data etc. + + //scale starts at 44; + + var mat; + offset += 44; + switch ((flags>>14) & 0x03) { //texture scaling mode + case 0: + mat = mat3.create(); //no scale + break; + case 1: + mat = mat3.create(); + mat3.scale(mat, mat, [view.getInt32(offset, true)/4096, view.getInt32(offset+4, true)/4096]); + //mat3.translate(mat, mat, [-anim.translateS[(texFrame>>anim.frameStep.translateS)%anim.translateS.length], anim.translateT[(texFrame>>anim.frameStep.translateT)%anim.translateT.length]]) //for some mystery reason I need to negate the S translation + + break; + case 2: + case 3: + mat = mat3.create(); //custom tex mat + alert("custom"); + for (var i=0; i<16; i++) { + mat[i] = view.getInt32(offset, true)/4096; + offset += 4; + } + } + + var cullMode = ((polyAttrib>>6)&3); + + var alpha = ((polyAttrib>>16)&31)/31; + if (alpha == 0) alpha = 1; + + return { + height: 8 << ((flags>>7)&7), + width: 8 << ((flags>>4)&7), + repeatX: flags&1, + repeatY: (flags>>1)&1, + flipX: (flags>>2)&1, + flipY: (flags>>3)&1, + texMat: mat, + alpha: alpha, + cullMode: cullMode, + nextoff: off + 4 + } + } + + function texInfoHandler(view, off, base, ind) { + var oDat = texPalOff+view.getUint16(off, true); //contains offset to array of materials to bind to + var num = view.getUint8(off+2, true); + var mats = []; + for (var i=0; i>4)&15; + neg = (flag>>8)&15; + A = view.getInt16(offset+0x4, true)/4096; + B = view.getInt16(offset+0x6, true)/4096; + + pivot[mode] = (neg&1)?-1:1; + var horiz = mode%3; + var vert = Math.floor(mode/3) + var left = (horiz==0)?1:0; var top = ((vert==0)?1:0)*3; + var right = (horiz==2)?1:2; var btm = ((vert==2)?1:2)*3; + pivot[left+top] = A; + pivot[right+top] = B; + pivot[left+btm] = (neg&2)?-B:B; + pivot[right+btm] = (neg&4)?-A:A; + + offset += 4; + } else { + pivot = mat3.create() + } + var scale = vec3.create(); + if (!(flag&4)) { + scale[0] = view.getInt32(offset+0x4, true)/4096; + scale[1] = view.getInt32(offset+0x8, true)/4096; + scale[2] = view.getInt32(offset+0xC, true)/4096; + offset += 0xC; + } else { + scale[0] = 1; + scale[1] = 1; + scale[2] = 1; + } + if ((!(flag&8)) && (!(flag&2))) { //rotate matrix, replaces pivot + pivot[0] = rotTerm1; + pivot[1] = view.getInt16(offset+0x4, true)/4096; + pivot[2] = view.getInt16(offset+0x6, true)/4096; + pivot[3] = view.getInt16(offset+0x8, true)/4096; + pivot[4] = view.getInt16(offset+0xA, true)/4096; + pivot[5] = view.getInt16(offset+0xC, true)/4096; + pivot[6] = view.getInt16(offset+0xE, true)/4096; + pivot[7] = view.getInt16(offset+0x10, true)/4096; + pivot[8] = view.getInt16(offset+0x12, true)/4096; + offset += 16; + } + var mat = mat4.create(); + mat4.translate(mat, mat, translate); + mat4.multiply(mat, mat, mat4FromMat3(pivot)); + mat4.scale(mat, mat, scale); + return { + translate: translate, + pivot: pivot, + + pA: A, + pB: B, + pMode: mode, + pNeg: neg, + + scale: scale, + flag: flag, + mat: mat, + billboardMode: 0, + nextoff: off + 4 + } + } + + function mat4FromMat3(mat) { + dest = mat4.create(); + + dest[0] = mat[0]; + dest[1] = mat[1]; + dest[2] = mat[2]; + dest[3] = 0; + + dest[4] = mat[3]; + dest[5] = mat[4]; + dest[6] = mat[5]; + dest[7] = 0; + + dest[8] = mat[6]; + dest[9] = mat[7]; + dest[10] = mat[8]; + dest[11] = 0; + + dest[12] = 0; + dest[13] = 0; + dest[14] = 0; + dest[15] = 1; + + return dest; + } + + function readChar(view, offset) { + return String.fromCharCode(view.getUint8(offset)); + } +} \ No newline at end of file diff --git a/code/formats/nsbta.js b/code/formats/nsbta.js new file mode 100644 index 0000000..d9ab0e0 --- /dev/null +++ b/code/formats/nsbta.js @@ -0,0 +1,142 @@ +// +// nsbta.js +//-------------------- +// Reads NSBTA files (texture uv animation via uv transform matrices within a polygon) for use in combination with an NSBMD (model) file +// by RHY3756547 +// +// includes: gl-matrix.js (glMatrix 2.0) +// /formats/nitro.js +// + +// man oh man if only there were some documentation on this that weren't shoddily written code in mkds course modifier +// well i guess we can find out how the format works +// together :') + +window.nsbta = function(input) { + + var mainOff; + var animData; + var mainObj = this; + var prop = [ + "scaleS", + "scaleT", + "rotation", + "translateS", + "translateT" + ] + + if (input != null) { + load(input); + } + this.load = load; + + + function load(input) { + var view = new DataView(input); + var header = null; + var offset = 0; + var tex; + + //nitro 3d header + header = nitro.readHeader(view); + if (header.stamp != "BTA0") throw "NSBTA invalid. Expected BTA0, found "+header.stamp; + if (header.numSections > 1) throw "NSBTA invalid. Too many sections - should have 1 maximum."; + offset = header.sectionOffsets[0]; + //end nitro + + mainOff = offset; + + var stamp = readChar(view, offset+0x0)+readChar(view, offset+0x1)+readChar(view, offset+0x2)+readChar(view, offset+0x3); + if (stamp != "SRT0") throw "NSBTA invalid. Expected SRT0, found "+stamp; + + animData = nitro.read3dInfo(view, mainOff+8, animInfoHandler); + mainObj.animData = animData; + } + + function animInfoHandler(view, offset) { + var animOff = view.getUint32(offset, true); + + var off = mainOff+animOff; + var obj = readAnimData(view, off); + obj.nextoff = offset+4; + + return obj; + } + + function readAnimData(view, offset) { + var stamp = readChar(view, offset+0x0)+readChar(view, offset+0x1)+readChar(view, offset+0x2)+readChar(view, offset+0x3); //should be M_AT, where _ is a 0 character + var unknown1 = view.getUint16(offset+4, true); + var unknown2 = view.getUint8(offset+6, false); + var unknown3 = view.getUint8(offset+7, false); + var data = nitro.read3dInfo(view, offset+8, matInfoHandler); + return {data: data, nextoff: data.nextoff}; + } + + function matInfoHandler(view, offset, base) { + // there doesn't seem to be any documentation on this so I'm going to take the first step and maybe explain a few things here: + // each material has 5 sets of 16 bit values of the following type: + // + // frames: determines the number of frames worth of transforms of this type are stored + // flags: if >4096 then multiple frames are used instead of inline data. not much else is known + // offset/data: depending on previous flag, either points to an array of data or provides the data for the sole frame. relative to base of this 3dinfoobject + // data2: used for rotation matrix (second value) + // + // order is as follows: + // scaleS, scaleT, rotation, translateS, translateT (all values are signed fixed point 1.3.12) + // + // note: rotation external data has two 16 bit integers instead of one per frame. + // + // also!! rotation matrices work as follows: + // + // | B A | + // | -A B | + // + // kind of like nsbmd pivot + + var obj = {} + obj.flags = []; //for debug + obj.frames = []; + obj.frameStep = {}; + + for (var i=0; i<5; i++) { + + obj[prop[i]] = []; + var frames = view.getUint16(offset, true); + var flags = view.getUint16(offset+2, true); + var value = view.getUint16(offset+4, true); + var data2 = view.getInt16(offset+6, true)/4096; + + //flags research so far: + //bit 13 (8196) - set if inline single frame data, unset if multiple frame data at offset + //bit 14-15 - framestep, aka what to shift frame counters by (eg for half framerate this would be 1, frame>>1, essentially dividing the frame speed by 2.) + + obj.frameStep[prop[i]] = (flags>>14); + obj.flags[i] = flags; + obj.frames[i] = frames; + + if (flags & 8192) { + if (value & 32768) value = 65536-value; //convert to int + obj[prop[i]].push(value/4096); + if (i == 2) obj[prop[i]].push(data2); + } else { //data is found at offset + frames = frames>>obj.frameStep[prop[i]]; + //frames -= 1; + var off = base + value-8; + for (var j=0; j 1) throw "NSBTP invalid. Too many sections - should have 1 maximum."; + offset = header.sectionOffsets[0]; + //end nitro + + mainOff = offset; + + var stamp = readChar(view, offset+0x0)+readChar(view, offset+0x1)+readChar(view, offset+0x2)+readChar(view, offset+0x3); + if (stamp != "PAT0") throw "NSBTP invalid. Expected PAT0, found "+stamp; + + animData = nitro.read3dInfo(view, mainOff+8, animInfoHandler); + debugger; + mainObj.animData = animData; + } + + function animInfoHandler(view, offset) { + var animOff = view.getUint32(offset, true); + + var off = mainOff+animOff; + var obj = readAnimData(view, off); + obj.nextoff = offset+4; + + return obj; + } + + function readAnimData(view, offset) { + matOff = offset; + var stamp = readChar(view, offset+0x0)+readChar(view, offset+0x1)+readChar(view, offset+0x2)+readChar(view, offset+0x3); //should be M_PT, where _ is a 0 character + + offset += 4; + //b400 0303 4400 7400 - countdown (3..2..1.. then start is another model, duration 180 frames, 3 frames of anim) + //1400 0404 4800 8800 - kuribo (4 frames, shorter animation duration) + //1e00 0202 4000 6000 - pinball stage (2 frames) + //0200 0202 4000 6000 - fish, cow and crab (duration and total 2 frames, unusually short animation) + //0d00 0404 5000 9000 - bat (duration 13, 6 frames, uneven pacing) + + //16bit duration (60fps frames, total) + //8bit tex start + //8bit pal start + //16bit unknown (flags? kuribo repeats by playing backwards) + //16bit unknown + + //example data, for 3 mat 3 pal data + //var tinfo = texInfoHandler(view, offset+4); + //8 bytes here? looks like texinfo + + var duration = view.getUint16(offset, true); + var tframes = view.getUint8(offset+2); + var pframes = view.getUint8(offset+3); + var unknown = view.getUint16(offset+4, true); + var unknown2 = view.getUint16(offset+6, true); + + //...then another nitro + var data = nitro.read3dInfo(view, offset+8, matInfoHandler); + + return {data: data, nextoff: data.nextoff, tframes:tframes, pframes:pframes, unknown:unknown, unknown2:unknown2, duration:duration}; + } + + function matInfoHandler(view, offset, base) { + var obj = {} + obj.frames = []; + + // in here... + // 16bit frames + // 16bit maybe material number (probably? mostly 0) to replace + // 16bit unknown (flags? 0x4400 count, 0x1101 waluigi, 0x3303 goomba, 0x0010 fish) + // 16bit offset from M_PT (always 0x38) + + //at offset (frame of these) + // 16bit happenAt + // 8bit tex + // 8bit pal + + //then (frame of these) + // 16char texname + //then (frame of these) + // 16char palname + + var frames = view.getUint16(offset, true); + obj.matinfo = view.getUint16(offset+2, true); + obj.flags = view.getUint16(offset+4, true); + var offset2 = view.getUint16(offset+6, true); + offset += 8; + obj.nextoff = offset; + + offset = matOff + offset2; + //info and timing for each frame + for (var i=0; i 1) throw "NSBTX invalid. Too many sections - should only have one."; + offset = header.sectionOffsets[0]; + } + + mainOff = offset; + + var stamp = readChar(view, offset+0x0)+readChar(view, offset+0x1)+readChar(view, offset+0x2)+readChar(view, offset+0x3); + if (stamp != "TEX0") throw "NSBTX invalid. Expected TEX0, found "+stamp; + var size = view.getUint32(offset+0x04, true); + texDataSize = view.getUint16(offset+0x0C, true)<<3; + texInfoOff = view.getUint16(offset+0x0E, true); + texOffset = view.getUint16(offset+0x14, true); + + compTexSize = view.getUint16(offset+0x1C, true)<<3; + compTexInfoOff = view.getUint16(offset+0x1E, true); + compTexOffset = view.getUint32(offset+0x24, true); + compTexInfoDataOff = view.getUint32(offset+0x28, true); + + palSize = view.getUint32(offset+0x30, true)<<3; + palInfoOff = view.getUint32(offset+0x34, true); + palOffset = view.getUint32(offset+0x38, true); + + //read palletes, then textures. + var po = mainOff + palOffset; + palData = input.slice(po, po+palSize); + + var to = mainOff + texOffset; + texData = input.slice(to, to+texDataSize); + + var co = mainOff + compTexOffset; + compData = input.slice(co, co+compTexSize); //pixel information for compression. 2bpp, 16 pixels, so per 4x4 block takes up 4 bytes + + var cio = mainOff + compTexInfoDataOff; + compInfoData = input.slice(cio, cio+compTexSize/2); //each 4x4 block has a 16bit information uint. 2 bytes per block, thus half the size of above. + + + paletteInfo = nitro.read3dInfo(view, mainOff + palInfoOff, palInfoHandler); + textureInfo = nitro.read3dInfo(view, mainOff + texInfoOff, texInfoHandler); + + thisObj.paletteInfo = paletteInfo; + thisObj.textureInfo = textureInfo; + } + + function readTexWithPal(textureId, palId) { + var tex = textureInfo.objectData[textureId]; + var pal = paletteInfo.objectData[palId]; + + var format = tex.format; + var trans = tex.pal0trans; + + if (format == 5) return readCompressedTex(tex, pal); //compressed 4x4 texture, different processing entirely + + var off = tex.texOffset; + var palView = new DataView(palData); + var texView = new DataView(texData); + var palOff = pal.palOffset; + + var canvas = document.createElement("canvas"); + canvas.width = tex.width; + canvas.height = tex.height; + var ctx = canvas.getContext("2d"); + var img = ctx.getImageData(0, 0, tex.width, tex.height); + + var total = tex.width*tex.height; + var databuf; + for (var i=0; i>5)*(255/7); + + } else if (format == 2) { //2 bit pal + if (i%4 == 0) databuf = texView.getUint8(off++); + col = readPalColour(palView, palOff, (databuf>>((i%4)*2))&3, trans) + + } else if (format == 3) { //4 bit pal + if (i%2 == 0) { + databuf = texView.getUint8(off++); + col = readPalColour(palView, palOff, databuf&15, trans) + } else { + col = readPalColour(palView, palOff, databuf>>4, trans) + } + + } else if (format == 4) { //8 bit pal + col = readPalColour(palView, palOff, texView.getUint8(off++), trans) + + } else if (format == 6) { //A5I3 encoding. 5 bits alpha 3 bits pal index + var dat = texView.getUint8(off++) + col = readPalColour(palView, palOff, dat&7, trans); + col[3] = (dat>>3)*(255/31); + + } else if (format == 7) { //raw color data + col = texView.getUint16(off, true); + colourBuffer[0] = Math.round(((col&31)/31)*255) + colourBuffer[1] = Math.round((((col>>5)&31)/31)*255) + colourBuffer[2] = Math.round((((col>>10)&31)/31)*255) + colourBuffer[3] = Math.round((col>>15)*255); + col = colourBuffer; + off += 2; + + } else { + console.log("texture format is none, ignoring") + return canvas; + } + img.data.set(col, i*4); + } + ctx.putImageData(img, 0, 0) + return canvas; + } + + function readCompressedTex(tex, pal) { //format 5, 4x4 texels. I'll keep this well documented so it's easy to understand. + var off = tex.texOffset; + var texView = new DataView(compData); //real texture data - 32 bits per 4x4 block (one byte per 4px horizontal line, each descending 1px) + var compView = new DataView(compInfoData); //view into compression info - informs of pallete and parameters. + var palView = new DataView(palData); //view into the texture pallete + var compOff = off/2; //info is 2 bytes per block, so the offset is half that of the tex offset. + var palOff = pal.palOffset; + var transColor = new Uint8Array([0, 0, 0, 0]); //transparent black + + var canvas = document.createElement("canvas"); + canvas.width = tex.width; + canvas.height = tex.height; + var ctx = canvas.getContext("2d"); + var img = ctx.getImageData(0, 0, tex.width, tex.height); + + var w = tex.width>>2; //iterate over blocks, block w and h is /4. + var h = tex.height>>2; + + for (var y=0; y> 14) & 3); + + var finalPo = palOff+addr*4; + var imgoff = x*4+(y*w*16); + for (var iy=0; iy<4; iy++) { + var dat = texView.getUint8(off++); + for (var ix=0; ix<4; ix++) { //iterate over horiz lines + var part = (dat>>(ix*2))&3; + var col; + + switch (mode) { + case 0: //value 3 is transparent, otherwise pal colour + if (part == 3) col = transColor; + else col = readPalColour(palView, finalPo, part); + break; + case 1: //average mode - colour 2 is average of 1st two, 3 is transparent. 0&1 are normal. + if (part == 3) col = transColor; + else if (part == 2) col = readFractionalPal(palView, finalPo, 0.5); + else col = readPalColour(palView, finalPo, part); + break; + case 2: //pal colour + col = readPalColour(palView, finalPo, part); + break; + case 3: //5/8 3/8 mode - colour 2 is 5/8 of col0 plus 3/8 of col1, 3 is 3/8 of col0 plus 5/8 of col1. 0&1 are normal. + if (part == 3) col = readFractionalPal(palView, finalPo, 3/8); + else if (part == 2) col = readFractionalPal(palView, finalPo, 5/8); + else col = readPalColour(palView, finalPo, part); + break; + } + + img.data.set(col, (imgoff++)*4) + } + imgoff += tex.width-4; + } + compOff += 2; //align off to next block + } + } + + ctx.putImageData(img, 0, 0) + return canvas; + } + + function readPalColour(view, palOff, ind, pal0trans) { + var col = view.getUint16(palOff+ind*2, true); + var f = 255/31; + colourBuffer[0] = Math.round((col&31)*f) + colourBuffer[1] = Math.round(((col>>5)&31)*f) + colourBuffer[2] = Math.round(((col>>10)&31)*f) + colourBuffer[3] = (pal0trans && ind == 0)?0:255; + return colourBuffer; + } + + function readFractionalPal(view, palOff, i) { + var col = view.getUint16(palOff, true); + var col2 = view.getUint16(palOff+2, true); + var ni = 1-i; + var f = 255/31; + colourBuffer[0] = Math.round((col&31)*f*i + (col2&31)*f*ni) + colourBuffer[1] = Math.round(((col>>5)&31)*f*i + ((col2>>5)&31)*f*ni) + colourBuffer[2] = Math.round(((col>>10)&31)*f*i + ((col2>>10)&31)*f*ni) + colourBuffer[3] = 255; + return colourBuffer; + } + + function palInfoHandler(view, offset) { + var palOffset = view.getUint16(offset, true)<<3; + var unknown = view.getUint16(offset+2, true); + return { + palOffset: palOffset, + unknown: unknown, + nextoff: offset+4 + } + } + + function texInfoHandler(view, offset) { + var texOffset = view.getUint16(offset, true)<<3; + var flags = view.getUint16(offset+2, true); + var width2 = view.getUint8(offset+4, true); + var unknown = view.getUint8(offset+5, true); + var height2 = view.getUint8(offset+6, true); + var unknown2 = view.getUint8(offset+7, true); + return { + texOffset: texOffset, + pal0trans: (flags>>13)&1, //two top flags are texture matrix modes. not sure if it really matters (except for nsbta animation maybe, but 0 = no transform and things that have tex animations are set to 0 anyways). + format: ((flags>>10)&7), + height: 8 << ((flags>>7)&7), + width: 8 << ((flags>>4)&7), + repeatX: flags&1, + repeatY: (flags>>1)&1, + flipX: (flags>>2)&1, + flipY: (flags>>3)&1, + + unkWidth: width2, + unk1: unknown, + unkHeight: height2, + unk2: unknown2, + + nextoff: offset+8 + } + } + + function readChar(view, offset) { + return String.fromCharCode(view.getUint8(offset)); + } +} \ No newline at end of file diff --git a/code/formats/sbnk.js b/code/formats/sbnk.js new file mode 100644 index 0000000..70737a2 --- /dev/null +++ b/code/formats/sbnk.js @@ -0,0 +1,102 @@ +// +// sbnk.js +//-------------------- +// Reads sbnk files. +// by RHY3756547 +// +// includes: gl-matrix.js (glMatrix 2.0) +// + +window.sbnk = function(input, dataView) { + var t = this; + this.load = load; + + function load(input, dataView) { + var view = (dataView)?input:(new DataView(input)); + var header = null; + var offset = 0; + + var stamp = readChar(view, 0x0)+readChar(view, 0x1)+readChar(view, 0x2)+readChar(view, 0x3); + if (stamp != "SBNK") throw "SWAV invalid. Expected SWAV, found "+stamp; + offset += 16; + var data = readChar(view, offset)+readChar(view, offset+1)+readChar(view, offset+2)+readChar(view, offset+3); + if (data != "DATA") throw "SWAV invalid, expected DATA, found "+data; + offset += 8; + + offset += 32; //skip reserved + + var numInst = view.getUint32(offset, true); + t.instruments = []; + offset += 4; + for (var i=0; i-1; i--) { //reverse order so we can process files into js objects + var off = (view.getUint32(0x10+i*8, true)); + var size = (view.getUint32(0x14+i*8, true)); + if (size != 0) readSection(view, off); + } + + } + + function readSection(view, off) { + var stamp = "$"+readChar(view, off)+readChar(view, off+1)+readChar(view, off+2)+readChar(view, off+3); + if (sectionFunc[stamp] != null) t.sections[stamp] = sectionFunc[stamp](view, off+8); + else console.error("Invalid section in SDAT! No handler for section type "+stamp.substr(1, 4)); + } + + var sectionFunc = {} + + sectionFunc["$SYMB"] = function(view, off) { + + } + + sectionFunc["$INFO"] = function(view, off) { + var obj = []; + for (var i=0; i<8; i++) { + var relOff = off+view.getUint32(off+i*4, true)-8; + + var count = view.getUint32(relOff, true); + obj[i] = []; + relOff += 4; + var last = null; + for (var j=0; j 96000) return ctx.createBuffer(1, 1, 44000); //give up and return an empty buffer + } + } + + var indChanges = [-1, -1, -1, -1, 2, 4, 6, 8]; + var ADPCMTable = [ + 0x0007,0x0008,0x0009,0x000A,0x000B,0x000C,0x000D,0x000E,0x0010,0x0011,0x0013,0x0015, + 0x0017,0x0019,0x001C,0x001F,0x0022,0x0025,0x0029,0x002D,0x0032,0x0037,0x003C,0x0042, + 0x0049,0x0050,0x0058,0x0061,0x006B,0x0076,0x0082,0x008F,0x009D,0x00AD,0x00BE,0x00D1, + 0x00E6,0x00FD,0x0117,0x0133,0x0151,0x0173,0x0198,0x01C1,0x01EE,0x0220,0x0256,0x0292, + 0x02D4,0x031C,0x036C,0x03C3,0x0424,0x048E,0x0502,0x0583,0x0610,0x06AB,0x0756,0x0812, + 0x08E0,0x09C3,0x0ABD,0x0BD0,0x0CFF,0x0E4C,0x0FBA,0x114C,0x1307,0x14EE,0x1706,0x1954, + 0x1BDC,0x1EA5,0x21B6,0x2515,0x28CA,0x2CDF,0x315B,0x364B,0x3BB9,0x41B2,0x4844,0x4F7E, + 0x5771,0x602F,0x69CE,0x7462,0x7FFF + ]; //thanks no$gba docs + + function decodeADPCM(view, off) { + var pcm = view.getUint16(off, true); //initial pcm + var ind = view.getUint8(off+2); //initial index + off += 4; + + var size = t.bytesize-4; + var out = new Float32Array((size*2)); + var write = 0; + //out[write++] = pcm/0x7FFF; + + for (var i=0; i>(j*4))&15; + + var diff = Math.floor(((nibble&7)*2+1)*ADPCMTable[ind]/8); + if (nibble&8) pcm = Math.max(pcm-diff, -0x7FFF); + else pcm = Math.min(pcm+diff, 0x7FFF); + out[write++] = pcm/0x7FFF; + + ind = Math.min(88, Math.max(0, ind + indChanges[nibble&7])); + } + } + return out; + } + + + function readChar(view, offset) { + return String.fromCharCode(view.getUint8(offset)); + } + + if (input != null) { + load(input, hasHead, dataView); + } +} \ No newline at end of file diff --git a/code/glmatrix/gl-matrix-min.js b/code/glmatrix/gl-matrix-min.js new file mode 100644 index 0000000..973d11c --- /dev/null +++ b/code/glmatrix/gl-matrix-min.js @@ -0,0 +1,28 @@ +/** + * @fileoverview gl-matrix - High performance matrix and vector operations + * @author Brandon Jones + * @author Colin MacKenzie IV + * @version 2.2.1 + */ +/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +(function(e){"use strict";var t={};typeof exports=="undefined"?typeof define=="function"&&typeof define.amd=="object"&&define.amd?(t.exports={},define(function(){return t.exports})):t.exports=typeof window!="undefined"?window:e:t.exports=exports,function(e){if(!t)var t=1e-6;if(!n)var n=typeof Float32Array!="undefined"?Float32Array:Array;if(!r)var r=Math.random;var i={};i.setMatrixArrayType=function(e){n=e},typeof e!="undefined"&&(e.glMatrix=i);var s=Math.PI/180;i.toRadian=function(e){return e*s};var o={};o.create=function(){var e=new n(2);return e[0]=0,e[1]=0,e},o.clone=function(e){var t=new n(2);return t[0]=e[0],t[1]=e[1],t},o.fromValues=function(e,t){var r=new n(2);return r[0]=e,r[1]=t,r},o.copy=function(e,t){return e[0]=t[0],e[1]=t[1],e},o.set=function(e,t,n){return e[0]=t,e[1]=n,e},o.add=function(e,t,n){return e[0]=t[0]+n[0],e[1]=t[1]+n[1],e},o.subtract=function(e,t,n){return e[0]=t[0]-n[0],e[1]=t[1]-n[1],e},o.sub=o.subtract,o.multiply=function(e,t,n){return e[0]=t[0]*n[0],e[1]=t[1]*n[1],e},o.mul=o.multiply,o.divide=function(e,t,n){return e[0]=t[0]/n[0],e[1]=t[1]/n[1],e},o.div=o.divide,o.min=function(e,t,n){return e[0]=Math.min(t[0],n[0]),e[1]=Math.min(t[1],n[1]),e},o.max=function(e,t,n){return e[0]=Math.max(t[0],n[0]),e[1]=Math.max(t[1],n[1]),e},o.scale=function(e,t,n){return e[0]=t[0]*n,e[1]=t[1]*n,e},o.scaleAndAdd=function(e,t,n,r){return e[0]=t[0]+n[0]*r,e[1]=t[1]+n[1]*r,e},o.distance=function(e,t){var n=t[0]-e[0],r=t[1]-e[1];return Math.sqrt(n*n+r*r)},o.dist=o.distance,o.squaredDistance=function(e,t){var n=t[0]-e[0],r=t[1]-e[1];return n*n+r*r},o.sqrDist=o.squaredDistance,o.length=function(e){var t=e[0],n=e[1];return Math.sqrt(t*t+n*n)},o.len=o.length,o.squaredLength=function(e){var t=e[0],n=e[1];return t*t+n*n},o.sqrLen=o.squaredLength,o.negate=function(e,t){return e[0]=-t[0],e[1]=-t[1],e},o.normalize=function(e,t){var n=t[0],r=t[1],i=n*n+r*r;return i>0&&(i=1/Math.sqrt(i),e[0]=t[0]*i,e[1]=t[1]*i),e},o.dot=function(e,t){return e[0]*t[0]+e[1]*t[1]},o.cross=function(e,t,n){var r=t[0]*n[1]-t[1]*n[0];return e[0]=e[1]=0,e[2]=r,e},o.lerp=function(e,t,n,r){var i=t[0],s=t[1];return e[0]=i+r*(n[0]-i),e[1]=s+r*(n[1]-s),e},o.random=function(e,t){t=t||1;var n=r()*2*Math.PI;return e[0]=Math.cos(n)*t,e[1]=Math.sin(n)*t,e},o.transformMat2=function(e,t,n){var r=t[0],i=t[1];return e[0]=n[0]*r+n[2]*i,e[1]=n[1]*r+n[3]*i,e},o.transformMat2d=function(e,t,n){var r=t[0],i=t[1];return e[0]=n[0]*r+n[2]*i+n[4],e[1]=n[1]*r+n[3]*i+n[5],e},o.transformMat3=function(e,t,n){var r=t[0],i=t[1];return e[0]=n[0]*r+n[3]*i+n[6],e[1]=n[1]*r+n[4]*i+n[7],e},o.transformMat4=function(e,t,n){var r=t[0],i=t[1];return e[0]=n[0]*r+n[4]*i+n[12],e[1]=n[1]*r+n[5]*i+n[13],e},o.forEach=function(){var e=o.create();return function(t,n,r,i,s,o){var u,a;n||(n=2),r||(r=0),i?a=Math.min(i*n+r,t.length):a=t.length;for(u=r;u0&&(s=1/Math.sqrt(s),e[0]=t[0]*s,e[1]=t[1]*s,e[2]=t[2]*s),e},u.dot=function(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]},u.cross=function(e,t,n){var r=t[0],i=t[1],s=t[2],o=n[0],u=n[1],a=n[2];return e[0]=i*a-s*u,e[1]=s*o-r*a,e[2]=r*u-i*o,e},u.lerp=function(e,t,n,r){var i=t[0],s=t[1],o=t[2];return e[0]=i+r*(n[0]-i),e[1]=s+r*(n[1]-s),e[2]=o+r*(n[2]-o),e},u.random=function(e,t){t=t||1;var n=r()*2*Math.PI,i=r()*2-1,s=Math.sqrt(1-i*i)*t;return e[0]=Math.cos(n)*s,e[1]=Math.sin(n)*s,e[2]=i*t,e},u.transformMat4=function(e,t,n){var r=t[0],i=t[1],s=t[2];return e[0]=n[0]*r+n[4]*i+n[8]*s+n[12],e[1]=n[1]*r+n[5]*i+n[9]*s+n[13],e[2]=n[2]*r+n[6]*i+n[10]*s+n[14],e},u.transformMat3=function(e,t,n){var r=t[0],i=t[1],s=t[2];return e[0]=r*n[0]+i*n[3]+s*n[6],e[1]=r*n[1]+i*n[4]+s*n[7],e[2]=r*n[2]+i*n[5]+s*n[8],e},u.transformQuat=function(e,t,n){var r=t[0],i=t[1],s=t[2],o=n[0],u=n[1],a=n[2],f=n[3],l=f*r+u*s-a*i,c=f*i+a*r-o*s,h=f*s+o*i-u*r,p=-o*r-u*i-a*s;return e[0]=l*f+p*-o+c*-a-h*-u,e[1]=c*f+p*-u+h*-o-l*-a,e[2]=h*f+p*-a+l*-u-c*-o,e},u.rotateX=function(e,t,n,r){var i=[],s=[];return i[0]=t[0]-n[0],i[1]=t[1]-n[1],i[2]=t[2]-n[2],s[0]=i[0],s[1]=i[1]*Math.cos(r)-i[2]*Math.sin(r),s[2]=i[1]*Math.sin(r)+i[2]*Math.cos(r),e[0]=s[0]+n[0],e[1]=s[1]+n[1],e[2]=s[2]+n[2],e},u.rotateY=function(e,t,n,r){var i=[],s=[];return i[0]=t[0]-n[0],i[1]=t[1]-n[1],i[2]=t[2]-n[2],s[0]=i[2]*Math.sin(r)+i[0]*Math.cos(r),s[1]=i[1],s[2]=i[2]*Math.cos(r)-i[0]*Math.sin(r),e[0]=s[0]+n[0],e[1]=s[1]+n[1],e[2]=s[2]+n[2],e},u.rotateZ=function(e,t,n,r){var i=[],s=[];return i[0]=t[0]-n[0],i[1]=t[1]-n[1],i[2]=t[2]-n[2],s[0]=i[0]*Math.cos(r)-i[1]*Math.sin(r),s[1]=i[0]*Math.sin(r)+i[1]*Math.cos(r),s[2]=i[2],e[0]=s[0]+n[0],e[1]=s[1]+n[1],e[2]=s[2]+n[2],e},u.forEach=function(){var e=u.create();return function(t,n,r,i,s,o){var u,a;n||(n=3),r||(r=0),i?a=Math.min(i*n+r,t.length):a=t.length;for(u=r;u0&&(o=1/Math.sqrt(o),e[0]=t[0]*o,e[1]=t[1]*o,e[2]=t[2]*o,e[3]=t[3]*o),e},a.dot=function(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3]},a.lerp=function(e,t,n,r){var i=t[0],s=t[1],o=t[2],u=t[3];return e[0]=i+r*(n[0]-i),e[1]=s+r*(n[1]-s),e[2]=o+r*(n[2]-o),e[3]=u+r*(n[3]-u),e},a.random=function(e,t){return t=t||1,e[0]=r(),e[1]=r(),e[2]=r(),e[3]=r(),a.normalize(e,e),a.scale(e,e,t),e},a.transformMat4=function(e,t,n){var r=t[0],i=t[1],s=t[2],o=t[3];return e[0]=n[0]*r+n[4]*i+n[8]*s+n[12]*o,e[1]=n[1]*r+n[5]*i+n[9]*s+n[13]*o,e[2]=n[2]*r+n[6]*i+n[10]*s+n[14]*o,e[3]=n[3]*r+n[7]*i+n[11]*s+n[15]*o,e},a.transformQuat=function(e,t,n){var r=t[0],i=t[1],s=t[2],o=n[0],u=n[1],a=n[2],f=n[3],l=f*r+u*s-a*i,c=f*i+a*r-o*s,h=f*s+o*i-u*r,p=-o*r-u*i-a*s;return e[0]=l*f+p*-o+c*-a-h*-u,e[1]=c*f+p*-u+h*-o-l*-a,e[2]=h*f+p*-a+l*-u-c*-o,e},a.forEach=function(){var e=a.create();return function(t,n,r,i,s,o){var u,a;n||(n=4),r||(r=0),i?a=Math.min(i*n+r,t.length):a=t.length;for(u=r;u.999999?(r[0]=0,r[1]=0,r[2]=0,r[3]=1,r):(u.cross(e,i,s),r[0]=e[0],r[1]=e[1],r[2]=e[2],r[3]=1+o,p.normalize(r,r))}}(),p.setAxes=function(){var e=c.create();return function(t,n,r,i){return e[0]=r[0],e[3]=r[1],e[6]=r[2],e[1]=i[0],e[4]=i[1],e[7]=i[2],e[2]=-n[0],e[5]=-n[1],e[8]=-n[2],p.normalize(t,p.fromMat3(t,e))}}(),p.clone=a.clone,p.fromValues=a.fromValues,p.copy=a.copy,p.set=a.set,p.identity=function(e){return e[0]=0,e[1]=0,e[2]=0,e[3]=1,e},p.setAxisAngle=function(e,t,n){n*=.5;var r=Math.sin(n);return e[0]=r*t[0],e[1]=r*t[1],e[2]=r*t[2],e[3]=Math.cos(n),e},p.add=a.add,p.multiply=function(e,t,n){var r=t[0],i=t[1],s=t[2],o=t[3],u=n[0],a=n[1],f=n[2],l=n[3];return e[0]=r*l+o*u+i*f-s*a,e[1]=i*l+o*a+s*u-r*f,e[2]=s*l+o*f+r*a-i*u,e[3]=o*l-r*u-i*a-s*f,e},p.mul=p.multiply,p.scale=a.scale,p.rotateX=function(e,t,n){n*=.5;var r=t[0],i=t[1],s=t[2],o=t[3],u=Math.sin(n),a=Math.cos(n);return e[0]=r*a+o*u,e[1]=i*a+s*u,e[2]=s*a-i*u,e[3]=o*a-r*u,e},p.rotateY=function(e,t,n){n*=.5;var r=t[0],i=t[1],s=t[2],o=t[3],u=Math.sin(n),a=Math.cos(n);return e[0]=r*a-s*u,e[1]=i*a+o*u,e[2]=s*a+r*u,e[3]=o*a-i*u,e},p.rotateZ=function(e,t,n){n*=.5;var r=t[0],i=t[1],s=t[2],o=t[3],u=Math.sin(n),a=Math.cos(n);return e[0]=r*a+i*u,e[1]=i*a-r*u,e[2]=s*a+o*u,e[3]=o*a-s*u,e},p.calculateW=function(e,t){var n=t[0],r=t[1],i=t[2];return e[0]=n,e[1]=r,e[2]=i,e[3]=-Math.sqrt(Math.abs(1-n*n-r*r-i*i)),e},p.dot=a.dot,p.lerp=a.lerp,p.slerp=function(e,t,n,r){var i=t[0],s=t[1],o=t[2],u=t[3],a=n[0],f=n[1],l=n[2],c=n[3],h,p,d,v,m;return p=i*a+s*f+o*l+u*c,p<0&&(p=-p,a=-a,f=-f,l=-l,c=-c),1-p>1e-6?(h=Math.acos(p),d=Math.sin(h),v=Math.sin((1-r)*h)/d,m=Math.sin(r*h)/d):(v=1-r,m=r),e[0]=v*i+m*a,e[1]=v*s+m*f,e[2]=v*o+m*l,e[3]=v*u+m*c,e},p.invert=function(e,t){var n=t[0],r=t[1],i=t[2],s=t[3],o=n*n+r*r+i*i+s*s,u=o?1/o:0;return e[0]=-n*u,e[1]=-r*u,e[2]=-i*u,e[3]=s*u,e},p.conjugate=function(e,t){return e[0]=-t[0],e[1]=-t[1],e[2]=-t[2],e[3]=t[3],e},p.length=a.length,p.len=p.length,p.squaredLength=a.squaredLength,p.sqrLen=p.squaredLength,p.normalize=a.normalize,p.fromMat3=function(e,t){var n=t[0]+t[4]+t[8],r;if(n>0)r=Math.sqrt(n+1),e[3]=.5*r,r=.5/r,e[0]=(t[7]-t[5])*r,e[1]=(t[2]-t[6])*r,e[2]=(t[3]-t[1])*r;else{var i=0;t[4]>t[0]&&(i=1),t[8]>t[i*3+i]&&(i=2);var s=(i+1)%3,o=(i+2)%3;r=Math.sqrt(t[i*3+i]-t[s*3+s]-t[o*3+o]+1),e[i]=.5*r,r=.5/r,e[3]=(t[o*3+s]-t[s*3+o])*r,e[s]=(t[s*3+i]+t[i*3+s])*r,e[o]=(t[o*3+i]+t[i*3+o])*r}return e},p.str=function(e){return"quat("+e[0]+", "+e[1]+", "+e[2]+", "+e[3]+")"},typeof e!="undefined"&&(e.quat=p)}(t.exports)})(this); diff --git a/code/glmatrix/gl-matrix.js b/code/glmatrix/gl-matrix.js new file mode 100644 index 0000000..9316004 --- /dev/null +++ b/code/glmatrix/gl-matrix.js @@ -0,0 +1,4292 @@ +/** + * @fileoverview gl-matrix - High performance matrix and vector operations + * @author Brandon Jones + * @author Colin MacKenzie IV + * @version 2.2.2 + */ + +/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + + +(function(_global) { + "use strict"; + + var shim = {}; + if (typeof(exports) === 'undefined') { + if(typeof define == 'function' && typeof define.amd == 'object' && define.amd) { + shim.exports = {}; + define(function() { + return shim.exports; + }); + } else { + // gl-matrix lives in a browser, define its namespaces in global + shim.exports = typeof(window) !== 'undefined' ? window : _global; + } + } + else { + // gl-matrix lives in commonjs, define its namespaces in exports + shim.exports = exports; + } + + (function(exports) { + /* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + + +if(!GLMAT_EPSILON) { + var GLMAT_EPSILON = 0.000001; +} + +if(!GLMAT_ARRAY_TYPE) { + var GLMAT_ARRAY_TYPE = (typeof Float32Array !== 'undefined') ? Float32Array : Array; +} + +if(!GLMAT_RANDOM) { + var GLMAT_RANDOM = Math.random; +} + +/** + * @class Common utilities + * @name glMatrix + */ +var glMatrix = {}; + +/** + * Sets the type of array used when creating new vectors and matrices + * + * @param {Type} type Array type, such as Float32Array or Array + */ +glMatrix.setMatrixArrayType = function(type) { + GLMAT_ARRAY_TYPE = type; +} + +if(typeof(exports) !== 'undefined') { + exports.glMatrix = glMatrix; +} + +var degree = Math.PI / 180; + +/** +* Convert Degree To Radian +* +* @param {Number} Angle in Degrees +*/ +glMatrix.toRadian = function(a){ + return a * degree; +} +; +/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + +/** + * @class 2 Dimensional Vector + * @name vec2 + */ + +var vec2 = {}; + +/** + * Creates a new, empty vec2 + * + * @returns {vec2} a new 2D vector + */ +vec2.create = function() { + var out = new GLMAT_ARRAY_TYPE(2); + out[0] = 0; + out[1] = 0; + return out; +}; + +/** + * Creates a new vec2 initialized with values from an existing vector + * + * @param {vec2} a vector to clone + * @returns {vec2} a new 2D vector + */ +vec2.clone = function(a) { + var out = new GLMAT_ARRAY_TYPE(2); + out[0] = a[0]; + out[1] = a[1]; + return out; +}; + +/** + * Creates a new vec2 initialized with the given values + * + * @param {Number} x X component + * @param {Number} y Y component + * @returns {vec2} a new 2D vector + */ +vec2.fromValues = function(x, y) { + var out = new GLMAT_ARRAY_TYPE(2); + out[0] = x; + out[1] = y; + return out; +}; + +/** + * Copy the values from one vec2 to another + * + * @param {vec2} out the receiving vector + * @param {vec2} a the source vector + * @returns {vec2} out + */ +vec2.copy = function(out, a) { + out[0] = a[0]; + out[1] = a[1]; + return out; +}; + +/** + * Set the components of a vec2 to the given values + * + * @param {vec2} out the receiving vector + * @param {Number} x X component + * @param {Number} y Y component + * @returns {vec2} out + */ +vec2.set = function(out, x, y) { + out[0] = x; + out[1] = y; + return out; +}; + +/** + * Adds two vec2's + * + * @param {vec2} out the receiving vector + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @returns {vec2} out + */ +vec2.add = function(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + return out; +}; + +/** + * Subtracts vector b from vector a + * + * @param {vec2} out the receiving vector + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @returns {vec2} out + */ +vec2.subtract = function(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + return out; +}; + +/** + * Alias for {@link vec2.subtract} + * @function + */ +vec2.sub = vec2.subtract; + +/** + * Multiplies two vec2's + * + * @param {vec2} out the receiving vector + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @returns {vec2} out + */ +vec2.multiply = function(out, a, b) { + out[0] = a[0] * b[0]; + out[1] = a[1] * b[1]; + return out; +}; + +/** + * Alias for {@link vec2.multiply} + * @function + */ +vec2.mul = vec2.multiply; + +/** + * Divides two vec2's + * + * @param {vec2} out the receiving vector + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @returns {vec2} out + */ +vec2.divide = function(out, a, b) { + out[0] = a[0] / b[0]; + out[1] = a[1] / b[1]; + return out; +}; + +/** + * Alias for {@link vec2.divide} + * @function + */ +vec2.div = vec2.divide; + +/** + * Returns the minimum of two vec2's + * + * @param {vec2} out the receiving vector + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @returns {vec2} out + */ +vec2.min = function(out, a, b) { + out[0] = Math.min(a[0], b[0]); + out[1] = Math.min(a[1], b[1]); + return out; +}; + +/** + * Returns the maximum of two vec2's + * + * @param {vec2} out the receiving vector + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @returns {vec2} out + */ +vec2.max = function(out, a, b) { + out[0] = Math.max(a[0], b[0]); + out[1] = Math.max(a[1], b[1]); + return out; +}; + +/** + * Scales a vec2 by a scalar number + * + * @param {vec2} out the receiving vector + * @param {vec2} a the vector to scale + * @param {Number} b amount to scale the vector by + * @returns {vec2} out + */ +vec2.scale = function(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + return out; +}; + +/** + * Adds two vec2's after scaling the second operand by a scalar value + * + * @param {vec2} out the receiving vector + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @param {Number} scale the amount to scale b by before adding + * @returns {vec2} out + */ +vec2.scaleAndAdd = function(out, a, b, scale) { + out[0] = a[0] + (b[0] * scale); + out[1] = a[1] + (b[1] * scale); + return out; +}; + +/** + * Calculates the euclidian distance between two vec2's + * + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @returns {Number} distance between a and b + */ +vec2.distance = function(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1]; + return Math.sqrt(x*x + y*y); +}; + +/** + * Alias for {@link vec2.distance} + * @function + */ +vec2.dist = vec2.distance; + +/** + * Calculates the squared euclidian distance between two vec2's + * + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @returns {Number} squared distance between a and b + */ +vec2.squaredDistance = function(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1]; + return x*x + y*y; +}; + +/** + * Alias for {@link vec2.squaredDistance} + * @function + */ +vec2.sqrDist = vec2.squaredDistance; + +/** + * Calculates the length of a vec2 + * + * @param {vec2} a vector to calculate length of + * @returns {Number} length of a + */ +vec2.length = function (a) { + var x = a[0], + y = a[1]; + return Math.sqrt(x*x + y*y); +}; + +/** + * Alias for {@link vec2.length} + * @function + */ +vec2.len = vec2.length; + +/** + * Calculates the squared length of a vec2 + * + * @param {vec2} a vector to calculate squared length of + * @returns {Number} squared length of a + */ +vec2.squaredLength = function (a) { + var x = a[0], + y = a[1]; + return x*x + y*y; +}; + +/** + * Alias for {@link vec2.squaredLength} + * @function + */ +vec2.sqrLen = vec2.squaredLength; + +/** + * Negates the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to negate + * @returns {vec2} out + */ +vec2.negate = function(out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + return out; +}; + +/** + * Returns the inverse of the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to invert + * @returns {vec2} out + */ +vec2.inverse = function(out, a) { + out[0] = 1.0 / a[0]; + out[1] = 1.0 / a[1]; + return out; +}; + +/** + * Normalize a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to normalize + * @returns {vec2} out + */ +vec2.normalize = function(out, a) { + var x = a[0], + y = a[1]; + var len = x*x + y*y; + if (len > 0) { + //TODO: evaluate use of glm_invsqrt here? + len = 1 / Math.sqrt(len); + out[0] = a[0] * len; + out[1] = a[1] * len; + } + return out; +}; + +/** + * Calculates the dot product of two vec2's + * + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @returns {Number} dot product of a and b + */ +vec2.dot = function (a, b) { + return a[0] * b[0] + a[1] * b[1]; +}; + +/** + * Computes the cross product of two vec2's + * Note that the cross product must by definition produce a 3D vector + * + * @param {vec3} out the receiving vector + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @returns {vec3} out + */ +vec2.cross = function(out, a, b) { + var z = a[0] * b[1] - a[1] * b[0]; + out[0] = out[1] = 0; + out[2] = z; + return out; +}; + +/** + * Performs a linear interpolation between two vec2's + * + * @param {vec2} out the receiving vector + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @param {Number} t interpolation amount between the two inputs + * @returns {vec2} out + */ +vec2.lerp = function (out, a, b, t) { + var ax = a[0], + ay = a[1]; + out[0] = ax + t * (b[0] - ax); + out[1] = ay + t * (b[1] - ay); + return out; +}; + +/** + * Generates a random vector with the given scale + * + * @param {vec2} out the receiving vector + * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns {vec2} out + */ +vec2.random = function (out, scale) { + scale = scale || 1.0; + var r = GLMAT_RANDOM() * 2.0 * Math.PI; + out[0] = Math.cos(r) * scale; + out[1] = Math.sin(r) * scale; + return out; +}; + +/** + * Transforms the vec2 with a mat2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a the vector to transform + * @param {mat2} m matrix to transform with + * @returns {vec2} out + */ +vec2.transformMat2 = function(out, a, m) { + var x = a[0], + y = a[1]; + out[0] = m[0] * x + m[2] * y; + out[1] = m[1] * x + m[3] * y; + return out; +}; + +/** + * Transforms the vec2 with a mat2d + * + * @param {vec2} out the receiving vector + * @param {vec2} a the vector to transform + * @param {mat2d} m matrix to transform with + * @returns {vec2} out + */ +vec2.transformMat2d = function(out, a, m) { + var x = a[0], + y = a[1]; + out[0] = m[0] * x + m[2] * y + m[4]; + out[1] = m[1] * x + m[3] * y + m[5]; + return out; +}; + +/** + * Transforms the vec2 with a mat3 + * 3rd vector component is implicitly '1' + * + * @param {vec2} out the receiving vector + * @param {vec2} a the vector to transform + * @param {mat3} m matrix to transform with + * @returns {vec2} out + */ +vec2.transformMat3 = function(out, a, m) { + var x = a[0], + y = a[1]; + out[0] = m[0] * x + m[3] * y + m[6]; + out[1] = m[1] * x + m[4] * y + m[7]; + return out; +}; + +/** + * Transforms the vec2 with a mat4 + * 3rd vector component is implicitly '0' + * 4th vector component is implicitly '1' + * + * @param {vec2} out the receiving vector + * @param {vec2} a the vector to transform + * @param {mat4} m matrix to transform with + * @returns {vec2} out + */ +vec2.transformMat4 = function(out, a, m) { + var x = a[0], + y = a[1]; + out[0] = m[0] * x + m[4] * y + m[12]; + out[1] = m[1] * x + m[5] * y + m[13]; + return out; +}; + +/** + * Perform some operation over an array of vec2s. + * + * @param {Array} a the array of vectors to iterate over + * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed + * @param {Number} offset Number of elements to skip at the beginning of the array + * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array + * @param {Function} fn Function to call for each vector in the array + * @param {Object} [arg] additional argument to pass to fn + * @returns {Array} a + * @function + */ +vec2.forEach = (function() { + var vec = vec2.create(); + + return function(a, stride, offset, count, fn, arg) { + var i, l; + if(!stride) { + stride = 2; + } + + if(!offset) { + offset = 0; + } + + if(count) { + l = Math.min((count * stride) + offset, a.length); + } else { + l = a.length; + } + + for(i = offset; i < l; i += stride) { + vec[0] = a[i]; vec[1] = a[i+1]; + fn(vec, vec, arg); + a[i] = vec[0]; a[i+1] = vec[1]; + } + + return a; + }; +})(); + +/** + * Returns a string representation of a vector + * + * @param {vec2} vec vector to represent as a string + * @returns {String} string representation of the vector + */ +vec2.str = function (a) { + return 'vec2(' + a[0] + ', ' + a[1] + ')'; +}; + +if(typeof(exports) !== 'undefined') { + exports.vec2 = vec2; +} +; +/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + +/** + * @class 3 Dimensional Vector + * @name vec3 + */ + +var vec3 = {}; + +/** + * Creates a new, empty vec3 + * + * @returns {vec3} a new 3D vector + */ +vec3.create = function() { + var out = new GLMAT_ARRAY_TYPE(3); + out[0] = 0; + out[1] = 0; + out[2] = 0; + return out; +}; + +/** + * Creates a new vec3 initialized with values from an existing vector + * + * @param {vec3} a vector to clone + * @returns {vec3} a new 3D vector + */ +vec3.clone = function(a) { + var out = new GLMAT_ARRAY_TYPE(3); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + return out; +}; + +/** + * Creates a new vec3 initialized with the given values + * + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @returns {vec3} a new 3D vector + */ +vec3.fromValues = function(x, y, z) { + var out = new GLMAT_ARRAY_TYPE(3); + out[0] = x; + out[1] = y; + out[2] = z; + return out; +}; + +/** + * Copy the values from one vec3 to another + * + * @param {vec3} out the receiving vector + * @param {vec3} a the source vector + * @returns {vec3} out + */ +vec3.copy = function(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + return out; +}; + +/** + * Set the components of a vec3 to the given values + * + * @param {vec3} out the receiving vector + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @returns {vec3} out + */ +vec3.set = function(out, x, y, z) { + out[0] = x; + out[1] = y; + out[2] = z; + return out; +}; + +/** + * Adds two vec3's + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @returns {vec3} out + */ +vec3.add = function(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + out[2] = a[2] + b[2]; + return out; +}; + +/** + * Subtracts vector b from vector a + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @returns {vec3} out + */ +vec3.subtract = function(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + out[2] = a[2] - b[2]; + return out; +}; + +/** + * Alias for {@link vec3.subtract} + * @function + */ +vec3.sub = vec3.subtract; + +/** + * Multiplies two vec3's + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @returns {vec3} out + */ +vec3.multiply = function(out, a, b) { + out[0] = a[0] * b[0]; + out[1] = a[1] * b[1]; + out[2] = a[2] * b[2]; + return out; +}; + +/** + * Alias for {@link vec3.multiply} + * @function + */ +vec3.mul = vec3.multiply; + +/** + * Divides two vec3's + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @returns {vec3} out + */ +vec3.divide = function(out, a, b) { + out[0] = a[0] / b[0]; + out[1] = a[1] / b[1]; + out[2] = a[2] / b[2]; + return out; +}; + +/** + * Alias for {@link vec3.divide} + * @function + */ +vec3.div = vec3.divide; + +/** + * Returns the minimum of two vec3's + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @returns {vec3} out + */ +vec3.min = function(out, a, b) { + out[0] = Math.min(a[0], b[0]); + out[1] = Math.min(a[1], b[1]); + out[2] = Math.min(a[2], b[2]); + return out; +}; + +/** + * Returns the maximum of two vec3's + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @returns {vec3} out + */ +vec3.max = function(out, a, b) { + out[0] = Math.max(a[0], b[0]); + out[1] = Math.max(a[1], b[1]); + out[2] = Math.max(a[2], b[2]); + return out; +}; + +/** + * Scales a vec3 by a scalar number + * + * @param {vec3} out the receiving vector + * @param {vec3} a the vector to scale + * @param {Number} b amount to scale the vector by + * @returns {vec3} out + */ +vec3.scale = function(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + out[2] = a[2] * b; + return out; +}; + +/** + * Adds two vec3's after scaling the second operand by a scalar value + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @param {Number} scale the amount to scale b by before adding + * @returns {vec3} out + */ +vec3.scaleAndAdd = function(out, a, b, scale) { + out[0] = a[0] + (b[0] * scale); + out[1] = a[1] + (b[1] * scale); + out[2] = a[2] + (b[2] * scale); + return out; +}; + +/** + * Calculates the euclidian distance between two vec3's + * + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @returns {Number} distance between a and b + */ +vec3.distance = function(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1], + z = b[2] - a[2]; + return Math.sqrt(x*x + y*y + z*z); +}; + +/** + * Alias for {@link vec3.distance} + * @function + */ +vec3.dist = vec3.distance; + +/** + * Calculates the squared euclidian distance between two vec3's + * + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @returns {Number} squared distance between a and b + */ +vec3.squaredDistance = function(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1], + z = b[2] - a[2]; + return x*x + y*y + z*z; +}; + +/** + * Alias for {@link vec3.squaredDistance} + * @function + */ +vec3.sqrDist = vec3.squaredDistance; + +/** + * Calculates the length of a vec3 + * + * @param {vec3} a vector to calculate length of + * @returns {Number} length of a + */ +vec3.length = function (a) { + var x = a[0], + y = a[1], + z = a[2]; + return Math.sqrt(x*x + y*y + z*z); +}; + +/** + * Alias for {@link vec3.length} + * @function + */ +vec3.len = vec3.length; + +/** + * Calculates the squared length of a vec3 + * + * @param {vec3} a vector to calculate squared length of + * @returns {Number} squared length of a + */ +vec3.squaredLength = function (a) { + var x = a[0], + y = a[1], + z = a[2]; + return x*x + y*y + z*z; +}; + +/** + * Alias for {@link vec3.squaredLength} + * @function + */ +vec3.sqrLen = vec3.squaredLength; + +/** + * Negates the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to negate + * @returns {vec3} out + */ +vec3.negate = function(out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + out[2] = -a[2]; + return out; +}; + +/** + * Returns the inverse of the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to invert + * @returns {vec3} out + */ +vec3.inverse = function(out, a) { + out[0] = 1.0 / a[0]; + out[1] = 1.0 / a[1]; + out[2] = 1.0 / a[2]; + return out; +}; + +/** + * Normalize a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to normalize + * @returns {vec3} out + */ +vec3.normalize = function(out, a) { + var x = a[0], + y = a[1], + z = a[2]; + var len = x*x + y*y + z*z; + if (len > 0) { + //TODO: evaluate use of glm_invsqrt here? + len = 1 / Math.sqrt(len); + out[0] = a[0] * len; + out[1] = a[1] * len; + out[2] = a[2] * len; + } + return out; +}; + +/** + * Calculates the dot product of two vec3's + * + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @returns {Number} dot product of a and b + */ +vec3.dot = function (a, b) { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; +}; + +/** + * Computes the cross product of two vec3's + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @returns {vec3} out + */ +vec3.cross = function(out, a, b) { + var ax = a[0], ay = a[1], az = a[2], + bx = b[0], by = b[1], bz = b[2]; + + out[0] = ay * bz - az * by; + out[1] = az * bx - ax * bz; + out[2] = ax * by - ay * bx; + return out; +}; + +/** + * Performs a linear interpolation between two vec3's + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @param {Number} t interpolation amount between the two inputs + * @returns {vec3} out + */ +vec3.lerp = function (out, a, b, t) { + var ax = a[0], + ay = a[1], + az = a[2]; + out[0] = ax + t * (b[0] - ax); + out[1] = ay + t * (b[1] - ay); + out[2] = az + t * (b[2] - az); + return out; +}; + +/** + * Generates a random vector with the given scale + * + * @param {vec3} out the receiving vector + * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns {vec3} out + */ +vec3.random = function (out, scale) { + scale = scale || 1.0; + + var r = GLMAT_RANDOM() * 2.0 * Math.PI; + var z = (GLMAT_RANDOM() * 2.0) - 1.0; + var zScale = Math.sqrt(1.0-z*z) * scale; + + out[0] = Math.cos(r) * zScale; + out[1] = Math.sin(r) * zScale; + out[2] = z * scale; + return out; +}; + +/** + * Transforms the vec3 with a mat4. + * 4th vector component is implicitly '1' + * + * @param {vec3} out the receiving vector + * @param {vec3} a the vector to transform + * @param {mat4} m matrix to transform with + * @returns {vec3} out + */ +vec3.transformMat4 = function(out, a, m) { + var x = a[0], y = a[1], z = a[2], + w = m[3] * x + m[7] * y + m[11] * z + m[15]; + w = w || 1.0; + out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w; + out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w; + out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w; + return out; +}; + +/** + * Transforms the vec3 with a mat3. + * + * @param {vec3} out the receiving vector + * @param {vec3} a the vector to transform + * @param {mat4} m the 3x3 matrix to transform with + * @returns {vec3} out + */ +vec3.transformMat3 = function(out, a, m) { + var x = a[0], y = a[1], z = a[2]; + out[0] = x * m[0] + y * m[3] + z * m[6]; + out[1] = x * m[1] + y * m[4] + z * m[7]; + out[2] = x * m[2] + y * m[5] + z * m[8]; + return out; +}; + +/** + * Transforms the vec3 with a quat + * + * @param {vec3} out the receiving vector + * @param {vec3} a the vector to transform + * @param {quat} q quaternion to transform with + * @returns {vec3} out + */ +vec3.transformQuat = function(out, a, q) { + // benchmarks: http://jsperf.com/quaternion-transform-vec3-implementations + + var x = a[0], y = a[1], z = a[2], + qx = q[0], qy = q[1], qz = q[2], qw = q[3], + + // calculate quat * vec + ix = qw * x + qy * z - qz * y, + iy = qw * y + qz * x - qx * z, + iz = qw * z + qx * y - qy * x, + iw = -qx * x - qy * y - qz * z; + + // calculate result * inverse quat + out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy; + out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz; + out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx; + return out; +}; + +/** + * Rotate a 3D vector around the x-axis + * @param {vec3} out The receiving vec3 + * @param {vec3} a The vec3 point to rotate + * @param {vec3} b The origin of the rotation + * @param {Number} c The angle of rotation + * @returns {vec3} out + */ +vec3.rotateX = function(out, a, b, c){ + var p = [], r=[]; + //Translate point to the origin + p[0] = a[0] - b[0]; + p[1] = a[1] - b[1]; + p[2] = a[2] - b[2]; + + //perform rotation + r[0] = p[0]; + r[1] = p[1]*Math.cos(c) - p[2]*Math.sin(c); + r[2] = p[1]*Math.sin(c) + p[2]*Math.cos(c); + + //translate to correct position + out[0] = r[0] + b[0]; + out[1] = r[1] + b[1]; + out[2] = r[2] + b[2]; + + return out; +}; + +/** + * Rotate a 3D vector around the y-axis + * @param {vec3} out The receiving vec3 + * @param {vec3} a The vec3 point to rotate + * @param {vec3} b The origin of the rotation + * @param {Number} c The angle of rotation + * @returns {vec3} out + */ +vec3.rotateY = function(out, a, b, c){ + var p = [], r=[]; + //Translate point to the origin + p[0] = a[0] - b[0]; + p[1] = a[1] - b[1]; + p[2] = a[2] - b[2]; + + //perform rotation + r[0] = p[2]*Math.sin(c) + p[0]*Math.cos(c); + r[1] = p[1]; + r[2] = p[2]*Math.cos(c) - p[0]*Math.sin(c); + + //translate to correct position + out[0] = r[0] + b[0]; + out[1] = r[1] + b[1]; + out[2] = r[2] + b[2]; + + return out; +}; + +/** + * Rotate a 3D vector around the z-axis + * @param {vec3} out The receiving vec3 + * @param {vec3} a The vec3 point to rotate + * @param {vec3} b The origin of the rotation + * @param {Number} c The angle of rotation + * @returns {vec3} out + */ +vec3.rotateZ = function(out, a, b, c){ + var p = [], r=[]; + //Translate point to the origin + p[0] = a[0] - b[0]; + p[1] = a[1] - b[1]; + p[2] = a[2] - b[2]; + + //perform rotation + r[0] = p[0]*Math.cos(c) - p[1]*Math.sin(c); + r[1] = p[0]*Math.sin(c) + p[1]*Math.cos(c); + r[2] = p[2]; + + //translate to correct position + out[0] = r[0] + b[0]; + out[1] = r[1] + b[1]; + out[2] = r[2] + b[2]; + + return out; +}; + +/** + * Perform some operation over an array of vec3s. + * + * @param {Array} a the array of vectors to iterate over + * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed + * @param {Number} offset Number of elements to skip at the beginning of the array + * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array + * @param {Function} fn Function to call for each vector in the array + * @param {Object} [arg] additional argument to pass to fn + * @returns {Array} a + * @function + */ +vec3.forEach = (function() { + var vec = vec3.create(); + + return function(a, stride, offset, count, fn, arg) { + var i, l; + if(!stride) { + stride = 3; + } + + if(!offset) { + offset = 0; + } + + if(count) { + l = Math.min((count * stride) + offset, a.length); + } else { + l = a.length; + } + + for(i = offset; i < l; i += stride) { + vec[0] = a[i]; vec[1] = a[i+1]; vec[2] = a[i+2]; + fn(vec, vec, arg); + a[i] = vec[0]; a[i+1] = vec[1]; a[i+2] = vec[2]; + } + + return a; + }; +})(); + +/** + * Returns a string representation of a vector + * + * @param {vec3} vec vector to represent as a string + * @returns {String} string representation of the vector + */ +vec3.str = function (a) { + return 'vec3(' + a[0] + ', ' + a[1] + ', ' + a[2] + ')'; +}; + +if(typeof(exports) !== 'undefined') { + exports.vec3 = vec3; +} +; +/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + +/** + * @class 4 Dimensional Vector + * @name vec4 + */ + +var vec4 = {}; + +/** + * Creates a new, empty vec4 + * + * @returns {vec4} a new 4D vector + */ +vec4.create = function() { + var out = new GLMAT_ARRAY_TYPE(4); + out[0] = 0; + out[1] = 0; + out[2] = 0; + out[3] = 0; + return out; +}; + +/** + * Creates a new vec4 initialized with values from an existing vector + * + * @param {vec4} a vector to clone + * @returns {vec4} a new 4D vector + */ +vec4.clone = function(a) { + var out = new GLMAT_ARRAY_TYPE(4); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + return out; +}; + +/** + * Creates a new vec4 initialized with the given values + * + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @param {Number} w W component + * @returns {vec4} a new 4D vector + */ +vec4.fromValues = function(x, y, z, w) { + var out = new GLMAT_ARRAY_TYPE(4); + out[0] = x; + out[1] = y; + out[2] = z; + out[3] = w; + return out; +}; + +/** + * Copy the values from one vec4 to another + * + * @param {vec4} out the receiving vector + * @param {vec4} a the source vector + * @returns {vec4} out + */ +vec4.copy = function(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + return out; +}; + +/** + * Set the components of a vec4 to the given values + * + * @param {vec4} out the receiving vector + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @param {Number} w W component + * @returns {vec4} out + */ +vec4.set = function(out, x, y, z, w) { + out[0] = x; + out[1] = y; + out[2] = z; + out[3] = w; + return out; +}; + +/** + * Adds two vec4's + * + * @param {vec4} out the receiving vector + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @returns {vec4} out + */ +vec4.add = function(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + out[2] = a[2] + b[2]; + out[3] = a[3] + b[3]; + return out; +}; + +/** + * Subtracts vector b from vector a + * + * @param {vec4} out the receiving vector + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @returns {vec4} out + */ +vec4.subtract = function(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + out[2] = a[2] - b[2]; + out[3] = a[3] - b[3]; + return out; +}; + +/** + * Alias for {@link vec4.subtract} + * @function + */ +vec4.sub = vec4.subtract; + +/** + * Multiplies two vec4's + * + * @param {vec4} out the receiving vector + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @returns {vec4} out + */ +vec4.multiply = function(out, a, b) { + out[0] = a[0] * b[0]; + out[1] = a[1] * b[1]; + out[2] = a[2] * b[2]; + out[3] = a[3] * b[3]; + return out; +}; + +/** + * Alias for {@link vec4.multiply} + * @function + */ +vec4.mul = vec4.multiply; + +/** + * Divides two vec4's + * + * @param {vec4} out the receiving vector + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @returns {vec4} out + */ +vec4.divide = function(out, a, b) { + out[0] = a[0] / b[0]; + out[1] = a[1] / b[1]; + out[2] = a[2] / b[2]; + out[3] = a[3] / b[3]; + return out; +}; + +/** + * Alias for {@link vec4.divide} + * @function + */ +vec4.div = vec4.divide; + +/** + * Returns the minimum of two vec4's + * + * @param {vec4} out the receiving vector + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @returns {vec4} out + */ +vec4.min = function(out, a, b) { + out[0] = Math.min(a[0], b[0]); + out[1] = Math.min(a[1], b[1]); + out[2] = Math.min(a[2], b[2]); + out[3] = Math.min(a[3], b[3]); + return out; +}; + +/** + * Returns the maximum of two vec4's + * + * @param {vec4} out the receiving vector + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @returns {vec4} out + */ +vec4.max = function(out, a, b) { + out[0] = Math.max(a[0], b[0]); + out[1] = Math.max(a[1], b[1]); + out[2] = Math.max(a[2], b[2]); + out[3] = Math.max(a[3], b[3]); + return out; +}; + +/** + * Scales a vec4 by a scalar number + * + * @param {vec4} out the receiving vector + * @param {vec4} a the vector to scale + * @param {Number} b amount to scale the vector by + * @returns {vec4} out + */ +vec4.scale = function(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + out[2] = a[2] * b; + out[3] = a[3] * b; + return out; +}; + +/** + * Adds two vec4's after scaling the second operand by a scalar value + * + * @param {vec4} out the receiving vector + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @param {Number} scale the amount to scale b by before adding + * @returns {vec4} out + */ +vec4.scaleAndAdd = function(out, a, b, scale) { + out[0] = a[0] + (b[0] * scale); + out[1] = a[1] + (b[1] * scale); + out[2] = a[2] + (b[2] * scale); + out[3] = a[3] + (b[3] * scale); + return out; +}; + +/** + * Calculates the euclidian distance between two vec4's + * + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @returns {Number} distance between a and b + */ +vec4.distance = function(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1], + z = b[2] - a[2], + w = b[3] - a[3]; + return Math.sqrt(x*x + y*y + z*z + w*w); +}; + +/** + * Alias for {@link vec4.distance} + * @function + */ +vec4.dist = vec4.distance; + +/** + * Calculates the squared euclidian distance between two vec4's + * + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @returns {Number} squared distance between a and b + */ +vec4.squaredDistance = function(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1], + z = b[2] - a[2], + w = b[3] - a[3]; + return x*x + y*y + z*z + w*w; +}; + +/** + * Alias for {@link vec4.squaredDistance} + * @function + */ +vec4.sqrDist = vec4.squaredDistance; + +/** + * Calculates the length of a vec4 + * + * @param {vec4} a vector to calculate length of + * @returns {Number} length of a + */ +vec4.length = function (a) { + var x = a[0], + y = a[1], + z = a[2], + w = a[3]; + return Math.sqrt(x*x + y*y + z*z + w*w); +}; + +/** + * Alias for {@link vec4.length} + * @function + */ +vec4.len = vec4.length; + +/** + * Calculates the squared length of a vec4 + * + * @param {vec4} a vector to calculate squared length of + * @returns {Number} squared length of a + */ +vec4.squaredLength = function (a) { + var x = a[0], + y = a[1], + z = a[2], + w = a[3]; + return x*x + y*y + z*z + w*w; +}; + +/** + * Alias for {@link vec4.squaredLength} + * @function + */ +vec4.sqrLen = vec4.squaredLength; + +/** + * Negates the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to negate + * @returns {vec4} out + */ +vec4.negate = function(out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + out[2] = -a[2]; + out[3] = -a[3]; + return out; +}; + +/** + * Returns the inverse of the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to invert + * @returns {vec4} out + */ +vec4.inverse = function(out, a) { + out[0] = 1.0 / a[0]; + out[1] = 1.0 / a[1]; + out[2] = 1.0 / a[2]; + out[3] = 1.0 / a[3]; + return out; +}; + +/** + * Normalize a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to normalize + * @returns {vec4} out + */ +vec4.normalize = function(out, a) { + var x = a[0], + y = a[1], + z = a[2], + w = a[3]; + var len = x*x + y*y + z*z + w*w; + if (len > 0) { + len = 1 / Math.sqrt(len); + out[0] = a[0] * len; + out[1] = a[1] * len; + out[2] = a[2] * len; + out[3] = a[3] * len; + } + return out; +}; + +/** + * Calculates the dot product of two vec4's + * + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @returns {Number} dot product of a and b + */ +vec4.dot = function (a, b) { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; +}; + +/** + * Performs a linear interpolation between two vec4's + * + * @param {vec4} out the receiving vector + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @param {Number} t interpolation amount between the two inputs + * @returns {vec4} out + */ +vec4.lerp = function (out, a, b, t) { + var ax = a[0], + ay = a[1], + az = a[2], + aw = a[3]; + out[0] = ax + t * (b[0] - ax); + out[1] = ay + t * (b[1] - ay); + out[2] = az + t * (b[2] - az); + out[3] = aw + t * (b[3] - aw); + return out; +}; + +/** + * Generates a random vector with the given scale + * + * @param {vec4} out the receiving vector + * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns {vec4} out + */ +vec4.random = function (out, scale) { + scale = scale || 1.0; + + //TODO: This is a pretty awful way of doing this. Find something better. + out[0] = GLMAT_RANDOM(); + out[1] = GLMAT_RANDOM(); + out[2] = GLMAT_RANDOM(); + out[3] = GLMAT_RANDOM(); + vec4.normalize(out, out); + vec4.scale(out, out, scale); + return out; +}; + +/** + * Transforms the vec4 with a mat4. + * + * @param {vec4} out the receiving vector + * @param {vec4} a the vector to transform + * @param {mat4} m matrix to transform with + * @returns {vec4} out + */ +vec4.transformMat4 = function(out, a, m) { + var x = a[0], y = a[1], z = a[2], w = a[3]; + out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w; + out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w; + out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w; + out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w; + return out; +}; + +/** + * Transforms the vec4 with a quat + * + * @param {vec4} out the receiving vector + * @param {vec4} a the vector to transform + * @param {quat} q quaternion to transform with + * @returns {vec4} out + */ +vec4.transformQuat = function(out, a, q) { + var x = a[0], y = a[1], z = a[2], + qx = q[0], qy = q[1], qz = q[2], qw = q[3], + + // calculate quat * vec + ix = qw * x + qy * z - qz * y, + iy = qw * y + qz * x - qx * z, + iz = qw * z + qx * y - qy * x, + iw = -qx * x - qy * y - qz * z; + + // calculate result * inverse quat + out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy; + out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz; + out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx; + return out; +}; + +/** + * Perform some operation over an array of vec4s. + * + * @param {Array} a the array of vectors to iterate over + * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed + * @param {Number} offset Number of elements to skip at the beginning of the array + * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array + * @param {Function} fn Function to call for each vector in the array + * @param {Object} [arg] additional argument to pass to fn + * @returns {Array} a + * @function + */ +vec4.forEach = (function() { + var vec = vec4.create(); + + return function(a, stride, offset, count, fn, arg) { + var i, l; + if(!stride) { + stride = 4; + } + + if(!offset) { + offset = 0; + } + + if(count) { + l = Math.min((count * stride) + offset, a.length); + } else { + l = a.length; + } + + for(i = offset; i < l; i += stride) { + vec[0] = a[i]; vec[1] = a[i+1]; vec[2] = a[i+2]; vec[3] = a[i+3]; + fn(vec, vec, arg); + a[i] = vec[0]; a[i+1] = vec[1]; a[i+2] = vec[2]; a[i+3] = vec[3]; + } + + return a; + }; +})(); + +/** + * Returns a string representation of a vector + * + * @param {vec4} vec vector to represent as a string + * @returns {String} string representation of the vector + */ +vec4.str = function (a) { + return 'vec4(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ')'; +}; + +if(typeof(exports) !== 'undefined') { + exports.vec4 = vec4; +} +; +/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + +/** + * @class 2x2 Matrix + * @name mat2 + */ + +var mat2 = {}; + +/** + * Creates a new identity mat2 + * + * @returns {mat2} a new 2x2 matrix + */ +mat2.create = function() { + var out = new GLMAT_ARRAY_TYPE(4); + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 1; + return out; +}; + +/** + * Creates a new mat2 initialized with values from an existing matrix + * + * @param {mat2} a matrix to clone + * @returns {mat2} a new 2x2 matrix + */ +mat2.clone = function(a) { + var out = new GLMAT_ARRAY_TYPE(4); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + return out; +}; + +/** + * Copy the values from one mat2 to another + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the source matrix + * @returns {mat2} out + */ +mat2.copy = function(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + return out; +}; + +/** + * Set a mat2 to the identity matrix + * + * @param {mat2} out the receiving matrix + * @returns {mat2} out + */ +mat2.identity = function(out) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 1; + return out; +}; + +/** + * Transpose the values of a mat2 + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the source matrix + * @returns {mat2} out + */ +mat2.transpose = function(out, a) { + // If we are transposing ourselves we can skip a few steps but have to cache some values + if (out === a) { + var a1 = a[1]; + out[1] = a[2]; + out[2] = a1; + } else { + out[0] = a[0]; + out[1] = a[2]; + out[2] = a[1]; + out[3] = a[3]; + } + + return out; +}; + +/** + * Inverts a mat2 + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the source matrix + * @returns {mat2} out + */ +mat2.invert = function(out, a) { + var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], + + // Calculate the determinant + det = a0 * a3 - a2 * a1; + + if (!det) { + return null; + } + det = 1.0 / det; + + out[0] = a3 * det; + out[1] = -a1 * det; + out[2] = -a2 * det; + out[3] = a0 * det; + + return out; +}; + +/** + * Calculates the adjugate of a mat2 + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the source matrix + * @returns {mat2} out + */ +mat2.adjoint = function(out, a) { + // Caching this value is nessecary if out == a + var a0 = a[0]; + out[0] = a[3]; + out[1] = -a[1]; + out[2] = -a[2]; + out[3] = a0; + + return out; +}; + +/** + * Calculates the determinant of a mat2 + * + * @param {mat2} a the source matrix + * @returns {Number} determinant of a + */ +mat2.determinant = function (a) { + return a[0] * a[3] - a[2] * a[1]; +}; + +/** + * Multiplies two mat2's + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @returns {mat2} out + */ +mat2.multiply = function (out, a, b) { + var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3]; + var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3]; + out[0] = a0 * b0 + a2 * b1; + out[1] = a1 * b0 + a3 * b1; + out[2] = a0 * b2 + a2 * b3; + out[3] = a1 * b2 + a3 * b3; + return out; +}; + +/** + * Alias for {@link mat2.multiply} + * @function + */ +mat2.mul = mat2.multiply; + +/** + * Rotates a mat2 by the given angle + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat2} out + */ +mat2.rotate = function (out, a, rad) { + var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], + s = Math.sin(rad), + c = Math.cos(rad); + out[0] = a0 * c + a2 * s; + out[1] = a1 * c + a3 * s; + out[2] = a0 * -s + a2 * c; + out[3] = a1 * -s + a3 * c; + return out; +}; + +/** + * Scales the mat2 by the dimensions in the given vec2 + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the matrix to rotate + * @param {vec2} v the vec2 to scale the matrix by + * @returns {mat2} out + **/ +mat2.scale = function(out, a, v) { + var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], + v0 = v[0], v1 = v[1]; + out[0] = a0 * v0; + out[1] = a1 * v0; + out[2] = a2 * v1; + out[3] = a3 * v1; + return out; +}; + +/** + * Returns a string representation of a mat2 + * + * @param {mat2} mat matrix to represent as a string + * @returns {String} string representation of the matrix + */ +mat2.str = function (a) { + return 'mat2(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ')'; +}; + +/** + * Returns Frobenius norm of a mat2 + * + * @param {mat2} a the matrix to calculate Frobenius norm of + * @returns {Number} Frobenius norm + */ +mat2.frob = function (a) { + return(Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2) + Math.pow(a[2], 2) + Math.pow(a[3], 2))) +}; + +/** + * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix + * @param {mat2} L the lower triangular matrix + * @param {mat2} D the diagonal matrix + * @param {mat2} U the upper triangular matrix + * @param {mat2} a the input matrix to factorize + */ + +mat2.LDU = function (L, D, U, a) { + L[2] = a[2]/a[0]; + U[0] = a[0]; + U[1] = a[1]; + U[3] = a[3] - L[2] * U[1]; + return [L, D, U]; +}; + +if(typeof(exports) !== 'undefined') { + exports.mat2 = mat2; +} +; +/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + +/** + * @class 2x3 Matrix + * @name mat2d + * + * @description + * A mat2d contains six elements defined as: + *
+ * [a, c, tx,
+ *  b, d, ty]
+ * 
+ * This is a short form for the 3x3 matrix: + *
+ * [a, c, tx,
+ *  b, d, ty,
+ *  0, 0, 1]
+ * 
+ * The last row is ignored so the array is shorter and operations are faster. + */ + +var mat2d = {}; + +/** + * Creates a new identity mat2d + * + * @returns {mat2d} a new 2x3 matrix + */ +mat2d.create = function() { + var out = new GLMAT_ARRAY_TYPE(6); + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 1; + out[4] = 0; + out[5] = 0; + return out; +}; + +/** + * Creates a new mat2d initialized with values from an existing matrix + * + * @param {mat2d} a matrix to clone + * @returns {mat2d} a new 2x3 matrix + */ +mat2d.clone = function(a) { + var out = new GLMAT_ARRAY_TYPE(6); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + return out; +}; + +/** + * Copy the values from one mat2d to another + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the source matrix + * @returns {mat2d} out + */ +mat2d.copy = function(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + return out; +}; + +/** + * Set a mat2d to the identity matrix + * + * @param {mat2d} out the receiving matrix + * @returns {mat2d} out + */ +mat2d.identity = function(out) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 1; + out[4] = 0; + out[5] = 0; + return out; +}; + +/** + * Inverts a mat2d + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the source matrix + * @returns {mat2d} out + */ +mat2d.invert = function(out, a) { + var aa = a[0], ab = a[1], ac = a[2], ad = a[3], + atx = a[4], aty = a[5]; + + var det = aa * ad - ab * ac; + if(!det){ + return null; + } + det = 1.0 / det; + + out[0] = ad * det; + out[1] = -ab * det; + out[2] = -ac * det; + out[3] = aa * det; + out[4] = (ac * aty - ad * atx) * det; + out[5] = (ab * atx - aa * aty) * det; + return out; +}; + +/** + * Calculates the determinant of a mat2d + * + * @param {mat2d} a the source matrix + * @returns {Number} determinant of a + */ +mat2d.determinant = function (a) { + return a[0] * a[3] - a[1] * a[2]; +}; + +/** + * Multiplies two mat2d's + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @returns {mat2d} out + */ +mat2d.multiply = function (out, a, b) { + var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], a4 = a[4], a5 = a[5], + b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3], b4 = b[4], b5 = b[5]; + out[0] = a0 * b0 + a2 * b1; + out[1] = a1 * b0 + a3 * b1; + out[2] = a0 * b2 + a2 * b3; + out[3] = a1 * b2 + a3 * b3; + out[4] = a0 * b4 + a2 * b5 + a4; + out[5] = a1 * b4 + a3 * b5 + a5; + return out; +}; + +/** + * Alias for {@link mat2d.multiply} + * @function + */ +mat2d.mul = mat2d.multiply; + + +/** + * Rotates a mat2d by the given angle + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat2d} out + */ +mat2d.rotate = function (out, a, rad) { + var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], a4 = a[4], a5 = a[5], + s = Math.sin(rad), + c = Math.cos(rad); + out[0] = a0 * c + a2 * s; + out[1] = a1 * c + a3 * s; + out[2] = a0 * -s + a2 * c; + out[3] = a1 * -s + a3 * c; + out[4] = a4; + out[5] = a5; + return out; +}; + +/** + * Scales the mat2d by the dimensions in the given vec2 + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the matrix to translate + * @param {vec2} v the vec2 to scale the matrix by + * @returns {mat2d} out + **/ +mat2d.scale = function(out, a, v) { + var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], a4 = a[4], a5 = a[5], + v0 = v[0], v1 = v[1]; + out[0] = a0 * v0; + out[1] = a1 * v0; + out[2] = a2 * v1; + out[3] = a3 * v1; + out[4] = a4; + out[5] = a5; + return out; +}; + +/** + * Translates the mat2d by the dimensions in the given vec2 + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the matrix to translate + * @param {vec2} v the vec2 to translate the matrix by + * @returns {mat2d} out + **/ +mat2d.translate = function(out, a, v) { + var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], a4 = a[4], a5 = a[5], + v0 = v[0], v1 = v[1]; + out[0] = a0; + out[1] = a1; + out[2] = a2; + out[3] = a3; + out[4] = a0 * v0 + a2 * v1 + a4; + out[5] = a1 * v0 + a3 * v1 + a5; + return out; +}; + +/** + * Returns a string representation of a mat2d + * + * @param {mat2d} a matrix to represent as a string + * @returns {String} string representation of the matrix + */ +mat2d.str = function (a) { + return 'mat2d(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + + a[3] + ', ' + a[4] + ', ' + a[5] + ')'; +}; + +/** + * Returns Frobenius norm of a mat2d + * + * @param {mat2d} a the matrix to calculate Frobenius norm of + * @returns {Number} Frobenius norm + */ +mat2d.frob = function (a) { + return(Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2) + Math.pow(a[2], 2) + Math.pow(a[3], 2) + Math.pow(a[4], 2) + Math.pow(a[5], 2) + 1)) +}; + +if(typeof(exports) !== 'undefined') { + exports.mat2d = mat2d; +} +; +/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + +/** + * @class 3x3 Matrix + * @name mat3 + */ + +var mat3 = {}; + +/** + * Creates a new identity mat3 + * + * @returns {mat3} a new 3x3 matrix + */ +mat3.create = function() { + var out = new GLMAT_ARRAY_TYPE(9); + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 1; + out[5] = 0; + out[6] = 0; + out[7] = 0; + out[8] = 1; + return out; +}; + +/** + * Copies the upper-left 3x3 values into the given mat3. + * + * @param {mat3} out the receiving 3x3 matrix + * @param {mat4} a the source 4x4 matrix + * @returns {mat3} out + */ +mat3.fromMat4 = function(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[4]; + out[4] = a[5]; + out[5] = a[6]; + out[6] = a[8]; + out[7] = a[9]; + out[8] = a[10]; + return out; +}; + +/** + * Creates a new mat3 initialized with values from an existing matrix + * + * @param {mat3} a matrix to clone + * @returns {mat3} a new 3x3 matrix + */ +mat3.clone = function(a) { + var out = new GLMAT_ARRAY_TYPE(9); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + return out; +}; + +/** + * Copy the values from one mat3 to another + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the source matrix + * @returns {mat3} out + */ +mat3.copy = function(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + return out; +}; + +/** + * Set a mat3 to the identity matrix + * + * @param {mat3} out the receiving matrix + * @returns {mat3} out + */ +mat3.identity = function(out) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 1; + out[5] = 0; + out[6] = 0; + out[7] = 0; + out[8] = 1; + return out; +}; + +/** + * Transpose the values of a mat3 + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the source matrix + * @returns {mat3} out + */ +mat3.transpose = function(out, a) { + // If we are transposing ourselves we can skip a few steps but have to cache some values + if (out === a) { + var a01 = a[1], a02 = a[2], a12 = a[5]; + out[1] = a[3]; + out[2] = a[6]; + out[3] = a01; + out[5] = a[7]; + out[6] = a02; + out[7] = a12; + } else { + out[0] = a[0]; + out[1] = a[3]; + out[2] = a[6]; + out[3] = a[1]; + out[4] = a[4]; + out[5] = a[7]; + out[6] = a[2]; + out[7] = a[5]; + out[8] = a[8]; + } + + return out; +}; + +/** + * Inverts a mat3 + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the source matrix + * @returns {mat3} out + */ +mat3.invert = function(out, a) { + var a00 = a[0], a01 = a[1], a02 = a[2], + a10 = a[3], a11 = a[4], a12 = a[5], + a20 = a[6], a21 = a[7], a22 = a[8], + + b01 = a22 * a11 - a12 * a21, + b11 = -a22 * a10 + a12 * a20, + b21 = a21 * a10 - a11 * a20, + + // Calculate the determinant + det = a00 * b01 + a01 * b11 + a02 * b21; + + if (!det) { + return null; + } + det = 1.0 / det; + + out[0] = b01 * det; + out[1] = (-a22 * a01 + a02 * a21) * det; + out[2] = (a12 * a01 - a02 * a11) * det; + out[3] = b11 * det; + out[4] = (a22 * a00 - a02 * a20) * det; + out[5] = (-a12 * a00 + a02 * a10) * det; + out[6] = b21 * det; + out[7] = (-a21 * a00 + a01 * a20) * det; + out[8] = (a11 * a00 - a01 * a10) * det; + return out; +}; + +/** + * Calculates the adjugate of a mat3 + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the source matrix + * @returns {mat3} out + */ +mat3.adjoint = function(out, a) { + var a00 = a[0], a01 = a[1], a02 = a[2], + a10 = a[3], a11 = a[4], a12 = a[5], + a20 = a[6], a21 = a[7], a22 = a[8]; + + out[0] = (a11 * a22 - a12 * a21); + out[1] = (a02 * a21 - a01 * a22); + out[2] = (a01 * a12 - a02 * a11); + out[3] = (a12 * a20 - a10 * a22); + out[4] = (a00 * a22 - a02 * a20); + out[5] = (a02 * a10 - a00 * a12); + out[6] = (a10 * a21 - a11 * a20); + out[7] = (a01 * a20 - a00 * a21); + out[8] = (a00 * a11 - a01 * a10); + return out; +}; + +/** + * Calculates the determinant of a mat3 + * + * @param {mat3} a the source matrix + * @returns {Number} determinant of a + */ +mat3.determinant = function (a) { + var a00 = a[0], a01 = a[1], a02 = a[2], + a10 = a[3], a11 = a[4], a12 = a[5], + a20 = a[6], a21 = a[7], a22 = a[8]; + + return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20); +}; + +/** + * Multiplies two mat3's + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @returns {mat3} out + */ +mat3.multiply = function (out, a, b) { + var a00 = a[0], a01 = a[1], a02 = a[2], + a10 = a[3], a11 = a[4], a12 = a[5], + a20 = a[6], a21 = a[7], a22 = a[8], + + b00 = b[0], b01 = b[1], b02 = b[2], + b10 = b[3], b11 = b[4], b12 = b[5], + b20 = b[6], b21 = b[7], b22 = b[8]; + + out[0] = b00 * a00 + b01 * a10 + b02 * a20; + out[1] = b00 * a01 + b01 * a11 + b02 * a21; + out[2] = b00 * a02 + b01 * a12 + b02 * a22; + + out[3] = b10 * a00 + b11 * a10 + b12 * a20; + out[4] = b10 * a01 + b11 * a11 + b12 * a21; + out[5] = b10 * a02 + b11 * a12 + b12 * a22; + + out[6] = b20 * a00 + b21 * a10 + b22 * a20; + out[7] = b20 * a01 + b21 * a11 + b22 * a21; + out[8] = b20 * a02 + b21 * a12 + b22 * a22; + return out; +}; + +/** + * Alias for {@link mat3.multiply} + * @function + */ +mat3.mul = mat3.multiply; + +/** + * Translate a mat3 by the given vector + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the matrix to translate + * @param {vec2} v vector to translate by + * @returns {mat3} out + */ +mat3.translate = function(out, a, v) { + var a00 = a[0], a01 = a[1], a02 = a[2], + a10 = a[3], a11 = a[4], a12 = a[5], + a20 = a[6], a21 = a[7], a22 = a[8], + x = v[0], y = v[1]; + + out[0] = a00; + out[1] = a01; + out[2] = a02; + + out[3] = a10; + out[4] = a11; + out[5] = a12; + + out[6] = x * a00 + y * a10 + a20; + out[7] = x * a01 + y * a11 + a21; + out[8] = x * a02 + y * a12 + a22; + return out; +}; + +/** + * Rotates a mat3 by the given angle + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat3} out + */ +mat3.rotate = function (out, a, rad) { + var a00 = a[0], a01 = a[1], a02 = a[2], + a10 = a[3], a11 = a[4], a12 = a[5], + a20 = a[6], a21 = a[7], a22 = a[8], + + s = Math.sin(rad), + c = Math.cos(rad); + + out[0] = c * a00 + s * a10; + out[1] = c * a01 + s * a11; + out[2] = c * a02 + s * a12; + + out[3] = c * a10 - s * a00; + out[4] = c * a11 - s * a01; + out[5] = c * a12 - s * a02; + + out[6] = a20; + out[7] = a21; + out[8] = a22; + return out; +}; + +/** + * Scales the mat3 by the dimensions in the given vec2 + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the matrix to rotate + * @param {vec2} v the vec2 to scale the matrix by + * @returns {mat3} out + **/ +mat3.scale = function(out, a, v) { + var x = v[0], y = v[1]; + + out[0] = x * a[0]; + out[1] = x * a[1]; + out[2] = x * a[2]; + + out[3] = y * a[3]; + out[4] = y * a[4]; + out[5] = y * a[5]; + + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + return out; +}; + +/** + * Copies the values from a mat2d into a mat3 + * + * @param {mat3} out the receiving matrix + * @param {mat2d} a the matrix to copy + * @returns {mat3} out + **/ +mat3.fromMat2d = function(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = 0; + + out[3] = a[2]; + out[4] = a[3]; + out[5] = 0; + + out[6] = a[4]; + out[7] = a[5]; + out[8] = 1; + return out; +}; + +/** +* Calculates a 3x3 matrix from the given quaternion +* +* @param {mat3} out mat3 receiving operation result +* @param {quat} q Quaternion to create matrix from +* +* @returns {mat3} out +*/ +mat3.fromQuat = function (out, q) { + var x = q[0], y = q[1], z = q[2], w = q[3], + x2 = x + x, + y2 = y + y, + z2 = z + z, + + xx = x * x2, + yx = y * x2, + yy = y * y2, + zx = z * x2, + zy = z * y2, + zz = z * z2, + wx = w * x2, + wy = w * y2, + wz = w * z2; + + out[0] = 1 - yy - zz; + out[3] = yx - wz; + out[6] = zx + wy; + + out[1] = yx + wz; + out[4] = 1 - xx - zz; + out[7] = zy - wx; + + out[2] = zx - wy; + out[5] = zy + wx; + out[8] = 1 - xx - yy; + + return out; +}; + +/** +* Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix +* +* @param {mat3} out mat3 receiving operation result +* @param {mat4} a Mat4 to derive the normal matrix from +* +* @returns {mat3} out +*/ +mat3.normalFromMat4 = function (out, a) { + var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], + a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], + a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], + a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], + + b00 = a00 * a11 - a01 * a10, + b01 = a00 * a12 - a02 * a10, + b02 = a00 * a13 - a03 * a10, + b03 = a01 * a12 - a02 * a11, + b04 = a01 * a13 - a03 * a11, + b05 = a02 * a13 - a03 * a12, + b06 = a20 * a31 - a21 * a30, + b07 = a20 * a32 - a22 * a30, + b08 = a20 * a33 - a23 * a30, + b09 = a21 * a32 - a22 * a31, + b10 = a21 * a33 - a23 * a31, + b11 = a22 * a33 - a23 * a32, + + // Calculate the determinant + det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; + + if (!det) { + return null; + } + det = 1.0 / det; + + out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; + out[1] = (a12 * b08 - a10 * b11 - a13 * b07) * det; + out[2] = (a10 * b10 - a11 * b08 + a13 * b06) * det; + + out[3] = (a02 * b10 - a01 * b11 - a03 * b09) * det; + out[4] = (a00 * b11 - a02 * b08 + a03 * b07) * det; + out[5] = (a01 * b08 - a00 * b10 - a03 * b06) * det; + + out[6] = (a31 * b05 - a32 * b04 + a33 * b03) * det; + out[7] = (a32 * b02 - a30 * b05 - a33 * b01) * det; + out[8] = (a30 * b04 - a31 * b02 + a33 * b00) * det; + + return out; +}; + +/** + * Returns a string representation of a mat3 + * + * @param {mat3} mat matrix to represent as a string + * @returns {String} string representation of the matrix + */ +mat3.str = function (a) { + return 'mat3(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + + a[3] + ', ' + a[4] + ', ' + a[5] + ', ' + + a[6] + ', ' + a[7] + ', ' + a[8] + ')'; +}; + +/** + * Returns Frobenius norm of a mat3 + * + * @param {mat3} a the matrix to calculate Frobenius norm of + * @returns {Number} Frobenius norm + */ +mat3.frob = function (a) { + return(Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2) + Math.pow(a[2], 2) + Math.pow(a[3], 2) + Math.pow(a[4], 2) + Math.pow(a[5], 2) + Math.pow(a[6], 2) + Math.pow(a[7], 2) + Math.pow(a[8], 2))) +}; + + +if(typeof(exports) !== 'undefined') { + exports.mat3 = mat3; +} +; +/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + +/** + * @class 4x4 Matrix + * @name mat4 + */ + +var mat4 = {}; + +/** + * Creates a new identity mat4 + * + * @returns {mat4} a new 4x4 matrix + */ +mat4.create = function() { + var out = new GLMAT_ARRAY_TYPE(16); + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = 1; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 1; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +}; + +/** + * Creates a new mat4 initialized with values from an existing matrix + * + * @param {mat4} a matrix to clone + * @returns {mat4} a new 4x4 matrix + */ +mat4.clone = function(a) { + var out = new GLMAT_ARRAY_TYPE(16); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + return out; +}; + +/** + * Copy the values from one mat4 to another + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the source matrix + * @returns {mat4} out + */ +mat4.copy = function(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + return out; +}; + +/** + * Set a mat4 to the identity matrix + * + * @param {mat4} out the receiving matrix + * @returns {mat4} out + */ +mat4.identity = function(out) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = 1; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 1; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +}; + +/** + * Transpose the values of a mat4 + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the source matrix + * @returns {mat4} out + */ +mat4.transpose = function(out, a) { + // If we are transposing ourselves we can skip a few steps but have to cache some values + if (out === a) { + var a01 = a[1], a02 = a[2], a03 = a[3], + a12 = a[6], a13 = a[7], + a23 = a[11]; + + out[1] = a[4]; + out[2] = a[8]; + out[3] = a[12]; + out[4] = a01; + out[6] = a[9]; + out[7] = a[13]; + out[8] = a02; + out[9] = a12; + out[11] = a[14]; + out[12] = a03; + out[13] = a13; + out[14] = a23; + } else { + out[0] = a[0]; + out[1] = a[4]; + out[2] = a[8]; + out[3] = a[12]; + out[4] = a[1]; + out[5] = a[5]; + out[6] = a[9]; + out[7] = a[13]; + out[8] = a[2]; + out[9] = a[6]; + out[10] = a[10]; + out[11] = a[14]; + out[12] = a[3]; + out[13] = a[7]; + out[14] = a[11]; + out[15] = a[15]; + } + + return out; +}; + +/** + * Inverts a mat4 + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the source matrix + * @returns {mat4} out + */ +mat4.invert = function(out, a) { + var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], + a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], + a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], + a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], + + b00 = a00 * a11 - a01 * a10, + b01 = a00 * a12 - a02 * a10, + b02 = a00 * a13 - a03 * a10, + b03 = a01 * a12 - a02 * a11, + b04 = a01 * a13 - a03 * a11, + b05 = a02 * a13 - a03 * a12, + b06 = a20 * a31 - a21 * a30, + b07 = a20 * a32 - a22 * a30, + b08 = a20 * a33 - a23 * a30, + b09 = a21 * a32 - a22 * a31, + b10 = a21 * a33 - a23 * a31, + b11 = a22 * a33 - a23 * a32, + + // Calculate the determinant + det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; + + if (!det) { + return null; + } + det = 1.0 / det; + + out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; + out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; + out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; + out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det; + out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; + out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; + out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; + out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det; + out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; + out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; + out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; + out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det; + out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; + out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; + out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; + out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det; + + return out; +}; + +/** + * Calculates the adjugate of a mat4 + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the source matrix + * @returns {mat4} out + */ +mat4.adjoint = function(out, a) { + var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], + a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], + a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], + a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15]; + + out[0] = (a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22)); + out[1] = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22)); + out[2] = (a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12)); + out[3] = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12)); + out[4] = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22)); + out[5] = (a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22)); + out[6] = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12)); + out[7] = (a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12)); + out[8] = (a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21)); + out[9] = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21)); + out[10] = (a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11)); + out[11] = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11)); + out[12] = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21)); + out[13] = (a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21)); + out[14] = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11)); + out[15] = (a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11)); + return out; +}; + +/** + * Calculates the determinant of a mat4 + * + * @param {mat4} a the source matrix + * @returns {Number} determinant of a + */ +mat4.determinant = function (a) { + var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], + a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], + a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], + a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], + + b00 = a00 * a11 - a01 * a10, + b01 = a00 * a12 - a02 * a10, + b02 = a00 * a13 - a03 * a10, + b03 = a01 * a12 - a02 * a11, + b04 = a01 * a13 - a03 * a11, + b05 = a02 * a13 - a03 * a12, + b06 = a20 * a31 - a21 * a30, + b07 = a20 * a32 - a22 * a30, + b08 = a20 * a33 - a23 * a30, + b09 = a21 * a32 - a22 * a31, + b10 = a21 * a33 - a23 * a31, + b11 = a22 * a33 - a23 * a32; + + // Calculate the determinant + return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; +}; + +/** + * Multiplies two mat4's + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @returns {mat4} out + */ +mat4.multiply = function (out, a, b) { + var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], + a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], + a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], + a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15]; + + // Cache only the current line of the second matrix + var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3]; + out[0] = b0*a00 + b1*a10 + b2*a20 + b3*a30; + out[1] = b0*a01 + b1*a11 + b2*a21 + b3*a31; + out[2] = b0*a02 + b1*a12 + b2*a22 + b3*a32; + out[3] = b0*a03 + b1*a13 + b2*a23 + b3*a33; + + b0 = b[4]; b1 = b[5]; b2 = b[6]; b3 = b[7]; + out[4] = b0*a00 + b1*a10 + b2*a20 + b3*a30; + out[5] = b0*a01 + b1*a11 + b2*a21 + b3*a31; + out[6] = b0*a02 + b1*a12 + b2*a22 + b3*a32; + out[7] = b0*a03 + b1*a13 + b2*a23 + b3*a33; + + b0 = b[8]; b1 = b[9]; b2 = b[10]; b3 = b[11]; + out[8] = b0*a00 + b1*a10 + b2*a20 + b3*a30; + out[9] = b0*a01 + b1*a11 + b2*a21 + b3*a31; + out[10] = b0*a02 + b1*a12 + b2*a22 + b3*a32; + out[11] = b0*a03 + b1*a13 + b2*a23 + b3*a33; + + b0 = b[12]; b1 = b[13]; b2 = b[14]; b3 = b[15]; + out[12] = b0*a00 + b1*a10 + b2*a20 + b3*a30; + out[13] = b0*a01 + b1*a11 + b2*a21 + b3*a31; + out[14] = b0*a02 + b1*a12 + b2*a22 + b3*a32; + out[15] = b0*a03 + b1*a13 + b2*a23 + b3*a33; + return out; +}; + +/** + * Alias for {@link mat4.multiply} + * @function + */ +mat4.mul = mat4.multiply; + +/** + * Translate a mat4 by the given vector + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to translate + * @param {vec3} v vector to translate by + * @returns {mat4} out + */ +mat4.translate = function (out, a, v) { + var x = v[0], y = v[1], z = v[2], + a00, a01, a02, a03, + a10, a11, a12, a13, + a20, a21, a22, a23; + + if (a === out) { + out[12] = a[0] * x + a[4] * y + a[8] * z + a[12]; + out[13] = a[1] * x + a[5] * y + a[9] * z + a[13]; + out[14] = a[2] * x + a[6] * y + a[10] * z + a[14]; + out[15] = a[3] * x + a[7] * y + a[11] * z + a[15]; + } else { + a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3]; + a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7]; + a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11]; + + out[0] = a00; out[1] = a01; out[2] = a02; out[3] = a03; + out[4] = a10; out[5] = a11; out[6] = a12; out[7] = a13; + out[8] = a20; out[9] = a21; out[10] = a22; out[11] = a23; + + out[12] = a00 * x + a10 * y + a20 * z + a[12]; + out[13] = a01 * x + a11 * y + a21 * z + a[13]; + out[14] = a02 * x + a12 * y + a22 * z + a[14]; + out[15] = a03 * x + a13 * y + a23 * z + a[15]; + } + + return out; +}; + +/** + * Scales the mat4 by the dimensions in the given vec3 + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to scale + * @param {vec3} v the vec3 to scale the matrix by + * @returns {mat4} out + **/ +mat4.scale = function(out, a, v) { + var x = v[0], y = v[1], z = v[2]; + + out[0] = a[0] * x; + out[1] = a[1] * x; + out[2] = a[2] * x; + out[3] = a[3] * x; + out[4] = a[4] * y; + out[5] = a[5] * y; + out[6] = a[6] * y; + out[7] = a[7] * y; + out[8] = a[8] * z; + out[9] = a[9] * z; + out[10] = a[10] * z; + out[11] = a[11] * z; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + return out; +}; + +/** + * Rotates a mat4 by the given angle + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @param {vec3} axis the axis to rotate around + * @returns {mat4} out + */ +mat4.rotate = function (out, a, rad, axis) { + var x = axis[0], y = axis[1], z = axis[2], + len = Math.sqrt(x * x + y * y + z * z), + s, c, t, + a00, a01, a02, a03, + a10, a11, a12, a13, + a20, a21, a22, a23, + b00, b01, b02, + b10, b11, b12, + b20, b21, b22; + + if (Math.abs(len) < GLMAT_EPSILON) { return null; } + + len = 1 / len; + x *= len; + y *= len; + z *= len; + + s = Math.sin(rad); + c = Math.cos(rad); + t = 1 - c; + + a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3]; + a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7]; + a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11]; + + // Construct the elements of the rotation matrix + b00 = x * x * t + c; b01 = y * x * t + z * s; b02 = z * x * t - y * s; + b10 = x * y * t - z * s; b11 = y * y * t + c; b12 = z * y * t + x * s; + b20 = x * z * t + y * s; b21 = y * z * t - x * s; b22 = z * z * t + c; + + // Perform rotation-specific matrix multiplication + out[0] = a00 * b00 + a10 * b01 + a20 * b02; + out[1] = a01 * b00 + a11 * b01 + a21 * b02; + out[2] = a02 * b00 + a12 * b01 + a22 * b02; + out[3] = a03 * b00 + a13 * b01 + a23 * b02; + out[4] = a00 * b10 + a10 * b11 + a20 * b12; + out[5] = a01 * b10 + a11 * b11 + a21 * b12; + out[6] = a02 * b10 + a12 * b11 + a22 * b12; + out[7] = a03 * b10 + a13 * b11 + a23 * b12; + out[8] = a00 * b20 + a10 * b21 + a20 * b22; + out[9] = a01 * b20 + a11 * b21 + a21 * b22; + out[10] = a02 * b20 + a12 * b21 + a22 * b22; + out[11] = a03 * b20 + a13 * b21 + a23 * b22; + + if (a !== out) { // If the source and destination differ, copy the unchanged last row + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } + return out; +}; + +/** + * Rotates a matrix by the given angle around the X axis + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ +mat4.rotateX = function (out, a, rad) { + var s = Math.sin(rad), + c = Math.cos(rad), + a10 = a[4], + a11 = a[5], + a12 = a[6], + a13 = a[7], + a20 = a[8], + a21 = a[9], + a22 = a[10], + a23 = a[11]; + + if (a !== out) { // If the source and destination differ, copy the unchanged rows + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } + + // Perform axis-specific matrix multiplication + out[4] = a10 * c + a20 * s; + out[5] = a11 * c + a21 * s; + out[6] = a12 * c + a22 * s; + out[7] = a13 * c + a23 * s; + out[8] = a20 * c - a10 * s; + out[9] = a21 * c - a11 * s; + out[10] = a22 * c - a12 * s; + out[11] = a23 * c - a13 * s; + return out; +}; + +/** + * Rotates a matrix by the given angle around the Y axis + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ +mat4.rotateY = function (out, a, rad) { + var s = Math.sin(rad), + c = Math.cos(rad), + a00 = a[0], + a01 = a[1], + a02 = a[2], + a03 = a[3], + a20 = a[8], + a21 = a[9], + a22 = a[10], + a23 = a[11]; + + if (a !== out) { // If the source and destination differ, copy the unchanged rows + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } + + // Perform axis-specific matrix multiplication + out[0] = a00 * c - a20 * s; + out[1] = a01 * c - a21 * s; + out[2] = a02 * c - a22 * s; + out[3] = a03 * c - a23 * s; + out[8] = a00 * s + a20 * c; + out[9] = a01 * s + a21 * c; + out[10] = a02 * s + a22 * c; + out[11] = a03 * s + a23 * c; + return out; +}; + +/** + * Rotates a matrix by the given angle around the Z axis + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ +mat4.rotateZ = function (out, a, rad) { + var s = Math.sin(rad), + c = Math.cos(rad), + a00 = a[0], + a01 = a[1], + a02 = a[2], + a03 = a[3], + a10 = a[4], + a11 = a[5], + a12 = a[6], + a13 = a[7]; + + if (a !== out) { // If the source and destination differ, copy the unchanged last row + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } + + // Perform axis-specific matrix multiplication + out[0] = a00 * c + a10 * s; + out[1] = a01 * c + a11 * s; + out[2] = a02 * c + a12 * s; + out[3] = a03 * c + a13 * s; + out[4] = a10 * c - a00 * s; + out[5] = a11 * c - a01 * s; + out[6] = a12 * c - a02 * s; + out[7] = a13 * c - a03 * s; + return out; +}; + +/** + * Creates a matrix from a quaternion rotation and vector translation + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * var quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * + * @param {mat4} out mat4 receiving operation result + * @param {quat4} q Rotation quaternion + * @param {vec3} v Translation vector + * @returns {mat4} out + */ +mat4.fromRotationTranslation = function (out, q, v) { + // Quaternion math + var x = q[0], y = q[1], z = q[2], w = q[3], + x2 = x + x, + y2 = y + y, + z2 = z + z, + + xx = x * x2, + xy = x * y2, + xz = x * z2, + yy = y * y2, + yz = y * z2, + zz = z * z2, + wx = w * x2, + wy = w * y2, + wz = w * z2; + + out[0] = 1 - (yy + zz); + out[1] = xy + wz; + out[2] = xz - wy; + out[3] = 0; + out[4] = xy - wz; + out[5] = 1 - (xx + zz); + out[6] = yz + wx; + out[7] = 0; + out[8] = xz + wy; + out[9] = yz - wx; + out[10] = 1 - (xx + yy); + out[11] = 0; + out[12] = v[0]; + out[13] = v[1]; + out[14] = v[2]; + out[15] = 1; + + return out; +}; + +mat4.fromQuat = function (out, q) { + var x = q[0], y = q[1], z = q[2], w = q[3], + x2 = x + x, + y2 = y + y, + z2 = z + z, + + xx = x * x2, + yx = y * x2, + yy = y * y2, + zx = z * x2, + zy = z * y2, + zz = z * z2, + wx = w * x2, + wy = w * y2, + wz = w * z2; + + out[0] = 1 - yy - zz; + out[1] = yx + wz; + out[2] = zx - wy; + out[3] = 0; + + out[4] = yx - wz; + out[5] = 1 - xx - zz; + out[6] = zy + wx; + out[7] = 0; + + out[8] = zx + wy; + out[9] = zy - wx; + out[10] = 1 - xx - yy; + out[11] = 0; + + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + + return out; +}; + +/** + * Generates a frustum matrix with the given bounds + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {Number} left Left bound of the frustum + * @param {Number} right Right bound of the frustum + * @param {Number} bottom Bottom bound of the frustum + * @param {Number} top Top bound of the frustum + * @param {Number} near Near bound of the frustum + * @param {Number} far Far bound of the frustum + * @returns {mat4} out + */ +mat4.frustum = function (out, left, right, bottom, top, near, far) { + var rl = 1 / (right - left), + tb = 1 / (top - bottom), + nf = 1 / (near - far); + out[0] = (near * 2) * rl; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = (near * 2) * tb; + out[6] = 0; + out[7] = 0; + out[8] = (right + left) * rl; + out[9] = (top + bottom) * tb; + out[10] = (far + near) * nf; + out[11] = -1; + out[12] = 0; + out[13] = 0; + out[14] = (far * near * 2) * nf; + out[15] = 0; + return out; +}; + +/** + * Generates a perspective projection matrix with the given bounds + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {number} fovy Vertical field of view in radians + * @param {number} aspect Aspect ratio. typically viewport width/height + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum + * @returns {mat4} out + */ +mat4.perspective = function (out, fovy, aspect, near, far) { + var f = 1.0 / Math.tan(fovy / 2), + nf = 1 / (near - far); + out[0] = f / aspect; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = f; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = (far + near) * nf; + out[11] = -1; + out[12] = 0; + out[13] = 0; + out[14] = (2 * far * near) * nf; + out[15] = 0; + return out; +}; + +/** + * Generates a orthogonal projection matrix with the given bounds + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {number} left Left bound of the frustum + * @param {number} right Right bound of the frustum + * @param {number} bottom Bottom bound of the frustum + * @param {number} top Top bound of the frustum + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum + * @returns {mat4} out + */ +mat4.ortho = function (out, left, right, bottom, top, near, far) { + var lr = 1 / (left - right), + bt = 1 / (bottom - top), + nf = 1 / (near - far); + out[0] = -2 * lr; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = -2 * bt; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 2 * nf; + out[11] = 0; + out[12] = (left + right) * lr; + out[13] = (top + bottom) * bt; + out[14] = (far + near) * nf; + out[15] = 1; + return out; +}; + +/** + * Generates a look-at matrix with the given eye position, focal point, and up axis + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {vec3} eye Position of the viewer + * @param {vec3} center Point the viewer is looking at + * @param {vec3} up vec3 pointing up + * @returns {mat4} out + */ +mat4.lookAt = function (out, eye, center, up) { + var x0, x1, x2, y0, y1, y2, z0, z1, z2, len, + eyex = eye[0], + eyey = eye[1], + eyez = eye[2], + upx = up[0], + upy = up[1], + upz = up[2], + centerx = center[0], + centery = center[1], + centerz = center[2]; + + if (Math.abs(eyex - centerx) < GLMAT_EPSILON && + Math.abs(eyey - centery) < GLMAT_EPSILON && + Math.abs(eyez - centerz) < GLMAT_EPSILON) { + return mat4.identity(out); + } + + z0 = eyex - centerx; + z1 = eyey - centery; + z2 = eyez - centerz; + + len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2); + z0 *= len; + z1 *= len; + z2 *= len; + + x0 = upy * z2 - upz * z1; + x1 = upz * z0 - upx * z2; + x2 = upx * z1 - upy * z0; + len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2); + if (!len) { + x0 = 0; + x1 = 0; + x2 = 0; + } else { + len = 1 / len; + x0 *= len; + x1 *= len; + x2 *= len; + } + + y0 = z1 * x2 - z2 * x1; + y1 = z2 * x0 - z0 * x2; + y2 = z0 * x1 - z1 * x0; + + len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2); + if (!len) { + y0 = 0; + y1 = 0; + y2 = 0; + } else { + len = 1 / len; + y0 *= len; + y1 *= len; + y2 *= len; + } + + out[0] = x0; + out[1] = y0; + out[2] = z0; + out[3] = 0; + out[4] = x1; + out[5] = y1; + out[6] = z1; + out[7] = 0; + out[8] = x2; + out[9] = y2; + out[10] = z2; + out[11] = 0; + out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez); + out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez); + out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez); + out[15] = 1; + + return out; +}; + +/** + * Returns a string representation of a mat4 + * + * @param {mat4} mat matrix to represent as a string + * @returns {String} string representation of the matrix + */ +mat4.str = function (a) { + return 'mat4(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ', ' + + a[4] + ', ' + a[5] + ', ' + a[6] + ', ' + a[7] + ', ' + + a[8] + ', ' + a[9] + ', ' + a[10] + ', ' + a[11] + ', ' + + a[12] + ', ' + a[13] + ', ' + a[14] + ', ' + a[15] + ')'; +}; + +/** + * Returns Frobenius norm of a mat4 + * + * @param {mat4} a the matrix to calculate Frobenius norm of + * @returns {Number} Frobenius norm + */ +mat4.frob = function (a) { + return(Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2) + Math.pow(a[2], 2) + Math.pow(a[3], 2) + Math.pow(a[4], 2) + Math.pow(a[5], 2) + Math.pow(a[6], 2) + Math.pow(a[7], 2) + Math.pow(a[8], 2) + Math.pow(a[9], 2) + Math.pow(a[10], 2) + Math.pow(a[11], 2) + Math.pow(a[12], 2) + Math.pow(a[13], 2) + Math.pow(a[14], 2) + Math.pow(a[15], 2) )) +}; + + +if(typeof(exports) !== 'undefined') { + exports.mat4 = mat4; +} +; +/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + +/** + * @class Quaternion + * @name quat + */ + +var quat = {}; + +/** + * Creates a new identity quat + * + * @returns {quat} a new quaternion + */ +quat.create = function() { + var out = new GLMAT_ARRAY_TYPE(4); + out[0] = 0; + out[1] = 0; + out[2] = 0; + out[3] = 1; + return out; +}; + +/** + * Sets a quaternion to represent the shortest rotation from one + * vector to another. + * + * Both vectors are assumed to be unit length. + * + * @param {quat} out the receiving quaternion. + * @param {vec3} a the initial vector + * @param {vec3} b the destination vector + * @returns {quat} out + */ +quat.rotationTo = (function() { + var tmpvec3 = vec3.create(); + var xUnitVec3 = vec3.fromValues(1,0,0); + var yUnitVec3 = vec3.fromValues(0,1,0); + + return function(out, a, b) { + var dot = vec3.dot(a, b); + if (dot < -0.999999) { + vec3.cross(tmpvec3, xUnitVec3, a); + if (vec3.length(tmpvec3) < 0.000001) + vec3.cross(tmpvec3, yUnitVec3, a); + vec3.normalize(tmpvec3, tmpvec3); + quat.setAxisAngle(out, tmpvec3, Math.PI); + return out; + } else if (dot > 0.999999) { + out[0] = 0; + out[1] = 0; + out[2] = 0; + out[3] = 1; + return out; + } else { + vec3.cross(tmpvec3, a, b); + out[0] = tmpvec3[0]; + out[1] = tmpvec3[1]; + out[2] = tmpvec3[2]; + out[3] = 1 + dot; + return quat.normalize(out, out); + } + }; +})(); + +/** + * Sets the specified quaternion with values corresponding to the given + * axes. Each axis is a vec3 and is expected to be unit length and + * perpendicular to all other specified axes. + * + * @param {vec3} view the vector representing the viewing direction + * @param {vec3} right the vector representing the local "right" direction + * @param {vec3} up the vector representing the local "up" direction + * @returns {quat} out + */ +quat.setAxes = (function() { + var matr = mat3.create(); + + return function(out, view, right, up) { + matr[0] = right[0]; + matr[3] = right[1]; + matr[6] = right[2]; + + matr[1] = up[0]; + matr[4] = up[1]; + matr[7] = up[2]; + + matr[2] = -view[0]; + matr[5] = -view[1]; + matr[8] = -view[2]; + + return quat.normalize(out, quat.fromMat3(out, matr)); + }; +})(); + +/** + * Creates a new quat initialized with values from an existing quaternion + * + * @param {quat} a quaternion to clone + * @returns {quat} a new quaternion + * @function + */ +quat.clone = vec4.clone; + +/** + * Creates a new quat initialized with the given values + * + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @param {Number} w W component + * @returns {quat} a new quaternion + * @function + */ +quat.fromValues = vec4.fromValues; + +/** + * Copy the values from one quat to another + * + * @param {quat} out the receiving quaternion + * @param {quat} a the source quaternion + * @returns {quat} out + * @function + */ +quat.copy = vec4.copy; + +/** + * Set the components of a quat to the given values + * + * @param {quat} out the receiving quaternion + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @param {Number} w W component + * @returns {quat} out + * @function + */ +quat.set = vec4.set; + +/** + * Set a quat to the identity quaternion + * + * @param {quat} out the receiving quaternion + * @returns {quat} out + */ +quat.identity = function(out) { + out[0] = 0; + out[1] = 0; + out[2] = 0; + out[3] = 1; + return out; +}; + +/** + * Sets a quat from the given angle and rotation axis, + * then returns it. + * + * @param {quat} out the receiving quaternion + * @param {vec3} axis the axis around which to rotate + * @param {Number} rad the angle in radians + * @returns {quat} out + **/ +quat.setAxisAngle = function(out, axis, rad) { + rad = rad * 0.5; + var s = Math.sin(rad); + out[0] = s * axis[0]; + out[1] = s * axis[1]; + out[2] = s * axis[2]; + out[3] = Math.cos(rad); + return out; +}; + +/** + * Adds two quat's + * + * @param {quat} out the receiving quaternion + * @param {quat} a the first operand + * @param {quat} b the second operand + * @returns {quat} out + * @function + */ +quat.add = vec4.add; + +/** + * Multiplies two quat's + * + * @param {quat} out the receiving quaternion + * @param {quat} a the first operand + * @param {quat} b the second operand + * @returns {quat} out + */ +quat.multiply = function(out, a, b) { + var ax = a[0], ay = a[1], az = a[2], aw = a[3], + bx = b[0], by = b[1], bz = b[2], bw = b[3]; + + out[0] = ax * bw + aw * bx + ay * bz - az * by; + out[1] = ay * bw + aw * by + az * bx - ax * bz; + out[2] = az * bw + aw * bz + ax * by - ay * bx; + out[3] = aw * bw - ax * bx - ay * by - az * bz; + return out; +}; + +/** + * Alias for {@link quat.multiply} + * @function + */ +quat.mul = quat.multiply; + +/** + * Scales a quat by a scalar number + * + * @param {quat} out the receiving vector + * @param {quat} a the vector to scale + * @param {Number} b amount to scale the vector by + * @returns {quat} out + * @function + */ +quat.scale = vec4.scale; + +/** + * Rotates a quaternion by the given angle about the X axis + * + * @param {quat} out quat receiving operation result + * @param {quat} a quat to rotate + * @param {number} rad angle (in radians) to rotate + * @returns {quat} out + */ +quat.rotateX = function (out, a, rad) { + rad *= 0.5; + + var ax = a[0], ay = a[1], az = a[2], aw = a[3], + bx = Math.sin(rad), bw = Math.cos(rad); + + out[0] = ax * bw + aw * bx; + out[1] = ay * bw + az * bx; + out[2] = az * bw - ay * bx; + out[3] = aw * bw - ax * bx; + return out; +}; + +/** + * Rotates a quaternion by the given angle about the Y axis + * + * @param {quat} out quat receiving operation result + * @param {quat} a quat to rotate + * @param {number} rad angle (in radians) to rotate + * @returns {quat} out + */ +quat.rotateY = function (out, a, rad) { + rad *= 0.5; + + var ax = a[0], ay = a[1], az = a[2], aw = a[3], + by = Math.sin(rad), bw = Math.cos(rad); + + out[0] = ax * bw - az * by; + out[1] = ay * bw + aw * by; + out[2] = az * bw + ax * by; + out[3] = aw * bw - ay * by; + return out; +}; + +/** + * Rotates a quaternion by the given angle about the Z axis + * + * @param {quat} out quat receiving operation result + * @param {quat} a quat to rotate + * @param {number} rad angle (in radians) to rotate + * @returns {quat} out + */ +quat.rotateZ = function (out, a, rad) { + rad *= 0.5; + + var ax = a[0], ay = a[1], az = a[2], aw = a[3], + bz = Math.sin(rad), bw = Math.cos(rad); + + out[0] = ax * bw + ay * bz; + out[1] = ay * bw - ax * bz; + out[2] = az * bw + aw * bz; + out[3] = aw * bw - az * bz; + return out; +}; + +/** + * Calculates the W component of a quat from the X, Y, and Z components. + * Assumes that quaternion is 1 unit in length. + * Any existing W component will be ignored. + * + * @param {quat} out the receiving quaternion + * @param {quat} a quat to calculate W component of + * @returns {quat} out + */ +quat.calculateW = function (out, a) { + var x = a[0], y = a[1], z = a[2]; + + out[0] = x; + out[1] = y; + out[2] = z; + out[3] = Math.sqrt(Math.abs(1.0 - x * x - y * y - z * z)); + return out; +}; + +/** + * Calculates the dot product of two quat's + * + * @param {quat} a the first operand + * @param {quat} b the second operand + * @returns {Number} dot product of a and b + * @function + */ +quat.dot = vec4.dot; + +/** + * Performs a linear interpolation between two quat's + * + * @param {quat} out the receiving quaternion + * @param {quat} a the first operand + * @param {quat} b the second operand + * @param {Number} t interpolation amount between the two inputs + * @returns {quat} out + * @function + */ +quat.lerp = vec4.lerp; + +/** + * Performs a spherical linear interpolation between two quat + * + * @param {quat} out the receiving quaternion + * @param {quat} a the first operand + * @param {quat} b the second operand + * @param {Number} t interpolation amount between the two inputs + * @returns {quat} out + */ +quat.slerp = function (out, a, b, t) { + // benchmarks: + // http://jsperf.com/quaternion-slerp-implementations + + var ax = a[0], ay = a[1], az = a[2], aw = a[3], + bx = b[0], by = b[1], bz = b[2], bw = b[3]; + + var omega, cosom, sinom, scale0, scale1; + + // calc cosine + cosom = ax * bx + ay * by + az * bz + aw * bw; + // adjust signs (if necessary) + if ( cosom < 0.0 ) { + cosom = -cosom; + bx = - bx; + by = - by; + bz = - bz; + bw = - bw; + } + // calculate coefficients + if ( (1.0 - cosom) > 0.000001 ) { + // standard case (slerp) + omega = Math.acos(cosom); + sinom = Math.sin(omega); + scale0 = Math.sin((1.0 - t) * omega) / sinom; + scale1 = Math.sin(t * omega) / sinom; + } else { + // "from" and "to" quaternions are very close + // ... so we can do a linear interpolation + scale0 = 1.0 - t; + scale1 = t; + } + // calculate final values + out[0] = scale0 * ax + scale1 * bx; + out[1] = scale0 * ay + scale1 * by; + out[2] = scale0 * az + scale1 * bz; + out[3] = scale0 * aw + scale1 * bw; + + return out; +}; + +/** + * Calculates the inverse of a quat + * + * @param {quat} out the receiving quaternion + * @param {quat} a quat to calculate inverse of + * @returns {quat} out + */ +quat.invert = function(out, a) { + var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], + dot = a0*a0 + a1*a1 + a2*a2 + a3*a3, + invDot = dot ? 1.0/dot : 0; + + // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0 + + out[0] = -a0*invDot; + out[1] = -a1*invDot; + out[2] = -a2*invDot; + out[3] = a3*invDot; + return out; +}; + +/** + * Calculates the conjugate of a quat + * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result. + * + * @param {quat} out the receiving quaternion + * @param {quat} a quat to calculate conjugate of + * @returns {quat} out + */ +quat.conjugate = function (out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + out[2] = -a[2]; + out[3] = a[3]; + return out; +}; + +/** + * Calculates the length of a quat + * + * @param {quat} a vector to calculate length of + * @returns {Number} length of a + * @function + */ +quat.length = vec4.length; + +/** + * Alias for {@link quat.length} + * @function + */ +quat.len = quat.length; + +/** + * Calculates the squared length of a quat + * + * @param {quat} a vector to calculate squared length of + * @returns {Number} squared length of a + * @function + */ +quat.squaredLength = vec4.squaredLength; + +/** + * Alias for {@link quat.squaredLength} + * @function + */ +quat.sqrLen = quat.squaredLength; + +/** + * Normalize a quat + * + * @param {quat} out the receiving quaternion + * @param {quat} a quaternion to normalize + * @returns {quat} out + * @function + */ +quat.normalize = vec4.normalize; + +/** + * Creates a quaternion from the given 3x3 rotation matrix. + * + * NOTE: The resultant quaternion is not normalized, so you should be sure + * to renormalize the quaternion yourself where necessary. + * + * @param {quat} out the receiving quaternion + * @param {mat3} m rotation matrix + * @returns {quat} out + * @function + */ +quat.fromMat3 = function(out, m) { + // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes + // article "Quaternion Calculus and Fast Animation". + var fTrace = m[0] + m[4] + m[8]; + var fRoot; + + if ( fTrace > 0.0 ) { + // |w| > 1/2, may as well choose w > 1/2 + fRoot = Math.sqrt(fTrace + 1.0); // 2w + out[3] = 0.5 * fRoot; + fRoot = 0.5/fRoot; // 1/(4w) + out[0] = (m[5]-m[7])*fRoot; + out[1] = (m[6]-m[2])*fRoot; + out[2] = (m[1]-m[3])*fRoot; + } else { + // |w| <= 1/2 + var i = 0; + if ( m[4] > m[0] ) + i = 1; + if ( m[8] > m[i*3+i] ) + i = 2; + var j = (i+1)%3; + var k = (i+2)%3; + + fRoot = Math.sqrt(m[i*3+i]-m[j*3+j]-m[k*3+k] + 1.0); + out[i] = 0.5 * fRoot; + fRoot = 0.5 / fRoot; + out[3] = (m[j*3+k] - m[k*3+j]) * fRoot; + out[j] = (m[j*3+i] + m[i*3+j]) * fRoot; + out[k] = (m[k*3+i] + m[i*3+k]) * fRoot; + } + + return out; +}; + +/** + * Returns a string representation of a quatenion + * + * @param {quat} vec vector to represent as a string + * @returns {String} string representation of the vector + */ +quat.str = function (a) { + return 'quat(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ')'; +}; + +if(typeof(exports) !== 'undefined') { + exports.quat = quat; +} +; + + + + + + + + + + + + + + })(shim.exports); +})(this); diff --git a/code/particles/itemboxShard.js b/code/particles/itemboxShard.js new file mode 100644 index 0000000..e3e4af9 --- /dev/null +++ b/code/particles/itemboxShard.js @@ -0,0 +1,39 @@ +// +// itemboxShard.js +//-------------------- +// by RHY3756547 +// + +window.ItemShard = function(scene, targ, model) { + var t = this; + t.update = update; + t.draw = draw; + + t.time = 0; + t.pos = vec3.clone(targ.pos); + t.vel = vec3.add([], targ.vel, [(Math.random()-0.5)*5, Math.random()*7, (Math.random()-0.5)*5]); + t.dirVel = [(Math.random()-0.5), (Math.random()-0.5), (Math.random()-0.5)]; + t.dir = [Math.random()*2*Math.PI, Math.random()*2*Math.PI, Math.random()*2*Math.PI]; + t.scale = Math.random()+0.5; + t.scale = [t.scale, t.scale, t.scale]; + + function update(scene) { + vec3.add(t.pos, t.pos, t.vel); + vec3.add(t.vel, t.vel, [0, -0.17, 0]); + vec3.add(t.dir, t.dir, t.dirVel); + + if (t.time++ > 30) scene.removeParticle(t); + } + + function draw(view, pMatrix, gl) { + var mat = mat4.translate(mat4.create(), view, t.pos); + + mat4.rotateZ(mat, mat, t.dir[2]); + mat4.rotateY(mat, mat, t.dir[1]); + mat4.rotateX(mat, mat, t.dir[0]); + + mat4.scale(mat, mat, vec3.scale([], t.scale, 16)); + model.draw(mat, pMatrix); + } + +} \ No newline at end of file diff --git a/code/render/nitroAnimator.js b/code/render/nitroAnimator.js new file mode 100644 index 0000000..63c743a --- /dev/null +++ b/code/render/nitroAnimator.js @@ -0,0 +1,244 @@ +// +// nitroAnimator.js +//-------------------- +// Runs nsbca animations and provides matrix stacks that can be used with nitroRender to draw them. +// by RHY3756547 +// +// includes: gl-matrix.js (glMatrix 2.0) +// /formats/* +// + +window.nitroAnimator = function(bmd, bca) { + var t = this; + t.bmd = bmd; + t.bca = bca; + var bmd = bmd; + var bca = bca; + t.setFrame = setFrame; + t.setAnim = setAnim; + t.getLength = getLength; + + var matBufEmpty = new Float32Array(31*16); + var workingMat = mat4.create(); + + var temp = mat4.create(); + var off=0; + var objMats = []; + for (var i=0; i<31; i++) { + matBufEmpty.set(temp, off); + objMats.push(mat4.create()); + off += 16; + } + + var matBuf = new Float32Array(31*16); + var matStack = {built: true, dat: matBuf}; + + function setAnim(b) { + bca = b; + t.bca = b; + } + + function getLength(anim) { + return bca.animData.objectData[anim].frames; + } + + function setFrame(anim, modelind, frame) { + + var b = bca.animData.objectData[anim]; + + var fLow = Math.floor(frame); + var fHigh = Math.ceil(frame); + var iterp = frame%1; + + var model = bmd.modelData.objectData[modelind]; + var fallback = model.objects.objectData; + + for (var i=0; i>4)&15; + var A = rot.a; + var B = rot.b; + + pivot[mode] = (neg&1)?-1:1; + var horiz = mode%3; + var vert = Math.floor(mode/3) + var left = (horiz==0)?1:0; var top = ((vert==0)?1:0)*3; + var right = (horiz==2)?1:2; var btm = ((vert==2)?1:2)*3; + pivot[left+top] = A; + pivot[right+top] = B; + pivot[left+btm] = (neg&2)?-B:B; + pivot[right+btm] = (neg&4)?-A:A; + return pivot; + } else { + return rot.mat; + } + } + + function lerpMat3(m1, m2, p) { //this is probably a dumb idea, but it's not the worst thing i've come up with... + var q = 1-p; + + return [ + m1[0]*q+m2[0]*p, m1[1]*q+m2[1]*p, m1[2]*q+m2[2]*p, + m1[3]*q+m2[3]*p, m1[4]*q+m2[4]*p, m1[5]*q+m2[5]*p, + m1[6]*q+m2[6]*p, m1[7]*q+m2[7]*p, m1[8]*q+m2[8]*p, + ] + } +} \ No newline at end of file diff --git a/code/render/nitroRender.js b/code/render/nitroRender.js new file mode 100644 index 0000000..16c0c6f --- /dev/null +++ b/code/render/nitroRender.js @@ -0,0 +1,741 @@ +// +// nitroRender.js +//-------------------- +// Provides an interface with which NSBMD models can be drawn to a fst canvas. +// by RHY3756547 +// +// includes: gl-matrix.js (glMatrix 2.0) +// /formats/nitro.js --passive requirement from other nitro formats +// /formats/nsbmd.js +// /formats/nsbta.js +// /formats/nsbtx.js +// + +window.nitroRender = new function() { + var gl, frag, vert, nitroShader; + var cVec, color, texCoord, norm; + var vecMode, vecPos, vecNorm, vecTx, vecCol, vecNum, vecMat, curMat; + var texWidth, texHeight, alphaMul = 1; + + this.cullModes = []; + + this.billboardID = 0; //incrememts every time billboards need to be updated. cycles &0xFFFFFF to avoid issues + this.lastMatStack = null; //used to check if we need to send the matStack again. will be used with a versioning system in future. + + this.last = {}; //obj: the last vertex buffers drawn + + var optimiseTriangles = true; //improves draw performance by >10x on most models. + + var modelBuffer; + var shaders = []; + + this.renderDispList = renderDispList; + this.setAlpha = setAlpha; + this.getViewWidth = getViewWidth; + this.getViewHeight = getViewHeight; + + this.flagShadow = false; + + var parameters = { + 0: 0, + 0x10:1, 0x11:0, 0x12:1, 0x13:1, 0x14:1, 0x15:0, 0x16:16, 0x17:12, 0x18:16, 0x19:12, 0x1A:9, 0x1B:3, 0x1C:3, //matrix commands + 0x20:1, 0x21:1, 0x22:1, 0x23:2, 0x24:1, 0x25:1, 0x26:1, 0x27:1, 0x28:1, 0x29:1, 0x2A:1, 0x2B:1, //vertex commands + 0x30:1, 0x31:1, 0x32:1, 0x33:1, 0x34:32, //material param + 0x40:1, 0x41:0, //begin or end vertices + 0x50:1, //swap buffers + 0x60:1, //viewport + 0x70:3, 0x71:2, 0x72:1 //tests + } + + var instructions = {}; + + instructions[0x14] = function(view, off) { //restore to matrix, used constantly for bone transforms + curMat = view.getUint8(off); + } + + instructions[0x20] = function(view, off) { //color + var dat = view.getUint16(off,true); + color[0] = (dat&31)/31; + color[1] = ((dat>>5)&31)/31; + color[2] = ((dat>>10)&31)/31; + } + + instructions[0x21] = function(view, off) { //normal + var dat = view.getUint32(off, true); + norm[0] = tenBitSign(dat); + norm[1] = tenBitSign(dat>>10); + norm[2] = tenBitSign(dat>>20); + } + + instructions[0x22] = function(view, off) { //texcoord + texCoord[0] = (view.getInt16(off, true)/16)/texWidth; + texCoord[1] = (view.getInt16(off+2, true)/16)/texHeight; + } + + instructions[0x23] = function(view, off) { //xyz 16 bit + cVec[0] = view.getInt16(off, true)/4096; + cVec[1] = view.getInt16(off+2, true)/4096; + cVec[2] = view.getInt16(off+4, true)/4096; + pushVector(); + } + + instructions[0x24] = function(view, off) { //xyz 10 bit + var dat = view.getUint32(off, true); + cVec[0] = tenBitSign(dat); + cVec[1] = tenBitSign(dat>>10); + cVec[2] = tenBitSign(dat>>20); + pushVector(); + } + + instructions[0x25] = function(view, off) { //xy 16 bit + cVec[0] = view.getInt16(off, true)/4096; + cVec[1] = view.getInt16(off+2, true)/4096; + pushVector(); + } + + + instructions[0x26] = function(view, off) { //xz 16 bit + cVec[0] = view.getInt16(off, true)/4096; + cVec[2] = view.getInt16(off+2, true)/4096; + pushVector(); + } + + + instructions[0x27] = function(view, off) { //yz 16 bit + cVec[1] = view.getInt16(off, true)/4096; + cVec[2] = view.getInt16(off+2, true)/4096; + pushVector(); + } + + instructions[0x28] = function(view, off) { //xyz 10 bit relative + var dat = view.getUint32(off, true); + cVec[0] += relativeSign(dat); + cVec[1] += relativeSign(dat>>10); + cVec[2] += relativeSign(dat>>20); + pushVector(); + } + + instructions[0x40] = function(view, off) { //begin vtx + var dat = view.getUint32(off, true); + vecMode = dat; + + if (!optimiseTriangles) { + vecPos = []; + vecNorm = []; + vecTx = []; + vecCol = []; + vecMat = []; + } + vecNum = 0; + } + + instructions[0x41] = function(view, off) { //end vtx + if (!optimiseTriangles) pushStrip(); + } + + function setAlpha(alpha) { //for fading specific things out or whatever + alphaMul = alpha; + } + + function getViewWidth(){ + return gl.viewportWidth; + } + + function getViewHeight() { + return gl.viewportHeight; + } + + function pushStrip() { //push the last group of triangles to the buffer. Should do this on matrix change... details fourthcoming + var modes = (optimiseTriangles)?[gl.TRIANGLES, gl.TRIANGLES, gl.TRIANGLES, gl.TRIANGLES]:[gl.TRIANGLES, gl.TRIANGLES, gl.TRIANGLE_STRIP, gl.TRIANGLE_STRIP]; + var pos = gl.createBuffer(); + var col = gl.createBuffer(); + var tx = gl.createBuffer(); + var mat = gl.createBuffer(); + var norm = gl.createBuffer(); + + var posArray = new Float32Array(vecPos); + + gl.bindBuffer(gl.ARRAY_BUFFER, pos); + gl.bufferData(gl.ARRAY_BUFFER, posArray, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, tx); + gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vecTx), gl.STATIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, col); + gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vecCol), gl.STATIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, mat); + gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vecMat), gl.STATIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, norm); + gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vecNorm), gl.STATIC_DRAW); + + modelBuffer.strips.push({ + posArray: posArray, + vPos: pos, + vTx: tx, + vCol: col, + vMat: mat, + vNorm: norm, + verts: vecPos.length/3, + mode: modes[vecMode] + }) + } + + function pushVector() { + if (vecMode == 1 && vecNum%4 == 3) { //quads - special case + vecPos = vecPos.concat(vecPos.slice(vecPos.length-9, vecPos.length-6)).concat(vecPos.slice(vecPos.length-3)); + vecNorm = vecNorm.concat(vecNorm.slice(vecNorm.length-9, vecNorm.length-6)).concat(vecNorm.slice(vecNorm.length-3)); + vecTx = vecTx.concat(vecTx.slice(vecTx.length-6, vecTx.length-4)).concat(vecTx.slice(vecTx.length-2)); + vecCol = vecCol.concat(vecCol.slice(vecCol.length-12, vecCol.length-8)).concat(vecCol.slice(vecCol.length-4)); + vecMat = vecMat.concat(vecMat.slice(vecMat.length-3, vecMat.length-2)).concat(vecMat.slice(vecMat.length-1)); + } + + if (optimiseTriangles && (vecMode > 1) && (vecNum > 2)) { //convert tri strips to individual triangles so we get one buffer per polygon + vecPos = vecPos.concat(vecPos.slice(vecPos.length-6)); + vecNorm = vecNorm.concat(vecNorm.slice(vecNorm.length-6)); + vecTx = vecTx.concat(vecTx.slice(vecTx.length-4)); + vecCol = vecCol.concat(vecCol.slice(vecCol.length-8)); + vecMat = vecMat.concat(vecMat.slice(vecMat.length-2)); + } + + vecNum++; + + vecPos = vecPos.concat(cVec); + vecTx = vecTx.concat(texCoord); + vecCol = vecCol.concat(color); + vecNorm = vecNorm.concat(norm); + vecMat.push(curMat); + + } + + function tenBitSign(val) { + val &= 1023; + if (val & 512) return (val-1024)/64; + else return val/64; + } + function relativeSign(val) { + val &= 1023; + if (val & 512) return (val-1024)/4096; + else return val/4096; + } + + this.init = function(ctx) { + gl = ctx; + this.gl = gl; + + shaders = nitroShaders.compileShaders(gl); + + this.nitroShader = shaders[0]; + this.cullModes = [gl.FRONT_AND_BACK, gl.FRONT, gl.BACK]; + } + + this.prepareShader = function() { + //prepares the shader so no redundant calls have to be made. Should be called upon every program change. + gl.enable(gl.BLEND); + gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); + this.last = {}; + gl.activeTexture(gl.TEXTURE0); + gl.uniform1i(this.nitroShader.samplerUniform, 0); + } + + this.setShadowMode = function(sTex, fsTex, sMat, fsMat) { + this.nitroShader = shaders[1]; + var shader = shaders[1]; + gl.useProgram(shader); + + gl.uniformMatrix4fv(shader.shadowMatUniform, false, sMat); + gl.uniformMatrix4fv(shader.farShadowMatUniform, false, fsMat); + + gl.uniform1f(shader.shadOffUniform, 0.00005+((mobile)?0.0005:0)); + gl.uniform1f(shader.farShadOffUniform, 0.0005); + + gl.activeTexture(gl.TEXTURE1); + gl.bindTexture(gl.TEXTURE_2D, sTex); + gl.uniform1i(shader.lightSamplerUniform, 1); + + gl.activeTexture(gl.TEXTURE2); + gl.bindTexture(gl.TEXTURE_2D, fsTex); + gl.uniform1i(shader.farLightSamplerUniform, 2); + + this.setColMult([1, 1, 1, 1]); + this.prepareShader(); + } + + this.unsetShadowMode = function() { + this.nitroShader = shaders[0]; + gl.useProgram(this.nitroShader); + + this.setColMult([1, 1, 1, 1]); + this.prepareShader(); + } + + this.setColMult = function(color) { + gl.useProgram(this.nitroShader); + gl.uniform4fv(this.nitroShader.colMultUniform, color); + } + + this.updateBillboards = function(view) { + this.billboardID = (this.billboardID+1)%0xFFFFFF; + + var nv = mat4.clone(view); + nv[12] = 0; + nv[13] = 0; + nv[14] = 0; //nullify translation + var nv2 = mat4.clone(nv); + this.billboardMat = mat4.invert(nv, nv); + nv2[4] = 0; + nv2[5] = 1; //do not invert y axis view + nv2[6] = 0; + this.yBillboardMat = mat4.invert(nv2, nv2); + } + + function renderDispList(disp, tex, startStack) { //renders the display list to a form of vertex buffer. The idea is that NSBTA and NSBCA can still be applied to the buffer at little performance cost. (rather than recompiling the model) + modelBuffer = { + strips: [] + /* strip entry format: + vPos: glBuffer, + vTx: glBuffer, + vCol: glBuffer, + verts: int count of vertices, + mode: (eg. gl.TRIANGLES, gl.TRIANGLESTRIP) + mat: transformation matrix to apply. unused atm as matrix functions are unimplemented + */ + } //the nitroModel will store this and use it for rendering instead of the display list in future. + + curMat = startStack; //start on root bone + var shader = nitroRender.nitroShader; + var gl = nitroRender.gl; + var off=0; + var view = new DataView(disp); + + texWidth = tex.width; + texHeight = tex.height; + + cVec = [0,0,0]; + norm = [0,1,0]; + texCoord = [0,0]; + color = [1,1,1,alphaMul]; //todo: polygon attributes + + vecMode = 0; + vecNum = 0; + vecPos = []; + vecNorm = []; + vecTx = []; + vecCol = []; + vecMat = []; + + while (off < disp.byteLength) { + var ioff = off; + off += 4; + for (var i=0; i<4; i++) { + var inst = view.getUint8(ioff++); + if (instructions[inst] != null) { + instructions[inst](view, off); + } else { + if (inst != 0) alert("invalid instruction 0x"+(inst.toString(16))); + } + var temp = parameters[inst]; + off += (temp == null)?0:temp*4; + } + } + + if (optimiseTriangles) pushStrip(); + + return modelBuffer; + } + +}; + +function nitroModel(bmd, btx, remap) { + var bmd = bmd; + this.bmd = bmd; + var thisObj = this; + var loadedTex; + var texCanvas; + var tex; + var texAnim; + var texFrame; + var modelBuffers; + var collisionModel = []; + var matBufEmpty = new Float32Array(31*16); + + var temp = mat4.create(); + var off=0; + for (var i=0; i<31; i++) { + matBufEmpty.set(temp, off); + off += 16; + } + temp = null; + + var texMap = { tex:{}, pal:{} }; + //var matStack; + this.draw = draw; + this.drawPoly = externDrawPoly; + this.drawModel = externDrawModel; + this.getCollisionModel = getCollisionModel; + + modelBuffers = [] + this.modelBuffers = modelBuffers; + var matBuf = []; + for (var i=0; i>anim.frameStep.scaleS)%anim.scaleS.length], anim.scaleT[(texFrame>>anim.frameStep.scaleT)%anim.scaleT.length]]); + mat3.translate(mat, mat, [-anim.translateS[(texFrame>>anim.frameStep.translateS)%anim.translateS.length], anim.translateT[(texFrame>>anim.frameStep.translateT)%anim.translateT.length]]) //for some mystery reason I need to negate the S translation + gl.uniformMatrix3fv(shader.texMatrixUniform, false, mat); + } else { + gl.uniformMatrix3fv(shader.texMatrixUniform, false, material.texMat); + } + + } else gl.uniformMatrix3fv(shader.texMatrixUniform, false, material.texMat); + + if (modelBuffers[modelind][polyind] == null) modelBuffers[modelind][polyind] = nitroRender.renderDispList(poly.disp, tex[poly.mat], (poly.stackID == null)?model.lastStackID:poly.stackID); + drawModelBuffer(modelBuffers[modelind][polyind], gl, shader); + } + +function generateMatrixStack(model, targ) { //this generates a matrix stack with the default bones. use nitroAnimator to pass custom matrix stacks using nsbca animations. + var matrices = []; + + var objs = model.objects.objectData; + var cmds = model.commands; + var curMat = mat4.create(); + var lastStackID = 0; + + for (var i=0; i1.0 || lightDist.y>1.0) {\n\ + if (texture2D(farLightDSampler, fLightDist.xy).r+farShadOff < fLightDist.z) {\n\ + gl_FragColor = gl_FragColor*vec4(0.5, 0.5, 0.7, 1);\n\ + }\n\ + } else {\n\ + if (texture2D(lightDSampler, lightDist.xy).r+shadOff < lightDist.z) {\n\ + gl_FragColor = gl_FragColor*vec4(0.5, 0.5, 0.7, 1);\n\ + }\n\ + }\n", + + extra: "" + } + + var baseConf = { + frag: this.defaultFrag, vert: this.defaultVert, + uniforms: [ + ["pMatrixUniform", "uPMatrix"], + ["matStackUniform", "matStack"], + ["mvMatrixUniform", "uMVMatrix"], + ["texMatrixUniform", "texMatrix"], + ["samplerUniform", "uSampler"], + ["colMultUniform", "colMult"], + ], + attributes: [ + ["vertexPositionAttribute", "aVertexPosition"], + ["textureCoordAttribute", "aTextureCoord"], + ["colorAttribute", "aColor"], + ["matAttribute", "matrixID"], + ["normAttribute", "aNormal"] + ] + }; + + var config = []; + + var fragParts = [ + dFrag, + lightFrag, + sdFrag + ] + + var shadUnif = [ + ["shadowMatUniform", "shadowMat"], + ["farShadowMatUniform", "farShadowMat"], + + ["shadOffUniform", "shadOff"], + ["farShadOffUniform", "farShadOff"], + + ["lightSamplerUniform", "lightDSampler"], + ["farLightSamplerUniform", "farLightDSampler"] + ] + + config[0] = baseConf; + + config[1] = {frag: this.shadFrag, vert: this.shadVert, uniforms: baseConf.uniforms.slice(0), attributes: baseConf.attributes.slice(0)}; + config[1].uniforms = config[1].uniforms.concat(shadUnif); + + function makeShader(source, base, id) { //makes shaders using flags + + } + + function combineGLSL(shaderParts) { + var out = ""; + + for (var i=0; i length) { + scene.removeEntity(t); + } + } +} \ No newline at end of file diff --git a/code/ui/uiPlace.js b/code/ui/uiPlace.js new file mode 100644 index 0000000..fa78509 --- /dev/null +++ b/code/ui/uiPlace.js @@ -0,0 +1,105 @@ +// +// !! all UI objects assume you have forced positive y as down! +// + +window.uiPlace = function(gl) { + + var WHITE = [1, 1, 1, 1]; + + var frontBuf = { + pos: gl.createBuffer(), + col: gl.createBuffer(), + tx: gl.createBuffer() + } + + var backBuf = { + pos: gl.createBuffer(), + col: gl.createBuffer(), + tx: gl.createBuffer() + } + + var backActive = false; + + function setPlace(num) { + if (nun < 10) { + + } else { + var tens = Math.floor(num/10)%10; + var suffix = (tens == 1)?3:(Math.min(3, (num-1)%10)); + } + } + + function genVertRect(targ, dx, dy, dwidth, dheight, sx, sy, swidth, sheight, z, cornerColours) { //y is down positive. we adjust texture coords to fit this. + var cornerColours = cornerColours + if (cornerColours == null) cornerColours = [WHITE, WHITE, WHITE, WHITE]; + + var vpos = targ.vpos; + var vcol = targ.vcol; + var vtx = targ.vtx; + + // tri 1 + // + // 1 2 + // --------- + // | / + // | / + // | / + // |/ + // + // 3 + // + + vpos.push(dx); + vpos.push(dy); + vpos.push(z); + vcol = vcol.concat(vcol, cornerColours[0]); + vtx.push(sx); + vtx.push(1-sy); + + vpos.push(dx+dwidth); + vpos.push(dy); + vpos.push(z); + vcol = vcol.concat(vcol, cornerColours[1]); + vtx.push(sx+swidth); + vtx.push(1-sy); + + vpos.push(dx); + vpos.push(dy+dheight); + vpos.push(z); + vcol = vcol.concat(vcol, cornerColours[2]); + vtx.push(sx); + vtx.push(1-(sy+sheight)); + + //tri 2 + // + // 1 + // /| + // / | + // / | + // / | + // --------- 3 + // 2 + + vpos.push(dx+dwidth); + vpos.push(dy); + vpos.push(z); + vcol = vcol.concat(vcol, cornerColours[1]); + vtx.push(sx+swidth); + vtx.push(1-sy); + + vpos.push(dx); + vpos.push(dy+dheight); + vpos.push(z); + vcol = vcol.concat(vcol, cornerColours[2]); + vtx.push(sx); + vtx.push(1-(sy+sheight)); + + vpos.push(dx+dwidth); + vpos.push(dy+dheight); + vpos.push(z); + vcol = vcol.concat(vcol, cornerColours[2]); + vtx.push(sx+swidth); + vtx.push(1-(sy+sheight)); + + } +} \ No newline at end of file diff --git a/resource/placeAtlas.png b/resource/placeAtlas.png new file mode 100644 index 0000000..d845b87 Binary files /dev/null and b/resource/placeAtlas.png differ diff --git a/server/Antlr3.Runtime.dll b/server/Antlr3.Runtime.dll new file mode 100644 index 0000000..34bd478 Binary files /dev/null and b/server/Antlr3.Runtime.dll differ diff --git a/server/Antlr3.Runtime.pdb b/server/Antlr3.Runtime.pdb new file mode 100644 index 0000000..315edcf Binary files /dev/null and b/server/Antlr3.Runtime.pdb differ diff --git a/server/ApplicationInsights.config b/server/ApplicationInsights.config new file mode 100644 index 0000000..ee9ea3c --- /dev/null +++ b/server/ApplicationInsights.config @@ -0,0 +1,84 @@ + + + + + + + + + + + + + + System.Web.Handlers.TransferRequestHandler + Microsoft.VisualStudio.Web.PageInspector.Runtime.Tracing.RequestDataHttpHandler + System.Web.StaticFileHandler + System.Web.Handlers.AssemblyResourceLoader + System.Web.Optimization.BundleHandler + System.Web.Script.Services.ScriptHandlerFactory + System.Web.Handlers.TraceHandler + System.Web.Services.Discovery.DiscoveryRequestHandler + System.Web.HttpDebugHandler + + + + + + + + 5 + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/server/Be.Windows.Forms.HexBox.dll b/server/Be.Windows.Forms.HexBox.dll new file mode 100644 index 0000000..318d8b8 Binary files /dev/null and b/server/Be.Windows.Forms.HexBox.dll differ diff --git a/server/CommandLine.dll b/server/CommandLine.dll new file mode 100644 index 0000000..d5497ef Binary files /dev/null and b/server/CommandLine.dll differ diff --git a/server/CommandLine.xml b/server/CommandLine.xml new file mode 100644 index 0000000..4620bee --- /dev/null +++ b/server/CommandLine.xml @@ -0,0 +1,1390 @@ + + + + CommandLine + + + + + Provides base properties for creating an attribute, used to define rules for command line parsing. + + + + + Initializes a new instance of the class. + + + + + Initializes a new instance of the class. + Validating and . + + Short name of the option. + Long name of the option. + + + + Initializes a new instance of the class. Validating + and . This constructor accepts a as short name. + + Short name of the option. + Long name of the option. + + + + Gets a short name of this command line option. You can use only one character. + + + + + Gets long name of this command line option. This name is usually a single english word. + + + + + Gets or sets the option's mutually exclusive set. + + + + + Gets or sets a value indicating whether a command line option is required. + + + + + Gets or sets mapped property default value. + + + + + Gets or sets mapped property meta value. + + + + + Gets or sets a short description of this command line option. Usually a sentence summary. + + + + + Models an option specification. + + + + + Initializes a new instance of the class. + The default long name will be inferred from target property. + + + + + Initializes a new instance of the class. + + The short name of the option.. + + + + Initializes a new instance of the class. + + The long name of the option. + + + + Initializes a new instance of the class. + + The short name of the option. + The long name of the option or null if not used. + + + + Helper factory method for testing purpose. + + An instance. + + + + Models an option that can accept multiple values as separated arguments. + + + + + Initializes a new instance of the class. + The default long name will be inferred from target property. + + + + + Initializes a new instance of the class. + + The short name of the option. + + + + Initializes a new instance of the class. + + The long name of the option. + + + + Initializes a new instance of the class. + + The short name of the option. + The long name of the option or null if not used. + + + + Indicates the instance method that must be invoked when it becomes necessary show your help screen. + The method signature is an instance method with no parameters and + return value. + + + + + Initializes a new instance of the class. + Although it is possible, it is strongly discouraged redefine the long name for this option + not to disorient your users. It is also recommended not to define a short one. + + + + + Initializes a new instance of the class + with the specified short name. Use parameter less constructor instead. + + The short name of the option. + + It's highly not recommended change the way users invoke help. It may create confusion. + + + + + Initializes a new instance of the class + with the specified long name. Use parameter less constructor instead. + + The long name of the option or null if not used. + + It's highly not recommended change the way users invoke help. It may create confusion. + + + + + Initializes a new instance of the class. + Allows you to define short and long option names. + + The short name of the option. + The long name of the option or null if not used. + + It's highly not recommended change the way users invoke help. It may create confusion. + + + + + Returns always false for this kind of option. + This behaviour can't be changed by design; if you try set + an will be thrown. + + + + + Models an option that can accept multiple values. + Must be applied to a field compatible with an interface + of instances. + + + + + Initializes a new instance of the class. + The default long name will be inferred from target property. + + + + + Initializes a new instance of the class. + + The short name of the option. + + + + Initializes a new instance of the class. + + The long name of the option or null if not used. + + + + Initializes a new instance of the class. + + The short name of the option. + The long name of the option or null if not used. + + + + Initializes a new instance of the class. + + The short name of the option or null if not used. + The long name of the option or null if not used. + Values separator character. + + + + Gets or sets the values separator character. + + + + + Indicates that the property can receive an instance of type . + + + + + Models a list of command line arguments that are not options. + Must be applied to a field compatible with an interface + of instances. + + To map individual values use instead . + + + + Initializes a new instance of the class. + + A type that implements . + Thrown if is null. + + + + Gets or sets the maximum element allow for the list managed by type. + If lesser than 0, no upper bound is fixed. + If equal to 0, no elements are allowed. + + + + + Gets the concrete type specified during initialization. + + + + + Maps a single unnamed option to the target property. Values will be mapped in order of Index. + This attribute takes precedence over with which + can coexist. + + It can handle only scalar values. Do not apply to arrays or lists. + + + + Initializes a new instance of the class. + + The _index of the option. + + + + Gets the position this option has on the command line. + + + + + Utility extension methods for System.Char. + + + + + Encapsulates property writing primitives. + + + + + Utility extension methods for System.String. + + + + + Gets or sets the assembly from which to pull information. Setter provided for testing purpose. + + + + + Utility extension methods for query target capabilities. + + + + + Maps unnamed options to property using and . + + + + + Helper method for testing purpose. + + An argument enumerator instance. + The next input value. + + + + Initializes a new instance of the class. Used for unit testing purpose. + + Option short name. + Option long name. + + + + Initializes a new instance of the class. + It is internal rather than private for unit testing purpose. + + Initial internal capacity. + Parser settings instance. + + + + Provides means to format an help screen. + You can assign it in place of a instance. + + + + + Initializes a new instance of the class. + + + + + Initializes a new instance of the class + specifying the sentence builder. + + + A instance. + + + + + Initializes a new instance of the class + specifying heading string. + + An heading string or an instance of . + Thrown when parameter is null or empty string. + + + + Initializes a new instance of the class + specifying the sentence builder and heading string. + + A instance. + A string with heading or an instance of . + + + + Initializes a new instance of the class + specifying heading and copyright strings. + + A string with heading or an instance of . + A string with copyright or an instance of . + Thrown when one or more parameters are null or empty strings. + + + + Initializes a new instance of the class + specifying heading and copyright strings. + + A instance. + A string with heading or an instance of . + A string with copyright or an instance of . + Thrown when one or more parameters are null or empty strings. + + + + Initializes a new instance of the class + specifying heading and copyright strings. + + A string with heading or an instance of . + A string with copyright or an instance of . + The instance that collected command line arguments parsed with class. + Thrown when one or more parameters are null or empty strings. + + + + Initializes a new instance of the class + specifying heading and copyright strings. + + A instance. + A string with heading or an instance of . + A string with copyright or an instance of . + The instance that collected command line arguments parsed with class. + Thrown when one or more parameters are null or empty strings. + + + + Creates a new instance of the class using common defaults. + + + An instance of class. + + The instance that collected command line arguments parsed with class. + + + + Creates a new instance of the class using common defaults. + + + An instance of class. + + The instance that collected command line arguments parsed with class. + A delegate used to customize the text block for reporting parsing errors. + If true the output style is consistent with verb commands (no dashes), otherwise it outputs options. + + + + Creates a new instance of the class using common defaults, + for verb commands scenario. + + + An instance of class. + + The instance that collected command line arguments parsed with class. + The verb command invoked. + + + + Supplies a default parsing error handler implementation. + + The instance that collects parsed arguments parsed and associates + to a property of type . + The instance. + + + + Converts the help instance to a . + + This instance. + The that contains the help screen. + + + + Adds a text line after copyright and before options usage strings. + + A instance. + Thrown when parameter is null or empty string. + + + + Adds a text line at the bottom, after options usage string. + + A instance. + Thrown when parameter is null or empty string. + + + + Adds a text block with options usage string. + + The instance that collected command line arguments parsed with class. + Thrown when parameter is null. + + + + Adds a text block with options usage string. + + The instance that collected command line arguments parsed with the class. + The word to use when the option is required. + Thrown when parameter is null. + Thrown when parameter is null or empty string. + + + + Adds a text block with options usage string. + + The instance that collected command line arguments parsed with the class. + The word to use when the option is required. + The maximum length of the help documentation. + Thrown when parameter is null. + Thrown when parameter is null or empty string. + + + + Builds a string that contains a parsing error message. + + An options target instance that collects parsed arguments parsed with the + associated to a property of type . + Number of spaces used to indent text. + The that contains the parsing error message. + + + + Returns the help screen as a . + + The that contains the help screen. + + + + The OnFormatOptionHelpText method also allows derived classes to handle the event without attaching a delegate. + This is the preferred technique for handling the event in a derived class. + + Data for the event. + + + + Occurs when an option help text is formatted. + + + + + Gets or sets the heading string. + You can directly assign a instance. + + + + + Gets or sets the copyright string. + You can directly assign a instance. + + + + + Gets or sets the maximum width of the display. This determines word wrap when displaying the text. + + The maximum width of the display. + + + + Gets or sets a value indicating whether the format of options should contain dashes. + It modifies behavior of method. + + + + + Gets or sets a value indicating whether to add an additional line after the description of the option. + + + + + Gets the instance specified in constructor. + + + + + Models an abstract sentence builder. + + + + + Creates the built in sentence builder. + + The built in sentence builder. + + + + Gets a string containing word 'option'. + + The word 'option'. + + + + Gets a string containing the word 'and'. + + The word 'and'. + + + + Gets a string containing the sentence 'required option missing'. + + The sentence 'required option missing'. + + + + Gets a string containing the sentence 'violates format'. + + The sentence 'violates format'. + + + + Gets a string containing the sentence 'violates mutual exclusiveness'. + + The sentence 'violates mutual exclusiveness'. + + + + Gets a string containing the error heading text. + + The error heading text. + + + + Models an english sentence builder, currently the default one. + + + + + Gets a string containing word 'option' in english. + + The word 'option' in english. + + + + Gets a string containing the word 'and' in english. + + The word 'and' in english. + + + + Gets a string containing the sentence 'required option missing' in english. + + The sentence 'required option missing' in english. + + + + Gets a string containing the sentence 'violates format' in english. + + The sentence 'violates format' in english. + + + + Gets a string containing the sentence 'violates mutual exclusiveness' in english. + + The sentence 'violates mutual exclusiveness' in english. + + + + Gets a string containing the error heading text in english. + + The error heading text in english. + + + + Models the copyright part of an help text. + You can assign it where you assign any instance. + + + + + Initializes a new instance of the class + specifying author and year. + + The company or person holding the copyright. + The year of coverage of copyright. + Thrown when parameter is null or empty string. + + + + Initializes a new instance of the class + specifying author and copyrightYears. + + The company or person holding the copyright. + The copyrightYears of coverage of copyright. + Thrown when parameter is null or empty string. + Thrown when parameter is not supplied. + + + + Initializes a new instance of the class + specifying symbol case, author and copyrightYears. + + The case of the copyright symbol. + The company or person holding the copyright. + The copyrightYears of coverage of copyright. + Thrown when parameter is null or empty string. + Thrown when parameter is not supplied. + + + + Initializes a new instance of the class. + + + + + Initializes a new instance of the class + with an assembly attribute, this overrides all formatting. + + The attribute which text to use. + + + + Converts the copyright instance to a . + + This instance. + The that contains the copyright. + + + + Returns the copyright as a . + + The that contains the copyright. + + + + When overridden in a derived class, allows to specify a new algorithm to render copyright copyrightYears + as a instance. + + A array of copyrightYears. + A instance with copyright copyrightYears. + + + + Gets the default copyright information. + Retrieved from , if it exists, + otherwise it uses as copyright holder with the current year. + If neither exists it throws an . + + + + + Gets a different copyright word when overridden in a derived class. + + + + + Models the heading part of an help text. + You can assign it where you assign any instance. + + + + + Initializes a new instance of the class + specifying program name. + + The name of the program. + Thrown when parameter is null or empty string. + + + + Initializes a new instance of the class + specifying program name and version. + + The name of the program. + The version of the program. + Thrown when parameter is null or empty string. + + + + Converts the heading to a . + + This instance. + The that contains the heading. + + + + Returns the heading as a . + + The that contains the heading. + + + + Writes out a string and a new line using the program name specified in the constructor + and parameter. + + The message to write. + The target derived type. + Thrown when parameter is null or empty string. + Thrown when parameter is null. + + + + Writes out a string and a new line using the program name specified in the constructor + and parameter to standard output stream. + + The message to write. + Thrown when parameter is null or empty string. + + + + Writes out a string and a new line using the program name specified in the constructor + and parameter to standard error stream. + + The message to write. + Thrown when parameter is null or empty string. + + + + Gets the default heading instance. + The title is retrieved from , + or the assembly short name if its not defined. + The version is retrieved from , + or the assembly version if its not defined. + + + + + Provides base properties for creating an attribute, used to define multiple lines of text. + + + + + Initializes a new instance of the class. Used in derived type + using one line of text. + + The first line of text. + + + + Initializes a new instance of the class. Used in type + using two lines of text. + + The first line of text. + The second line of text. + + + + Initializes a new instance of the class. Used in type + using three lines of text. + + The first line of text. + The second line of text. + The third line of text. + + + + Initializes a new instance of the class. Used in type + using four lines of text. + + The first line of text. + The second line of text. + The third line of text. + The fourth line of text. + + + + Initializes a new instance of the class. Used in type + using five lines of text. + + The first line of text. + The second line of text. + The third line of text. + The fourth line of text. + The fifth line of text. + + + + Returns the last line with text. Preserves blank lines if user intended by skipping a line. + + The last index of line of the non-blank line. + + The string array to process. + + + + Gets the all non-blank lines as string. + + A string of all non-blank lines. + + + + Gets the first line of text. + + + + + Gets the second line of text. + + + + + Gets third line of text. + + + + + Gets the fourth line of text. + + + + + Gets the fifth line of text. + + + + + Models a multiline assembly license text. + + + + + Initializes a new instance of the class + with one line of text. + + First line of license text. + + + + Initializes a new instance of the class + with two lines of text. + + First line of license text. + Second line of license text. + + + + Initializes a new instance of the class + with three lines of text. + + First line of license text. + Second line of license text. + Third line of license text. + + + + Initializes a new instance of the class + with four lines of text. + + First line of license text. + Second line of license text. + Third line of license text. + Fourth line of license text. + + + + Initializes a new instance of the class + with five lines of text. + + First line of license text. + Second line of license text. + Third line of license text. + Fourth line of license text. + Fifth line of license text. + + + + Models a multiline assembly usage text. + + + + + Initializes a new instance of the class + with one line of text. + + First line of usage text. + + + + Initializes a new instance of the class + with two lines of text. + + First line of usage text. + Second line of usage text. + + + + Initializes a new instance of the class + with three lines of text. + + First line of usage text. + Second line of usage text. + Third line of usage text. + + + + Initializes a new instance of the class + with four lines of text. + + First line of usage text. + Second line of usage text. + Third line of usage text. + Fourth line of usage text. + + + + Initializes a new instance of the class + with five lines of text. + + First line of usage text. + Second line of usage text. + Third line of usage text. + Fourth line of usage text. + Fifth line of usage text. + + + + Provides data for the FormatOptionHelpText event. + + + + + Initializes a new instance of the class. + + Option to format. + + + + Gets the option to format. + + + + + Indicates the instance method that must be invoked when it becomes necessary show your help screen. + The method signature is an instance method with that accepts and returns a . + + + + + Initializes a new instance of the class. + Although it is possible, it is strongly discouraged redefine the long name for this option + not to disorient your users. + + + + + Initializes a new instance of the class + with the specified long name. Use parameter less constructor instead. + + Help verb option alternative name. + + It's highly not recommended change the way users invoke help. It may create confusion. + + + + + Help verb command do not support short name by design. + + + + + Help verb command like ordinary help option cannot be mandatory by design. + + + + + Models a verb command specification. + + + + + Initializes a new instance of the class. + + The long name of the verb command. + + + + Verb commands do not support short name by design. + + + + + Verb commands cannot be mandatory since are mutually exclusive by design. + + + + + Models a bad parsed option. + + + + + Gets the short name of the option. + + Returns the short name of the option. + + + + Gets the long name of the option. + + Returns the long name of the option. + + + + Provides methods to parse command line arguments. + + + + + Default exit code (1) used by + and overloads. + + + + + Initializes a new instance of the class. + + + + + Initializes a new instance of the class, + configurable with a object. + + The object is used to configure + aspects and behaviors of the parser. + + + + Initializes a new instance of the class, + configurable with using a delegate. + + The delegate used to configure + aspects and behaviors of the parser. + + + + Finalizes an instance of the class. + + + + + Parses a array of command line arguments, setting values in + parameter instance's public fields decorated with appropriate attributes. + + A array of command line arguments. + An instance used to receive values. + Parsing rules are defined using derived types. + True if parsing process succeed. + Thrown if is null. + Thrown if is null. + + + + Parses a array of command line arguments with verb commands, setting values in + parameter instance's public fields decorated with appropriate attributes. + This overload supports verb commands. + + A array of command line arguments. + An instance used to receive values. + Parsing rules are defined using derived types. + Delegate executed to capture verb command name and instance. + True if parsing process succeed. + Thrown if is null. + Thrown if is null. + Thrown if is null. + + + + Parses a array of command line arguments, setting values in + parameter instance's public fields decorated with appropriate attributes. If parsing fails, the method invokes + the delegate, if null exits with . + + A array of command line arguments. + An object's instance used to receive values. + Parsing rules are defined using derived types. + The delegate executed when parsing fails. + True if parsing process succeed. + Thrown if is null. + Thrown if is null. + + + + Parses a array of command line arguments with verb commands, setting values in + parameter instance's public fields decorated with appropriate attributes. If parsing fails, the method invokes + the delegate, if null exits with . + This overload supports verb commands. + + A array of command line arguments. + An instance used to receive values. + Parsing rules are defined using derived types. + Delegate executed to capture verb command name and instance. + The delegate executed when parsing fails. + True if parsing process succeed. + Thrown if is null. + Thrown if is null. + Thrown if is null. + + + + Frees resources owned by the instance. + + + + + Gets the singleton instance created with basic defaults. + + + + + Gets the instance that implements in use. + + + + + This exception is thrown when a generic parsing error occurs. + + + + + Initializes a new instance of the class. The exception is thrown + when something unexpected occurs during the parsing process. + + + + + Initializes a new instance of the class. The exception is thrown + when something unexpected occurs during the parsing process. + + Error message string. + + + + Initializes a new instance of the class. The exception is thrown + when something unexpected occurs during the parsing process. + + Error message string. + Inner exception reference. + + + + Initializes a new instance of the class. The exception is thrown + when something unexpected occurs during the parsing process. + + The object that holds the serialized object data. + The contextual information about the source or destination. + + + + Provides settings for . Once consumed cannot be reused. + + + + + Initializes a new instance of the class. + + + + + Initializes a new instance of the class, + setting the case comparison behavior. + + If set to true, parsing will be case sensitive. + + + + Initializes a new instance of the class, + setting the used for help method output. + + Any instance derived from , + default . Setting this argument to null, will disable help screen. + + + + Initializes a new instance of the class, + setting case comparison and help output options. + + If set to true, parsing will be case sensitive. + Any instance derived from , + default . Setting this argument to null, will disable help screen. + + + + Initializes a new instance of the class, + setting case comparison and mutually exclusive behaviors. + + If set to true, parsing will be case sensitive. + If set to true, enable mutually exclusive behavior. + + + + Initializes a new instance of the class, + setting case comparison, mutually exclusive behavior and help output option. + + If set to true, parsing will be case sensitive. + If set to true, enable mutually exclusive behavior. + Any instance derived from , + default . Setting this argument to null, will disable help screen. + + + + Initializes a new instance of the class, + setting case comparison, mutually exclusive behavior and help output option. + + If set to true, parsing will be case sensitive. + If set to true, enable mutually exclusive behavior. + If set to true, allow the parser to skip unknown argument, otherwise return a parse failure + Any instance derived from , + default . Setting this argument to null, will disable help screen. + + + + Finalizes an instance of the class. + + + + + Frees resources owned by the instance. + + + + + Gets or sets a value indicating whether perform case sensitive comparisons. + + + + + Gets or sets a value indicating whether set a mutually exclusive behavior. + Default is set to false. + + + + + Gets or sets the used for help method output. + Setting this property to null, will disable help screen. + + + + + Gets or sets a value indicating whether the parser shall move on to the next argument and ignore the given argument if it + encounter an unknown arguments + + + true to allow parsing the arguments with different class options that do not have all the arguments. + + + This allows fragmented version class parsing, useful for project with add-on where add-ons also requires command line arguments but + when these are unknown by the main program at build time. + + + + + Gets or sets the culture used when parsing arguments to typed properties. + + + Default is CurrentCulture of . + + + + + Represents the parser state. + + + + + Gets errors occurred during parsing. + + + + + Models a type that records the parser state after parsing. + + + + + Gets a list of parsing errors. + + + Parsing errors. + + + + + Models a parsing error. + + + + + Gets or a the bad parsed option. + + + The bad option. + + + + + Gets or sets a value indicating whether this violates required. + + + true if violates required; otherwise, false. + + + + + Gets or sets a value indicating whether this violates format. + + + true if violates format; otherwise, false. + + + + + Gets or sets a value indicating whether this violates mutual exclusiveness. + + + true if violates mutual exclusiveness; otherwise, false. + + + + diff --git a/server/Common.Logging.Core.dll b/server/Common.Logging.Core.dll new file mode 100644 index 0000000..066d4ed Binary files /dev/null and b/server/Common.Logging.Core.dll differ diff --git a/server/Common.Logging.Core.pdb b/server/Common.Logging.Core.pdb new file mode 100644 index 0000000..7299360 Binary files /dev/null and b/server/Common.Logging.Core.pdb differ diff --git a/server/Common.Logging.Core.xml b/server/Common.Logging.Core.xml new file mode 100644 index 0000000..193c514 --- /dev/null +++ b/server/Common.Logging.Core.xml @@ -0,0 +1,876 @@ + + + + Common.Logging.Core + + + + + Indicates that the marked method builds string by format pattern and (optional) arguments. + Parameter, which contains format string, should be given in constructor. The format string + should be in -like form + + + [StringFormatMethod("message")] + public void ShowError(string message, params object[] args) { /* do something */ } + public void Foo() { + ShowError("Failed: {0}"); // Warning: Non-existing argument in format string + } + + + + + Specifies which parameter of an annotated method should be treated as format-string + + + + + The name of the string parameter being formatted + + + + + The type of method that is passed into e.g. + and allows the callback method to "submit" it's message to the underlying output system. + + the format argument as in + the argument list as in + + Erich Eichinger + + + + Interface for basic operations to read .NET application configuration information. + + Provides a simple abstraction to handle BCL API differences between .NET 1.x and 2.0. Also + useful for testing scenarios. + Mark Pollack + + + + Parses the configuration section and returns the resulting object. + + +

+ Primary purpose of this method is to allow us to parse and + load configuration sections using the same API regardless + of the .NET framework version. +

+ + See also System.Configuration.ConfigurationManager +
+ Name of the configuration section. + Object created by a corresponding IConfigurationSectionHandler. +
+ + + A simple logging interface abstracting logging APIs. + + + + Implementations should defer calling a message's until the message really needs + to be logged to avoid performance penalties. + + + Each log method offers to pass in a instead of the actual message. + Using this style has the advantage to defer possibly expensive message argument evaluation and formatting (and formatting arguments!) until the message gets + actually logged. If the message is not logged at all (e.g. due to settings), + you won't have to pay the peformance penalty of creating the message. + + + + The example below demonstrates using callback style for creating the message, where the call to the + and the underlying only happens, if level is enabled: + + Log.Debug( m=>m("result is {0}", random.NextDouble()) ); + Log.Debug(delegate(m) { m("result is {0}", random.NextDouble()); }); + + + + Mark Pollack + Bruno Baia + Erich Eichinger + + + + Log a message object with the level. + + The message object to log. + + + + Log a message object with the level including + the stack trace of the passed + as a parameter. + + The message object to log. + The exception to log, including its stack trace. + + + + Log a message with the level. + + The format of the message object to log. + the list of format arguments + + + + Log a message with the level. + + The format of the message object to log. + The exception to log. + the list of format arguments + + + + Log a message with the level. + + An that supplies culture-specific formatting information. + The format of the message object to log. + + + + + Log a message with the level. + + An that supplies culture-specific formatting information. + The format of the message object to log. + The exception to log. + + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + A callback used by the logger to obtain the message if log level is matched + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack trace. + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack trace. + + + + Log a message object with the level. + + The message object to log. + + + + Log a message object with the level including + the stack trace of the passed + as a parameter. + + The message object to log. + The exception to log, including its stack trace. + + + + Log a message with the level. + + The format of the message object to log. + the list of format arguments + + + + Log a message with the level. + + The format of the message object to log. + The exception to log. + the list of format arguments + + + + Log a message with the level. + + An that supplies culture-specific formatting information. + The format of the message object to log. + + + + + Log a message with the level. + + An that supplies culture-specific formatting information. + The format of the message object to log. + The exception to log. + + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + A callback used by the logger to obtain the message if log level is matched + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack trace. + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack Debug. + + + + Log a message object with the level. + + The message object to log. + + + + Log a message object with the level including + the stack trace of the passed + as a parameter. + + The message object to log. + The exception to log, including its stack trace. + + + + Log a message with the level. + + The format of the message object to log. + the list of format arguments + + + + Log a message with the level. + + The format of the message object to log. + The exception to log. + the list of format arguments + + + + Log a message with the level. + + An that supplies culture-specific formatting information. + The format of the message object to log. + + + + + Log a message with the level. + + An that supplies culture-specific formatting information. + The format of the message object to log. + The exception to log. + + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + A callback used by the logger to obtain the message if log level is matched + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack trace. + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack Info. + + + + Log a message object with the level. + + The message object to log. + + + + Log a message object with the level including + the stack trace of the passed + as a parameter. + + The message object to log. + The exception to log, including its stack trace. + + + + Log a message with the level. + + The format of the message object to log. + the list of format arguments + + + + Log a message with the level. + + The format of the message object to log. + The exception to log. + the list of format arguments + + + + Log a message with the level. + + An that supplies culture-specific formatting information. + The format of the message object to log. + + + + + Log a message with the level. + + An that supplies culture-specific formatting information. + The format of the message object to log. + The exception to log. + + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + A callback used by the logger to obtain the message if log level is matched + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack trace. + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack Warn. + + + + Log a message object with the level. + + The message object to log. + + + + Log a message object with the level including + the stack trace of the passed + as a parameter. + + The message object to log. + The exception to log, including its stack trace. + + + + Log a message with the level. + + The format of the message object to log. + the list of format arguments + + + + Log a message with the level. + + The format of the message object to log. + The exception to log. + the list of format arguments + + + + Log a message with the level. + + An that supplies culture-specific formatting information. + The format of the message object to log. + + + + + Log a message with the level. + + An that supplies culture-specific formatting information. + The format of the message object to log. + The exception to log. + + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + A callback used by the logger to obtain the message if log level is matched + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack trace. + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack Error. + + + + Log a message object with the level. + + The message object to log. + + + + Log a message object with the level including + the stack trace of the passed + as a parameter. + + The message object to log. + The exception to log, including its stack trace. + + + + Log a message with the level. + + The format of the message object to log. + the list of format arguments + + + + Log a message with the level. + + The format of the message object to log. + The exception to log. + the list of format arguments + + + + Log a message with the level. + + An that supplies culture-specific formatting information. + The format of the message object to log. + + + + + Log a message with the level. + + An that supplies culture-specific formatting information. + The format of the message object to log. + The exception to log. + + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + A callback used by the logger to obtain the message if log level is matched + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack trace. + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack Fatal. + + + + Checks if this logger is enabled for the level. + + + + + Checks if this logger is enabled for the level. + + + + + Checks if this logger is enabled for the level. + + + + + Checks if this logger is enabled for the level. + + + + + Checks if this logger is enabled for the level. + + + + + Checks if this logger is enabled for the level. + + + + + Returns the global context for variables + + + + + Returns the thread-specific context for variables + + + + + LoggerFactoryAdapter interface is used internally by LogManager + Only developers wishing to write new Common.Logging adapters need to + worry about this interface. + + Gilles Bayon + + + + Get a ILog instance by type. + + The type to use for the logger + + + + + Get a ILog instance by key. + + The key of the logger + + + + + Interface for LogManager + + + + + Reset the infrastructure to its default settings. This means, that configuration settings + will be re-read from section <common/logging> of your app.config. + + + This is mainly used for unit testing, you wouldn't normally use this in your applications.
+ Note: instances already handed out from this LogManager are not(!) affected. + Resetting LogManager only affects new instances being handed out. +
+
+ + + Reset the infrastructure to its default settings. This means, that configuration settings + will be re-read from section <common/logging> of your app.config. + + + This is mainly used for unit testing, you wouldn't normally use this in your applications.
+ Note: instances already handed out from this LogManager are not(!) affected. + Resetting LogManager only affects new instances being handed out. +
+ + the instance to obtain settings for + re-initializing the LogManager. + +
+ + + Gets the logger by calling + on the currently configured using the type of the calling class. + + + This method needs to inspect the StackTrace in order to determine the calling + class. This of course comes with a performance penalty, thus you shouldn't call it too + often in your application. + + + the logger instance obtained from the current + + + + Gets the logger by calling + on the currently configured using the specified type. + + the logger instance obtained from the current + + + + Gets the logger by calling + on the currently configured using the specified type. + + The type. + the logger instance obtained from the current + + + + Gets the logger by calling + on the currently configured using the specified key. + + The key. + the logger instance obtained from the current + + + + The key of the default configuration section to read settings from. + + + You can always change the source of your configuration settings by setting another instance + on . + + + + + Gets the configuration reader used to initialize the LogManager. + + Primarily used for testing purposes but maybe useful to obtain configuration + information from some place other than the .NET application configuration file. + The configuration reader. + + + + Gets or sets the adapter. + + The adapter. + + + + A context for logger variables + + + + + Sets the value of a new or existing variable within the global context + + The key of the variable that is to be added + The value to add + + + + Gets the value of a variable within the global context + + The key of the variable to get + The value or null if not found + + + + Checks if a variable is set within the global context + + The key of the variable to check for + True if the variable is set + + + + Removes a variable from the global context by key + + The key of the variable to remove + + + + Clears the global context variables + + + + + The 7 possible logging levels + + Gilles Bayon + + + + All logging levels + + + + + A trace logging level + + + + + A debug logging level + + + + + A info logging level + + + + + A warn logging level + + + + + An error logging level + + + + + A fatal logging level + + + + + Do not log anything. + + +
+
diff --git a/server/Common.Logging.dll b/server/Common.Logging.dll new file mode 100644 index 0000000..30ca3fd Binary files /dev/null and b/server/Common.Logging.dll differ diff --git a/server/Common.Logging.pdb b/server/Common.Logging.pdb new file mode 100644 index 0000000..992b020 Binary files /dev/null and b/server/Common.Logging.pdb differ diff --git a/server/Common.Logging.xml b/server/Common.Logging.xml new file mode 100644 index 0000000..68b25f8 --- /dev/null +++ b/server/Common.Logging.xml @@ -0,0 +1,2774 @@ + + + + Common.Logging + + + + + Indicates classes or members to be ignored by NCover + + + Note, the key is chosen, because TestDriven.NET uses it as //ea argument to "Test With... Coverage" + + Erich Eichinger + + + + The exception that is thrown when a configuration system error has occurred with Common.Logging + + Mark Pollack + + + Creates a new instance of the ObjectsException class. + + + + Creates a new instance of the ConfigurationException class. with the specified message. + + + A message about the exception. + + + + + Creates a new instance of the ConfigurationException class with the specified message + and root cause. + + + A message about the exception. + + + The root exception that is being wrapped. + + + + + Creates a new instance of the ConfigurationException class. + + + The + that holds the serialized object data about the exception being thrown. + + + The + that contains contextual information about the source or destination. + + + + + Various utility methods for using during factory and logger instance configuration + + Erich Eichinger + + + + Initialize all members before any of this class' methods can be accessed (avoids beforeFieldInit) + + + + + Adds the parser to the list of known type parsers. + + + .NET intrinsic types are pre-registerd: short, int, long, float, double, decimal, bool + + + + + Retrieves the named value from the specified . + + may be null + the value's key + if is not null, the value returned by values[key]. null otherwise. + + + + Retrieves the named value from the specified . + + may be null + the value's key + the default value, if not found + if is not null, the value returned by values[key]. null otherwise. + + + + Returns the first nonnull, nonempty value among its arguments. + + + Returns null, if the initial list was null or empty. + + + + + + Returns the first nonnull, nonempty value among its arguments. + + + Also + + + + + Tries parsing into an enum of the type of . + + the default value to return if parsing fails + the string value to parse + the successfully parsed value, otherwise. + + + + Tries parsing into the specified return type. + + the default value to return if parsing fails + the string value to parse + the successfully parsed value, otherwise. + + + + Throws a if is null. + + + + + Throws a if is null. + + + + + Throws a if an object of type is not + assignable to type . + + + + + Throws a if an object of type is not + assignable to type . + + + + + Ensures any exception thrown by the given is wrapped with an + . + + + If already throws a ConfigurationException, it will not be wrapped. + + the action to execute + the message to be set on the thrown + args to be passed to to format the message + + + + Ensures any exception thrown by the given is wrapped with an + . + + + If already throws a ConfigurationException, it will not be wrapped. + + the action to execute + the message to be set on the thrown + args to be passed to to format the message + + + + A delegate converting a string representation into the target type + + + + + An anonymous action delegate with no arguments and no return value. + + + + + + An anonymous action delegate with no arguments and no return value. + + + + + + Implementation of that uses the standard .NET + configuration APIs, ConfigurationSettings in 1.x and ConfigurationManager in 2.0 + + Mark Pollack + + + + Parses the configuration section and returns the resulting object. + Using the System.Configuration.ConfigurationManager + + Name of the configuration section. + + Object created by a corresponding IConfigurationSectionHandler" + + +

+ Primary purpose of this method is to allow us to parse and + load configuration sections using the same API regardless + of the .NET framework version. +

+
+
+ + + Container used to hold configuration information from config file. + + Gilles Bayon + + + + + + + The type + that will be used for creating + + + Additional user supplied properties that are passed to the + 's constructor. + + + + + The type that will be used for creating + instances. + + + + + Additional user supplied properties that are passed to the 's constructor. + + + + + Substitute NameValueCollection in System.Collections.Specialized. + + + + + Creates a new instance of NameValueCollection. + + + + + Gets the values (only a single one) for the specified key (configuration name) + + The key. + an array with one value, or null if no value exist + + + + Gets or sets the value with the specified key. + + + The value corrsponding to the key, or null if no value exist + + The key. + value store for the key + + + + Helper class for working with NameValueCollection + + + + + Convert a into the corresponding + common logging equivalent + + The properties. + + + + + An implementation of that caches loggers handed out by this factory. + + + Implementors just need to override . + + Erich Eichinger + + + + Creates a new instance, the logger cache being case-sensitive. + + + + + Creates a new instance, the logger cache being . + + + + + + Purges all loggers from cache + + + + + Create the specified named logger instance + + + Derived factories need to implement this method to create the + actual logger instance. + + + + + Get a ILog instance by . + + Usually the of the current class. + + An ILog instance either obtained from the internal cache or created by a call to . + + + + + Get a ILog instance by key. + + Usually a 's Name or FullName property. + + An ILog instance either obtained from the internal cache or created by a call to . + + + + + Get or create a ILog instance by key. + + Usually a 's Name or FullName property. + + An ILog instance either obtained from the internal cache or created by a call to . + + + + + Provides base implementation suitable for almost all logger adapters + + Erich Eichinger + + + + Holds the method for writing a message to the log system. + + + + + Creates a new logger instance using for + writing log events to the underlying log system. + + + + + + Override this method to use a different method than + for writing log events to the underlying log system. + + + Usually you don't need to override thise method. The default implementation returns + null to indicate that the default handler should be + used. + + + + + Actually sends the message to the underlying log system. + + the level of this log event. + the message to log + the exception to log (may be null) + + + + Log a message object with the level. + + The message object to log. + + + + Log a message object with the level including + the stack trace of the passed + as a parameter. + + The message object to log. + The exception to log, including its stack trace. + + + + Log a message with the level. + + An that supplies culture-specific formatting information. + The format of the message object to log. + + + + + Log a message with the level. + + An that supplies culture-specific formatting information. + The format of the message object to log. + The exception to log. + + + + + Log a message with the level. + + The format of the message object to log. + the list of format arguments + + + + Log a message with the level. + + The format of the message object to log. + The exception to log. + the list of format arguments + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + A callback used by the logger to obtain the message if log level is matched + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack trace. + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack trace. + + + + Log a message object with the level. + + The message object to log. + + + + Log a message object with the level including + the stack Debug of the passed + as a parameter. + + The message object to log. + The exception to log, including its stack Debug. + + + + Log a message with the level. + + An that supplies culture-specific formatting information. + The format of the message object to log. + + + + + Log a message with the level. + + An that supplies culture-specific formatting information. + The format of the message object to log. + The exception to log. + + + + + Log a message with the level. + + The format of the message object to log. + the list of format arguments + + + + Log a message with the level. + + The format of the message object to log. + The exception to log. + the list of format arguments + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + A callback used by the logger to obtain the message if log level is matched + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack Debug. + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack Debug. + + + + Log a message object with the level. + + The message object to log. + + + + Log a message object with the level including + the stack Info of the passed + as a parameter. + + The message object to log. + The exception to log, including its stack Info. + + + + Log a message with the level. + + An that supplies culture-specific formatting information. + The format of the message object to log. + + + + + Log a message with the level. + + An that supplies culture-specific formatting information. + The format of the message object to log. + The exception to log. + + + + + Log a message with the level. + + The format of the message object to log. + the list of format arguments + + + + Log a message with the level. + + The format of the message object to log. + The exception to log. + the list of format arguments + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + A callback used by the logger to obtain the message if log level is matched + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack Info. + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack Info. + + + + Log a message object with the level. + + The message object to log. + + + + Log a message object with the level including + the stack Warn of the passed + as a parameter. + + The message object to log. + The exception to log, including its stack Warn. + + + + Log a message with the level. + + An that supplies culture-specific formatting Information. + The format of the message object to log. + + + + + Log a message with the level. + + An that supplies culture-specific formatting information. + The format of the message object to log. + The exception to log. + + + + + Log a message with the level. + + The format of the message object to log. + the list of format arguments + + + + Log a message with the level. + + The format of the message object to log. + The exception to log. + the list of format arguments + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + A callback used by the logger to obtain the message if log level is matched + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack Warn. + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack Warn. + + + + Log a message object with the level. + + The message object to log. + + + + Log a message object with the level including + the stack Error of the passed + as a parameter. + + The message object to log. + The exception to log, including its stack Error. + + + + Log a message with the level. + + An that supplies culture-specific formatting Errorrmation. + The format of the message object to log. + + + + + Log a message with the level. + + An that supplies culture-specific formatting Errorrmation. + The format of the message object to log. + The exception to log. + + + + + Log a message with the level. + + The format of the message object to log. + the list of format arguments + + + + Log a message with the level. + + The format of the message object to log. + The exception to log. + the list of format arguments + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + A callback used by the logger to obtain the message if log level is matched + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack Error. + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack Error. + + + + Log a message object with the level. + + The message object to log. + + + + Log a message object with the level including + the stack Fatal of the passed + as a parameter. + + The message object to log. + The exception to log, including its stack Fatal. + + + + Log a message with the level. + + An that supplies culture-specific formatting Fatalrmation. + The format of the message object to log. + + + + + Log a message with the level. + + An that supplies culture-specific formatting Fatalrmation. + The format of the message object to log. + The exception to log. + + + + + Log a message with the level. + + The format of the message object to log. + the list of format arguments + + + + Log a message with the level. + + The format of the message object to log. + The exception to log. + the list of format arguments + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + A callback used by the logger to obtain the message if log level is matched + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack Fatal. + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + + + + Log a message with the level using a callback to obtain the message + + + Using this method avoids the cost of creating a message and evaluating message arguments + that probably won't be logged due to loglevel settings. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack Fatal. + + + + Checks if this logger is enabled for the level. + + + Override this in your derived class to comply with the underlying logging system + + + + + Checks if this logger is enabled for the level. + + + Override this in your derived class to comply with the underlying logging system + + + + + Checks if this logger is enabled for the level. + + + Override this in your derived class to comply with the underlying logging system + + + + + Checks if this logger is enabled for the level. + + + Override this in your derived class to comply with the underlying logging system + + + + + Checks if this logger is enabled for the level. + + + Override this in your derived class to comply with the underlying logging system + + + + + Checks if this logger is enabled for the level. + + + Override this in your derived class to comply with the underlying logging system + + + + + Returns the global context for variables + + + + + Returns the thread-specific context for variables + + + + + Format message on demand. + + + + + Initializes a new instance of the class. + + The format message callback. + + + + Initializes a new instance of the class. + + The format provider. + The format message callback. + + + + Calls and returns result. + + + + + + Format string on demand. + + + + + Initializes a new instance of the class. + + The format provider. + The message. + The args. + + + + Runs on supplied arguemnts. + + string + + + + Represents a method responsible for writing a message to the log system. + + + + + Use the LogManager's or + methods to obtain instances for logging. + + + For configuring the underlying log system using application configuration, see the example + at System.Configuration.ConfigurationManager + For configuring programmatically, see the example section below. + + + The example below shows the typical use of LogManager to obtain a reference to a logger + and log an exception: + + + ILog log = LogManager.GetLogger(this.GetType()); + ... + try + { + /* .... */ + } + catch(Exception ex) + { + log.ErrorFormat("Hi {0}", ex, "dude"); + } + + + The example below shows programmatic configuration of the underlying log system: + + + // create properties + NameValueCollection properties = new NameValueCollection(); + properties["showDateTime"] = "true"; + + // set Adapter + Common.Logging.LogManager.Adapter = new + Common.Logging.Simple.ConsoleOutLoggerFactoryAdapter(properties); + + + + + + + Gilles Bayon + + + + Performs static 1-time init of LogManager by calling + + + + + Reset the infrastructure to its default settings. This means, that configuration settings + will be re-read from section <common/logging> of your app.config. + + + This is mainly used for unit testing, you wouldn't normally use this in your applications.
+ Note: instances already handed out from this LogManager are not(!) affected. + Resetting LogManager only affects new instances being handed out. +
+
+ + + Reset the infrastructure to its default settings. This means, that configuration settings + will be re-read from section <common/logging> of your app.config. + + + This is mainly used for unit testing, you wouldn't normally use this in your applications.
+ Note: instances already handed out from this LogManager are not(!) affected. + Resetting LogManager only affects new instances being handed out. +
+ + the instance to obtain settings for + re-initializing the LogManager. + +
+ + + Gets the logger by calling + on the currently configured using the type of the calling class. + + + This method needs to inspect the in order to determine the calling + class. This of course comes with a performance penalty, thus you shouldn't call it too + often in your application. + + + the logger instance obtained from the current + + + + Gets the logger by calling + on the currently configured using the type of the calling class. + + + This method needs to inspect the in order to determine the calling + class. This of course comes with a performance penalty, thus you shouldn't call it too + often in your application. + + + the logger instance obtained from the current + + + + Gets the logger by calling + on the currently configured using the specified type. + + the logger instance obtained from the current + + + + Gets the logger by calling + on the currently configured using the specified type. + + the logger instance obtained from the current + + + + Gets the logger by calling + on the currently configured using the specified type. + + The type. + the logger instance obtained from the current + + + + Gets the logger by calling + on the currently configured using the specified type. + + The type. + the logger instance obtained from the current + + + + Gets the logger by calling + on the currently configured using the specified key. + + The key. + the logger instance obtained from the current + + + + Gets the logger by calling + on the currently configured using the specified key. + + The key. + the logger instance obtained from the current + + + + Builds the logger factory adapter. + + a factory adapter instance. Is never null. + + + + Builds a instance from the given + using . + + + the instance. Is never null + + + + The key of the default configuration section to read settings from. + + + You can always change the source of your configuration settings by setting another instance + on . + + + + + The key of the default configuration section to read settings from. + + + You can always change the source of your configuration settings by setting another instance + on . + + + + + Gets the configuration reader used to initialize the LogManager. + + Primarily used for testing purposes but maybe useful to obtain configuration + information from some place other than the .NET application configuration file. + The configuration reader. + + + + Gets the configuration reader used to initialize the LogManager. + + Primarily used for testing purposes but maybe useful to obtain configuration + information from some place other than the .NET application configuration file. + The configuration reader. + + + + Gets or sets the adapter. + + The adapter. + + + + Gets or sets the adapter. + + The adapter. + + + + Abstract class providing a standard implementation of simple loggers. + + Erich Eichinger + + + + Creates and initializes a the simple logger. + + The key, usually type key of the calling class, of the logger. + The current logging threshold. Messages recieved that are beneath this threshold will not be logged. + Include level in the log message. + Include the current time in the log message. + Include the instance key in the log message. + The date and time format to use in the log message. + + + + Appends the formatted message to the specified . + + the that receíves the formatted message. + + + + + + + Determines if the given log level is currently enabled. + + + + + + + The key of the logger. + + + + + Include the current log level in the log message. + + + + + Include the current time in the log message. + + + + + Include the instance key in the log message. + + + + + The current logging threshold. Messages recieved that are beneath this threshold will not be logged. + + + + + The date and time format to use in the log message. + + + + + Determines Whether is set. + + + + + Returns if the current is greater than or + equal to . If it is, all messages will be sent to . + + + + + Returns if the current is greater than or + equal to . If it is, all messages will be sent to . + + + + + Returns if the current is greater than or + equal to . If it is, only messages with a of + , , , and + will be sent to . + + + + + Returns if the current is greater than or + equal to . If it is, only messages with a of + , , and + will be sent to . + + + + + Returns if the current is greater than or + equal to . If it is, only messages with a of + and will be sent to . + + + + + Returns if the current is greater than or + equal to . If it is, only messages with a of + will be sent to . + + + + + Base factory implementation for creating simple instances. + + Default settings are LogLevel.All, showDateTime = true, showLogName = true, and no DateTimeFormat. + The keys in the NameValueCollection to configure this adapter are the following + + level + showDateTime + showLogName + dateTimeFormat + + + Here is an example how to implement your own logging adapter: + + public class ConsoleOutLogger : AbstractSimpleLogger + { + public ConsoleOutLogger(string logName, LogLevel logLevel, bool showLevel, bool showDateTime, + bool showLogName, string dateTimeFormat) + : base(logName, logLevel, showLevel, showDateTime, showLogName, dateTimeFormat) + { + } + + protected override void WriteInternal(LogLevel level, object message, Exception e) + { + // Use a StringBuilder for better performance + StringBuilder sb = new StringBuilder(); + FormatOutput(sb, level, message, e); + + // Print to the appropriate destination + Console.Out.WriteLine(sb.ToString()); + } + } + + public class ConsoleOutLoggerFactoryAdapter : AbstractSimpleLoggerFactoryAdapter + { + public ConsoleOutLoggerFactoryAdapter(NameValueCollection properties) + : base(properties) + { } + + protected override ILog CreateLogger(string key, LogLevel level, bool showLevel, bool + showDateTime, bool showLogName, string dateTimeFormat) + { + ILog log = new ConsoleOutLogger(key, level, showLevel, showDateTime, showLogName, + dateTimeFormat); + return log; + } + } + + + + Gilles Bayon + Mark Pollack + Erich Eichinger + + + + Initializes a new instance of the class. + + + Looks for level, showDateTime, showLogName, dateTimeFormat items from + for use when the GetLogger methods are called. + System.Configuration.ConfigurationManager for more information on how to use the + standard .NET application configuraiton file (App.config/Web.config) + to configure this adapter. + + The key value collection, typically specified by the user in + a configuration section named common/logging. + + + + Initializes a new instance of the class with + default settings for the loggers created by this factory. + + + + + Create the specified logger instance + + + + + Derived factories need to implement this method to create the + actual logger instance. + + a new logger instance. Must never be null! + + + + The default to use when creating new instances. + + + + + The default setting to use when creating new instances. + + + + + The default setting to use when creating new instances. + + + + + The default setting to use when creating new instances. + + + + + The default setting to use when creating new instances. + + + + + A logger created by that + sends all log events to the owning adapter's + + Erich Eichinger + + + + The adapter that created this logger instance. + + + + + Clears all captured events + + + + + Resets the to null. + + + + + Holds the list of logged events. + + + To access this collection in a multithreaded application, put a lock on the list instance. + + + + + instances send their captured log events to this method. + + + + + Create a new logger instance. + + + + + Create a new and send it to + + + + + + + + Holds the last log event received from any of this adapter's loggers. + + + + + A logging event captured by + + Erich Eichinger + + + + The logger that logged this event + + + + + The level used to log this event + + + + + The raw message object + + + + + A logged exception + + + + + Create a new event instance + + + + + Retrieves the formatted message text + + + + + An adapter, who's loggers capture all log events and send them to . + Retrieve the list of log events from . + + + This logger factory is mainly for debugging and test purposes. + + This is an example how you might use this adapter for testing: + + // configure for capturing + CapturingLoggerFactoryAdapter adapter = new CapturingLoggerFactoryAdapter(); + LogManager.Adapter = adapter; + + // reset capture state + adapter.Clear(); + // log something + ILog log = LogManager.GetCurrentClassLogger(); + log.DebugFormat("Current Time:{0}", DateTime.Now); + + // check logged data + Assert.AreEqual(1, adapter.LoggerEvents.Count); + Assert.AreEqual(LogLevel.Debug, adapter.LastEvent.Level); + + + + Erich Eichinger + + + + Clears all captured events + + + + + Resets the to null. + + + + + Holds the list of logged events. + + + To access this collection in a multithreaded application, put a lock on the list instance. + + + + + instances send their captured log events to this method. + + + + + Get a instance for the given type. + + + + + Get a instance for the given key. + + + + + Holds the last log event received from any of this adapter's loggers. + + + + + Sends log messages to . + + Gilles Bayon + + + + Creates and initializes a logger that writes messages to . + + The key, usually type key of the calling class, of the logger. + The current logging threshold. Messages recieved that are beneath this threshold will not be logged. + Include the current log level in the log message. + Include the current time in the log message. + Include the instance key in the log message. + The date and time format to use in the log message. + + + + Do the actual logging by constructing the log message using a then + sending the output to . + + The of the message. + The log message. + An optional associated with the message. + + + + Factory for creating instances that write data using . + + + + Below is an example how to configure this adapter: + + <configuration> + + <configSections> + <sectionGroup key="common"> + <section key="logging" + type="Common.Logging.ConfigurationSectionHandler, Common.Logging" + requirePermission="false" /> + </sectionGroup> + </configSections> + + <common> + <logging> + <factoryAdapter type="Common.Logging.Simple.DebugLoggerFactoryAdapter, Common.Logging"> + <arg key="level" value="ALL" /> + </factoryAdapter> + </logging> + </common> + + </configuration> + + + + + Gilles Bayon + Mark Pollack + Erich Eichinger + + + + Initializes a new instance of the class using default + settings. + + + + + Initializes a new instance of the class. + + + Looks for level, showDateTime, showLogName, dateTimeFormat items from + for use when the GetLogger methods are called. + for more information on how to use the + standard .NET application configuraiton file (App.config/Web.config) + to configure this adapter. + + The key value collection, typically specified by the user in + a configuration section named common/logging. + + + + Initializes a new instance of the class with + default settings for the loggers created by this factory. + + + + + Creates a new instance. + + + + + + + + + Silently ignores all log messages. + + Gilles Bayon + Erich Eichinger + + + + Ignores message. + + + + + + Ignores message. + + + + + + + Ignores message. + + The format of the message object to log. + + + + + Ignores message. + + The format of the message object to log. + The exception to log. + the list of message format arguments + + + + Ignores message. + + An that supplies culture-specific formatting information. + The format of the message object to log. + the list of message format arguments + + + + Ignores message. + + An that supplies culture-specific formatting information. + The format of the message object to log. + The exception to log. + the list of message format arguments + + + + Ignores message. + + A callback used by the logger to obtain the message if log level is matched + + + + Ignores message. + + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack trace. + + + + Ignores message. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + + + + Ignores message. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack trace. + + + + Ignores message. + + + + + + Ignores message. + + + + + + + Ignores message. + + The format of the message object to log. + + + + + Ignores message. + + The format of the message object to log. + The exception to log. + the list of message format arguments + + + + Ignores message. + + An that supplies culture-specific formatting information. + The format of the message object to log. + the list of message format arguments + + + + Ignores message. + + An that supplies culture-specific formatting information. + The format of the message object to log. + The exception to log. + the list of message format arguments + + + + Ignores message. + + A callback used by the logger to obtain the message if log level is matched + + + + Ignores message. + + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack Debug. + + + + Ignores message. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + + + + Ignores message. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack Debug. + + + + Ignores message. + + + + + + Ignores message. + + + + + + + Ignores message. + + The format of the message object to log. + + + + + Ignores message. + + The format of the message object to log. + The exception to log. + the list of message format arguments + + + + Ignores message. + + An that supplies culture-specific formatting information. + The format of the message object to log. + the list of message format arguments + + + + Ignores message. + + An that supplies culture-specific formatting information. + The format of the message object to log. + The exception to log. + the list of message format arguments + + + + Ignores message. + + A callback used by the logger to obtain the message if log level is matched + + + + Ignores message. + + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack Info. + + + + Ignores message. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + + + + Ignores message. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack Info. + + + + Ignores message. + + + + + + Ignores message. + + + + + + + Ignores message. + + The format of the message object to log. + + + + + Ignores message. + + The format of the message object to log. + The exception to log. + the list of message format arguments + + + + Ignores message. + + An that supplies culture-specific formatting Information. + The format of the message object to log. + the list of message format arguments + + + + Ignores message. + + An that supplies culture-specific formatting Information. + The format of the message object to log. + The exception to log. + the list of message format arguments + + + + Ignores message. + + A callback used by the logger to obtain the message if log level is matched + + + + Ignores message. + + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack Warn. + + + + Ignores message. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + + + + Ignores message. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack Warn. + + + + Ignores message. + + + + + + Ignores message. + + + + + + + Ignores message. + + The format of the message object to log. + + + + + Ignores message. + + The format of the message object to log. + The exception to log. + the list of message format arguments + + + + Ignores message. + + An that supplies culture-specific formatting Errorrmation. + The format of the message object to log. + the list of message format arguments + + + + Ignores message. + + An that supplies culture-specific formatting Errorrmation. + The format of the message object to log. + The exception to log. + the list of message format arguments + + + + Ignores message. + + A callback used by the logger to obtain the message if log level is matched + + + + Ignores message. + + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack Error. + + + + Ignores message. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + + + + Ignores message. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack Error. + + + + Ignores message. + + + + + + Ignores message. + + + + + + + Ignores message. + + The format of the message object to log. + + + + + Ignores message. + + The format of the message object to log. + The exception to log. + the list of message format arguments + + + + Ignores message. + + An that supplies culture-specific formatting Fatalrmation. + The format of the message object to log. + the list of message format arguments + + + + Ignores message. + + An that supplies culture-specific formatting Fatalrmation. + The format of the message object to log. + The exception to log. + the list of message format arguments + + + + Ignores message. + + A callback used by the logger to obtain the message if log level is matched + + + + Ignores message. + + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack Fatal. + + + + Ignores message. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + + + + Ignores message. + + An that supplies culture-specific formatting information. + A callback used by the logger to obtain the message if log level is matched + The exception to log, including its stack Fatal. + + + + Always returns . + + + + + Always returns . + + + + + Always returns . + + + + + Always returns . + + + + + Always returns . + + + + + Always returns . + + + + + Returns the global context for variables + + + + + Returns the thread-specific context for variables + + + + + Factory for creating instances that silently ignores + logging requests. + + + This logger adapter is the default used by Common.Logging if unconfigured. Using this logger adapter is the most efficient + way to suppress any logging output. + + Below is an example how to configure this adapter: + + <configuration> + + <configSections> + <sectionGroup key="common"> + <section key="logging" + type="Common.Logging.ConfigurationSectionHandler, Common.Logging" + requirePermission="false" /> + </sectionGroup> + </configSections> + + <common> + <logging> + <factoryAdapter type="Common.Logging.Simple.NoOpLoggerFactoryAdapter, Common.Logging"> + <arg key="level" value="ALL" /> + </factoryAdapter> + </logging> + </common> + + </configuration> + + + + Gilles Bayon + + + + Constructor + + + + + Constructor + + + + + Get a ILog instance by type + + + + + + + Get a ILog instance by type key + + + + + + + A null-functionality implementation of + + + + + Sets the value of a new or existing variable within the global context + + The key of the variable that is to be added + The value to add + + + + Gets the value of a variable within the global context + + The key of the variable to get + The value or null if not found + + + + Checks if a variable is set within the global context + + The key of the variable to check for + True if the variable is set + + + + Removes a variable from the global context by key + + The key of the variable to remove + + + + Clears the global context variables + + + + + A implementation sending all System.Diagnostics.Trace output to + the Common.Logging infrastructure. + + + This listener captures all output sent by calls to System.Diagnostics.Trace and + and and sends it to an instance.
+ The instance to be used is obtained by calling + . The name of the logger is created by passing + this listener's and any source or category passed + into this listener (see or for example). +
+ + The snippet below shows how to add and configure this listener to your app.config: + + <system.diagnostics> + <sharedListeners> + <add name="Diagnostics" + type="Common.Logging.Simple.CommonLoggingTraceListener, Common.Logging" + initializeData="DefaultTraceEventType=Information; LoggerNameFormat={listenerName}.{sourceName}"> + <filter type="System.Diagnostics.EventTypeFilter" initializeData="Information"/> + </add> + </sharedListeners> + <trace> + <listeners> + <add name="Diagnostics" /> + </listeners> + </trace> + </system.diagnostics> + + + Erich Eichinger +
+ + + Creates a new instance with the default name "Diagnostics" and "Trace". + + + + + Creates a new instance initialized with properties from the . string. + + + is a semicolon separated string of name/value pairs, where each pair has + the form key=value. E.g. + "Name=MyLoggerName;LogLevel=Debug" + + a semicolon separated list of name/value pairs. + + + + Creates a new instance initialized with the specified properties. + + name/value configuration properties. + + + + Logs the given message to the Common.Logging infrastructure. + + the eventType + the name or category name passed into e.g. . + the id of this event + the message format + the message arguments + + + + Writes message to logger provided by . + + + + + Writes message to logger provided by . + + + + + Writes message to logger provided by . + + + + + Writes message to logger provided by . + + + + + Writes message to logger provided by . + + + + + Writes message to logger provided by . + + + + + Writes message to logger provided by . + + + + + Writes message to logger provided by + + + + + Writes message to logger provided by + + + + + Writes message to logger provided by + + + + + Writes message to logger provided by + + + + + Writes message to logger provided by + + + + + Writes message to logger provided by + + + + + Sets the default to use for logging + all events emitted by .Write(...) and + .WriteLine(...) methods. + + + This listener captures all output sent by calls to and + sends it to an instance using the specified + on . + + + + + Format to use for creating the logger name. Defaults to "{listenerName}.{sourceName}". + + + Available placeholders are: + + {listenerName}: the configured name of this listener instance. + {sourceName}: the trace source name an event originates from (see e.g. . + + + + + + Used in an application's configuration file (App.Config or Web.Config) to configure the logging subsystem. + + + An example configuration section that writes log messages to the Console using the + built-in Console Logger. + + <configuration> + <configSections> + <sectionGroup name="common"> + <section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" /> + </sectionGroup> + </configSections> + <common> + <logging> + <factoryAdapter type="Common.Logging.Simple.ConsoleOutLoggerFactoryAdapter, Common.Logging"> + <arg key="showLogName" value="true" /> + <arg key="showDateTime" value="true" /> + <arg key="level" value="ALL" /> + <arg key="dateTimeFormat" value="yyyy/MM/dd HH:mm:ss:fff" /> + </factoryAdapter> + </logging> + </common> + </configuration> + + + + + + Ensure static fields get initialized before any class member + can be accessed (avoids beforeFieldInit) + + + + + Constructor + + + + + Retrieves the of the logger the use by looking at the logFactoryAdapter element + of the logging configuration element. + + + + A object containing the specified type that implements + along with zero or more properties that will be + passed to the logger factory adapter's constructor as an . + + + + + Verifies that the logFactoryAdapter element appears once in the configuration section. + + settings of a parent section - atm this must always be null + Additional information about the configuration process. + The configuration section to apply an XPath query too. + + A object containing the specified logFactoryAdapter type + along with user supplied configuration properties. + + + + + Verifies that the logFactoryAdapter element appears once in the configuration section. + + The parent of the current item. + Additional information about the configuration process. + The configuration section to apply an XPath query too. + + A object containing the specified logFactoryAdapter type + along with user supplied configuration properties. + + + + + Sends log messages to . + + Gilles Bayon + + + + Creates and initializes a logger that writes messages to . + + The name, usually type name of the calling class, of the logger. + The current logging threshold. Messages recieved that are beneath this threshold will not be logged. + Include the current log level in the log message. + Include the current time in the log message. + Include the instance name in the log message. + The date and time format to use in the log message. + + + + Creates and initializes a logger that writes messages to . + + The name, usually type name of the calling class, of the logger. + The current logging threshold. Messages recieved that are beneath this threshold will not be logged. + Include the current log level in the log message. + Include the current time in the log message. + Include the instance name in the log message. + The date and time format to use in the log message. + Use color when writing the log message. + + + + Do the actual logging by constructing the log message using a then + sending the output to . + + The of the message. + The log message. + An optional associated with the message. + + + + Factory for creating instances that write data to . + + + + Below is an example how to configure this adapter: + + <configuration> + + <configSections> + <sectionGroup name="common"> + <section name="logging" + type="Common.Logging.ConfigurationSectionHandler, Common.Logging" + requirePermission="false" /> + </sectionGroup> + </configSections> + + <common> + <logging> + <factoryAdapter type="Common.Logging.Simple.ConsoleOutLoggerFactoryAdapter, Common.Logging"> + <arg key="level" value="ALL" /> + </factoryAdapter> + </logging> + </common> + + </configuration> + + + + + + + Gilles Bayon + Mark Pollack + Erich Eichinger + + + + Initializes a new instance of the class using default + settings. + + + + + Initializes a new instance of the class. + + + Looks for level, showDateTime, showLogName, dateTimeFormat items from + for use when the GetLogger methods are called. + for more information on how to use the + standard .NET application configuraiton file (App.config/Web.config) + to configure this adapter. + + The name value collection, typically specified by the user in + a configuration section named common/logging. + + + + Constructor for binary backwards compatibility with non-portableversions + + The properties. + + + + Initializes a new instance of the class with + default settings for the loggers created by this factory. + + + + + Initializes a new instance of the class with + default settings for the loggers created by this factory. + + + + + Creates a new instance. + + + + + Logger sending everything to the trace output stream using . + + + Beware not to use in combination with this logger as + this would result in an endless loop for obvious reasons! + + + + Gilles Bayon + Erich Eichinger + + + + Creates a new TraceLogger instance. + + whether to use or for logging. + the name of this logger + the default log level to use + Include the current log level in the log message. + Include the current time in the log message. + Include the instance name in the log message. + The date and time format to use in the log message. + + + + Determines if the given log level is currently enabled. + checks if is true. + + + + + Do the actual logging. + + + + + + + + Called after deserialization completed. + + + + + Used to defer message formatting until it is really needed. + + + This class also improves performance when multiple + s are configured. + + + + + Factory for creating instances that send + everything to the output stream. + + + Beware not to use in combination with this logger factory + as this would result in an endless loop for obvious reasons! + + Below is an example how to configure this adapter: + + <configuration> + + <configSections> + <sectionGroup name="common"> + <section name="logging" + type="Common.Logging.ConfigurationSectionHandler, Common.Logging" + requirePermission="false" /> + </sectionGroup> + </configSections> + + <common> + <logging> + <factoryAdapter type="Common.Logging.Simple.TraceLoggerFactoryAdapter, Common.Logging"> + <arg key="level" value="ALL" /> + </factoryAdapter> + </logging> + </common> + + </configuration> + + + + + + + Gilles Bayon + Mark Pollack + Erich Eichinger + + + + Initializes a new instance of the class using default settings. + + + + + Initializes a new instance of the class. + + + Looks for level, showDateTime, showLogName, dateTimeFormat items from + for use when the GetLogger methods are called. + for more information on how to use the + standard .NET application configuraiton file (App.config/Web.config) + to configure this adapter. + + The name value collection, typically specified by the user in + a configuration section named common/logging. + + + + Initializes a new instance of the class with + default settings for the loggers created by this factory. + + + + + Creates a new instance. + + + + + Whether to use .TraceXXXX(string,object[]) methods for logging + or . + + +
+
diff --git a/server/Dapper.dll b/server/Dapper.dll new file mode 100644 index 0000000..7b11f54 Binary files /dev/null and b/server/Dapper.dll differ diff --git a/server/Dapper.pdb b/server/Dapper.pdb new file mode 100644 index 0000000..c874074 Binary files /dev/null and b/server/Dapper.pdb differ diff --git a/server/Dapper.xml b/server/Dapper.xml new file mode 100644 index 0000000..c7dde8d --- /dev/null +++ b/server/Dapper.xml @@ -0,0 +1,1412 @@ + + + + Dapper + + + + + Additional state flags that control command behaviour + + + + + No additional flags + + + + + Should data be buffered before returning? + + + + + Can async queries be pipelined? + + + + + Should the plan cache be bypassed? + + + + + Represents the key aspects of a sql operation + + + + + The command (sql or a stored-procedure name) to execute + + + + + The parameters associated with the command + + + + + The active transaction for the command + + + + + The effective timeout for the command + + + + + The type of command that the command-text represents + + + + + Should data be buffered before returning? + + + + + Should the plan for this query be cached? + + + + + Additional state flags against this command + + + + + Can async queries be pipelined? + + + + + Initialize the command definition + + + + + For asynchronous operations, the cancellation-token + + + + + Dapper, a light weight object mapper for ADO.NET + + + + + Implement this interface to pass an arbitrary db specific set of parameters to Dapper + + + + + Add all the parameters needed to the command just before it executes + + The raw command prior to execution + Information about the query + + + + Extends IDynamicParameters providing by-name lookup of parameter values + + + + + Get the value of the specified parameter (return null if not found) + + + + + Extends IDynamicParameters with facilities for executing callbacks after commands have completed + + + + + Invoked when the command has executed + + + + + Implement this interface to pass an arbitrary db specific parameter to Dapper + + + + + Add the parameter needed to the command before it executes + + The raw command prior to execution + Parameter name + + + + Implement this interface to perform custom type-based parameter handling and value parsing + + + + + Assign the value of a parameter before a command executes + + The parameter to configure + Parameter value + + + + Parse a database value back to a typed value + + The value from the database + The type to parse to + The typed value + + + + A type handler for data-types that are supported by the underlying provider, but which need + a well-known UdtTypeName to be specified + + + + + Creates a new instance of UdtTypeHandler with the specified UdtTypeName + + + + + Base-class for simple type-handlers + + + + + Assign the value of a parameter before a command executes + + The parameter to configure + Parameter value + + + + Parse a database value back to a typed value + + The value from the database + The typed value + + + + Implement this interface to change default mapping of reader columns to type members + + + + + Finds best constructor + + DataReader column names + DataReader column types + Matching constructor or default one + + + + Returns a constructor which should *always* be used. + + Parameters will be default values, nulls for reference types and zero'd for value types. + + Use this class to force object creation away from parameterless constructors you don't control. + + + + + Gets mapping for constructor parameter + + Constructor to resolve + DataReader column name + Mapping implementation + + + + Gets member mapping for column + + DataReader column name + Mapping implementation + + + + Implements this interface to provide custom member mapping + + + + + Source DataReader column name + + + + + Target member type + + + + + Target property + + + + + Target field + + + + + Target constructor parameter + + + + + This is a micro-cache; suitable when the number of terms is controllable (a few hundred, for example), + and strictly append-only; you cannot change existing values. All key matches are on **REFERENCE** + equality. The type is fully thread-safe. + + + + + Called if the query cache is purged via PurgeQueryCache + + + + + Purge the query cache + + + + + Return a count of all the cached queries by dapper + + + + + + Return a list of all the queries cached by dapper + + + + + + + Deep diagnostics only: find any hash collisions in the cache + + + + + + Clear the registered type handlers + + + + + Configure the specified type to be mapped to a given db-type + + + + + Configure the specified type to be processed by a custom handler + + + + + Configure the specified type to be processed by a custom handler + + + + + Configure the specified type to be processed by a custom handler + + + + + Not intended for direct usage + + + + + Not intended for direct usage + + + + + Not intended for direct usage + + + + + Get the DbType that maps to a given value + + + + + Identity of a cached query in Dapper, used for extensibility + + + + + Create an identity for use with DynamicParameters, internal use only + + + + + + + + + + + + + + The sql + + + + + The command type + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Compare 2 Identity objects + + + + + + + Obtains the data as a list; if it is *already* a list, the original object is returned without + any duplication; otherwise, ToList() is invoked. + + + + + Execute parameterized SQL + + Number of rows affected + + + + Execute parameterized SQL + + Number of rows affected + + + + Execute parameterized SQL that selects a single value + + The first cell selected + + + + Execute parameterized SQL that selects a single value + + The first cell selected + + + + Execute parameterized SQL that selects a single value + + The first cell selected + + + + Execute parameterized SQL that selects a single value + + The first cell selected + + + + Execute parameterized SQL and return an + + An that can be used to iterate over the results of the SQL query. + + This is typically used when the results of a query are not processed by Dapper, for example, used to fill a + or . + + + + + + + + + + Execute parameterized SQL and return an + + An that can be used to iterate over the results of the SQL query. + + This is typically used when the results of a query are not processed by Dapper, for example, used to fill a + or . + + + + + Execute parameterized SQL and return an + + An that can be used to iterate over the results of the SQL query. + + This is typically used when the results of a query are not processed by Dapper, for example, used to fill a + or . + + + + + Return a list of dynamic objects, reader is closed after the call + + Note: each row can be accessed via "dynamic", or by casting to an IDictionary<string,object> + + + + Executes a query, returning the data typed as per T + + the dynamic param may seem a bit odd, but this works around a major usability issue in vs, if it is Object vs completion gets annoying. Eg type new [space] get new object + A sequence of data of the supplied type; if a basic type (int, string, etc) is queried then the data from the first column in assumed, otherwise an instance is + created per row, and a direct column-name===member-name mapping is assumed (case insensitive). + + + + + Executes a query, returning the data typed as per the Type suggested + + A sequence of data of the supplied type; if a basic type (int, string, etc) is queried then the data from the first column in assumed, otherwise an instance is + created per row, and a direct column-name===member-name mapping is assumed (case insensitive). + + + + + Executes a query, returning the data typed as per T + + the dynamic param may seem a bit odd, but this works around a major usability issue in vs, if it is Object vs completion gets annoying. Eg type new [space] get new object + A sequence of data of the supplied type; if a basic type (int, string, etc) is queried then the data from the first column in assumed, otherwise an instance is + created per row, and a direct column-name===member-name mapping is assumed (case insensitive). + + + + + Execute a command that returns multiple result sets, and access each in turn + + + + + Execute a command that returns multiple result sets, and access each in turn + + + + + Maps a query to objects + + The first type in the record set + The second type in the record set + The return type + + + + + + + The Field we should split and read the second object from (default: id) + Number of seconds before command execution timeout + Is it a stored proc or a batch? + + + + + Maps a query to objects + + + + + + + + + + + + The Field we should split and read the second object from (default: id) + Number of seconds before command execution timeout + + + + + + Perform a multi mapping query with 4 input parameters + + + + + + + + + + + + + + + + + + + + Perform a multi mapping query with 5 input parameters + + + + + + + + + + + + + + + + + + + + + Perform a multi mapping query with 6 input parameters + + + + + + + + + + + + + + + + + + + + + + Perform a multi mapping query with 7 input parameters + + + + + + + + + + + + + + + + + + + + + + + Perform a multi mapping query with arbitrary input parameters + + The return type + + + array of types in the record set + + + + + The Field we should split and read the second object from (default: id) + Number of seconds before command execution timeout + Is it a stored proc or a batch? + + + + + Internal use only + + + + + + + Internal use only + + + + + Internal use only + + + + + Internal use only + + + + + Represents a placeholder for a value that should be replaced as a literal value in the resulting sql + + + + + The text in the original command that should be replaced + + + + + The name of the member referred to by the token + + + + + Replace all literal tokens with their text form + + + + + Convert numeric values to their string form for SQL literal purposes + + + + + Internal use only + + + + + Gets type-map for the given type + + Type map implementation, DefaultTypeMap instance if no override present + + + + Set custom mapping for type deserializers + + Entity type to override + Mapping rules impementation, null to remove custom map + + + + Internal use only + + + + + + + + + + + Throws a data exception, only used internally + + + + + Key used to indicate the type name associated with a DataTable + + + + + How should connection strings be compared for equivalence? Defaults to StringComparer.Ordinal. + Providing a custom implementation can be useful for allowing multi-tenancy databases with identical + schema to share strategies. Note that usual equivalence rules apply: any equivalent connection strings + MUST yield the same hash-code. + + + + + The grid reader provides interfaces for reading multiple result sets from a Dapper query + + + + + Read the next grid of results, returned as a dynamic object + + Note: each row can be accessed via "dynamic", or by casting to an IDictionary<string,object> + + + + Read the next grid of results + + + + + Read the next grid of results + + + + + Read multiple objects from a single record set on the grid + + + + + Read multiple objects from a single record set on the grid + + + + + Read multiple objects from a single record set on the grid + + + + + Read multiple objects from a single record set on the grid + + + + + Read multiple objects from a single record set on the grid + + + + + Read multiple objects from a single record set on the grid + + + + + Has the underlying reader been consumed? + + + + + Dispose the grid, closing and disposing both the underlying reader and command. + + + + + Read the next grid of results, returned as a dynamic object + + Note: each row can be accessed via "dynamic", or by casting to an IDictionary<string,object> + + + + Read the next grid of results + + + + + Read the next grid of results + + + + + Used to pass a DataTable as a TableValuedParameter + + + + + Associate a DataTable with a type name + + + + + Fetch the type name associated with a DataTable + + + + + Execute a query asynchronously using .NET 4.5 Task. + + Note: each row can be accessed via "dynamic", or by casting to an IDictionary<string,object> + + + + Execute a query asynchronously using .NET 4.5 Task. + + Note: each row can be accessed via "dynamic", or by casting to an IDictionary<string,object> + + + + Execute a query asynchronously using .NET 4.5 Task. + + + + + Execute a query asynchronously using .NET 4.5 Task. + + + + + Execute a query asynchronously using .NET 4.5 Task. + + + + + Execute a query asynchronously using .NET 4.5 Task. + + + + + Execute a command asynchronously using .NET 4.5 Task. + + + + + Execute a command asynchronously using .NET 4.5 Task. + + + + + Maps a query to objects + + The first type in the recordset + The second type in the recordset + The return type + + + + + + + The field we should split and read the second object from (default: id) + Number of seconds before command execution timeout + Is it a stored proc or a batch? + + + + + Maps a query to objects + + The first type in the recordset + The second type in the recordset + The return type + + The field we should split and read the second object from (default: id) + The command to execute + + + + + + Maps a query to objects + + + + + + + + + + + + The Field we should split and read the second object from (default: id) + Number of seconds before command execution timeout + + + + + + Maps a query to objects + + + + + + + The field we should split and read the second object from (default: id) + The command to execute + + + + + + Perform a multi mapping query with 4 input parameters + + + + + + + + + + + + + + + + + + + + Perform a multi mapping query with 4 input parameters + + + + + + + + The field we should split and read the second object from (default: id) + The command to execute + + + + + + Perform a multi mapping query with 5 input parameters + + + + + Perform a multi mapping query with 5 input parameters + + + + + Perform a multi mapping query with 6 input parameters + + + + + Perform a multi mapping query with 6 input parameters + + + + + Perform a multi mapping query with 7 input parameters + + + + + Perform a multi mapping query with 7 input parameters + + + + + Perform a multi mapping query with arbitrary input parameters + + The return type + + + array of types in the recordset + + + + + The Field we should split and read the second object from (default: id) + Number of seconds before command execution timeout + Is it a stored proc or a batch? + + + + + Execute a command that returns multiple result sets, and access each in turn + + + + + Execute a command that returns multiple result sets, and access each in turn + + + + + Execute parameterized SQL and return an + + An that can be used to iterate over the results of the SQL query. + + This is typically used when the results of a query are not processed by Dapper, for example, used to fill a + or . + + + + + + + + + + Execute parameterized SQL and return an + + An that can be used to iterate over the results of the SQL query. + + This is typically used when the results of a query are not processed by Dapper, for example, used to fill a + or . + + + + + Execute parameterized SQL that selects a single value + + The first cell selected + + + + Execute parameterized SQL that selects a single value + + The first cell selected + + + + Execute parameterized SQL that selects a single value + + The first cell selected + + + + Execute parameterized SQL that selects a single value + + The first cell selected + + + + A bag of parameters that can be passed to the Dapper Query and Execute methods + + + + + construct a dynamic parameter bag + + + + + construct a dynamic parameter bag + + can be an anonymous type or a DynamicParameters bag + + + + Append a whole object full of params to the dynamic + EG: AddDynamicParams(new {A = 1, B = 2}) // will add property A and B to the dynamic + + + + + + Add a parameter to this dynamic parameter list + + + + + Add a parameter to this dynamic parameter list + + + + + If true, the command-text is inspected and only values that are clearly used are included on the connection + + + + + Add all the parameters needed to the command just before it executes + + The raw command prior to execution + Information about the query + + + + All the names of the param in the bag, use Get to yank them out + + + + + Get the value of a parameter + + + + The value, note DBNull.Value is not returned, instead the value is returned as null + + + + Allows you to automatically populate a target property/field from output parameters. It actually + creates an InputOutput parameter, so you can still pass data in. + + + The object whose property/field you wish to populate. + A MemberExpression targeting a property/field of the target (or descendant thereof.) + + The size to set on the parameter. Defaults to 0, or DbString.DefaultLength in case of strings. + The DynamicParameters instance + + + + Used to pass a DataTable as a TableValuedParameter + + + + + Create a new instance of TableValuedParameter + + + + + Create a new instance of TableValuedParameter + + + + + This class represents a SQL string, it can be used if you need to denote your parameter is a Char vs VarChar vs nVarChar vs nChar + + + + + A value to set the default value of strings + going through Dapper. Default is 4000, any value larger than this + field will not have the default value applied. + + + + + Create a new DbString + + + + + Ansi vs Unicode + + + + + Fixed length + + + + + Length of the string -1 for max + + + + + The value of the string + + + + + Add the parameter to the command... internal use only + + + + + + + Handles variances in features per DBMS + + + + + Gets the feature set based on the passed connection + + + + + True if the db supports array columns e.g. Postgresql + + + + + Represents simple member map for one of target parameter or property or field to source DataReader column + + + + + Creates instance for simple property mapping + + DataReader column name + Target property + + + + Creates instance for simple field mapping + + DataReader column name + Target property + + + + Creates instance for simple constructor parameter mapping + + DataReader column name + Target constructor parameter + + + + DataReader column name + + + + + Target member type + + + + + Target property + + + + + Target field + + + + + Target constructor parameter + + + + + Represents default type mapping strategy used by Dapper + + + + + Creates default type map + + Entity type + + + + Finds best constructor + + DataReader column names + DataReader column types + Matching constructor or default one + + + + Returns the constructor, if any, that has the ExplicitConstructorAttribute on it. + + + + + Gets mapping for constructor parameter + + Constructor to resolve + DataReader column name + Mapping implementation + + + + Gets member mapping for column + + DataReader column name + Mapping implementation + + + + Should column names like User_Id be allowed to match properties/fields like UserId ? + + + + + Implements custom property mapping by user provided criteria (usually presence of some custom attribute with column to member mapping) + + + + + Creates custom property mapping + + Target entity type + Property selector based on target type and DataReader column name + + + + Always returns default constructor + + DataReader column names + DataReader column types + Default constructor + + + + Always returns null + + + + + + Not implemented as far as default constructor used for all cases + + + + + + + + Returns property based on selector strategy + + DataReader column name + Poperty member map + + + + Describes a reader that controls the lifetime of both a command and a reader, + exposing the downstream command/reader as properties. + + + + + Obtain the underlying reader + + + + + Obtain the underlying command + + + + + Tell Dapper to use an explicit constructor, passing nulls or 0s for all parameters + + + + diff --git a/server/FSO.Common.DataService.dll b/server/FSO.Common.DataService.dll new file mode 100644 index 0000000..91aea43 Binary files /dev/null and b/server/FSO.Common.DataService.dll differ diff --git a/server/FSO.Common.DataService.pdb b/server/FSO.Common.DataService.pdb new file mode 100644 index 0000000..3c54ab7 Binary files /dev/null and b/server/FSO.Common.DataService.pdb differ diff --git a/server/FSO.Common.DatabaseService.dll b/server/FSO.Common.DatabaseService.dll new file mode 100644 index 0000000..20dcfb0 Binary files /dev/null and b/server/FSO.Common.DatabaseService.dll differ diff --git a/server/FSO.Common.DatabaseService.pdb b/server/FSO.Common.DatabaseService.pdb new file mode 100644 index 0000000..41aa894 Binary files /dev/null and b/server/FSO.Common.DatabaseService.pdb differ diff --git a/server/FSO.Common.Domain.dll b/server/FSO.Common.Domain.dll new file mode 100644 index 0000000..e7f5d2b Binary files /dev/null and b/server/FSO.Common.Domain.dll differ diff --git a/server/FSO.Common.Domain.pdb b/server/FSO.Common.Domain.pdb new file mode 100644 index 0000000..528dc29 Binary files /dev/null and b/server/FSO.Common.Domain.pdb differ diff --git a/server/FSO.Common.dll b/server/FSO.Common.dll new file mode 100644 index 0000000..9fc4b9d Binary files /dev/null and b/server/FSO.Common.dll differ diff --git a/server/FSO.Common.pdb b/server/FSO.Common.pdb new file mode 100644 index 0000000..d343e34 Binary files /dev/null and b/server/FSO.Common.pdb differ diff --git a/server/FSO.Content.dll b/server/FSO.Content.dll new file mode 100644 index 0000000..054462c Binary files /dev/null and b/server/FSO.Content.dll differ diff --git a/server/FSO.Content.pdb b/server/FSO.Content.pdb new file mode 100644 index 0000000..75cefcd Binary files /dev/null and b/server/FSO.Content.pdb differ diff --git a/server/FSO.Files.dll b/server/FSO.Files.dll new file mode 100644 index 0000000..2c761cf Binary files /dev/null and b/server/FSO.Files.dll differ diff --git a/server/FSO.Files.dll.config b/server/FSO.Files.dll.config new file mode 100644 index 0000000..a80813a --- /dev/null +++ b/server/FSO.Files.dll.config @@ -0,0 +1,3 @@ + + + diff --git a/server/FSO.Files.pdb b/server/FSO.Files.pdb new file mode 100644 index 0000000..90313a5 Binary files /dev/null and b/server/FSO.Files.pdb differ diff --git a/server/FSO.HIT.dll b/server/FSO.HIT.dll new file mode 100644 index 0000000..a11433c Binary files /dev/null and b/server/FSO.HIT.dll differ diff --git a/server/FSO.HIT.pdb b/server/FSO.HIT.pdb new file mode 100644 index 0000000..0ed50f0 Binary files /dev/null and b/server/FSO.HIT.pdb differ diff --git a/server/FSO.LotView.dll b/server/FSO.LotView.dll new file mode 100644 index 0000000..412f455 Binary files /dev/null and b/server/FSO.LotView.dll differ diff --git a/server/FSO.LotView.pdb b/server/FSO.LotView.pdb new file mode 100644 index 0000000..65801fd Binary files /dev/null and b/server/FSO.LotView.pdb differ diff --git a/server/FSO.Server.Api.dll b/server/FSO.Server.Api.dll new file mode 100644 index 0000000..8807adb Binary files /dev/null and b/server/FSO.Server.Api.dll differ diff --git a/server/FSO.Server.Api.dll.config b/server/FSO.Server.Api.dll.config new file mode 100644 index 0000000..e978c83 --- /dev/null +++ b/server/FSO.Server.Api.dll.config @@ -0,0 +1,74 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/server/FSO.Server.Api.pdb b/server/FSO.Server.Api.pdb new file mode 100644 index 0000000..5e1f3de Binary files /dev/null and b/server/FSO.Server.Api.pdb differ diff --git a/server/FSO.Server.Clients.dll b/server/FSO.Server.Clients.dll new file mode 100644 index 0000000..68ef477 Binary files /dev/null and b/server/FSO.Server.Clients.dll differ diff --git a/server/FSO.Server.Clients.pdb b/server/FSO.Server.Clients.pdb new file mode 100644 index 0000000..4fb3550 Binary files /dev/null and b/server/FSO.Server.Clients.pdb differ diff --git a/server/FSO.Server.Common.dll b/server/FSO.Server.Common.dll new file mode 100644 index 0000000..613cb61 Binary files /dev/null and b/server/FSO.Server.Common.dll differ diff --git a/server/FSO.Server.Common.pdb b/server/FSO.Server.Common.pdb new file mode 100644 index 0000000..4ce7bcc Binary files /dev/null and b/server/FSO.Server.Common.pdb differ diff --git a/server/FSO.Server.Database.dll b/server/FSO.Server.Database.dll new file mode 100644 index 0000000..c0c539e Binary files /dev/null and b/server/FSO.Server.Database.dll differ diff --git a/server/FSO.Server.Database.dll.config b/server/FSO.Server.Database.dll.config new file mode 100644 index 0000000..5153de7 --- /dev/null +++ b/server/FSO.Server.Database.dll.config @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/server/FSO.Server.Database.pdb b/server/FSO.Server.Database.pdb new file mode 100644 index 0000000..81dccc4 Binary files /dev/null and b/server/FSO.Server.Database.pdb differ diff --git a/server/FSO.Server.Debug.exe.config b/server/FSO.Server.Debug.exe.config new file mode 100644 index 0000000..d1428ad --- /dev/null +++ b/server/FSO.Server.Debug.exe.config @@ -0,0 +1,6 @@ + + + + + + diff --git a/server/FSO.Server.Debug.pdb b/server/FSO.Server.Debug.pdb new file mode 100644 index 0000000..485b942 Binary files /dev/null and b/server/FSO.Server.Debug.pdb differ diff --git a/server/FSO.Server.Domain.dll b/server/FSO.Server.Domain.dll new file mode 100644 index 0000000..3c2bc6e Binary files /dev/null and b/server/FSO.Server.Domain.dll differ diff --git a/server/FSO.Server.Domain.pdb b/server/FSO.Server.Domain.pdb new file mode 100644 index 0000000..7159662 Binary files /dev/null and b/server/FSO.Server.Domain.pdb differ diff --git a/server/FSO.Server.Protocol.dll b/server/FSO.Server.Protocol.dll new file mode 100644 index 0000000..8de5ada Binary files /dev/null and b/server/FSO.Server.Protocol.dll differ diff --git a/server/FSO.Server.Protocol.pdb b/server/FSO.Server.Protocol.pdb new file mode 100644 index 0000000..b0847e5 Binary files /dev/null and b/server/FSO.Server.Protocol.pdb differ diff --git a/server/FSO.SimAntics.dll b/server/FSO.SimAntics.dll new file mode 100644 index 0000000..bde26a7 Binary files /dev/null and b/server/FSO.SimAntics.dll differ diff --git a/server/FSO.SimAntics.pdb b/server/FSO.SimAntics.pdb new file mode 100644 index 0000000..41eda2d Binary files /dev/null and b/server/FSO.SimAntics.pdb differ diff --git a/server/FSO.Vitaboy.dll b/server/FSO.Vitaboy.dll new file mode 100644 index 0000000..f6dcaef Binary files /dev/null and b/server/FSO.Vitaboy.dll differ diff --git a/server/config.json b/server/config.json new file mode 100644 index 0000000..ac916b4 --- /dev/null +++ b/server/config.json @@ -0,0 +1,52 @@ +{ + "port": 8081, + "instances": 1, + "defaultInstance": { + "mapRotation": [ + "mkdsDefault" + ], + "mapMode": "random", + "itemConfig": [ + { + "item": 0, + "cfg": {} + }, + { + "item": 1, + "cfg": {} + }, + { + "item": 2, + "cfg": {} + } + ], + "itemChance": [ + { + "placement": 0.25, + "choices": [ + { + "item": 0, + "chance": 0.5 + }, + { + "item": 1, + "chance": 0.75 + }, + { + "item": 2, + "chance": 1 + } + ] + }, + { + "placement": 1, + "choices": [ + { + "item": 2, + "chance": 1 + } + ] + } + ] + } +} \ No newline at end of file diff --git a/server/configdefault.json b/server/configdefault.json new file mode 100644 index 0000000..4a0faba --- /dev/null +++ b/server/configdefault.json @@ -0,0 +1,105 @@ +{ + "gameLocation": "C:\\Program Files\\Maxis\\The Sims Online\\TSOClient\\", + "secret": "38F7E3B816EF9F31BFAB8F4C9716C90D106BD85E9D6913FBB4D833C866F837B0", + "simNFS": "C:\\Files\\Temp\\fso", + + "database": { + "connectionString": "server=127.0.0.1;uid=root;pwd=;database=fso2;" + }, + + "services": { + "tasks":{ + "enabled": true, + "call_sign": "callisto", + "binding": "0.0.0.0:35100", + "internal_host": "127.0.0.1:35", + "public_host": "127.0.0.1:35", + "certificate": "auth.east.ea.com.pfx", + + "schedule":[ + { + "cron":"0 3 * * *", + "task":"prune_database", + "timeout":3600, + "parameter":{ + } + }, + { + "cron":"0 4 * * *", + "task":"bonus", + "timeout":3600, + "shard_id": 1, + "parameter":{ + } + } + ], + + "tuning":{ + "bonus":{ + "property_bonus":{ + "per_unit": 10, + "overrides":{ + "1": 1500, + "2": 1250, + "3": 1000 + } + }, + "visitor_bonus":{ + "per_unit": 8 + } + } + } + }, + + "api": { + "enabled": true, + "bindings": [ "https://auth.east.ea.com:443/", "http://localhost:80/" ], + "controllers": [ "auth", "citySelector" ] + }, + + "userApi": { + "enabled": true, + "bindings": [ "http://localhost:9000/" ], + "controllers": [ "auth", "citySelector" ], + "updateUrl": "http://some-url" + }, + + "cities": [ + { + "call_sign": "ganymede", + "id": 1, + "binding": "0.0.0.0:33100", + "internal_host": "127.0.0.1:33", + "public_host": "127.0.0.1:33", + + "certificate": "auth.east.ea.com.pfx", + + "maintenance":{ + "cron":"0 4 * * *", + "timeout":3600, + "visits_retention_period":7, + "top100_average_period": 4 + } + } + ], + + "lots": [ + { + "call_sign": "europa", + "binding": "0.0.0.0:34100", + "internal_host": "127.0.0.1:34", + "public_host": "127.0.0.1:34", + "certificate": "auth.east.ea.com.pfx", + + "max_lots": 5, + + "cities": [ + { + "id": 1, + "host":"127.0.0.1:33100" + } + ] + } + ] + } +} \ No newline at end of file diff --git a/server/crypto.dll b/server/crypto.dll new file mode 100644 index 0000000..b768536 Binary files /dev/null and b/server/crypto.dll differ diff --git a/server/crypto.xml b/server/crypto.xml new file mode 100644 index 0000000..9e9a4d1 --- /dev/null +++ b/server/crypto.xml @@ -0,0 +1,19296 @@ + + + + crypto + + + + Base class for both the compress and decompress classes. + Holds common arrays, and static data. + + @author Keiron Liddle + + + An input stream that decompresses from the BZip2 format (with the file + header chars) to be read as any other stream. + + @author Keiron Liddle + + NB: note this class has been modified to read the leading BZ from the + start of the BZIP2 stream to make it compatible with other PGP programs. + + + An output stream that compresses into the BZip2 format (with the file + header chars) into another stream. + + @author Keiron Liddle + + TODO: Update to BZip2 1.0.1 + NB: note this class has been modified to add a leading BZ to the + start of the BZIP2 stream to make it compatible with other PGP programs. + + + + modified by Oliver Merkel, 010128 + + + + A simple class the hold and calculate the CRC for sanity checking + of the data. + + @author Keiron Liddle + + + Return the DER encoding of the object, null if the DER encoding can not be made. + + @return a DER byte array, null otherwise. + + + a general purpose ASN.1 decoder - note: this class differs from the + others in that it returns null after it has read the last object in + the stream. If an ASN.1 Null is encountered a Der/BER Null object is + returned. + + + Create an ASN1InputStream where no DER object will be longer than limit. + + @param input stream containing ASN.1 encoded data. + @param limit maximum size of a DER encoded object. + + + Create an ASN1InputStream based on the input byte array. The length of DER objects in + the stream is automatically limited to the length of the input array. + + @param input array containing ASN.1 encoded data. + + + build an object given its tag and the number of bytes to construct it from. + + + A Null object. + + + Create a base ASN.1 object from a byte array. + The byte array to parse. + The base ASN.1 object represented by the byte array. + If there is a problem parsing the data. + + + Read a base ASN.1 object from a stream. + The stream to parse. + The base ASN.1 object represented by the byte array. + If there is a problem parsing the data. + + + return an Octet string from a tagged object. + + @param obj the tagged object holding the object we want. + @param explicitly true if the object is meant to be explicitly + tagged false otherwise. + @exception ArgumentException if the tagged object cannot + be converted. + + + return an Octet string from the given object. + + @param obj the object we want converted. + @exception ArgumentException if the object cannot be converted. + + + @param string the octets making up the octet string. + + + return an Asn1Sequence from the given object. + + @param obj the object we want converted. + @exception ArgumentException if the object cannot be converted. + + + Return an ASN1 sequence from a tagged object. There is a special + case here, if an object appears to have been explicitly tagged on + reading but we were expecting it to be implicitly tagged in the + normal course of events it indicates that we lost the surrounding + sequence - so we need to add it back (this will happen if the tagged + object is a sequence that contains other sequences). If you are + dealing with implicitly tagged sequences you really should + be using this method. + + @param obj the tagged object. + @param explicitly true if the object is meant to be explicitly tagged, + false otherwise. + @exception ArgumentException if the tagged object cannot + be converted. + + + return the object at the sequence position indicated by index. + + @param index the sequence number (starting at zero) of the object + @return the object at the sequence position indicated by index. + + + return an ASN1Set from the given object. + + @param obj the object we want converted. + @exception ArgumentException if the object cannot be converted. + + + Return an ASN1 set from a tagged object. There is a special + case here, if an object appears to have been explicitly tagged on + reading but we were expecting it to be implicitly tagged in the + normal course of events it indicates that we lost the surrounding + set - so we need to add it back (this will happen if the tagged + object is a sequence that contains other sequences). If you are + dealing with implicitly tagged sets you really should + be using this method. + + @param obj the tagged object. + @param explicitly true if the object is meant to be explicitly tagged + false otherwise. + @exception ArgumentException if the tagged object cannot + be converted. + + + return the object at the set position indicated by index. + + @param index the set number (starting at zero) of the object + @return the object at the set position indicated by index. + + + return true if a <= b (arrays are assumed padded with zeros). + + + ASN.1 TaggedObject - in ASN.1 notation this is any object preceded by + a [n] where n is some number - these are assumed to follow the construction + rules (as with sequences). + + + @param tagNo the tag number for this object. + @param obj the tagged object. + + + @param explicitly true if the object is explicitly tagged. + @param tagNo the tag number for this object. + @param obj the tagged object. + + + return whether or not the object may be explicitly tagged. +

+ Note: if the object has been read from an input stream, the only + time you can be sure if isExplicit is returning the true state of + affairs is if it returns false. An implicitly tagged object may appear + to be explicitly tagged, so you need to understand the context under + which the reading was done as well, see GetObject below.

+
+ + return whatever was following the tag. +

+ Note: tagged objects are generally context dependent if you're + trying to extract a tagged object you should be going via the + appropriate GetInstance method.

+
+ + Return the object held in this tagged object as a parser assuming it has + the type of the passed in tag. If the object doesn't have a parser + associated with it, the base object is returned. + + + A BER Null object. + + + convert a vector of octet strings into a single byte string + + + The octets making up the octet string. + + + return the DER octets that make up this string. + + + create an empty sequence + + + create a sequence containing one object + + + create a sequence containing a vector of objects. + + + create an empty sequence + + + create a set containing one object + + + create a set containing a vector of objects. + + + BER TaggedObject - in ASN.1 notation this is any object preceded by + a [n] where n is some number - these are assumed to follow the construction + rules (as with sequences). + + + @param tagNo the tag number for this object. + @param obj the tagged object. + + + @param explicitly true if an explicitly tagged object. + @param tagNo the tag number for this object. + @param obj the tagged object. + + + create an implicitly tagged object that contains a zero + length sequence. + + +
+            CAKeyUpdAnnContent ::= SEQUENCE {
+                                        oldWithNew   CmpCertificate, -- old pub signed with new priv
+                                        newWithOld   CmpCertificate, -- new pub signed with old priv
+                                        newWithNew   CmpCertificate  -- new pub signed with new priv
+             }
+            
+ @return a basic ASN.1 object representation. +
+ +
+            CertConfirmContent ::= SEQUENCE OF CertStatus
+            
+ @return a basic ASN.1 object representation. +
+ +
+            CertifiedKeyPair ::= SEQUENCE {
+                                             certOrEncCert       CertOrEncCert,
+                                             privateKey      [0] EncryptedValue      OPTIONAL,
+                                             -- see [CRMF] for comment on encoding
+                                             publicationInfo [1] PKIPublicationInfo  OPTIONAL
+                  }
+            
+ @return a basic ASN.1 object representation. +
+ +
+            CertOrEncCert ::= CHOICE {
+                                 certificate     [0] CMPCertificate,
+                                 encryptedCert   [1] EncryptedValue
+                      }
+            
+ @return a basic ASN.1 object representation. +
+ +
+            CertRepMessage ::= SEQUENCE {
+                                     caPubs       [1] SEQUENCE SIZE (1..MAX) OF CMPCertificate
+                                                                                        OPTIONAL,
+                                     response         SEQUENCE OF CertResponse
+            }
+            
+ @return a basic ASN.1 object representation. +
+ +
+            CertResponse ::= SEQUENCE {
+                                       certReqId           INTEGER,
+                                       -- to match this response with corresponding request (a value
+                                       -- of -1 is to be used if certReqId is not specified in the
+                                       -- corresponding request)
+                                       status              PKIStatusInfo,
+                                       certifiedKeyPair    CertifiedKeyPair    OPTIONAL,
+                                       rspInfo             OCTET STRING        OPTIONAL
+                                       -- analogous to the id-regInfo-utf8Pairs string defined
+                                       -- for regInfo in CertReqMsg [CRMF]
+                        }
+            
+ @return a basic ASN.1 object representation. +
+ +
+            CertStatus ::= SEQUENCE {
+                              certHash    OCTET STRING,
+                              -- the hash of the certificate, using the same hash algorithm
+                              -- as is used to create and verify the certificate signature
+                              certReqId   INTEGER,
+                              -- to match this confirmation with the corresponding req/rep
+                              statusInfo  PKIStatusInfo OPTIONAL
+            }
+            
+ @return a basic ASN.1 object representation. +
+ +
+             Challenge ::= SEQUENCE {
+                             owf                 AlgorithmIdentifier  OPTIONAL,
+            
+                             -- MUST be present in the first Challenge; MAY be omitted in
+                             -- any subsequent Challenge in POPODecKeyChallContent (if
+                             -- omitted, then the owf used in the immediately preceding
+                             -- Challenge is to be used).
+            
+                             witness             OCTET STRING,
+                             -- the result of applying the one-way function (owf) to a
+                             -- randomly-generated INTEGER, A.  [Note that a different
+                             -- INTEGER MUST be used for each Challenge.]
+                             challenge           OCTET STRING
+                             -- the encryption (under the public key for which the cert.
+                             -- request is being made) of Rand, where Rand is specified as
+                             --   Rand ::= SEQUENCE {
+                             --      int      INTEGER,
+                             --       - the randomly-generated INTEGER A (above)
+                             --      sender   GeneralName
+                             --       - the sender's name (as included in PKIHeader)
+                             --   }
+                  }
+             
+ @return a basic ASN.1 object representation. +
+ + Note: the addition of attribute certificates is a BC extension. + + +
+             CMPCertificate ::= CHOICE {
+                        x509v3PKCert        Certificate
+                        x509v2AttrCert      [1] AttributeCertificate
+              }
+             
+ Note: the addition of attribute certificates is a BC extension. + + @return a basic ASN.1 object representation. +
+ +
+            CrlAnnContent ::= SEQUENCE OF CertificateList
+            
+ @return a basic ASN.1 object representation. +
+ +
+            ErrorMsgContent ::= SEQUENCE {
+                                   pKIStatusInfo          PKIStatusInfo,
+                                   errorCode              INTEGER           OPTIONAL,
+                                   -- implementation-specific error codes
+                                   errorDetails           PKIFreeText       OPTIONAL
+                                   -- implementation-specific error details
+            }
+            
+ @return a basic ASN.1 object representation. +
+ +
+            GenMsgContent ::= SEQUENCE OF InfoTypeAndValue
+            
+ @return a basic ASN.1 object representation. +
+ +
+            GenRepContent ::= SEQUENCE OF InfoTypeAndValue
+            
+ @return a basic ASN.1 object representation. +
+ + Example InfoTypeAndValue contents include, but are not limited + to, the following (un-comment in this ASN.1 module and use as + appropriate for a given environment): +
+               id-it-caProtEncCert    OBJECT IDENTIFIER ::= {id-it 1}
+                  CAProtEncCertValue      ::= CMPCertificate
+               id-it-signKeyPairTypes OBJECT IDENTIFIER ::= {id-it 2}
+                 SignKeyPairTypesValue   ::= SEQUENCE OF AlgorithmIdentifier
+               id-it-encKeyPairTypes  OBJECT IDENTIFIER ::= {id-it 3}
+                 EncKeyPairTypesValue    ::= SEQUENCE OF AlgorithmIdentifier
+               id-it-preferredSymmAlg OBJECT IDENTIFIER ::= {id-it 4}
+                  PreferredSymmAlgValue   ::= AlgorithmIdentifier
+               id-it-caKeyUpdateInfo  OBJECT IDENTIFIER ::= {id-it 5}
+                  CAKeyUpdateInfoValue    ::= CAKeyUpdAnnContent
+               id-it-currentCRL       OBJECT IDENTIFIER ::= {id-it 6}
+                  CurrentCRLValue         ::= CertificateList
+               id-it-unsupportedOIDs  OBJECT IDENTIFIER ::= {id-it 7}
+                  UnsupportedOIDsValue    ::= SEQUENCE OF OBJECT IDENTIFIER
+               id-it-keyPairParamReq  OBJECT IDENTIFIER ::= {id-it 10}
+                  KeyPairParamReqValue    ::= OBJECT IDENTIFIER
+               id-it-keyPairParamRep  OBJECT IDENTIFIER ::= {id-it 11}
+                  KeyPairParamRepValue    ::= AlgorithmIdentifer
+               id-it-revPassphrase    OBJECT IDENTIFIER ::= {id-it 12}
+                  RevPassphraseValue      ::= EncryptedValue
+               id-it-implicitConfirm  OBJECT IDENTIFIER ::= {id-it 13}
+                  ImplicitConfirmValue    ::= NULL
+               id-it-confirmWaitTime  OBJECT IDENTIFIER ::= {id-it 14}
+                  ConfirmWaitTimeValue    ::= GeneralizedTime
+               id-it-origPKIMessage   OBJECT IDENTIFIER ::= {id-it 15}
+                  OrigPKIMessageValue     ::= PKIMessages
+               id-it-suppLangTags     OBJECT IDENTIFIER ::= {id-it 16}
+                  SuppLangTagsValue       ::= SEQUENCE OF UTF8String
+            
+             where
+            
+               id-pkix OBJECT IDENTIFIER ::= {
+                  iso(1) identified-organization(3)
+                  dod(6) internet(1) security(5) mechanisms(5) pkix(7)}
+             and
+                  id-it   OBJECT IDENTIFIER ::= {id-pkix 4}
+             
+
+ +
+            InfoTypeAndValue ::= SEQUENCE {
+                                    infoType               OBJECT IDENTIFIER,
+                                    infoValue              ANY DEFINED BY infoType  OPTIONAL
+            }
+            
+ @return a basic ASN.1 object representation. +
+ +
+            KeyRecRepContent ::= SEQUENCE {
+                                    status                  PKIStatusInfo,
+                                    newSigCert          [0] CMPCertificate OPTIONAL,
+                                    caCerts             [1] SEQUENCE SIZE (1..MAX) OF
+                                                                      CMPCertificate OPTIONAL,
+                                    keyPairHist         [2] SEQUENCE SIZE (1..MAX) OF
+                                                                      CertifiedKeyPair OPTIONAL
+                         }
+            
+ @return a basic ASN.1 object representation. +
+ +
+            OobCertHash ::= SEQUENCE {
+                                 hashAlg     [0] AlgorithmIdentifier     OPTIONAL,
+                                 certId      [1] CertId                  OPTIONAL,
+                                 hashVal         BIT STRING
+                                 -- hashVal is calculated over the Der encoding of the
+                                 -- self-signed certificate with the identifier certID.
+                  }
+            
+ @return a basic ASN.1 object representation. +
+ +
+             PbmParameter ::= SEQUENCE {
+                                   salt                OCTET STRING,
+                                   -- note:  implementations MAY wish to limit acceptable sizes
+                                   -- of this string to values appropriate for their environment
+                                   -- in order to reduce the risk of denial-of-service attacks
+                                   owf                 AlgorithmIdentifier,
+                                   -- AlgId for a One-Way Function (SHA-1 recommended)
+                                   iterationCount      INTEGER,
+                                   -- number of times the OWF is applied
+                                   -- note:  implementations MAY wish to limit acceptable sizes
+                                   -- of this integer to values appropriate for their environment
+                                   -- in order to reduce the risk of denial-of-service attacks
+                                   mac                 AlgorithmIdentifier
+                                   -- the MAC AlgId (e.g., DES-MAC, Triple-DES-MAC [PKCS11],
+               }   -- or HMAC [RFC2104, RFC2202])
+            
+ @return a basic ASN.1 object representation. +
+ + Creates a new PkiBody. + @param type one of the TYPE_* constants + @param content message content + + +
+            PkiBody ::= CHOICE {       -- message-specific body elements
+                   ir       [0]  CertReqMessages,        --Initialization Request
+                   ip       [1]  CertRepMessage,         --Initialization Response
+                   cr       [2]  CertReqMessages,        --Certification Request
+                   cp       [3]  CertRepMessage,         --Certification Response
+                   p10cr    [4]  CertificationRequest,   --imported from [PKCS10]
+                   popdecc  [5]  POPODecKeyChallContent, --pop Challenge
+                   popdecr  [6]  POPODecKeyRespContent,  --pop Response
+                   kur      [7]  CertReqMessages,        --Key Update Request
+                   kup      [8]  CertRepMessage,         --Key Update Response
+                   krr      [9]  CertReqMessages,        --Key Recovery Request
+                   krp      [10] KeyRecRepContent,       --Key Recovery Response
+                   rr       [11] RevReqContent,          --Revocation Request
+                   rp       [12] RevRepContent,          --Revocation Response
+                   ccr      [13] CertReqMessages,        --Cross-Cert. Request
+                   ccp      [14] CertRepMessage,         --Cross-Cert. Response
+                   ckuann   [15] CAKeyUpdAnnContent,     --CA Key Update Ann.
+                   cann     [16] CertAnnContent,         --Certificate Ann.
+                   rann     [17] RevAnnContent,          --Revocation Ann.
+                   crlann   [18] CRLAnnContent,          --CRL Announcement
+                   pkiconf  [19] PKIConfirmContent,      --Confirmation
+                   nested   [20] NestedMessageContent,   --Nested Message
+                   genm     [21] GenMsgContent,          --General Message
+                   genp     [22] GenRepContent,          --General Response
+                   error    [23] ErrorMsgContent,        --Error Message
+                   certConf [24] CertConfirmContent,     --Certificate confirm
+                   pollReq  [25] PollReqContent,         --Polling request
+                   pollRep  [26] PollRepContent          --Polling response
+            }
+            
+ @return a basic ASN.1 object representation. +
+ +
+            PkiConfirmContent ::= NULL
+            
+ @return a basic ASN.1 object representation. +
+ +
+            PKIFailureInfo ::= BIT STRING {
+            badAlg               (0),
+              -- unrecognized or unsupported Algorithm Identifier
+            badMessageCheck      (1), -- integrity check failed (e.g., signature did not verify)
+            badRequest           (2),
+              -- transaction not permitted or supported
+            badTime              (3), -- messageTime was not sufficiently close to the system time, as defined by local policy
+            badCertId            (4), -- no certificate could be found matching the provided criteria
+            badDataFormat        (5),
+              -- the data submitted has the wrong format
+            wrongAuthority       (6), -- the authority indicated in the request is different from the one creating the response token
+            incorrectData        (7), -- the requester's data is incorrect (for notary services)
+            missingTimeStamp     (8), -- when the timestamp is missing but should be there (by policy)
+            badPOP               (9)  -- the proof-of-possession failed
+            timeNotAvailable    (14),
+              -- the TSA's time source is not available
+            unacceptedPolicy    (15),
+              -- the requested TSA policy is not supported by the TSA
+            unacceptedExtension (16),
+              -- the requested extension is not supported by the TSA
+             addInfoNotAvailable (17)
+               -- the additional information requested could not be understood
+               -- or is not available
+             systemFailure       (25)
+               -- the request cannot be handled due to system failure
+            
+
+ + Basic constructor. + + + Return the number of string elements present. + + @return number of elements present. + + + Return the UTF8STRING at index. + + @param index index of the string of interest + @return the string at index. + + +
+            PkiFreeText ::= SEQUENCE SIZE (1..MAX) OF UTF8String
+            
+
+ + Value for a "null" recipient or sender. + + +
+             PkiHeader ::= SEQUENCE {
+                       pvno                INTEGER     { cmp1999(1), cmp2000(2) },
+                       sender              GeneralName,
+                       -- identifies the sender
+                       recipient           GeneralName,
+                       -- identifies the intended recipient
+                       messageTime     [0] GeneralizedTime         OPTIONAL,
+                       -- time of production of this message (used when sender
+                       -- believes that the transport will be "suitable"; i.e.,
+                       -- that the time will still be meaningful upon receipt)
+                       protectionAlg   [1] AlgorithmIdentifier     OPTIONAL,
+                       -- algorithm used for calculation of protection bits
+                       senderKID       [2] KeyIdentifier           OPTIONAL,
+                       recipKID        [3] KeyIdentifier           OPTIONAL,
+                       -- to identify specific keys used for protection
+                       transactionID   [4] OCTET STRING            OPTIONAL,
+                       -- identifies the transaction; i.e., this will be the same in
+                       -- corresponding request, response, certConf, and PKIConf
+                       -- messages
+                       senderNonce     [5] OCTET STRING            OPTIONAL,
+                       recipNonce      [6] OCTET STRING            OPTIONAL,
+                       -- nonces used to provide replay protection, senderNonce
+                       -- is inserted by the creator of this message; recipNonce
+                       -- is a nonce previously inserted in a related message by
+                       -- the intended recipient of this message
+                       freeText        [7] PKIFreeText             OPTIONAL,
+                       -- this may be used to indicate context-specific instructions
+                       -- (this field is intended for human consumption)
+                       generalInfo     [8] SEQUENCE SIZE (1..MAX) OF
+                                            InfoTypeAndValue     OPTIONAL
+                       -- this may be used to convey context-specific information
+                       -- (this field not primarily intended for human consumption)
+            }
+            
+ @return a basic ASN.1 object representation. +
+ +
+             PKIHeader ::= SEQUENCE {
+                       pvno                INTEGER     { cmp1999(1), cmp2000(2) },
+                       sender              GeneralName,
+                       -- identifies the sender
+                       recipient           GeneralName,
+                       -- identifies the intended recipient
+                       messageTime     [0] GeneralizedTime         OPTIONAL,
+                       -- time of production of this message (used when sender
+                       -- believes that the transport will be "suitable"; i.e.,
+                       -- that the time will still be meaningful upon receipt)
+                       protectionAlg   [1] AlgorithmIdentifier     OPTIONAL,
+                       -- algorithm used for calculation of protection bits
+                       senderKID       [2] KeyIdentifier           OPTIONAL,
+                       recipKID        [3] KeyIdentifier           OPTIONAL,
+                       -- to identify specific keys used for protection
+                       transactionID   [4] OCTET STRING            OPTIONAL,
+                       -- identifies the transaction; i.e., this will be the same in
+                       -- corresponding request, response, certConf, and PKIConf
+                       -- messages
+                       senderNonce     [5] OCTET STRING            OPTIONAL,
+                       recipNonce      [6] OCTET STRING            OPTIONAL,
+                       -- nonces used to provide replay protection, senderNonce
+                       -- is inserted by the creator of this message; recipNonce
+                       -- is a nonce previously inserted in a related message by
+                       -- the intended recipient of this message
+                       freeText        [7] PKIFreeText             OPTIONAL,
+                       -- this may be used to indicate context-specific instructions
+                       -- (this field is intended for human consumption)
+                       generalInfo     [8] SEQUENCE SIZE (1..MAX) OF
+                                            InfoTypeAndValue     OPTIONAL
+                       -- this may be used to convey context-specific information
+                       -- (this field not primarily intended for human consumption)
+            }
+            
+ @return a basic ASN.1 object representation. +
+ + Creates a new PkiMessage. + + @param header message header + @param body message body + @param protection message protection (may be null) + @param extraCerts extra certificates (may be null) + + +
+            PkiMessage ::= SEQUENCE {
+                             header           PKIHeader,
+                             body             PKIBody,
+                             protection   [0] PKIProtection OPTIONAL,
+                             extraCerts   [1] SEQUENCE SIZE (1..MAX) OF CMPCertificate
+                                                                                OPTIONAL
+            }
+            
+ @return a basic ASN.1 object representation. +
+ +
+            PkiMessages ::= SEQUENCE SIZE (1..MAX) OF PkiMessage
+            
+ @return a basic ASN.1 object representation. +
+ + @param status + + + @param status + @param statusString + + +
+             PkiStatusInfo ::= SEQUENCE {
+                 status        PKIStatus,                (INTEGER)
+                 statusString  PkiFreeText     OPTIONAL,
+                 failInfo      PkiFailureInfo  OPTIONAL  (BIT STRING)
+             }
+            
+             PKIStatus:
+               granted                (0), -- you got exactly what you asked for
+               grantedWithMods        (1), -- you got something like what you asked for
+               rejection              (2), -- you don't get it, more information elsewhere in the message
+               waiting                (3), -- the request body part has not yet been processed, expect to hear more later
+               revocationWarning      (4), -- this message contains a warning that a revocation is imminent
+               revocationNotification (5), -- notification that a revocation has occurred
+               keyUpdateWarning       (6)  -- update already done for the oldCertId specified in CertReqMsg
+            
+             PkiFailureInfo:
+               badAlg           (0), -- unrecognized or unsupported Algorithm Identifier
+               badMessageCheck  (1), -- integrity check failed (e.g., signature did not verify)
+               badRequest       (2), -- transaction not permitted or supported
+               badTime          (3), -- messageTime was not sufficiently close to the system time, as defined by local policy
+               badCertId        (4), -- no certificate could be found matching the provided criteria
+               badDataFormat    (5), -- the data submitted has the wrong format
+               wrongAuthority   (6), -- the authority indicated in the request is different from the one creating the response token
+               incorrectData    (7), -- the requester's data is incorrect (for notary services)
+               missingTimeStamp (8), -- when the timestamp is missing but should be there (by policy)
+               badPOP           (9)  -- the proof-of-possession failed
+            
+             
+
+ +
+            PollRepContent ::= SEQUENCE OF SEQUENCE {
+                    certReqId              INTEGER,
+                    checkAfter             INTEGER,  -- time in seconds
+                    reason                 PKIFreeText OPTIONAL
+                }
+            
+ @return a basic ASN.1 object representation. +
+ +
+            PollReqContent ::= SEQUENCE OF SEQUENCE {
+                                   certReqId              INTEGER
+            }
+            
+ @return a basic ASN.1 object representation. +
+ +
+            PopoDecKeyChallContent ::= SEQUENCE OF Challenge
+            
+ @return a basic ASN.1 object representation. +
+ +
+            PopoDecKeyRespContent ::= SEQUENCE OF INTEGER
+            
+ @return a basic ASN.1 object representation. +
+ +
+            ProtectedPart ::= SEQUENCE {
+                               header    PKIHeader,
+                               body      PKIBody
+            }
+            
+ @return a basic ASN.1 object representation. +
+ +
+            RevAnnContent ::= SEQUENCE {
+                  status              PKIStatus,
+                  certId              CertId,
+                  willBeRevokedAt     GeneralizedTime,
+                  badSinceDate        GeneralizedTime,
+                  crlDetails          Extensions  OPTIONAL
+                   -- extra CRL details (e.g., crl number, reason, location, etc.)
+            }
+            
+ @return a basic ASN.1 object representation. +
+ +
+            RevDetails ::= SEQUENCE {
+                             certDetails         CertTemplate,
+                              -- allows requester to specify as much as they can about
+                              -- the cert. for which revocation is requested
+                              -- (e.g., for cases in which serialNumber is not available)
+                              crlEntryDetails     Extensions       OPTIONAL
+                              -- requested crlEntryExtensions
+                        }
+            
+ @return a basic ASN.1 object representation. +
+ +
+            RevRepContent ::= SEQUENCE {
+                   status       SEQUENCE SIZE (1..MAX) OF PKIStatusInfo,
+                   -- in same order as was sent in RevReqContent
+                   revCerts [0] SEQUENCE SIZE (1..MAX) OF CertId OPTIONAL,
+                   -- IDs for which revocation was requested
+                   -- (same order as status)
+                   crls     [1] SEQUENCE SIZE (1..MAX) OF CertificateList OPTIONAL
+                   -- the resulting CRLs (there may be more than one)
+              }
+            
+ @return a basic ASN.1 object representation. +
+ +
+            RevReqContent ::= SEQUENCE OF RevDetails
+            
+ @return a basic ASN.1 object representation. +
+ + return an Attribute object from the given object. + + @param o the object we want converted. + @exception ArgumentException if the object cannot be converted. + + + Produce an object suitable for an Asn1OutputStream. +
+            Attribute ::= SEQUENCE {
+                attrType OBJECT IDENTIFIER,
+                attrValues SET OF AttributeValue
+            }
+            
+
+ +
+            Attributes ::=
+              SET SIZE(1..MAX) OF Attribute -- according to RFC 5652
+            
+ @return +
+ + Return the first attribute matching the given OBJECT IDENTIFIER + + + Return all the attributes matching the OBJECT IDENTIFIER oid. The vector will be + empty if there are no attributes of the required type present. + + @param oid type of attribute required. + @return a vector of all the attributes found of type oid. + + + Return a new table with the passed in attribute added. + + @param attrType + @param attrValue + @return + + + return an AuthenticatedData object from a tagged object. + + @param obj the tagged object holding the object we want. + @param isExplicit true if the object is meant to be explicitly + tagged false otherwise. + @throws ArgumentException if the object held by the + tagged object cannot be converted. + + + return an AuthenticatedData object from the given object. + + @param obj the object we want converted. + @throws ArgumentException if the object cannot be converted. + + + Produce an object suitable for an Asn1OutputStream. +
+             AuthenticatedData ::= SEQUENCE {
+                   version CMSVersion,
+                   originatorInfo [0] IMPLICIT OriginatorInfo OPTIONAL,
+                   recipientInfos RecipientInfos,
+                   macAlgorithm MessageAuthenticationCodeAlgorithm,
+                   digestAlgorithm [1] DigestAlgorithmIdentifier OPTIONAL,
+                   encapContentInfo EncapsulatedContentInfo,
+                   authAttrs [2] IMPLICIT AuthAttributes OPTIONAL,
+                   mac MessageAuthenticationCode,
+                   unauthAttrs [3] IMPLICIT UnauthAttributes OPTIONAL }
+            
+             AuthAttributes ::= SET SIZE (1..MAX) OF Attribute
+            
+             UnauthAttributes ::= SET SIZE (1..MAX) OF Attribute
+            
+             MessageAuthenticationCode ::= OCTET STRING
+             
+
+ + Produce an object suitable for an Asn1OutputStream. +
+             AuthenticatedData ::= SEQUENCE {
+                   version CMSVersion,
+                   originatorInfo [0] IMPLICIT OriginatorInfo OPTIONAL,
+                   recipientInfos RecipientInfos,
+                   macAlgorithm MessageAuthenticationCodeAlgorithm,
+                   digestAlgorithm [1] DigestAlgorithmIdentifier OPTIONAL,
+                   encapContentInfo EncapsulatedContentInfo,
+                   authAttrs [2] IMPLICIT AuthAttributes OPTIONAL,
+                   mac MessageAuthenticationCode,
+                   unauthAttrs [3] IMPLICIT UnauthAttributes OPTIONAL }
+            
+             AuthAttributes ::= SET SIZE (1..MAX) OF Attribute
+            
+             UnauthAttributes ::= SET SIZE (1..MAX) OF Attribute
+            
+             MessageAuthenticationCode ::= OCTET STRING
+             
+
+ + return an AuthEnvelopedData object from a tagged object. + + @param obj the tagged object holding the object we want. + @param isExplicit true if the object is meant to be explicitly + tagged false otherwise. + @throws ArgumentException if the object held by the + tagged object cannot be converted. + + + return an AuthEnvelopedData object from the given object. + + @param obj the object we want converted. + @throws ArgumentException if the object cannot be converted. + + + Produce an object suitable for an Asn1OutputStream. +
+            AuthEnvelopedData ::= SEQUENCE {
+              version CMSVersion,
+              originatorInfo [0] IMPLICIT OriginatorInfo OPTIONAL,
+              recipientInfos RecipientInfos,
+              authEncryptedContentInfo EncryptedContentInfo,
+              authAttrs [1] IMPLICIT AuthAttributes OPTIONAL,
+              mac MessageAuthenticationCode,
+              unauthAttrs [2] IMPLICIT UnauthAttributes OPTIONAL }
+            
+
+ + Produce an object suitable for an Asn1OutputStream. + +
+            AuthEnvelopedData ::= SEQUENCE {
+              version CMSVersion,
+              originatorInfo [0] IMPLICIT OriginatorInfo OPTIONAL,
+              recipientInfos RecipientInfos,
+              authEncryptedContentInfo EncryptedContentInfo,
+              authAttrs [1] IMPLICIT AuthAttributes OPTIONAL,
+              mac MessageAuthenticationCode,
+              unauthAttrs [2] IMPLICIT UnauthAttributes OPTIONAL }
+            
+
+ + RFC 3274 - CMS Compressed Data. +
+            CompressedData ::= Sequence {
+             version CMSVersion,
+             compressionAlgorithm CompressionAlgorithmIdentifier,
+             encapContentInfo EncapsulatedContentInfo
+            }
+            
+
+ + return a CompressedData object from a tagged object. + + @param ato the tagged object holding the object we want. + @param explicitly true if the object is meant to be explicitly + tagged false otherwise. + @exception ArgumentException if the object held by the + tagged object cannot be converted. + + + return a CompressedData object from the given object. + + @param _obj the object we want converted. + @exception ArgumentException if the object cannot be converted. + + + RFC 3274 - CMS Compressed Data. +
+            CompressedData ::= SEQUENCE {
+             version CMSVersion,
+             compressionAlgorithm CompressionAlgorithmIdentifier,
+             encapContentInfo EncapsulatedContentInfo
+            }
+            
+
+ + Produce an object suitable for an Asn1OutputStream. +
+            ContentInfo ::= Sequence {
+                     contentType ContentType,
+                     content
+                     [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL }
+            
+
+ + Produce an object suitable for an Asn1OutputStream. +
+            ContentInfo ::= SEQUENCE {
+                     contentType ContentType,
+                     content
+                     [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL }
+            
+
+ + return an AuthEnvelopedData object from a tagged object. + + @param obj the tagged object holding the object we want. + @param isExplicit true if the object is meant to be explicitly + tagged false otherwise. + @throws ArgumentException if the object held by the + tagged object cannot be converted. + + + return an AuthEnvelopedData object from the given object. + + @param obj the object we want converted. + @throws ArgumentException if the object cannot be converted. + + + Produce an object suitable for an Asn1OutputStream. +
+            MQVuserKeyingMaterial ::= SEQUENCE {
+              ephemeralPublicKey OriginatorPublicKey,
+              addedukm [0] EXPLICIT UserKeyingMaterial OPTIONAL  }
+            
+
+ + return an EncryptedContentInfo object from the given object. + + @param obj the object we want converted. + @exception ArgumentException if the object cannot be converted. + + + Produce an object suitable for an Asn1OutputStream. +
+            EncryptedContentInfo ::= Sequence {
+                contentType ContentType,
+                contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier,
+                encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL
+            }
+            
+
+ +
+            EncryptedContentInfo ::= SEQUENCE {
+                contentType ContentType,
+                contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier,
+                encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL
+            }
+            
+
+ +
+                  EncryptedData ::= SEQUENCE {
+                                version CMSVersion,
+                                encryptedContentInfo EncryptedContentInfo,
+                                unprotectedAttrs [1] IMPLICIT UnprotectedAttributes OPTIONAL }
+            
+ @return a basic ASN.1 object representation. +
+ + return an EnvelopedData object from a tagged object. + + @param obj the tagged object holding the object we want. + @param explicitly true if the object is meant to be explicitly + tagged false otherwise. + @exception ArgumentException if the object held by the + tagged object cannot be converted. + + + return an EnvelopedData object from the given object. + + @param obj the object we want converted. + @exception ArgumentException if the object cannot be converted. + + + Produce an object suitable for an Asn1OutputStream. +
+            EnvelopedData ::= Sequence {
+                version CMSVersion,
+                originatorInfo [0] IMPLICIT OriginatorInfo OPTIONAL,
+                recipientInfos RecipientInfos,
+                encryptedContentInfo EncryptedContentInfo,
+                unprotectedAttrs [1] IMPLICIT UnprotectedAttributes OPTIONAL
+            }
+            
+
+ + Produce an object suitable for an Asn1OutputStream. +
+            EnvelopedData ::= SEQUENCE {
+                version CMSVersion,
+                originatorInfo [0] IMPLICIT OriginatorInfo OPTIONAL,
+                recipientInfos RecipientInfos,
+                encryptedContentInfo EncryptedContentInfo,
+                unprotectedAttrs [1] IMPLICIT UnprotectedAttributes OPTIONAL
+            }
+            
+
+ + return a KekIdentifier object from a tagged object. + + @param obj the tagged object holding the object we want. + @param explicitly true if the object is meant to be explicitly + tagged false otherwise. + @exception ArgumentException if the object held by the + tagged object cannot be converted. + + + return a KekIdentifier object from the given object. + + @param obj the object we want converted. + @exception ArgumentException if the object cannot be converted. + + + Produce an object suitable for an Asn1OutputStream. +
+            KekIdentifier ::= Sequence {
+                keyIdentifier OCTET STRING,
+                date GeneralizedTime OPTIONAL,
+                other OtherKeyAttribute OPTIONAL
+            }
+            
+
+ + return a KekRecipientInfo object from a tagged object. + + @param obj the tagged object holding the object we want. + @param explicitly true if the object is meant to be explicitly + tagged false otherwise. + @exception ArgumentException if the object held by the + tagged object cannot be converted. + + + return a KekRecipientInfo object from the given object. + + @param obj the object we want converted. + @exception ArgumentException if the object cannot be converted. + + + Produce an object suitable for an Asn1OutputStream. +
+            KekRecipientInfo ::= Sequence {
+                version CMSVersion,  -- always set to 4
+                kekID KekIdentifier,
+                keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
+                encryptedKey EncryptedKey
+            }
+            
+
+ + return an KeyAgreeRecipientIdentifier object from a tagged object. + + @param obj the tagged object holding the object we want. + @param isExplicit true if the object is meant to be explicitly + tagged false otherwise. + @exception ArgumentException if the object held by the + tagged object cannot be converted. + + + return an KeyAgreeRecipientIdentifier object from the given object. + + @param obj the object we want converted. + @exception ArgumentException if the object cannot be converted. + + + Produce an object suitable for an Asn1OutputStream. +
+            KeyAgreeRecipientIdentifier ::= CHOICE {
+                issuerAndSerialNumber IssuerAndSerialNumber,
+                rKeyId [0] IMPLICIT RecipientKeyIdentifier
+            }
+            
+
+ + return a KeyAgreeRecipientInfo object from a tagged object. + + @param obj the tagged object holding the object we want. + @param explicitly true if the object is meant to be explicitly + tagged false otherwise. + @exception ArgumentException if the object held by the + tagged object cannot be converted. + + + return a KeyAgreeRecipientInfo object from the given object. + + @param obj the object we want converted. + @exception ArgumentException if the object cannot be converted. + + + * Produce an object suitable for an Asn1OutputStream. + *
+                     * KeyAgreeRecipientInfo ::= Sequence {
+                     *     version CMSVersion,  -- always set to 3
+                     *     originator [0] EXPLICIT OriginatorIdentifierOrKey,
+                     *     ukm [1] EXPLICIT UserKeyingMaterial OPTIONAL,
+                     *     keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
+                     *     recipientEncryptedKeys RecipientEncryptedKeys
+                     * }
+            		 *
+            		 * UserKeyingMaterial ::= OCTET STRING
+                     * 
+
+ + return a KeyTransRecipientInfo object from the given object. + + @param obj the object we want converted. + @exception ArgumentException if the object cannot be converted. + + + Produce an object suitable for an Asn1OutputStream. +
+            KeyTransRecipientInfo ::= Sequence {
+                version CMSVersion,  -- always set to 0 or 2
+                rid RecipientIdentifier,
+                keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
+                encryptedKey EncryptedKey
+            }
+            
+
+ +
+            MetaData ::= SEQUENCE {
+              hashProtected        BOOLEAN,
+              fileName             UTF8String OPTIONAL,
+              mediaType            IA5String OPTIONAL,
+              otherMetaData        Attributes OPTIONAL
+            }
+            
+ @return +
+ + return an OriginatorIdentifierOrKey object from a tagged object. + + @param o the tagged object holding the object we want. + @param explicitly true if the object is meant to be explicitly + tagged false otherwise. + @exception ArgumentException if the object held by the + tagged object cannot be converted. + + + return an OriginatorIdentifierOrKey object from the given object. + + @param o the object we want converted. + @exception ArgumentException if the object cannot be converted. + + + Produce an object suitable for an Asn1OutputStream. +
+             OriginatorIdentifierOrKey ::= CHOICE {
+                 issuerAndSerialNumber IssuerAndSerialNumber,
+                 subjectKeyIdentifier [0] SubjectKeyIdentifier,
+                 originatorKey [1] OriginatorPublicKey
+             }
+            
+             SubjectKeyIdentifier ::= OCTET STRING
+             
+
+ + return an OriginatorInfo object from a tagged object. + + @param obj the tagged object holding the object we want. + @param explicitly true if the object is meant to be explicitly + tagged false otherwise. + @exception ArgumentException if the object held by the + tagged object cannot be converted. + + + return an OriginatorInfo object from the given object. + + @param obj the object we want converted. + @exception ArgumentException if the object cannot be converted. + + + Produce an object suitable for an Asn1OutputStream. +
+            OriginatorInfo ::= Sequence {
+                certs [0] IMPLICIT CertificateSet OPTIONAL,
+                crls [1] IMPLICIT CertificateRevocationLists OPTIONAL
+            }
+            
+
+ + return an OriginatorPublicKey object from a tagged object. + + @param obj the tagged object holding the object we want. + @param explicitly true if the object is meant to be explicitly + tagged false otherwise. + @exception ArgumentException if the object held by the + tagged object cannot be converted. + + + return an OriginatorPublicKey object from the given object. + + @param obj the object we want converted. + @exception ArgumentException if the object cannot be converted. + + + Produce an object suitable for an Asn1OutputStream. +
+            OriginatorPublicKey ::= Sequence {
+                algorithm AlgorithmIdentifier,
+                publicKey BIT STRING
+            }
+            
+
+ + return an OtherKeyAttribute object from the given object. + + @param o the object we want converted. + @exception ArgumentException if the object cannot be converted. + + + Produce an object suitable for an Asn1OutputStream. +
+            OtherKeyAttribute ::= Sequence {
+                keyAttrId OBJECT IDENTIFIER,
+                keyAttr ANY DEFINED BY keyAttrId OPTIONAL
+            }
+            
+
+ + return a OtherRecipientInfo object from a tagged object. + + @param obj the tagged object holding the object we want. + @param explicitly true if the object is meant to be explicitly + tagged false otherwise. + @exception ArgumentException if the object held by the + tagged object cannot be converted. + + + return a OtherRecipientInfo object from the given object. + + @param obj the object we want converted. + @exception ArgumentException if the object cannot be converted. + + + Produce an object suitable for an Asn1OutputStream. +
+            OtherRecipientInfo ::= Sequence {
+               oriType OBJECT IDENTIFIER,
+               oriValue ANY DEFINED BY oriType }
+            
+
+ + return a PasswordRecipientInfo object from a tagged object. + + @param obj the tagged object holding the object we want. + @param explicitly true if the object is meant to be explicitly + tagged false otherwise. + @exception ArgumentException if the object held by the + tagged object cannot be converted. + + + return a PasswordRecipientInfo object from the given object. + + @param obj the object we want converted. + @exception ArgumentException if the object cannot be converted. + + + Produce an object suitable for an Asn1OutputStream. +
+            PasswordRecipientInfo ::= Sequence {
+              version CMSVersion,   -- Always set to 0
+              keyDerivationAlgorithm [0] KeyDerivationAlgorithmIdentifier
+                                        OPTIONAL,
+             keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
+             encryptedKey EncryptedKey }
+            
+
+ + return an RecipientEncryptedKey object from a tagged object. + + @param obj the tagged object holding the object we want. + @param isExplicit true if the object is meant to be explicitly + tagged false otherwise. + @exception ArgumentException if the object held by the + tagged object cannot be converted. + + + return a RecipientEncryptedKey object from the given object. + + @param obj the object we want converted. + @exception ArgumentException if the object cannot be converted. + + + Produce an object suitable for an Asn1OutputStream. +
+            RecipientEncryptedKey ::= SEQUENCE {
+                rid KeyAgreeRecipientIdentifier,
+                encryptedKey EncryptedKey
+            }
+            
+
+ + return a RecipientIdentifier object from the given object. + + @param o the object we want converted. + @exception ArgumentException if the object cannot be converted. + + + Produce an object suitable for an Asn1OutputStream. +
+             RecipientIdentifier ::= CHOICE {
+                 issuerAndSerialNumber IssuerAndSerialNumber,
+                 subjectKeyIdentifier [0] SubjectKeyIdentifier
+             }
+            
+             SubjectKeyIdentifier ::= OCTET STRING
+             
+
+ + Produce an object suitable for an Asn1OutputStream. +
+            RecipientInfo ::= CHOICE {
+                ktri KeyTransRecipientInfo,
+                kari [1] KeyAgreeRecipientInfo,
+                kekri [2] KekRecipientInfo,
+                pwri [3] PasswordRecipientInfo,
+                ori [4] OtherRecipientInfo }
+            
+
+ + return a RecipientKeyIdentifier object from a tagged object. + + @param _ato the tagged object holding the object we want. + @param _explicit true if the object is meant to be explicitly + tagged false otherwise. + @exception ArgumentException if the object held by the + tagged object cannot be converted. + + + return a RecipientKeyIdentifier object from the given object. + + @param _obj the object we want converted. + @exception ArgumentException if the object cannot be converted. + + + Produce an object suitable for an Asn1OutputStream. +
+             RecipientKeyIdentifier ::= Sequence {
+                 subjectKeyIdentifier SubjectKeyIdentifier,
+                 date GeneralizedTime OPTIONAL,
+                 other OtherKeyAttribute OPTIONAL
+             }
+            
+             SubjectKeyIdentifier ::= OCTET STRING
+             
+
+ + a signed data object. + + + Produce an object suitable for an Asn1OutputStream. +
+            SignedData ::= Sequence {
+                version CMSVersion,
+                digestAlgorithms DigestAlgorithmIdentifiers,
+                encapContentInfo EncapsulatedContentInfo,
+                certificates [0] IMPLICIT CertificateSet OPTIONAL,
+                crls [1] IMPLICIT CertificateRevocationLists OPTIONAL,
+                signerInfos SignerInfos
+              }
+            
+
+ +
+            SignedData ::= SEQUENCE {
+                version CMSVersion,
+                digestAlgorithms DigestAlgorithmIdentifiers,
+                encapContentInfo EncapsulatedContentInfo,
+                certificates [0] IMPLICIT CertificateSet OPTIONAL,
+                crls [1] IMPLICIT CertificateRevocationLists OPTIONAL,
+                signerInfos SignerInfos
+              }
+            
+
+ + return a SignerIdentifier object from the given object. + + @param o the object we want converted. + @exception ArgumentException if the object cannot be converted. + + + Produce an object suitable for an Asn1OutputStream. +
+             SignerIdentifier ::= CHOICE {
+                 issuerAndSerialNumber IssuerAndSerialNumber,
+                 subjectKeyIdentifier [0] SubjectKeyIdentifier
+             }
+            
+             SubjectKeyIdentifier ::= OCTET STRING
+             
+
+ + Produce an object suitable for an Asn1OutputStream. +
+              SignerInfo ::= Sequence {
+                  version Version,
+                  SignerIdentifier sid,
+                  digestAlgorithm DigestAlgorithmIdentifier,
+                  authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL,
+                  digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier,
+                  encryptedDigest EncryptedDigest,
+                  unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL
+              }
+            
+              EncryptedDigest ::= OCTET STRING
+            
+              DigestAlgorithmIdentifier ::= AlgorithmIdentifier
+            
+              DigestEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
+             
+
+ + creates a time object from a given date - if the date is between 1950 + and 2049 a UTCTime object is Generated, otherwise a GeneralizedTime + is used. + + + Produce an object suitable for an Asn1OutputStream. +
+            Time ::= CHOICE {
+                        utcTime        UTCTime,
+                        generalTime    GeneralizedTime }
+            
+
+ +
+            TimeStampAndCRL ::= SEQUENCE {
+                timeStamp   TimeStampToken,          -- according to RFC 3161
+                crl         CertificateList OPTIONAL -- according to RFC 5280
+             }
+            
+ @return +
+ +
+            TimeStampedData ::= SEQUENCE {
+              version              INTEGER { v1(1) },
+              dataUri              IA5String OPTIONAL,
+              metaData             MetaData OPTIONAL,
+              content              OCTET STRING OPTIONAL,
+              temporalEvidence     Evidence
+            }
+            
+ @return +
+ +
+            TimeStampTokenEvidence ::=
+               SEQUENCE SIZE(1..MAX) OF TimeStampAndCrl
+            
+ @return +
+ +
+            AttributeTypeAndValue ::= SEQUENCE {
+                      type         OBJECT IDENTIFIER,
+                      value        ANY DEFINED BY type }
+            
+ @return a basic ASN.1 object representation. +
+ +
+            CertId ::= SEQUENCE {
+                            issuer           GeneralName,
+                            serialNumber     INTEGER }
+            
+ @return a basic ASN.1 object representation. +
+ +
+            CertReqMessages ::= SEQUENCE SIZE (1..MAX) OF CertReqMsg
+            
+ @return a basic ASN.1 object representation. +
+ + Creates a new CertReqMsg. + @param certReq CertRequest + @param popo may be null + @param regInfo may be null + + +
+            CertReqMsg ::= SEQUENCE {
+                               certReq   CertRequest,
+                               pop       ProofOfPossession  OPTIONAL,
+                               -- content depends upon key type
+                               regInfo   SEQUENCE SIZE(1..MAX) OF AttributeTypeAndValue OPTIONAL }
+            
+ @return a basic ASN.1 object representation. +
+ +
+            CertRequest ::= SEQUENCE {
+                                 certReqId     INTEGER,          -- ID for matching request and reply
+                                 certTemplate  CertTemplate,  -- Selected fields of cert to be issued
+                                 controls      Controls OPTIONAL }   -- Attributes affecting issuance
+            
+ @return a basic ASN.1 object representation. +
+ +
+             CertTemplate ::= SEQUENCE {
+                 version      [0] Version               OPTIONAL,
+                 serialNumber [1] INTEGER               OPTIONAL,
+                 signingAlg   [2] AlgorithmIdentifier   OPTIONAL,
+                 issuer       [3] Name                  OPTIONAL,
+                 validity     [4] OptionalValidity      OPTIONAL,
+                 subject      [5] Name                  OPTIONAL,
+                 publicKey    [6] SubjectPublicKeyInfo  OPTIONAL,
+                 issuerUID    [7] UniqueIdentifier      OPTIONAL,
+                 subjectUID   [8] UniqueIdentifier      OPTIONAL,
+                 extensions   [9] Extensions            OPTIONAL }
+            
+ @return a basic ASN.1 object representation. +
+ + Sets the X.509 version. Note: for X509v3, use 2 here. + + + Sets the issuer unique ID (deprecated in X.509v3) + + + Sets the subject unique ID (deprecated in X.509v3) + + +
+             CertTemplate ::= SEQUENCE {
+                 version      [0] Version               OPTIONAL,
+                 serialNumber [1] INTEGER               OPTIONAL,
+                 signingAlg   [2] AlgorithmIdentifier   OPTIONAL,
+                 issuer       [3] Name                  OPTIONAL,
+                 validity     [4] OptionalValidity      OPTIONAL,
+                 subject      [5] Name                  OPTIONAL,
+                 publicKey    [6] SubjectPublicKeyInfo  OPTIONAL,
+                 issuerUID    [7] UniqueIdentifier      OPTIONAL,
+                 subjectUID   [8] UniqueIdentifier      OPTIONAL,
+                 extensions   [9] Extensions            OPTIONAL }
+            
+ @return a basic ASN.1 object representation. +
+ +
+            Controls  ::= SEQUENCE SIZE(1..MAX) OF AttributeTypeAndValue
+            
+ @return a basic ASN.1 object representation. +
+ +
+            EncKeyWithID ::= SEQUENCE {
+                 privateKey           PrivateKeyInfo,
+                 identifier CHOICE {
+                    string               UTF8String,
+                    generalName          GeneralName
+                } OPTIONAL
+            }
+            
+ @return +
+ +
+               EncryptedKey ::= CHOICE {
+                   encryptedValue        EncryptedValue, -- deprecated
+                   envelopedData     [0] EnvelopedData }
+                   -- The encrypted private key MUST be placed in the envelopedData
+                   -- encryptedContentInfo encryptedContent OCTET STRING.
+            
+
+ +
+            EncryptedValue ::= SEQUENCE {
+                                intendedAlg   [0] AlgorithmIdentifier  OPTIONAL,
+                                -- the intended algorithm for which the value will be used
+                                symmAlg       [1] AlgorithmIdentifier  OPTIONAL,
+                                -- the symmetric algorithm used to encrypt the value
+                                encSymmKey    [2] BIT STRING           OPTIONAL,
+                                -- the (encrypted) symmetric key used to encrypt the value
+                                keyAlg        [3] AlgorithmIdentifier  OPTIONAL,
+                                -- algorithm used to encrypt the symmetric key
+                                valueHint     [4] OCTET STRING         OPTIONAL,
+                                -- a brief description or identifier of the encValue content
+                                -- (may be meaningful only to the sending entity, and used only
+                                -- if EncryptedValue might be re-examined by the sending entity
+                                -- in the future)
+                                encValue       BIT STRING }
+                                -- the encrypted value itself
+            
+ @return a basic ASN.1 object representation. +
+ +
+            OptionalValidity ::= SEQUENCE {
+                                   notBefore  [0] Time OPTIONAL,
+                                   notAfter   [1] Time OPTIONAL } --at least one MUST be present
+            
+ @return a basic ASN.1 object representation. +
+ +
+             PkiArchiveOptions ::= CHOICE {
+                 encryptedPrivKey     [0] EncryptedKey,
+                 -- the actual value of the private key
+                 keyGenParameters     [1] KeyGenParameters,
+                 -- parameters which allow the private key to be re-generated
+                 archiveRemGenPrivKey [2] BOOLEAN }
+                 -- set to TRUE if sender wishes receiver to archive the private
+                 -- key of a key pair that the receiver generates in response to
+                 -- this request; set to FALSE if no archival is desired.
+            
+
+ +
+            PkiPublicationInfo ::= SEQUENCE {
+                             action     INTEGER {
+                                            dontPublish (0),
+                                            pleasePublish (1) },
+                             pubInfos  SEQUENCE SIZE (1..MAX) OF SinglePubInfo OPTIONAL }
+            -- pubInfos MUST NOT be present if action is "dontPublish"
+            -- (if action is "pleasePublish" and pubInfos is omitted,
+            -- "dontCare" is assumed)
+            
+ @return a basic ASN.1 object representation. +
+ + Password-based MAC value for use with POPOSigningKeyInput. + + + Creates a new PKMACValue. + @param params parameters for password-based MAC + @param value MAC of the DER-encoded SubjectPublicKeyInfo + + + Creates a new PKMACValue. + @param aid CMPObjectIdentifiers.passwordBasedMAC, with PBMParameter + @param value MAC of the DER-encoded SubjectPublicKeyInfo + + +
+            PKMACValue ::= SEQUENCE {
+                 algId  AlgorithmIdentifier,
+                 -- algorithm value shall be PasswordBasedMac 1.2.840.113533.7.66.13
+                 -- parameter value is PBMParameter
+                 value  BIT STRING }
+            
+ @return a basic ASN.1 object representation. +
+ +
+            PopoPrivKey ::= CHOICE {
+                   thisMessage       [0] BIT STRING,         -- Deprecated
+                    -- possession is proven in this message (which contains the private
+                    -- key itself (encrypted for the CA))
+                   subsequentMessage [1] SubsequentMessage,
+                    -- possession will be proven in a subsequent message
+                   dhMAC             [2] BIT STRING,         -- Deprecated
+                   agreeMAC          [3] PKMACValue,
+                   encryptedKey      [4] EnvelopedData }
+            
+
+ + Creates a new Proof of Possession object for a signing key. + @param poposkIn the PopoSigningKeyInput structure, or null if the + CertTemplate includes both subject and publicKey values. + @param aid the AlgorithmIdentifier used to sign the proof of possession. + @param signature a signature over the DER-encoded value of poposkIn, + or the DER-encoded value of certReq if poposkIn is null. + + +
+            PopoSigningKey ::= SEQUENCE {
+                                 poposkInput           [0] PopoSigningKeyInput OPTIONAL,
+                                 algorithmIdentifier   AlgorithmIdentifier,
+                                 signature             BIT STRING }
+             -- The signature (using "algorithmIdentifier") is on the
+             -- DER-encoded value of poposkInput.  NOTE: If the CertReqMsg
+             -- certReq CertTemplate contains the subject and publicKey values,
+             -- then poposkInput MUST be omitted and the signature MUST be
+             -- computed on the DER-encoded value of CertReqMsg certReq.  If
+             -- the CertReqMsg certReq CertTemplate does not contain the public
+             -- key and subject values, then poposkInput MUST be present and
+             -- MUST be signed.  This strategy ensures that the public key is
+             -- not present in both the poposkInput and CertReqMsg certReq
+             -- CertTemplate fields.
+            
+ @return a basic ASN.1 object representation. +
+ + Creates a new PopoSigningKeyInput with sender name as authInfo. + + + Creates a new PopoSigningKeyInput using password-based MAC. + + + Returns the sender field, or null if authInfo is publicKeyMac + + + Returns the publicKeyMac field, or null if authInfo is sender + + +
+            PopoSigningKeyInput ::= SEQUENCE {
+                   authInfo             CHOICE {
+                                            sender              [0] GeneralName,
+                                            -- used only if an authenticated identity has been
+                                            -- established for the sender (e.g., a DN from a
+                                            -- previously-issued and currently-valid certificate
+                                            publicKeyMac        PKMacValue },
+                                            -- used if no authenticated GeneralName currently exists for
+                                            -- the sender; publicKeyMac contains a password-based MAC
+                                            -- on the DER-encoded value of publicKey
+                   publicKey           SubjectPublicKeyInfo }  -- from CertTemplate
+            
+ @return a basic ASN.1 object representation. +
+ + Creates a ProofOfPossession with type raVerified. + + + Creates a ProofOfPossession for a signing key. + + + Creates a ProofOfPossession for key encipherment or agreement. + @param type one of TYPE_KEY_ENCIPHERMENT or TYPE_KEY_AGREEMENT + + +
+            ProofOfPossession ::= CHOICE {
+                                      raVerified        [0] NULL,
+                                      -- used if the RA has already verified that the requester is in
+                                      -- possession of the private key
+                                      signature         [1] PopoSigningKey,
+                                      keyEncipherment   [2] PopoPrivKey,
+                                      keyAgreement      [3] PopoPrivKey }
+            
+ @return a basic ASN.1 object representation. +
+ +
+            SinglePubInfo ::= SEQUENCE {
+                   pubMethod    INTEGER {
+                      dontCare    (0),
+                      x500        (1),
+                      web         (2),
+                      ldap        (3) },
+                  pubLocation  GeneralName OPTIONAL }
+            
+ @return a basic ASN.1 object representation. +
+ + table of the available named parameters for GOST 3410-2001. + + + return the ECDomainParameters object for the given OID, null if it + isn't present. + + @param oid an object identifier representing a named parameters, if present. + + + returns an enumeration containing the name strings for curves + contained in this structure. + + + return the named curve name represented by the given object identifier. + + +
+             Gost28147-89-Parameters ::=
+                           SEQUENCE {
+                                   iv                   Gost28147-89-IV,
+                                   encryptionParamSet   OBJECT IDENTIFIER
+                            }
+            
+               Gost28147-89-IV ::= OCTET STRING (SIZE (8))
+             
+
+ + table of the available named parameters for GOST 3410-94. + + + return the GOST3410ParamSetParameters object for the given OID, null if it + isn't present. + + @param oid an object identifier representing a named parameters, if present. + + + returns an enumeration containing the name strings for parameters + contained in this structure. + + + Base class for an application specific object + + + Return the enclosed object assuming explicit tagging. + + @return the resulting object + @throws IOException if reconstruction fails. + + + Return the enclosed object assuming implicit tagging. + + @param derTagNo the type tag that should be applied to the object's contents. + @return the resulting object + @throws IOException if reconstruction fails. + + + return the correct number of pad bits for a bit string defined in + a 32 bit constant + + + return the correct number of bytes for a bit string defined in + a 32 bit constant + + + return a Bit string from the passed in object + + @exception ArgumentException if the object cannot be converted. + + + return a Bit string from a tagged object. + + @param obj the tagged object holding the object we want + @param explicitly true if the object is meant to be explicitly + tagged false otherwise. + @exception ArgumentException if the tagged object cannot + be converted. + + + @param data the octets making up the bit string. + @param padBits the number of extra bits at the end of the string. + + + @return the value of the bit string as an int (truncating if necessary) + + + Der BMPString object. + + + return a BMP string from the given object. + + @param obj the object we want converted. + @exception ArgumentException if the object cannot be converted. + + + return a BMP string from a tagged object. + + @param obj the tagged object holding the object we want + @param explicitly true if the object is meant to be explicitly + tagged false otherwise. + @exception ArgumentException if the tagged object cannot + be converted. + + + basic constructor - byte encoded string. + + + basic constructor + + + return a bool from the passed in object. + + @exception ArgumentException if the object cannot be converted. + + + return a DerBoolean from the passed in bool. + + + return a Boolean from a tagged object. + + @param obj the tagged object holding the object we want + @param explicitly true if the object is meant to be explicitly + tagged false otherwise. + @exception ArgumentException if the tagged object cannot + be converted. + + + return an integer from the passed in object + + @exception ArgumentException if the object cannot be converted. + + + return an Enumerated from a tagged object. + + @param obj the tagged object holding the object we want + @param explicitly true if the object is meant to be explicitly + tagged false otherwise. + @exception ArgumentException if the tagged object cannot + be converted. + + + Class representing the DER-type External + + + Creates a new instance of DerExternal + See X.690 for more informations about the meaning of these parameters + @param directReference The direct reference or null if not set. + @param indirectReference The indirect reference or null if not set. + @param dataValueDescriptor The data value descriptor or null if not set. + @param externalData The external data in its encoded form. + + + Creates a new instance of DerExternal. + See X.690 for more informations about the meaning of these parameters + @param directReference The direct reference or null if not set. + @param indirectReference The indirect reference or null if not set. + @param dataValueDescriptor The data value descriptor or null if not set. + @param encoding The encoding to be used for the external data + @param externalData The external data + + + The encoding of the content. Valid values are +
    +
  • 0 single-ASN1-type
  • +
  • 1 OCTET STRING
  • +
  • 2 BIT STRING
  • +
+
+ + Generalized time object. + + + return a generalized time from the passed in object + + @exception ArgumentException if the object cannot be converted. + + + return a Generalized Time object from a tagged object. + + @param obj the tagged object holding the object we want + @param explicitly true if the object is meant to be explicitly + tagged false otherwise. + @exception ArgumentException if the tagged object cannot + be converted. + + + The correct format for this is YYYYMMDDHHMMSS[.f]Z, or without the Z + for local time, or Z+-HHMM on the end, for difference between local + time and UTC time. The fractional second amount f must consist of at + least one number with trailing zeroes removed. + + @param time the time string. + @exception ArgumentException if string is an illegal format. + + + base constructor from a local time object + + + Return the time. + @return The time string as it appeared in the encoded object. + + + return the time - always in the form of + YYYYMMDDhhmmssGMT(+hh:mm|-hh:mm). +

+ Normally in a certificate we would expect "Z" rather than "GMT", + however adding the "GMT" means we can just use: +

+                dateF = new SimpleDateFormat("yyyyMMddHHmmssz");
+            
+ To read in the time and Get a date which is compatible with our local + time zone.

+
+ + Der IA5String object - this is an ascii string. + + + return a IA5 string from the passed in object + + @exception ArgumentException if the object cannot be converted. + + + return an IA5 string from a tagged object. + + @param obj the tagged object holding the object we want + @param explicitly true if the object is meant to be explicitly + tagged false otherwise. + @exception ArgumentException if the tagged object cannot + be converted. + + + basic constructor - with bytes. + + + basic constructor - without validation. + + + Constructor with optional validation. + + @param string the base string to wrap. + @param validate whether or not to check the string. + @throws ArgumentException if validate is true and the string + contains characters that should not be in an IA5String. + + + return true if the passed in String can be represented without + loss as an IA5String, false otherwise. + + @return true if in printable set, false otherwise. + + + return an integer from the passed in object + + @exception ArgumentException if the object cannot be converted. + + + return an Integer from a tagged object. + + @param obj the tagged object holding the object we want + @param isExplicit true if the object is meant to be explicitly + tagged false otherwise. + @exception ArgumentException if the tagged object cannot + be converted. + + + in some cases positive values Get crammed into a space, + that's not quite big enough... + + + A Null object. + + + Der NumericString object - this is an ascii string of characters {0,1,2,3,4,5,6,7,8,9, }. + + + return a Numeric string from the passed in object + + @exception ArgumentException if the object cannot be converted. + + + return an Numeric string from a tagged object. + + @param obj the tagged object holding the object we want + @param explicitly true if the object is meant to be explicitly + tagged false otherwise. + @exception ArgumentException if the tagged object cannot + be converted. + + + basic constructor - with bytes. + + + basic constructor - without validation.. + + + Constructor with optional validation. + + @param string the base string to wrap. + @param validate whether or not to check the string. + @throws ArgumentException if validate is true and the string + contains characters that should not be in a NumericString. + + + Return true if the string can be represented as a NumericString ('0'..'9', ' ') + + @param str string to validate. + @return true if numeric, fale otherwise. + + + return an Oid from the passed in object + + @exception ArgumentException if the object cannot be converted. + + + return an object Identifier from a tagged object. + + @param obj the tagged object holding the object we want + @param explicitly true if the object is meant to be explicitly + tagged false otherwise. + @exception ArgumentException if the tagged object cannot + be converted. + + + Return true if this oid is an extension of the passed in branch, stem. + @param stem the arc or branch that is a possible parent. + @return true if the branch is on the passed in stem, false otherwise. + + + The octets making up the octet string. + + + Der PrintableString object. + + + return a printable string from the passed in object. + + @exception ArgumentException if the object cannot be converted. + + + return a Printable string from a tagged object. + + @param obj the tagged object holding the object we want + @param explicitly true if the object is meant to be explicitly + tagged false otherwise. + @exception ArgumentException if the tagged object cannot + be converted. + + + basic constructor - byte encoded string. + + + basic constructor - this does not validate the string + + + Constructor with optional validation. + + @param string the base string to wrap. + @param validate whether or not to check the string. + @throws ArgumentException if validate is true and the string + contains characters that should not be in a PrintableString. + + + return true if the passed in String can be represented without + loss as a PrintableString, false otherwise. + + @return true if in printable set, false otherwise. + + + create an empty sequence + + + create a sequence containing one object + + + create a sequence containing a vector of objects. + + + A Der encoded set object + + + create an empty set + + + @param obj - a single object that makes up the set. + + + @param v - a vector of objects making up the set. + + + Der T61String (also the teletex string) - 8-bit characters + + + return a T61 string from the passed in object. + + @exception ArgumentException if the object cannot be converted. + + + return an T61 string from a tagged object. + + @param obj the tagged object holding the object we want + @param explicitly true if the object is meant to be explicitly + tagged false otherwise. + @exception ArgumentException if the tagged object cannot + be converted. + + + basic constructor - with bytes. + + + basic constructor - with string. + + + DER TaggedObject - in ASN.1 notation this is any object preceded by + a [n] where n is some number - these are assumed to follow the construction + rules (as with sequences). + + + @param tagNo the tag number for this object. + @param obj the tagged object. + + + @param explicitly true if an explicitly tagged object. + @param tagNo the tag number for this object. + @param obj the tagged object. + + + create an implicitly tagged object that contains a zero + length sequence. + + + Der UniversalString object. + + + return a Universal string from the passed in object. + + @exception ArgumentException if the object cannot be converted. + + + return a Universal string from a tagged object. + + @param obj the tagged object holding the object we want + @param explicitly true if the object is meant to be explicitly + tagged false otherwise. + @exception ArgumentException if the tagged object cannot + be converted. + + + basic constructor - byte encoded string. + + + We insert one of these when we find a tag we don't recognise. + + + @param tag the tag value. + @param data the contents octets. + + + UTC time object. + + + return an UTC Time from the passed in object. + + @exception ArgumentException if the object cannot be converted. + + + return an UTC Time from a tagged object. + + @param obj the tagged object holding the object we want + @param explicitly true if the object is meant to be explicitly + tagged false otherwise. + @exception ArgumentException if the tagged object cannot + be converted. + + + The correct format for this is YYMMDDHHMMSSZ (it used to be that seconds were + never encoded. When you're creating one of these objects from scratch, that's + what you want to use, otherwise we'll try to deal with whatever Gets read from + the input stream... (this is why the input format is different from the GetTime() + method output). +

+ @param time the time string.

+
+ + base constructor from a DateTime object + + + return the time as a date based on whatever a 2 digit year will return. For + standardised processing use ToAdjustedDateTime(). + + @return the resulting date + @exception ParseException if the date string cannot be parsed. + + + return the time as an adjusted date + in the range of 1950 - 2049. + + @return a date in the range of 1950 to 2049. + @exception ParseException if the date string cannot be parsed. + + + return the time - always in the form of + YYMMDDhhmmssGMT(+hh:mm|-hh:mm). +

+ Normally in a certificate we would expect "Z" rather than "GMT", + however adding the "GMT" means we can just use: +

+                dateF = new SimpleDateFormat("yyMMddHHmmssz");
+            
+ To read in the time and Get a date which is compatible with our local + time zone.

+

+ Note: In some cases, due to the local date processing, this + may lead to unexpected results. If you want to stick the normal + convention of 1950 to 2049 use the GetAdjustedTime() method.

+
+ + + Return a time string as an adjusted date with a 4 digit year. + This goes in the range of 1950 - 2049. + + + + Der UTF8String object. + + + return an UTF8 string from the passed in object. + + @exception ArgumentException if the object cannot be converted. + + + return an UTF8 string from a tagged object. + + @param obj the tagged object holding the object we want + @param explicitly true if the object is meant to be explicitly + tagged false otherwise. + @exception ArgumentException if the tagged object cannot + be converted. + + + basic constructor - byte encoded string. + + + basic constructor + + + Der VisibleString object. + + + return a Visible string from the passed in object. + + @exception ArgumentException if the object cannot be converted. + + + return a Visible string from a tagged object. + + @param obj the tagged object holding the object we want + @param explicitly true if the object is meant to be explicitly + tagged false otherwise. + @exception ArgumentException if the tagged object cannot + be converted. + + + basic constructor - byte encoded string. + + + basic constructor + + + + RFC 3126: 4.3.1 Certificate Values Attribute Definition + + CertificateValues ::= SEQUENCE OF Certificate + + + + +
+            CommitmentTypeIndication ::= SEQUENCE {
+                 commitmentTypeId   CommitmentTypeIdentifier,
+                 commitmentTypeQualifier   SEQUENCE SIZE (1..MAX) OF
+                         CommitmentTypeQualifier OPTIONAL }
+            
+
+ + Commitment type qualifiers, used in the Commitment-Type-Indication attribute (RFC3126). + +
+               CommitmentTypeQualifier ::= SEQUENCE {
+                   commitmentTypeIdentifier  CommitmentTypeIdentifier,
+                   qualifier          ANY DEFINED BY commitmentTypeIdentifier OPTIONAL }
+             
+
+ + Creates a new CommitmentTypeQualifier instance. + + @param commitmentTypeIdentifier a CommitmentTypeIdentifier value + + + Creates a new CommitmentTypeQualifier instance. + + @param commitmentTypeIdentifier a CommitmentTypeIdentifier value + @param qualifier the qualifier, defined by the above field. + + + Creates a new CommitmentTypeQualifier instance. + + @param as CommitmentTypeQualifier structure + encoded as an Asn1Sequence. + + + Returns a DER-encodable representation of this instance. + + @return a Asn1Object value + + + + RFC 3126: 4.2.1 Complete Certificate Refs Attribute Definition + + CompleteCertificateRefs ::= SEQUENCE OF OtherCertID + + + + + + RFC 3126: 4.2.2 Complete Revocation Refs Attribute Definition + + CompleteRevocationRefs ::= SEQUENCE OF CrlOcspRef + + + + + + RFC 3126: 4.2.2 Complete Revocation Refs Attribute Definition + + CrlIdentifier ::= SEQUENCE + { + crlissuer Name, + crlIssuedTime UTCTime, + crlNumber INTEGER OPTIONAL + } + + + + + + RFC 3126: 4.2.2 Complete Revocation Refs Attribute Definition + + CRLListID ::= SEQUENCE + { + crls SEQUENCE OF CrlValidatedID + } + + + + + + RFC 3126: 4.2.2 Complete Revocation Refs Attribute Definition + + CrlOcspRef ::= SEQUENCE { + crlids [0] CRLListID OPTIONAL, + ocspids [1] OcspListID OPTIONAL, + otherRev [2] OtherRevRefs OPTIONAL + } + + + + + + RFC 3126: 4.2.2 Complete Revocation Refs Attribute Definition + + CrlValidatedID ::= SEQUENCE { + crlHash OtherHash, + crlIdentifier CrlIdentifier OPTIONAL} + + + + + + RFC 3126: 4.2.2 Complete Revocation Refs Attribute Definition + + OcspIdentifier ::= SEQUENCE { + ocspResponderID ResponderID, + -- As in OCSP response data + producedAt GeneralizedTime + -- As in OCSP response data + } + + + + + + RFC 3126: 4.2.2 Complete Revocation Refs Attribute Definition + + OcspListID ::= SEQUENCE { + ocspResponses SEQUENCE OF OcspResponsesID + } + + + + + + RFC 3126: 4.2.2 Complete Revocation Refs Attribute Definition + + OcspResponsesID ::= SEQUENCE { + ocspIdentifier OcspIdentifier, + ocspRepHash OtherHash OPTIONAL + } + + + + + + + OtherCertID ::= SEQUENCE { + otherCertHash OtherHash, + issuerSerial IssuerSerial OPTIONAL + } + + + + + + + OtherHash ::= CHOICE { + sha1Hash OtherHashValue, -- This contains a SHA-1 hash + otherHash OtherHashAlgAndValue + } + + OtherHashValue ::= OCTET STRING + + + + + + Summary description for OtherHashAlgAndValue. + + + + OtherHashAlgAndValue ::= SEQUENCE { + hashAlgorithm AlgorithmIdentifier, + hashValue OtherHashValue + } + + OtherHashValue ::= OCTET STRING + + + + + + RFC 3126: 4.2.2 Complete Revocation Refs Attribute Definition + + OtherRevRefs ::= SEQUENCE + { + otherRevRefType OtherRevRefType, + otherRevRefs ANY DEFINED BY otherRevRefType + } + + OtherRevRefType ::= OBJECT IDENTIFIER + + + + + + RFC 3126: 4.3.2 Revocation Values Attribute Definition + + OtherRevVals ::= SEQUENCE + { + otherRevValType OtherRevValType, + otherRevVals ANY DEFINED BY otherRevValType + } + + OtherRevValType ::= OBJECT IDENTIFIER + + + + + + + OtherSigningCertificate ::= SEQUENCE { + certs SEQUENCE OF OtherCertID, + policies SEQUENCE OF PolicyInformation OPTIONAL + } + + + + + + RFC 5126: 6.3.4. revocation-values Attribute Definition + + RevocationValues ::= SEQUENCE { + crlVals [0] SEQUENCE OF CertificateList OPTIONAL, + ocspVals [1] SEQUENCE OF BasicOCSPResponse OPTIONAL, + otherRevVals [2] OtherRevVals OPTIONAL + } + + + + + + + SignaturePolicyId ::= SEQUENCE { + sigPolicyIdentifier SigPolicyId, + sigPolicyHash SigPolicyHash, + sigPolicyQualifiers SEQUENCE SIZE (1..MAX) OF SigPolicyQualifierInfo OPTIONAL + } + + SigPolicyId ::= OBJECT IDENTIFIER + + SigPolicyHash ::= OtherHashAlgAndValue + + + + + + + SignaturePolicyIdentifier ::= CHOICE { + SignaturePolicyId SignaturePolicyId, + SignaturePolicyImplied SignaturePolicyImplied + } + + SignaturePolicyImplied ::= NULL + + + + + +
+              SignerAttribute ::= SEQUENCE OF CHOICE {
+                  claimedAttributes   [0] ClaimedAttributes,
+                  certifiedAttributes [1] CertifiedAttributes }
+            
+              ClaimedAttributes ::= SEQUENCE OF Attribute
+              CertifiedAttributes ::= AttributeCertificate -- as defined in RFC 3281: see clause 4.1.
+             
+
+ + Signer-Location attribute (RFC3126). + +
+               SignerLocation ::= SEQUENCE {
+                   countryName        [0] DirectoryString OPTIONAL,
+                   localityName       [1] DirectoryString OPTIONAL,
+                   postalAddress      [2] PostalAddress OPTIONAL }
+            
+               PostalAddress ::= SEQUENCE SIZE(1..6) OF DirectoryString
+             
+
+ +
+               SignerLocation ::= SEQUENCE {
+                   countryName        [0] DirectoryString OPTIONAL,
+                   localityName       [1] DirectoryString OPTIONAL,
+                   postalAddress      [2] PostalAddress OPTIONAL }
+            
+               PostalAddress ::= SEQUENCE SIZE(1..6) OF DirectoryString
+            
+               DirectoryString ::= CHOICE {
+                     teletexString           TeletexString (SIZE (1..MAX)),
+                     printableString         PrintableString (SIZE (1..MAX)),
+                     universalString         UniversalString (SIZE (1..MAX)),
+                     utf8String              UTF8String (SIZE (1.. MAX)),
+                     bmpString               BMPString (SIZE (1..MAX)) }
+             
+
+ + + + SigPolicyQualifierInfo ::= SEQUENCE { + sigPolicyQualifierId SigPolicyQualifierId, + sigQualifier ANY DEFINED BY sigPolicyQualifierId + } + + SigPolicyQualifierId ::= OBJECT IDENTIFIER + + + + + constructor + + +
+            ContentHints ::= SEQUENCE {
+              contentDescription UTF8String (SIZE (1..MAX)) OPTIONAL,
+              contentType ContentType }
+            
+
+ + Create from OCTET STRING whose octets represent the identifier. + + + Create from byte array representing the identifier. + + + The definition of ContentIdentifier is +
+            ContentIdentifier ::=  OCTET STRING
+            
+ id-aa-contentIdentifier OBJECT IDENTIFIER ::= { iso(1) + member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9) + smime(16) id-aa(2) 7 } +
+ + constructor + + +
+            EssCertID ::= SEQUENCE {
+                certHash Hash,
+                issuerSerial IssuerSerial OPTIONAL }
+            
+
+ +
+             EssCertIDv2 ::=  SEQUENCE {
+                 hashAlgorithm     AlgorithmIdentifier
+                          DEFAULT {algorithm id-sha256},
+                 certHash          Hash,
+                 issuerSerial      IssuerSerial OPTIONAL
+             }
+            
+             Hash ::= OCTET STRING
+            
+             IssuerSerial ::= SEQUENCE {
+                 issuer         GeneralNames,
+                 serialNumber   CertificateSerialNumber
+             }
+             
+
+ + constructor + + +
+             OtherCertID ::= SEQUENCE {
+                 otherCertHash    OtherHash,
+                 issuerSerial     IssuerSerial OPTIONAL }
+            
+             OtherHash ::= CHOICE {
+                 sha1Hash     OCTET STRING,
+                 otherHash    OtherHashAlgAndValue }
+            
+             OtherHashAlgAndValue ::= SEQUENCE {
+                 hashAlgorithm    AlgorithmIdentifier,
+                 hashValue        OCTET STRING }
+            
+             
+
+ + constructors + + + The definition of OtherSigningCertificate is +
+            OtherSigningCertificate ::=  SEQUENCE {
+                 certs        SEQUENCE OF OtherCertID,
+                 policies     SEQUENCE OF PolicyInformation OPTIONAL
+            }
+            
+ id-aa-ets-otherSigCert OBJECT IDENTIFIER ::= { iso(1) + member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9) + smime(16) id-aa(2) 19 } +
+ + constructors + + + The definition of SigningCertificate is +
+            SigningCertificate ::=  SEQUENCE {
+                 certs        SEQUENCE OF EssCertID,
+                 policies     SEQUENCE OF PolicyInformation OPTIONAL
+            }
+            
+ id-aa-signingCertificate OBJECT IDENTIFIER ::= { iso(1) + member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9) + smime(16) id-aa(2) 12 } +
+ + The definition of SigningCertificateV2 is +
+            SigningCertificateV2 ::=  SEQUENCE {
+                 certs        SEQUENCE OF EssCertIDv2,
+                 policies     SEQUENCE OF PolicyInformation OPTIONAL
+            }
+            
+ id-aa-signingCertificateV2 OBJECT IDENTIFIER ::= { iso(1) + member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9) + smime(16) id-aa(2) 47 } +
+ + Marker interface for CHOICE objects - if you implement this in a roll-your-own + object, any attempt to tag the object implicitly will convert the tag to an + explicit one as the encoding rules require. +

+ If you use this interface your class should also implement the getInstance + pattern which takes a tag object and the tagging mode used. +

+
+ + basic interface for Der string objects. + + + The CscaMasterList object. This object can be wrapped in a + CMSSignedData to be published in LDAP. + +
+             CscaMasterList ::= SEQUENCE {
+               version                CscaMasterListVersion,
+               certList               SET OF Certificate }
+               
+             CscaMasterListVersion :: INTEGER {v0(0)}
+             
+
+ + The DataGroupHash object. +
+             DataGroupHash  ::=  SEQUENCE {
+                  dataGroupNumber         DataGroupNumber,
+                  dataGroupHashValue     OCTET STRING }
+            
+             DataGroupNumber ::= INTEGER {
+                     dataGroup1    (1),
+                     dataGroup1    (2),
+                     dataGroup1    (3),
+                     dataGroup1    (4),
+                     dataGroup1    (5),
+                     dataGroup1    (6),
+                     dataGroup1    (7),
+                     dataGroup1    (8),
+                     dataGroup1    (9),
+                     dataGroup1    (10),
+                     dataGroup1    (11),
+                     dataGroup1    (12),
+                     dataGroup1    (13),
+                     dataGroup1    (14),
+                     dataGroup1    (15),
+                     dataGroup1    (16) }
+            
+             
+
+ + The LDSSecurityObject object (V1.8). +
+             LDSSecurityObject ::= SEQUENCE {
+               version                LDSSecurityObjectVersion,
+               hashAlgorithm          DigestAlgorithmIdentifier,
+               dataGroupHashValues    SEQUENCE SIZE (2..ub-DataGroups) OF DataHashGroup,
+               ldsVersionInfo         LDSVersionInfo OPTIONAL
+                 -- if present, version MUST be v1 }
+            
+             DigestAlgorithmIdentifier ::= AlgorithmIdentifier,
+            
+             LDSSecurityObjectVersion :: INTEGER {V0(0)}
+             
+
+ +
+            LDSVersionInfo ::= SEQUENCE {
+               ldsVersion PRINTABLE STRING
+               unicodeVersion PRINTABLE STRING
+             }
+            
+ @return +
+ + The id-isismtt-cp-accredited OID indicates that the certificate is a + qualified certificate according to Directive 1999/93/EC of the European + Parliament and of the Council of 13 December 1999 on a Community + Framework for Electronic Signatures, which additionally conforms the + special requirements of the SigG and has been issued by an accredited CA. + + + Certificate extensionDate of certificate generation + +
+            		DateOfCertGenSyntax ::= GeneralizedTime
+             
+
+ + Attribute to indicate that the certificate holder may sign in the name of + a third person. May also be used as extension in a certificate. + + + Attribute to indicate admissions to certain professions. May be used as + attribute in attribute certificate or as extension in a certificate + + + Monetary limit for transactions. The QcEuMonetaryLimit QC statement MUST + be used in new certificates in place of the extension/attribute + MonetaryLimit since January 1, 2004. For the sake of backward + compatibility with certificates already in use, SigG conforming + components MUST support MonetaryLimit (as well as QcEuLimitValue). + + + A declaration of majority. May be used as attribute in attribute + certificate or as extension in a certificate + + + + Serial number of the smart card containing the corresponding private key + +
+            		ICCSNSyntax ::= OCTET STRING (SIZE(8..20))
+             
+
+ + + Reference for a file of a smartcard that stores the public key of this + certificate and that is used as �security anchor�. + +
+            		PKReferenceSyntax ::= OCTET STRING (SIZE(20))
+             
+
+ + Some other restriction regarding the usage of this certificate. May be + used as attribute in attribute certificate or as extension in a + certificate. + +
+            		RestrictionSyntax ::= DirectoryString (SIZE(1..1024))
+             
+ + @see Org.BouncyCastle.Asn1.IsisMtt.X509.Restriction +
+ + + (Single)Request extension: Clients may include this extension in a + (single) Request to request the responder to send the certificate in the + response message along with the status information. Besides the LDAP + service, this extension provides another mechanism for the distribution + of certificates, which MAY optionally be provided by certificate + repositories. + +
+            		RetrieveIfAllowed ::= BOOLEAN
+             
+
+ + SingleOCSPResponse extension: The certificate requested by the client by + inserting the RetrieveIfAllowed extension in the request, will be + returned in this extension. + + @see Org.BouncyCastle.Asn1.IsisMtt.Ocsp.RequestedCertificate + + + Base ObjectIdentifier for naming authorities + + + SingleOCSPResponse extension: Date, when certificate has been published + in the directory and status information has become available. Currently, + accrediting authorities enforce that SigG-conforming OCSP servers include + this extension in the responses. + +
+            		CertInDirSince ::= GeneralizedTime
+             
+
+ + Hash of a certificate in OCSP. + + @see Org.BouncyCastle.Asn1.IsisMtt.Ocsp.CertHash + + +
+            		NameAtBirth ::= DirectoryString(SIZE(1..64)
+             
+ + Used in + {@link Org.BouncyCastle.Asn1.X509.SubjectDirectoryAttributes SubjectDirectoryAttributes} +
+ + Some other information of non-restrictive nature regarding the usage of + this certificate. May be used as attribute in atribute certificate or as + extension in a certificate. + +
+                          AdditionalInformationSyntax ::= DirectoryString (SIZE(1..2048))
+            
+ + @see Org.BouncyCastle.Asn1.IsisMtt.X509.AdditionalInformationSyntax +
+ + Indicates that an attribute certificate exists, which limits the + usability of this public key certificate. Whenever verifying a signature + with the help of this certificate, the content of the corresponding + attribute certificate should be concerned. This extension MUST be + included in a PKC, if a corresponding attribute certificate (having the + PKC as base certificate) contains some attribute that restricts the + usability of the PKC too. Attribute certificates with restricting content + MUST always be included in the signed document. + +
+            		LiabilityLimitationFlagSyntax ::= BOOLEAN
+             
+
+ + ISIS-MTT PROFILE: The responder may include this extension in a response to + send the hash of the requested certificate to the responder. This hash is + cryptographically bound to the certificate and serves as evidence that the + certificate is known to the responder (i.e. it has been issued and is present + in the directory). Hence, this extension is a means to provide a positive + statement of availability as described in T8.[8]. As explained in T13.[1], + clients may rely on this information to be able to validate signatures after + the expiry of the corresponding certificate. Hence, clients MUST support this + extension. If a positive statement of availability is to be delivered, this + extension syntax and OID MUST be used. +

+

+

+                CertHash ::= SEQUENCE {
+                  hashAlgorithm AlgorithmIdentifier,
+                  certificateHash OCTET STRING
+                }
+            
+
+ + Constructor from Asn1Sequence. +

+ The sequence is of type CertHash: +

+

+                 CertHash ::= SEQUENCE {
+                   hashAlgorithm AlgorithmIdentifier,
+                   certificateHash OCTET STRING
+                 }
+             
+ + @param seq The ASN.1 sequence. +
+ + Constructor from a given details. + + @param hashAlgorithm The hash algorithm identifier. + @param certificateHash The hash of the whole DER encoding of the certificate. + + + Produce an object suitable for an Asn1OutputStream. +

+ Returns: +

+

+                 CertHash ::= SEQUENCE {
+                   hashAlgorithm AlgorithmIdentifier,
+                   certificateHash OCTET STRING
+                 }
+             
+ + @return an Asn1Object +
+ + ISIS-MTT-Optional: The certificate requested by the client by inserting the + RetrieveIfAllowed extension in the request, will be returned in this + extension. +

+ ISIS-MTT-SigG: The signature act allows publishing certificates only then, + when the certificate owner gives his isExplicit permission. Accordingly, there + may be �nondownloadable� certificates, about which the responder must provide + status information, but MUST NOT include them in the response. Clients may + get therefore the following three kind of answers on a single request + including the RetrieveIfAllowed extension: +

    +
  • a) the responder supports the extension and is allowed to publish the + certificate: RequestedCertificate returned including the requested + certificate
  • +
  • b) the responder supports the extension but is NOT allowed to publish + the certificate: RequestedCertificate returned including an empty OCTET + STRING
  • +
  • c) the responder does not support the extension: RequestedCertificate is + not included in the response
  • +
+ Clients requesting RetrieveIfAllowed MUST be able to handle these cases. If + any of the OCTET STRING options is used, it MUST contain the DER encoding of + the requested certificate. +

+

+                       RequestedCertificate ::= CHOICE {
+                         Certificate Certificate,
+                         publicKeyCertificate [0] EXPLICIT OCTET STRING,
+                         attributeCertificate [1] EXPLICIT OCTET STRING
+                       }
+            
+
+ + Constructor from a given details. +

+ Only one parameter can be given. All other must be null. + + @param certificate Given as Certificate + + + Produce an object suitable for an Asn1OutputStream. +

+ Returns: +

+

+                        RequestedCertificate ::= CHOICE {
+                          Certificate Certificate,
+                          publicKeyCertificate [0] EXPLICIT OCTET STRING,
+                          attributeCertificate [1] EXPLICIT OCTET STRING
+                        }
+             
+ + @return an Asn1Object +
+ + Some other information of non-restrictive nature regarding the usage of this + certificate. + +
+               AdditionalInformationSyntax ::= DirectoryString (SIZE(1..2048))
+            
+
+ + Constructor from a given details. + + @param information The describtion of the information. + + + Produce an object suitable for an Asn1OutputStream. +

+ Returns: +

+

+               AdditionalInformationSyntax ::= DirectoryString (SIZE(1..2048))
+             
+ + @return an Asn1Object +
+ + An Admissions structure. +

+

+                        Admissions ::= SEQUENCE
+                        {
+                          admissionAuthority [0] EXPLICIT GeneralName OPTIONAL
+                          namingAuthority [1] EXPLICIT NamingAuthority OPTIONAL
+                          professionInfos SEQUENCE OF ProfessionInfo
+                        }
+             

+

+ + @see Org.BouncyCastle.Asn1.IsisMtt.X509.AdmissionSyntax + @see Org.BouncyCastle.Asn1.IsisMtt.X509.ProfessionInfo + @see Org.BouncyCastle.Asn1.IsisMtt.X509.NamingAuthority +
+ + Constructor from Asn1Sequence. +

+ The sequence is of type ProcurationSyntax: +

+

+                        Admissions ::= SEQUENCE
+                        {
+                          admissionAuthority [0] EXPLICIT GeneralName OPTIONAL
+                          namingAuthority [1] EXPLICIT NamingAuthority OPTIONAL
+                          professionInfos SEQUENCE OF ProfessionInfo
+                        }
+             
+ + @param seq The ASN.1 sequence. +
+ + Constructor from a given details. +

+ Parameter professionInfos is mandatory. + + @param admissionAuthority The admission authority. + @param namingAuthority The naming authority. + @param professionInfos The profession infos. + + + Produce an object suitable for an Asn1OutputStream. +

+ Returns: +

+

+                   Admissions ::= SEQUENCE
+                   {
+                     admissionAuthority [0] EXPLICIT GeneralName OPTIONAL
+                     namingAuthority [1] EXPLICIT NamingAuthority OPTIONAL
+                     professionInfos SEQUENCE OF ProfessionInfo
+                   }
+             

+

+ + @return an Asn1Object +
+ + Attribute to indicate admissions to certain professions. +

+

+                 AdmissionSyntax ::= SEQUENCE
+                 {
+                   admissionAuthority GeneralName OPTIONAL,
+                   contentsOfAdmissions SEQUENCE OF Admissions
+                 }
+             

+ Admissions ::= SEQUENCE + { + admissionAuthority [0] EXPLICIT GeneralName OPTIONAL + namingAuthority [1] EXPLICIT NamingAuthority OPTIONAL + professionInfos SEQUENCE OF ProfessionInfo + } +

+ NamingAuthority ::= SEQUENCE + { + namingAuthorityId OBJECT IDENTIFIER OPTIONAL, + namingAuthorityUrl IA5String OPTIONAL, + namingAuthorityText DirectoryString(SIZE(1..128)) OPTIONAL + } +

+ ProfessionInfo ::= SEQUENCE + { + namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL, + professionItems SEQUENCE OF DirectoryString (SIZE(1..128)), + professionOIDs SEQUENCE OF OBJECT IDENTIFIER OPTIONAL, + registrationNumber PrintableString(SIZE(1..128)) OPTIONAL, + addProfessionInfo OCTET STRING OPTIONAL + } +

+

+

+ ISIS-MTT PROFILE: The relatively complex structure of AdmissionSyntax + supports the following concepts and requirements: +

    +
  • External institutions (e.g. professional associations, chambers, unions, + administrative bodies, companies, etc.), which are responsible for granting + and verifying professional admissions, are indicated by means of the data + field admissionAuthority. An admission authority is indicated by a + GeneralName object. Here an X.501 directory name (distinguished name) can be + indicated in the field directoryName, a URL address can be indicated in the + field uniformResourceIdentifier, and an object identifier can be indicated in + the field registeredId.
  • +
  • The names of authorities which are responsible for the administration of + title registers are indicated in the data field namingAuthority. The name of + the authority can be identified by an object identifier in the field + namingAuthorityId, by means of a text string in the field + namingAuthorityText, by means of a URL address in the field + namingAuthorityUrl, or by a combination of them. For example, the text string + can contain the name of the authority, the country and the name of the title + register. The URL-option refers to a web page which contains lists with + �officially� registered professions (text and possibly OID) as well as + further information on these professions. Object identifiers for the + component namingAuthorityId are grouped under the OID-branch + id-isis-at-namingAuthorities and must be applied for.
  • +
  • See http://www.teletrust.de/anwend.asp?Id=30200&Sprache=E_&HomePG=0 + for an application form and http://www.teletrust.de/links.asp?id=30220,11 + for an overview of registered naming authorities.
  • +
  • By means of the data type ProfessionInfo certain professions, + specializations, disciplines, fields of activity, etc. are identified. A + profession is represented by one or more text strings, resp. profession OIDs + in the fields professionItems and professionOIDs and by a registration number + in the field registrationNumber. An indication in text form must always be + present, whereas the other indications are optional. The component + addProfessionInfo may contain additional applicationspecific information in + DER-encoded form.
  • +
+

+ By means of different namingAuthority-OIDs or profession OIDs hierarchies of + professions, specializations, disciplines, fields of activity, etc. can be + expressed. The issuing admission authority should always be indicated (field + admissionAuthority), whenever a registration number is presented. Still, + information on admissions can be given without indicating an admission or a + naming authority by the exclusive use of the component professionItems. In + this case the certification authority is responsible for the verification of + the admission information. +

+

+

+ This attribute is single-valued. Still, several admissions can be captured in + the sequence structure of the component contentsOfAdmissions of + AdmissionSyntax or in the component professionInfos of Admissions. The + component admissionAuthority of AdmissionSyntax serves as default value for + the component admissionAuthority of Admissions. Within the latter component + the default value can be overwritten, in case that another authority is + responsible. The component namingAuthority of Admissions serves as a default + value for the component namingAuthority of ProfessionInfo. Within the latter + component the default value can be overwritten, in case that another naming + authority needs to be recorded. +

+ The length of the string objects is limited to 128 characters. It is + recommended to indicate a namingAuthorityURL in all issued attribute + certificates. If a namingAuthorityURL is indicated, the field professionItems + of ProfessionInfo should contain only registered titles. If the field + professionOIDs exists, it has to contain the OIDs of the professions listed + in professionItems in the same order. In general, the field professionInfos + should contain only one entry, unless the admissions that are to be listed + are logically connected (e.g. they have been issued under the same admission + number). + + @see Org.BouncyCastle.Asn1.IsisMtt.X509.Admissions + @see Org.BouncyCastle.Asn1.IsisMtt.X509.ProfessionInfo + @see Org.BouncyCastle.Asn1.IsisMtt.X509.NamingAuthority + + + Constructor from Asn1Sequence. +

+ The sequence is of type ProcurationSyntax: +

+

+                 AdmissionSyntax ::= SEQUENCE
+                 {
+                   admissionAuthority GeneralName OPTIONAL,
+                   contentsOfAdmissions SEQUENCE OF Admissions
+                 }
+             

+ Admissions ::= SEQUENCE + { + admissionAuthority [0] EXPLICIT GeneralName OPTIONAL + namingAuthority [1] EXPLICIT NamingAuthority OPTIONAL + professionInfos SEQUENCE OF ProfessionInfo + } +

+ NamingAuthority ::= SEQUENCE + { + namingAuthorityId OBJECT IDENTIFIER OPTIONAL, + namingAuthorityUrl IA5String OPTIONAL, + namingAuthorityText DirectoryString(SIZE(1..128)) OPTIONAL + } +

+ ProfessionInfo ::= SEQUENCE + { + namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL, + professionItems SEQUENCE OF DirectoryString (SIZE(1..128)), + professionOIDs SEQUENCE OF OBJECT IDENTIFIER OPTIONAL, + registrationNumber PrintableString(SIZE(1..128)) OPTIONAL, + addProfessionInfo OCTET STRING OPTIONAL + } +

+ + @param seq The ASN.1 sequence. +
+ + Constructor from given details. + + @param admissionAuthority The admission authority. + @param contentsOfAdmissions The admissions. + + + Produce an object suitable for an Asn1OutputStream. +

+ Returns: +

+

+                 AdmissionSyntax ::= SEQUENCE
+                 {
+                   admissionAuthority GeneralName OPTIONAL,
+                   contentsOfAdmissions SEQUENCE OF Admissions
+                 }
+             

+ Admissions ::= SEQUENCE + { + admissionAuthority [0] EXPLICIT GeneralName OPTIONAL + namingAuthority [1] EXPLICIT NamingAuthority OPTIONAL + professionInfos SEQUENCE OF ProfessionInfo + } +

+ NamingAuthority ::= SEQUENCE + { + namingAuthorityId OBJECT IDENTIFIER OPTIONAL, + namingAuthorityUrl IA5String OPTIONAL, + namingAuthorityText DirectoryString(SIZE(1..128)) OPTIONAL + } +

+ ProfessionInfo ::= SEQUENCE + { + namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL, + professionItems SEQUENCE OF DirectoryString (SIZE(1..128)), + professionOIDs SEQUENCE OF OBJECT IDENTIFIER OPTIONAL, + registrationNumber PrintableString(SIZE(1..128)) OPTIONAL, + addProfessionInfo OCTET STRING OPTIONAL + } +

+ + @return an Asn1Object +
+ + @return Returns the admissionAuthority if present, null otherwise. + + + @return Returns the contentsOfAdmissions. + + + A declaration of majority. +

+

+                      DeclarationOfMajoritySyntax ::= CHOICE
+                      {
+                        notYoungerThan [0] IMPLICIT INTEGER,
+                        fullAgeAtCountry [1] IMPLICIT SEQUENCE
+                        {
+                          fullAge BOOLEAN DEFAULT TRUE,
+                          country PrintableString (SIZE(2))
+                        }
+                        dateOfBirth [2] IMPLICIT GeneralizedTime
+                      }
+            
+

+ fullAgeAtCountry indicates the majority of the owner with respect to the laws + of a specific country. + + + Produce an object suitable for an Asn1OutputStream. +

+ Returns: +

+

+                       DeclarationOfMajoritySyntax ::= CHOICE
+                       {
+                         notYoungerThan [0] IMPLICIT INTEGER,
+                         fullAgeAtCountry [1] IMPLICIT SEQUENCE
+                         {
+                           fullAge BOOLEAN DEFAULT TRUE,
+                           country PrintableString (SIZE(2))
+                         }
+                         dateOfBirth [2] IMPLICIT GeneralizedTime
+                       }
+             
+ + @return an Asn1Object +
+ + @return notYoungerThan if that's what we are, -1 otherwise + + + Monetary limit for transactions. The QcEuMonetaryLimit QC statement MUST be + used in new certificates in place of the extension/attribute MonetaryLimit + since January 1, 2004. For the sake of backward compatibility with + certificates already in use, components SHOULD support MonetaryLimit (as well + as QcEuLimitValue). +

+ Indicates a monetary limit within which the certificate holder is authorized + to act. (This value DOES NOT express a limit on the liability of the + certification authority). +

+

+               MonetaryLimitSyntax ::= SEQUENCE
+               {
+                 currency PrintableString (SIZE(3)),
+                 amount INTEGER,
+                 exponent INTEGER
+               }
+            
+

+ currency must be the ISO code. +

+ value = amount�10*exponent + + + Constructor from a given details. +

+

+ value = amount�10^exponent + + @param currency The currency. Must be the ISO code. + @param amount The amount + @param exponent The exponent + + + Produce an object suitable for an Asn1OutputStream. +

+ Returns: +

+

+                MonetaryLimitSyntax ::= SEQUENCE
+                {
+                  currency PrintableString (SIZE(3)),
+                  amount INTEGER,
+                  exponent INTEGER
+                }
+             
+ + @return an Asn1Object +
+ + Names of authorities which are responsible for the administration of title + registers. + +
+                        NamingAuthority ::= SEQUENCE 
+                        {
+                          namingAuthorityID OBJECT IDENTIFIER OPTIONAL,
+                          namingAuthorityUrl IA5String OPTIONAL,
+                          namingAuthorityText DirectoryString(SIZE(1..128)) OPTIONAL
+                        }
+            
+ @see Org.BouncyCastle.Asn1.IsisMtt.X509.AdmissionSyntax + +
+ + Profession OIDs should always be defined under the OID branch of the + responsible naming authority. At the time of this writing, the work group + �Recht, Wirtschaft, Steuern� (�Law, Economy, Taxes�) is registered as the + first naming authority under the OID id-isismtt-at-namingAuthorities. + + + Constructor from Asn1Sequence. +

+

+

+                         NamingAuthority ::= SEQUENCE
+                         {
+                           namingAuthorityID OBJECT IDENTIFIER OPTIONAL,
+                           namingAuthorityUrl IA5String OPTIONAL,
+                           namingAuthorityText DirectoryString(SIZE(1..128)) OPTIONAL
+                         }
+             
+ + @param seq The ASN.1 sequence. +
+ + @return Returns the namingAuthorityID. + + + @return Returns the namingAuthorityText. + + + @return Returns the namingAuthorityUrl. + + + Constructor from given details. +

+ All parameters can be combined. + + @param namingAuthorityID ObjectIdentifier for naming authority. + @param namingAuthorityUrl URL for naming authority. + @param namingAuthorityText Textual representation of naming authority. + + + Produce an object suitable for an Asn1OutputStream. +

+ Returns: +

+

+                         NamingAuthority ::= SEQUENCE
+                         {
+                           namingAuthorityID OBJECT IDENTIFIER OPTIONAL,
+                           namingAuthorityUrl IA5String OPTIONAL,
+                           namingAuthorityText DirectoryString(SIZE(1..128)) OPTIONAL
+                         }
+             
+ + @return an Asn1Object +
+ + Attribute to indicate that the certificate holder may sign in the name of a + third person. +

+ ISIS-MTT PROFILE: The corresponding ProcurationSyntax contains either the + name of the person who is represented (subcomponent thirdPerson) or a + reference to his/her base certificate (in the component signingFor, + subcomponent certRef), furthermore the optional components country and + typeSubstitution to indicate the country whose laws apply, and respectively + the type of procuration (e.g. manager, procuration, custody). +

+

+ ISIS-MTT PROFILE: The GeneralName MUST be of type directoryName and MAY only + contain: - RFC3039 attributes, except pseudonym (countryName, commonName, + surname, givenName, serialNumber, organizationName, organizationalUnitName, + stateOrProvincename, localityName, postalAddress) and - SubjectDirectoryName + attributes (title, dateOfBirth, placeOfBirth, gender, countryOfCitizenship, + countryOfResidence and NameAtBirth). +

+
+                          ProcurationSyntax ::= SEQUENCE {
+                            country [1] EXPLICIT PrintableString(SIZE(2)) OPTIONAL,
+                            typeOfSubstitution [2] EXPLICIT DirectoryString (SIZE(1..128)) OPTIONAL,
+                            signingFor [3] EXPLICIT SigningFor 
+                          }
+                          
+                          SigningFor ::= CHOICE 
+                          { 
+                            thirdPerson GeneralName,
+                            certRef IssuerSerial 
+                          }
+            
+ +
+ + Constructor from Asn1Sequence. +

+ The sequence is of type ProcurationSyntax: +

+

+                           ProcurationSyntax ::= SEQUENCE {
+                             country [1] EXPLICIT PrintableString(SIZE(2)) OPTIONAL,
+                             typeOfSubstitution [2] EXPLICIT DirectoryString (SIZE(1..128)) OPTIONAL,
+                             signingFor [3] EXPLICIT SigningFor
+                           }
+             

+ SigningFor ::= CHOICE + { + thirdPerson GeneralName, + certRef IssuerSerial + } +

+ + @param seq The ASN.1 sequence. +
+ + Constructor from a given details. +

+

+ Either generalName or certRef MUST be + null. + + @param country The country code whose laws apply. + @param typeOfSubstitution The type of procuration. + @param certRef Reference to certificate of the person who is represented. + + + Constructor from a given details. +

+

+ Either generalName or certRef MUST be + null. + + @param country The country code whose laws apply. + @param typeOfSubstitution The type of procuration. + @param thirdPerson The GeneralName of the person who is represented. + + + Produce an object suitable for an Asn1OutputStream. +

+ Returns: +

+

+                           ProcurationSyntax ::= SEQUENCE {
+                             country [1] EXPLICIT PrintableString(SIZE(2)) OPTIONAL,
+                             typeOfSubstitution [2] EXPLICIT DirectoryString (SIZE(1..128)) OPTIONAL,
+                             signingFor [3] EXPLICIT SigningFor
+                           }
+             

+ SigningFor ::= CHOICE + { + thirdPerson GeneralName, + certRef IssuerSerial + } +

+ + @return an Asn1Object +
+ + Professions, specializations, disciplines, fields of activity, etc. + +
+                          ProfessionInfo ::= SEQUENCE 
+                          {
+                            namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL,
+                            professionItems SEQUENCE OF DirectoryString (SIZE(1..128)),
+                            professionOids SEQUENCE OF OBJECT IDENTIFIER OPTIONAL,
+                            registrationNumber PrintableString(SIZE(1..128)) OPTIONAL,
+                            addProfessionInfo OCTET STRING OPTIONAL 
+                          }
+            
+ + @see Org.BouncyCastle.Asn1.IsisMtt.X509.AdmissionSyntax +
+ + Rechtsanw�ltin + + + Rechtsanwalt + + + Rechtsbeistand + + + Steuerberaterin + + + Steuerberater + + + Steuerbevollm�chtigte + + + Steuerbevollm�chtigter + + + Notarin + + + Notar + + + Notarvertreterin + + + Notarvertreter + + + Notariatsverwalterin + + + Notariatsverwalter + + + Wirtschaftspr�ferin + + + Wirtschaftspr�fer + + + Vereidigte Buchpr�ferin + + + Vereidigter Buchpr�fer + + + Patentanw�ltin + + + Patentanwalt + + + Constructor from Asn1Sequence. +

+

+

+                           ProfessionInfo ::= SEQUENCE
+                           {
+                             namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL,
+                             professionItems SEQUENCE OF DirectoryString (SIZE(1..128)),
+                             professionOids SEQUENCE OF OBJECT IDENTIFIER OPTIONAL,
+                             registrationNumber PrintableString(SIZE(1..128)) OPTIONAL,
+                             addProfessionInfo OCTET STRING OPTIONAL
+                           }
+             
+ + @param seq The ASN.1 sequence. +
+ + Constructor from given details. +

+ professionItems is mandatory, all other parameters are + optional. + + @param namingAuthority The naming authority. + @param professionItems Directory strings of the profession. + @param professionOids DERObjectIdentfier objects for the + profession. + @param registrationNumber Registration number. + @param addProfessionInfo Additional infos in encoded form. + + + Produce an object suitable for an Asn1OutputStream. +

+ Returns: +

+

+                           ProfessionInfo ::= SEQUENCE
+                           {
+                             namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL,
+                             professionItems SEQUENCE OF DirectoryString (SIZE(1..128)),
+                             professionOids SEQUENCE OF OBJECT IDENTIFIER OPTIONAL,
+                             registrationNumber PrintableString(SIZE(1..128)) OPTIONAL,
+                             addProfessionInfo OCTET STRING OPTIONAL
+                           }
+             
+ + @return an Asn1Object +
+ + @return Returns the addProfessionInfo. + + + @return Returns the namingAuthority. + + + @return Returns the professionItems. + + + @return Returns the professionOids. + + + @return Returns the registrationNumber. + + + Some other restriction regarding the usage of this certificate. +

+

+             RestrictionSyntax ::= DirectoryString (SIZE(1..1024))
+            
+
+ + Constructor from DirectoryString. +

+ The DirectoryString is of type RestrictionSyntax: +

+

+                  RestrictionSyntax ::= DirectoryString (SIZE(1..1024))
+             
+ + @param restriction A IAsn1String. +
+ + Constructor from a given details. + + @param restriction The description of the restriction. + + + Produce an object suitable for an Asn1OutputStream. +

+ Returns: +

+

+                  RestrictionSyntax ::= DirectoryString (SIZE(1..1024))
+             

+

+ + @return an Asn1Object +
+ + Produce an object suitable for an Asn1OutputStream. +
+            cast5CBCParameters ::= Sequence {
+                                      iv         OCTET STRING DEFAULT 0,
+                                             -- Initialization vector
+                                      keyLength  Integer
+                                             -- Key length, in bits
+                                 }
+            
+
+ + Produce an object suitable for an Asn1OutputStream. +
+            IDEA-CBCPar ::= Sequence {
+                                 iv    OCTET STRING OPTIONAL -- exactly 8 octets
+                             }
+            
+
+ + The NetscapeCertType object. +
+               NetscapeCertType ::= BIT STRING {
+                    SSLClient               (0),
+                    SSLServer               (1),
+                    S/MIME                  (2),
+                    Object Signing          (3),
+                    Reserved                (4),
+                    SSL CA                  (5),
+                    S/MIME CA               (6),
+                    Object Signing CA       (7) }
+            
+
+ + Basic constructor. + + @param usage - the bitwise OR of the Key Usage flags giving the + allowed uses for the key. + e.g. (X509NetscapeCertType.sslCA | X509NetscapeCertType.smimeCA) + + + This is designed to parse + the PublicKeyAndChallenge created by the KEYGEN tag included by + Mozilla based browsers. +
+              PublicKeyAndChallenge ::= SEQUENCE {
+                spki SubjectPublicKeyInfo,
+                challenge IA5STRING
+              }
+            
+              
+
+ + Utility class for fetching curves using their NIST names as published in FIPS-PUB 186-2 + + + return the X9ECParameters object for the named curve represented by + the passed in object identifier. Null if the curve isn't present. + + @param oid an object identifier representing a named curve, if present. + + + return the object identifier signified by the passed in name. Null + if there is no object identifier associated with name. + + @return the object identifier associated with name, if present. + + + return the named curve name represented by the given object identifier. + + + returns an enumeration containing the name strings for curves + contained in this structure. + + + From RFC 3657 + + + Produce an object suitable for an Asn1OutputStream. +
+            BasicOcspResponse       ::= Sequence {
+                 tbsResponseData      ResponseData,
+                 signatureAlgorithm   AlgorithmIdentifier,
+                 signature            BIT STRING,
+                 certs                [0] EXPLICIT Sequence OF Certificate OPTIONAL }
+            
+
+ + Produce an object suitable for an Asn1OutputStream. +
+            CertID          ::=     Sequence {
+                hashAlgorithm       AlgorithmIdentifier,
+                issuerNameHash      OCTET STRING, -- Hash of Issuer's DN
+                issuerKeyHash       OCTET STRING, -- Hash of Issuers public key
+                serialNumber        CertificateSerialNumber }
+            
+
+ + create a CertStatus object with a tag of zero. + + + Produce an object suitable for an Asn1OutputStream. +
+             CertStatus ::= CHOICE {
+                             good        [0]     IMPLICIT Null,
+                             revoked     [1]     IMPLICIT RevokedInfo,
+                             unknown     [2]     IMPLICIT UnknownInfo }
+            
+
+ + Produce an object suitable for an Asn1OutputStream. +
+            CrlID ::= Sequence {
+                crlUrl               [0]     EXPLICIT IA5String OPTIONAL,
+                crlNum               [1]     EXPLICIT Integer OPTIONAL,
+                crlTime              [2]     EXPLICIT GeneralizedTime OPTIONAL }
+            
+
+ + Produce an object suitable for an Asn1OutputStream. +
+            OcspRequest     ::=     Sequence {
+                tbsRequest                  TBSRequest,
+                optionalSignature   [0]     EXPLICIT Signature OPTIONAL }
+            
+
+ + Produce an object suitable for an Asn1OutputStream. +
+            OcspResponse ::= Sequence {
+                responseStatus         OcspResponseStatus,
+                responseBytes          [0] EXPLICIT ResponseBytes OPTIONAL }
+            
+
+ + The OcspResponseStatus enumeration. +
+            OcspResponseStatus ::= Enumerated {
+                successful            (0),  --Response has valid confirmations
+                malformedRequest      (1),  --Illegal confirmation request
+                internalError         (2),  --Internal error in issuer
+                tryLater              (3),  --Try again later
+                                            --(4) is not used
+                sigRequired           (5),  --Must sign the request
+                unauthorized          (6)   --Request unauthorized
+            }
+            
+
+ + Produce an object suitable for an Asn1OutputStream. +
+            Request         ::=     Sequence {
+                reqCert                     CertID,
+                singleRequestExtensions     [0] EXPLICIT Extensions OPTIONAL }
+            
+
+ + Produce an object suitable for an Asn1OutputStream. +
+            ResponderID ::= CHOICE {
+                 byName          [1] Name,
+                 byKey           [2] KeyHash }
+            
+
+ + Produce an object suitable for an Asn1OutputStream. +
+            ResponseBytes ::=       Sequence {
+                responseType   OBJECT IDENTIFIER,
+                response       OCTET STRING }
+            
+
+ + Produce an object suitable for an Asn1OutputStream. +
+            ResponseData ::= Sequence {
+                version              [0] EXPLICIT Version DEFAULT v1,
+                responderID              ResponderID,
+                producedAt               GeneralizedTime,
+                responses                Sequence OF SingleResponse,
+                responseExtensions   [1] EXPLICIT Extensions OPTIONAL }
+            
+
+ + Produce an object suitable for an Asn1OutputStream. +
+            RevokedInfo ::= Sequence {
+                 revocationTime              GeneralizedTime,
+                 revocationReason    [0]     EXPLICIT CRLReason OPTIONAL }
+            
+
+ + Produce an object suitable for an Asn1OutputStream. +
+            ServiceLocator ::= Sequence {
+                issuer    Name,
+                locator   AuthorityInfoAccessSyntax OPTIONAL }
+            
+
+ + Produce an object suitable for an Asn1OutputStream. +
+            Signature       ::=     Sequence {
+                signatureAlgorithm      AlgorithmIdentifier,
+                signature               BIT STRING,
+                certs               [0] EXPLICIT Sequence OF Certificate OPTIONAL}
+            
+
+ + Produce an object suitable for an Asn1OutputStream. +
+             SingleResponse ::= Sequence {
+                     certID                       CertID,
+                     certStatus                   CertStatus,
+                     thisUpdate                   GeneralizedTime,
+                     nextUpdate         [0]       EXPLICIT GeneralizedTime OPTIONAL,
+                     singleExtensions   [1]       EXPLICIT Extensions OPTIONAL }
+            
+
+ + Produce an object suitable for an Asn1OutputStream. +
+            TBSRequest      ::=     Sequence {
+                version             [0]     EXPLICIT Version DEFAULT v1,
+                requestorName       [1]     EXPLICIT GeneralName OPTIONAL,
+                requestList                 Sequence OF Request,
+                requestExtensions   [2]     EXPLICIT Extensions OPTIONAL }
+            
+
+ + class for breaking up an Oid into it's component tokens, ala + java.util.StringTokenizer. We need this class as some of the + lightweight Java environment don't support classes like + StringTokenizer. + + + return an Attribute object from the given object. + + @param o the object we want converted. + @exception ArgumentException if the object cannot be converted. + + + Produce an object suitable for an Asn1OutputStream. +
+            Attr ::= Sequence {
+                attrType OBJECT IDENTIFIER,
+                attrValues Set OF AttributeValue
+            }
+            
+
+ + Pkcs10 Certfication request object. +
+            CertificationRequest ::= Sequence {
+              certificationRequestInfo  CertificationRequestInfo,
+              signatureAlgorithm        AlgorithmIdentifier{{ SignatureAlgorithms }},
+              signature                 BIT STRING
+            }
+            
+
+ + Pkcs10 CertificationRequestInfo object. +
+              CertificationRequestInfo ::= Sequence {
+               version             Integer { v1(0) } (v1,...),
+               subject             Name,
+               subjectPKInfo   SubjectPublicKeyInfo{{ PKInfoAlgorithms }},
+               attributes          [0] Attributes{{ CRIAttributes }}
+              }
+            
+              Attributes { ATTRIBUTE:IOSet } ::= Set OF Attr{{ IOSet }}
+            
+              Attr { ATTRIBUTE:IOSet } ::= Sequence {
+                type    ATTRIBUTE.&id({IOSet}),
+                values  Set SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{\@type})
+              }
+             
+
+ + Produce an object suitable for an Asn1OutputStream. +
+            ContentInfo ::= Sequence {
+                     contentType ContentType,
+                     content
+                     [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL }
+            
+
+ + The EncryptedData object. +
+                  EncryptedData ::= Sequence {
+                       version Version,
+                       encryptedContentInfo EncryptedContentInfo
+                  }
+            
+            
+                  EncryptedContentInfo ::= Sequence {
+                      contentType ContentType,
+                      contentEncryptionAlgorithm  ContentEncryptionAlgorithmIdentifier,
+                      encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL
+                }
+            
+                EncryptedContent ::= OCTET STRING
+             
+
+ + Produce an object suitable for an Asn1OutputStream. +
+             EncryptedPrivateKeyInfo ::= Sequence {
+                  encryptionAlgorithm AlgorithmIdentifier {{KeyEncryptionAlgorithms}},
+                  encryptedData EncryptedData
+             }
+            
+             EncryptedData ::= OCTET STRING
+            
+             KeyEncryptionAlgorithms ALGORITHM-IDENTIFIER ::= {
+                      ... -- For local profiles
+             }
+             
+
+ +
+            MacData ::= SEQUENCE {
+                mac      DigestInfo,
+                macSalt  OCTET STRING,
+                iterations INTEGER DEFAULT 1
+                -- Note: The default is for historic reasons and its use is deprecated. A
+                -- higher value, like 1024 is recommended.
+            
+ @return the basic DERObject construction. +
+ + the infamous Pfx from Pkcs12 + + + write out an RSA private key with its associated information + as described in Pkcs8. +
+                  PrivateKeyInfo ::= Sequence {
+                                          version Version,
+                                          privateKeyAlgorithm AlgorithmIdentifier {{PrivateKeyAlgorithms}},
+                                          privateKey PrivateKey,
+                                          attributes [0] IMPLICIT Attributes OPTIONAL
+                                      }
+                  Version ::= Integer {v1(0)} (v1,...)
+            
+                  PrivateKey ::= OCTET STRING
+            
+                  Attributes ::= Set OF Attr
+             
+
+ + The default version + + +
+              RSAES-OAEP-params ::= SEQUENCE {
+                 hashAlgorithm      [0] OAEP-PSSDigestAlgorithms     DEFAULT sha1,
+                 maskGenAlgorithm   [1] PKCS1MGFAlgorithms  DEFAULT mgf1SHA1,
+                 pSourceAlgorithm   [2] PKCS1PSourceAlgorithms  DEFAULT pSpecifiedEmpty
+               }
+            
+               OAEP-PSSDigestAlgorithms    ALGORITHM-IDENTIFIER ::= {
+                 { OID id-sha1 PARAMETERS NULL   }|
+                 { OID id-sha256 PARAMETERS NULL }|
+                 { OID id-sha384 PARAMETERS NULL }|
+                 { OID id-sha512 PARAMETERS NULL },
+                 ...  -- Allows for future expansion --
+               }
+               PKCS1MGFAlgorithms    ALGORITHM-IDENTIFIER ::= {
+                 { OID id-mgf1 PARAMETERS OAEP-PSSDigestAlgorithms },
+                ...  -- Allows for future expansion --
+               }
+               PKCS1PSourceAlgorithms    ALGORITHM-IDENTIFIER ::= {
+                 { OID id-pSpecified PARAMETERS OCTET STRING },
+                 ...  -- Allows for future expansion --
+              }
+             
+ @return the asn1 primitive representing the parameters. +
+ + This outputs the key in Pkcs1v2 format. +
+                  RsaPrivateKey ::= Sequence {
+                                      version Version,
+                                      modulus Integer, -- n
+                                      publicExponent Integer, -- e
+                                      privateExponent Integer, -- d
+                                      prime1 Integer, -- p
+                                      prime2 Integer, -- q
+                                      exponent1 Integer, -- d mod (p-1)
+                                      exponent2 Integer, -- d mod (q-1)
+                                      coefficient Integer -- (inverse of q) mod p
+                                  }
+            
+                  Version ::= Integer
+             
+

This routine is written to output Pkcs1 version 0, private keys.

+
+ + The default version + + +
+             RSASSA-PSS-params ::= SEQUENCE {
+               hashAlgorithm      [0] OAEP-PSSDigestAlgorithms  DEFAULT sha1,
+                maskGenAlgorithm   [1] PKCS1MGFAlgorithms  DEFAULT mgf1SHA1,
+                saltLength         [2] INTEGER  DEFAULT 20,
+                trailerField       [3] TrailerField  DEFAULT trailerFieldBC
+              }
+            
+             OAEP-PSSDigestAlgorithms    ALGORITHM-IDENTIFIER ::= {
+                { OID id-sha1 PARAMETERS NULL   }|
+                { OID id-sha256 PARAMETERS NULL }|
+                { OID id-sha384 PARAMETERS NULL }|
+                { OID id-sha512 PARAMETERS NULL },
+                ...  -- Allows for future expansion --
+             }
+            
+             PKCS1MGFAlgorithms    ALGORITHM-IDENTIFIER ::= {
+               { OID id-mgf1 PARAMETERS OAEP-PSSDigestAlgorithms },
+                ...  -- Allows for future expansion --
+             }
+            
+             TrailerField ::= INTEGER { trailerFieldBC(1) }
+             
+ @return the asn1 primitive representing the parameters. +
+ + a Pkcs#7 signed data object. + + + Produce an object suitable for an Asn1OutputStream. +
+             SignedData ::= Sequence {
+                 version Version,
+                 digestAlgorithms DigestAlgorithmIdentifiers,
+                 contentInfo ContentInfo,
+                 certificates
+                     [0] IMPLICIT ExtendedCertificatesAndCertificates
+                              OPTIONAL,
+                 crls
+                     [1] IMPLICIT CertificateRevocationLists OPTIONAL,
+                 signerInfos SignerInfos }
+            
+
+ + a Pkcs#7 signer info object. + + + Produce an object suitable for an Asn1OutputStream. +
+              SignerInfo ::= Sequence {
+                  version Version,
+                  issuerAndSerialNumber IssuerAndSerialNumber,
+                  digestAlgorithm DigestAlgorithmIdentifier,
+                  authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL,
+                  digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier,
+                  encryptedDigest EncryptedDigest,
+                  unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL
+              }
+            
+              EncryptedDigest ::= OCTET STRING
+            
+              DigestAlgorithmIdentifier ::= AlgorithmIdentifier
+            
+              DigestEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
+             
+
+ + the elliptic curve private key object from SEC 1 + + + ECPrivateKey ::= SEQUENCE { + version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1), + privateKey OCTET STRING, + parameters [0] Parameters OPTIONAL, + publicKey [1] BIT STRING OPTIONAL } + + + return the X9ECParameters object for the named curve represented by + the passed in object identifier. Null if the curve isn't present. + + @param oid an object identifier representing a named curve, if present. + + + return the object identifier signified by the passed in name. Null + if there is no object identifier associated with name. + + @return the object identifier associated with name, if present. + + + return the named curve name represented by the given object identifier. + + + returns an enumeration containing the name strings for curves + contained in this structure. + + + EllipticCurve OBJECT IDENTIFIER ::= { + iso(1) identified-organization(3) certicom(132) curve(0) + } + + + Handler class for dealing with S/MIME Capabilities + + + general preferences + + + encryption algorithms preferences + + + return an Attr object from the given object. + + @param o the object we want converted. + @exception ArgumentException if the object cannot be converted. + + + returns an ArrayList with 0 or more objects of all the capabilities + matching the passed in capability Oid. If the Oid passed is null the + entire set is returned. + + + Produce an object suitable for an Asn1OutputStream. +
+            SMIMECapabilities ::= Sequence OF SMIMECapability
+            
+
+ + general preferences + + + encryption algorithms preferences + + + Produce an object suitable for an Asn1OutputStream. +
+            SMIMECapability ::= Sequence {
+                capabilityID OBJECT IDENTIFIER,
+                parameters ANY DEFINED BY capabilityID OPTIONAL
+            }
+            
+
+ + Handler for creating a vector S/MIME Capabilities + + + The SmimeEncryptionKeyPreference object. +
+            SmimeEncryptionKeyPreference ::= CHOICE {
+                issuerAndSerialNumber   [0] IssuerAndSerialNumber,
+                receipentKeyId          [1] RecipientKeyIdentifier,
+                subjectAltKeyIdentifier [2] SubjectKeyIdentifier
+            }
+            
+
+ + @param sKeyId the subjectKeyIdentifier value (normally the X.509 one) + + + elliptic curves defined in "ECC Brainpool Standard Curves and Curve Generation" + http://www.ecc-brainpool.org/download/draft_pkix_additional_ecc_dp.txt + + + return the X9ECParameters object for the named curve represented by + the passed in object identifier. Null if the curve isn't present. + + @param oid an object identifier representing a named curve, if present. + + + return the object identifier signified by the passed in name. Null + if there is no object identifier associated with name. + + @return the object identifier associated with name, if present. + + + return the named curve name represented by the given object identifier. + + + returns an enumeration containing the name strings for curves + contained in this structure. + + +
+            Accuracy ::= SEQUENCE {
+                        seconds        INTEGER              OPTIONAL,
+                        millis     [0] INTEGER  (1..999)    OPTIONAL,
+                        micros     [1] INTEGER  (1..999)    OPTIONAL
+                        }
+            
+
+ + @param o + @return a MessageImprint object. + + +
+               MessageImprint ::= SEQUENCE  {
+                  hashAlgorithm                AlgorithmIdentifier,
+                  hashedMessage                OCTET STRING  }
+            
+
+ +
+            TimeStampReq ::= SEQUENCE  {
+             version                      INTEGER  { v1(1) },
+             messageImprint               MessageImprint,
+               --a hash algorithm OID and the hash value of the data to be
+               --time-stamped
+             reqPolicy             TSAPolicyId              OPTIONAL,
+             nonce                 INTEGER                  OPTIONAL,
+             certReq               BOOLEAN                  DEFAULT FALSE,
+             extensions            [0] IMPLICIT Extensions  OPTIONAL
+            }
+            
+
+ +
+            TimeStampResp ::= SEQUENCE  {
+              status                  PkiStatusInfo,
+              timeStampToken          TimeStampToken     OPTIONAL  }
+            
+
+ +
+            
+                 TstInfo ::= SEQUENCE  {
+                    version                      INTEGER  { v1(1) },
+                    policy                       TSAPolicyId,
+                    messageImprint               MessageImprint,
+                      -- MUST have the same value as the similar field in
+                      -- TimeStampReq
+                    serialNumber                 INTEGER,
+                     -- Time-Stamping users MUST be ready to accommodate integers
+                     -- up to 160 bits.
+                    genTime                      GeneralizedTime,
+                    accuracy                     Accuracy                 OPTIONAL,
+                    ordering                     BOOLEAN             DEFAULT FALSE,
+                    nonce                        INTEGER                  OPTIONAL,
+                      -- MUST be present if the similar field was present
+                      -- in TimeStampReq.  In that case it MUST have the same value.
+                    tsa                          [0] GeneralName          OPTIONAL,
+                    extensions                   [1] IMPLICIT Extensions   OPTIONAL  }
+            
+             
+
+ + dump a Der object as a formatted string with indentation + + @param obj the Asn1Object to be dumped out. + + + dump out a DER object as a formatted string, in non-verbose mode + + @param obj the Asn1Encodable to be dumped out. + @return the resulting string. + + + Dump out the object as a string + + @param obj the Asn1Encodable to be dumped out. + @param verbose if true, dump out the contents of octet and bit strings. + @return the resulting string. + + +
+             DirectoryString ::= CHOICE {
+               teletexString               TeletexString (SIZE (1..MAX)),
+               printableString             PrintableString (SIZE (1..MAX)),
+               universalString             UniversalString (SIZE (1..MAX)),
+               utf8String                  UTF8String (SIZE (1..MAX)),
+               bmpString                   BMPString (SIZE (1..MAX))  }
+            
+
+ + The AccessDescription object. +
+            AccessDescription  ::=  SEQUENCE {
+                  accessMethod          OBJECT IDENTIFIER,
+                  accessLocation        GeneralName  }
+            
+
+ + create an AccessDescription with the oid and location provided. + + + + @return the access method. + + + + @return the access location + + + Produce an object suitable for an Asn1OutputStream. +
+                 AlgorithmIdentifier ::= Sequence {
+                                       algorithm OBJECT IDENTIFIER,
+                                       parameters ANY DEFINED BY algorithm OPTIONAL }
+            
+
+ + + Don't use this one if you are trying to be RFC 3281 compliant. + Use it for v1 attribute certificates only. + + Our GeneralNames structure + + + Produce an object suitable for an Asn1OutputStream. +
+             AttCertIssuer ::= CHOICE {
+                  v1Form   GeneralNames,  -- MUST NOT be used in this
+                                          -- profile
+                  v2Form   [0] V2Form     -- v2 only
+             }
+            
+
+ + Produce an object suitable for an Asn1OutputStream. +
+             AttCertValidityPeriod  ::= Sequence {
+                  notBeforeTime  GeneralizedTime,
+                  notAfterTime   GeneralizedTime
+             }
+            
+
+ + return an Attr object from the given object. + + @param o the object we want converted. + @exception ArgumentException if the object cannot be converted. + + + Produce an object suitable for an Asn1OutputStream. +
+            Attr ::= Sequence {
+                attrType OBJECT IDENTIFIER,
+                attrValues Set OF AttributeValue
+            }
+            
+
+ + @param obj + @return + + + Produce an object suitable for an Asn1OutputStream. +
+             AttributeCertificate ::= Sequence {
+                  acinfo               AttributeCertificateInfo,
+                  signatureAlgorithm   AlgorithmIdentifier,
+                  signatureValue       BIT STRING
+             }
+            
+
+ + Produce an object suitable for an Asn1OutputStream. +
+              AttributeCertificateInfo ::= Sequence {
+                   version              AttCertVersion -- version is v2,
+                   holder               Holder,
+                   issuer               AttCertIssuer,
+                   signature            AlgorithmIdentifier,
+                   serialNumber         CertificateSerialNumber,
+                   attrCertValidityPeriod   AttCertValidityPeriod,
+                   attributes           Sequence OF Attr,
+                   issuerUniqueID       UniqueIdentifier OPTIONAL,
+                   extensions           Extensions OPTIONAL
+              }
+            
+              AttCertVersion ::= Integer { v2(1) }
+             
+
+ + The AuthorityInformationAccess object. +
+             id-pe-authorityInfoAccess OBJECT IDENTIFIER ::= { id-pe 1 }
+            
+             AuthorityInfoAccessSyntax  ::=
+                  Sequence SIZE (1..MAX) OF AccessDescription
+             AccessDescription  ::=  Sequence {
+                   accessMethod          OBJECT IDENTIFIER,
+                   accessLocation        GeneralName  }
+            
+             id-ad OBJECT IDENTIFIER ::= { id-pkix 48 }
+             id-ad-caIssuers OBJECT IDENTIFIER ::= { id-ad 2 }
+             id-ad-ocsp OBJECT IDENTIFIER ::= { id-ad 1 }
+             
+
+ + create an AuthorityInformationAccess with the oid and location provided. + + + The AuthorityKeyIdentifier object. +
+             id-ce-authorityKeyIdentifier OBJECT IDENTIFIER ::=  { id-ce 35 }
+            
+               AuthorityKeyIdentifier ::= Sequence {
+                  keyIdentifier             [0] IMPLICIT KeyIdentifier           OPTIONAL,
+                  authorityCertIssuer       [1] IMPLICIT GeneralNames            OPTIONAL,
+                  authorityCertSerialNumber [2] IMPLICIT CertificateSerialNumber OPTIONAL  }
+            
+               KeyIdentifier ::= OCTET STRING
+             
+ +
+ + * + * Calulates the keyidentifier using a SHA1 hash over the BIT STRING + * from SubjectPublicKeyInfo as defined in RFC2459. + * + * Example of making a AuthorityKeyIdentifier: + *
+            	     *   SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((ASN1Sequence)new ASN1InputStream(
+            		 *       publicKey.getEncoded()).readObject());
+                     *   AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);
+                     * 
+ * + * +
+ + create an AuthorityKeyIdentifier with the GeneralNames tag and + the serial number provided as well. + + + create an AuthorityKeyIdentifier with the GeneralNames tag and + the serial number provided. + + + create an AuthorityKeyIdentifier with a precomputed key identifier + + + create an AuthorityKeyIdentifier with a precomupted key identifier + and the GeneralNames tag and the serial number provided as well. + + + Produce an object suitable for an Asn1OutputStream. + + + create a cA=true object for the given path length constraint. + + @param pathLenConstraint + + + Produce an object suitable for an Asn1OutputStream. +
+            BasicConstraints := Sequence {
+               cA                  Boolean DEFAULT FALSE,
+               pathLenConstraint   Integer (0..MAX) OPTIONAL
+            }
+            
+
+ + PKIX RFC-2459 + + The X.509 v2 CRL syntax is as follows. For signature calculation, + the data that is to be signed is ASN.1 Der encoded. + +
+             CertificateList  ::=  Sequence  {
+                  tbsCertList          TbsCertList,
+                  signatureAlgorithm   AlgorithmIdentifier,
+                  signatureValue       BIT STRING  }
+             
+
+ + This class helps to support crossCerfificatePairs in a LDAP directory + according RFC 2587 + +
+                 crossCertificatePairATTRIBUTE::={
+                   WITH SYNTAX   CertificatePair
+                   EQUALITY MATCHING RULE certificatePairExactMatch
+                   ID joint-iso-ccitt(2) ds(5) attributeType(4) crossCertificatePair(40)}
+             
+ +
The forward elements of the crossCertificatePair attribute of a + CA's directory entry shall be used to store all, except self-issued + certificates issued to this CA. Optionally, the reverse elements of the + crossCertificatePair attribute, of a CA's directory entry may contain a + subset of certificates issued by this CA to other CAs. When both the forward + and the reverse elements are present in a single attribute value, issuer name + in one certificate shall match the subject name in the other and vice versa, + and the subject public key in one certificate shall be capable of verifying + the digital signature on the other certificate and vice versa. + + When a reverse element is present, the forward element value and the reverse + element value need not be stored in the same attribute value; in other words, + they can be stored in either a single attribute value or two attribute + values.
+ +
+                   CertificatePair ::= SEQUENCE {
+                     forward		[0]	Certificate OPTIONAL,
+                     reverse		[1]	Certificate OPTIONAL,
+                     -- at least one of the pair shall be present -- }
+             
+
+ + Constructor from Asn1Sequence. +

+ The sequence is of type CertificatePair: +

+

+                   CertificatePair ::= SEQUENCE {
+                     forward		[0]	Certificate OPTIONAL,
+                     reverse		[1]	Certificate OPTIONAL,
+                     -- at least one of the pair shall be present -- }
+             
+ + @param seq The ASN.1 sequence. +
+ + Constructor from a given details. + + @param forward Certificates issued to this CA. + @param reverse Certificates issued by this CA to other CAs. + + + Produce an object suitable for an Asn1OutputStream. +

+ Returns: +

+

+                   CertificatePair ::= SEQUENCE {
+                     forward		[0]	Certificate OPTIONAL,
+                     reverse		[1]	Certificate OPTIONAL,
+                     -- at least one of the pair shall be present -- }
+             
+ + @return a DERObject +
+ + @return Returns the forward. + + + @return Returns the reverse. + + + CertPolicyId, used in the CertificatePolicies and PolicyMappings + X509V3 Extensions. + +
+                 CertPolicyId ::= OBJECT IDENTIFIER
+             
+
+ + Return the distribution points making up the sequence. + + @return DistributionPoint[] + + + Produce an object suitable for an Asn1OutputStream. +
+            CrlDistPoint ::= Sequence SIZE {1..MAX} OF DistributionPoint
+            
+
+ + The CRLNumber object. +
+            CRLNumber::= Integer(0..MAX)
+            
+
+ + The CRLReason enumeration. +
+            CRLReason ::= Enumerated {
+             unspecified             (0),
+             keyCompromise           (1),
+             cACompromise            (2),
+             affiliationChanged      (3),
+             superseded              (4),
+             cessationOfOperation    (5),
+             certificateHold         (6),
+             removeFromCRL           (8),
+             privilegeWithdrawn      (9),
+             aACompromise           (10)
+            }
+            
+
+ + The DigestInfo object. +
+            DigestInfo::=Sequence{
+                     digestAlgorithm  AlgorithmIdentifier,
+                     digest OCTET STRING }
+            
+
+ + DisplayText class, used in + CertificatePolicies X509 V3 extensions (in policy qualifiers). + +

It stores a string in a chosen encoding. +

+             DisplayText ::= CHOICE {
+                  ia5String        IA5String      (SIZE (1..200)),
+                  visibleString    VisibleString  (SIZE (1..200)),
+                  bmpString        BMPString      (SIZE (1..200)),
+                  utf8String       UTF8String     (SIZE (1..200)) }
+             

+ @see PolicyQualifierInfo + @see PolicyInformation +
+ + Constant corresponding to ia5String encoding. + + + + Constant corresponding to bmpString encoding. + + + + Constant corresponding to utf8String encoding. + + + + Constant corresponding to visibleString encoding. + + + + Describe constant DisplayTextMaximumSize here. + + + + Creates a new DisplayText instance. + + @param type the desired encoding type for the text. + @param text the text to store. Strings longer than 200 + characters are truncated. + + + Creates a new DisplayText instance. + + @param text the text to encapsulate. Strings longer than 200 + characters are truncated. + + + Creates a new DisplayText instance. +

Useful when reading back a DisplayText class + from it's Asn1Encodable form.

+ + @param contents an Asn1Encodable instance. +
+ + Returns the stored string object. + + @return the stored text as a string. + + + The DistributionPoint object. +
+            DistributionPoint ::= Sequence {
+                 distributionPoint [0] DistributionPointName OPTIONAL,
+                 reasons           [1] ReasonFlags OPTIONAL,
+                 cRLIssuer         [2] GeneralNames OPTIONAL
+            }
+            
+
+ + The DistributionPointName object. +
+            DistributionPointName ::= CHOICE {
+                fullName                 [0] GeneralNames,
+                nameRelativeToCRLIssuer  [1] RDN
+            }
+            
+
+ + The extendedKeyUsage object. +
+                 extendedKeyUsage ::= Sequence SIZE (1..MAX) OF KeyPurposeId
+            
+
+ + Returns all extended key usages. + The returned ArrayList contains DerObjectIdentifier instances. + @return An ArrayList with all key purposes. + + + The GeneralName object. +
+             GeneralName ::= CHOICE {
+                  otherName                       [0]     OtherName,
+                  rfc822Name                      [1]     IA5String,
+                  dNSName                         [2]     IA5String,
+                  x400Address                     [3]     ORAddress,
+                  directoryName                   [4]     Name,
+                  ediPartyName                    [5]     EDIPartyName,
+                  uniformResourceIdentifier       [6]     IA5String,
+                  iPAddress                       [7]     OCTET STRING,
+                  registeredID                    [8]     OBJECT IDENTIFIER}
+            
+             OtherName ::= Sequence {
+                  type-id    OBJECT IDENTIFIER,
+                  value      [0] EXPLICIT ANY DEFINED BY type-id }
+            
+             EDIPartyName ::= Sequence {
+                  nameAssigner            [0]     DirectoryString OPTIONAL,
+                  partyName               [1]     DirectoryString }
+             
+
+ + When the subjectAltName extension contains an Internet mail address, + the address MUST be included as an rfc822Name. The format of an + rfc822Name is an "addr-spec" as defined in RFC 822 [RFC 822]. + + When the subjectAltName extension contains a domain name service + label, the domain name MUST be stored in the dNSName (an IA5String). + The name MUST be in the "preferred name syntax," as specified by RFC + 1034 [RFC 1034]. + + When the subjectAltName extension contains a URI, the name MUST be + stored in the uniformResourceIdentifier (an IA5String). The name MUST + be a non-relative URL, and MUST follow the URL syntax and encoding + rules specified in [RFC 1738]. The name must include both a scheme + (e.g., "http" or "ftp") and a scheme-specific-part. The scheme- + specific-part must include a fully qualified domain name or IP + address as the host. + + When the subjectAltName extension contains a iPAddress, the address + MUST be stored in the octet string in "network byte order," as + specified in RFC 791 [RFC 791]. The least significant bit (LSB) of + each octet is the LSB of the corresponding byte in the network + address. For IP Version 4, as specified in RFC 791, the octet string + MUST contain exactly four octets. For IP Version 6, as specified in + RFC 1883, the octet string MUST contain exactly sixteen octets [RFC + 1883]. + + + Create a GeneralName for the given tag from the passed in string. +

+ This constructor can handle: +

    +
  • rfc822Name
  • +
  • iPAddress
  • +
  • directoryName
  • +
  • dNSName
  • +
  • uniformResourceIdentifier
  • +
  • registeredID
  • +
+ For x400Address, otherName and ediPartyName there is no common string + format defined. +

+ Note: A directory name can be encoded in different ways into a byte + representation. Be aware of this if the byte representation is used for + comparing results. +

+ + @param tag tag number + @param name string representation of name + @throws ArgumentException if the string encoding is not correct or + not supported. +
+ + Construct a GeneralNames object containing one GeneralName. + The name to be contained. + + + Produce an object suitable for an Asn1OutputStream. +
+            GeneralNames ::= Sequence SIZE {1..MAX} OF GeneralName
+            
+
+ + Class for containing a restriction object subtrees in NameConstraints. See + RFC 3280. + +
+            
+                   GeneralSubtree ::= SEQUENCE
+                   {
+                     baseName                    GeneralName,
+                     minimum         [0]     BaseDistance DEFAULT 0,
+                     maximum         [1]     BaseDistance OPTIONAL
+                   }
+             
+ + @see org.bouncycastle.asn1.x509.NameConstraints + +
+ + Constructor from a given details. + + According RFC 3280, the minimum and maximum fields are not used with any + name forms, thus minimum MUST be zero, and maximum MUST be absent. +

+ If minimum is null, zero is assumed, if + maximum is null, maximum is absent.

+ + @param baseName + A restriction. + @param minimum + Minimum + + @param maximum + Maximum +
+ + Produce an object suitable for an Asn1OutputStream. + + Returns: + +
+                   GeneralSubtree ::= SEQUENCE
+                   {
+                     baseName                    GeneralName,
+                     minimum         [0]     BaseDistance DEFAULT 0,
+                     maximum         [1]     BaseDistance OPTIONAL
+                   }
+             
+ + @return a DERObject +
+ + The Holder object. +

+ For an v2 attribute certificate this is: + +

+                       Holder ::= SEQUENCE {
+                             baseCertificateID   [0] IssuerSerial OPTIONAL,
+                                      -- the issuer and serial number of
+                                      -- the holder's Public Key Certificate
+                             entityName          [1] GeneralNames OPTIONAL,
+                                      -- the name of the claimant or role
+                             objectDigestInfo    [2] ObjectDigestInfo OPTIONAL
+                                      -- used to directly authenticate the holder,
+                                      -- for example, an executable
+                       }
+            
+

+

+ For an v1 attribute certificate this is: + +

+                    subject CHOICE {
+                     baseCertificateID [0] IssuerSerial,
+                     -- associated with a Public Key Certificate
+                     subjectName [1] GeneralNames },
+                     -- associated with a name
+            
+

+
+ + Constructor for a holder for an v1 attribute certificate. + + @param tagObj The ASN.1 tagged holder object. + + + Constructor for a holder for an v2 attribute certificate. * + + @param seq The ASN.1 sequence. + + + Constructs a holder from a IssuerSerial. + @param baseCertificateID The IssuerSerial. + @param version The version of the attribute certificate. + + + Returns 1 for v2 attribute certificates or 0 for v1 attribute + certificates. + @return The version of the attribute certificate. + + + Constructs a holder with an entityName for v2 attribute certificates or + with a subjectName for v1 attribute certificates. + + @param entityName The entity or subject name. + + + Constructs a holder with an entityName for v2 attribute certificates or + with a subjectName for v1 attribute certificates. + + @param entityName The entity or subject name. + @param version The version of the attribute certificate. + + + Constructs a holder from an object digest info. + + @param objectDigestInfo The object digest info object. + + + Returns the entityName for an v2 attribute certificate or the subjectName + for an v1 attribute certificate. + + @return The entityname or subjectname. + + + The Holder object. +
+             Holder ::= Sequence {
+                   baseCertificateID   [0] IssuerSerial OPTIONAL,
+                            -- the issuer and serial number of
+                            -- the holder's Public Key Certificate
+                   entityName          [1] GeneralNames OPTIONAL,
+                            -- the name of the claimant or role
+                   objectDigestInfo    [2] ObjectDigestInfo OPTIONAL
+                            -- used to directly authenticate the holder,
+                            -- for example, an executable
+             }
+            
+
+ + Implementation of IetfAttrSyntax as specified by RFC3281. + + + + + + +
+            
+              IetfAttrSyntax ::= Sequence {
+                policyAuthority [0] GeneralNames OPTIONAL,
+                values Sequence OF CHOICE {
+                  octets OCTET STRING,
+                  oid OBJECT IDENTIFIER,
+                  string UTF8String
+                }
+              }
+            
+             
+
+ + Produce an object suitable for an Asn1OutputStream. +
+             IssuerSerial  ::=  Sequence {
+                  issuer         GeneralNames,
+                  serial         CertificateSerialNumber,
+                  issuerUid      UniqueIdentifier OPTIONAL
+             }
+            
+
+ +
+            IssuingDistributionPoint ::= SEQUENCE { 
+              distributionPoint          [0] DistributionPointName OPTIONAL, 
+              onlyContainsUserCerts      [1] BOOLEAN DEFAULT FALSE, 
+              onlyContainsCACerts        [2] BOOLEAN DEFAULT FALSE, 
+              onlySomeReasons            [3] ReasonFlags OPTIONAL, 
+              indirectCRL                [4] BOOLEAN DEFAULT FALSE,
+              onlyContainsAttributeCerts [5] BOOLEAN DEFAULT FALSE }
+            
+
+ + Constructor from given details. + + @param distributionPoint + May contain an URI as pointer to most current CRL. + @param onlyContainsUserCerts Covers revocation information for end certificates. + @param onlyContainsCACerts Covers revocation information for CA certificates. + + @param onlySomeReasons + Which revocation reasons does this point cover. + @param indirectCRL + If true then the CRL contains revocation + information about certificates ssued by other CAs. + @param onlyContainsAttributeCerts Covers revocation information for attribute certificates. + + + Constructor from Asn1Sequence + + + @return Returns the distributionPoint. + + + @return Returns the onlySomeReasons. + + + The KeyPurposeID object. +
+                KeyPurposeID ::= OBJECT IDENTIFIER
+            
+
+ + The KeyUsage object. +
+                id-ce-keyUsage OBJECT IDENTIFIER ::=  { id-ce 15 }
+            
+                KeyUsage ::= BIT STRING {
+                     digitalSignature        (0),
+                     nonRepudiation          (1),
+                     keyEncipherment         (2),
+                     dataEncipherment        (3),
+                     keyAgreement            (4),
+                     keyCertSign             (5),
+                     cRLSign                 (6),
+                     encipherOnly            (7),
+                     decipherOnly            (8) }
+             
+
+ + Basic constructor. + + @param usage - the bitwise OR of the Key Usage flags giving the + allowed uses for the key. + e.g. (KeyUsage.keyEncipherment | KeyUsage.dataEncipherment) + + + Constructor from a given details. + +

permitted and excluded are Vectors of GeneralSubtree objects.

+ + @param permitted Permitted subtrees + @param excluded Excluded subtrees +
+ + NoticeReference class, used in + CertificatePolicies X509 V3 extensions + (in policy qualifiers). + +
+              NoticeReference ::= Sequence {
+                  organization     DisplayText,
+                  noticeNumbers    Sequence OF Integer }
+            
+             
+ + @see PolicyQualifierInfo + @see PolicyInformation +
+ + Creates a new NoticeReference instance. + + @param orgName a string value + @param numbers a ArrayList value + + + Creates a new NoticeReference instance. + + @param orgName a string value + @param numbers an Asn1Sequence value + + + Creates a new NoticeReference instance. + + @param displayTextType an int value + @param orgName a string value + @param numbers an Asn1Sequence value + + + Creates a new NoticeReference instance. +

Useful for reconstructing a NoticeReference + instance from its encodable/encoded form.

+ + @param as an Asn1Sequence value obtained from either + calling @{link ToAsn1Object()} for a NoticeReference + instance or from parsing it from a Der-encoded stream. +
+ + Describe ToAsn1Object method here. + + @return a Asn1Object value + + + ObjectDigestInfo ASN.1 structure used in v2 attribute certificates. + +
+             
+               ObjectDigestInfo ::= SEQUENCE {
+                    digestedObjectType  ENUMERATED {
+                            publicKey            (0),
+                            publicKeyCert        (1),
+                            otherObjectTypes     (2) },
+                                    -- otherObjectTypes MUST NOT
+                                    -- be used in this profile
+                    otherObjectTypeID   OBJECT IDENTIFIER OPTIONAL,
+                    digestAlgorithm     AlgorithmIdentifier,
+                    objectDigest        BIT STRING
+               }
+              
+            
+ +
+ + The public key is hashed. + + + The public key certificate is hashed. + + + An other object is hashed. + + + Constructor from given details. +

+ If digestedObjectType is not {@link #publicKeyCert} or + {@link #publicKey} otherObjectTypeID must be given, + otherwise it is ignored.

+ + @param digestedObjectType The digest object type. + @param otherObjectTypeID The object type ID for + otherObjectDigest. + @param digestAlgorithm The algorithm identifier for the hash. + @param objectDigest The hash value. +
+ + Produce an object suitable for an Asn1OutputStream. + +
+             
+               ObjectDigestInfo ::= SEQUENCE {
+                    digestedObjectType  ENUMERATED {
+                            publicKey            (0),
+                            publicKeyCert        (1),
+                            otherObjectTypes     (2) },
+                                    -- otherObjectTypes MUST NOT
+                                    -- be used in this profile
+                    otherObjectTypeID   OBJECT IDENTIFIER OPTIONAL,
+                    digestAlgorithm     AlgorithmIdentifier,
+                    objectDigest        BIT STRING
+               }
+              
+            
+
+ + PolicyMappings V3 extension, described in RFC3280. +
+                PolicyMappings ::= Sequence SIZE (1..MAX) OF Sequence {
+                  issuerDomainPolicy      CertPolicyId,
+                  subjectDomainPolicy     CertPolicyId }
+             
+ + @see RFC 3280, section 4.2.1.6 +
+ + Creates a new PolicyMappings instance. + + @param seq an Asn1Sequence constructed as specified + in RFC 3280 + + + Creates a new PolicyMappings instance. + + @param mappings a HashMap value that maps + string oids + to other string oids. + + + PolicyQualifierId, used in the CertificatePolicies + X509V3 extension. + +
+                id-qt          OBJECT IDENTIFIER ::=  { id-pkix 2 }
+                id-qt-cps      OBJECT IDENTIFIER ::=  { id-qt 1 }
+                id-qt-unotice  OBJECT IDENTIFIER ::=  { id-qt 2 }
+              PolicyQualifierId ::=
+                   OBJECT IDENTIFIER ( id-qt-cps | id-qt-unotice )
+             
+
+ + Policy qualifiers, used in the X509V3 CertificatePolicies + extension. + +
+               PolicyQualifierInfo ::= Sequence {
+                   policyQualifierId  PolicyQualifierId,
+                   qualifier          ANY DEFINED BY policyQualifierId }
+             
+
+ + Creates a new PolicyQualifierInfo instance. + + @param policyQualifierId a PolicyQualifierId value + @param qualifier the qualifier, defined by the above field. + + + Creates a new PolicyQualifierInfo containing a + cPSuri qualifier. + + @param cps the CPS (certification practice statement) uri as a + string. + + + Creates a new PolicyQualifierInfo instance. + + @param as PolicyQualifierInfo X509 structure + encoded as an Asn1Sequence. + + + Returns a Der-encodable representation of this instance. + + @return a Asn1Object value + + + +
+            PrivateKeyUsagePeriod ::= SEQUENCE
+            {
+            notBefore       [0]     GeneralizedTime OPTIONAL,
+            notAfter        [1]     GeneralizedTime OPTIONAL }
+            
+
+
+ + The BiometricData object. +
+            BiometricData  ::=  SEQUENCE {
+                  typeOfBiometricData  TypeOfBiometricData,
+                  hashAlgorithm        AlgorithmIdentifier,
+                  biometricDataHash    OCTET STRING,
+                  sourceDataUri        IA5String OPTIONAL  }
+            
+
+ + The Iso4217CurrencyCode object. +
+            Iso4217CurrencyCode  ::=  CHOICE {
+                  alphabetic              PrintableString (SIZE 3), --Recommended
+                  numeric              INTEGER (1..999) }
+            -- Alphabetic or numeric currency code as defined in ISO 4217
+            -- It is recommended that the Alphabetic form is used
+            
+
+ + The MonetaryValue object. +
+            MonetaryValue  ::=  SEQUENCE {
+                  currency              Iso4217CurrencyCode,
+                  amount               INTEGER,
+                  exponent             INTEGER }
+            -- value = amount * 10^exponent
+            
+
+ + The QCStatement object. +
+            QCStatement ::= SEQUENCE {
+              statementId        OBJECT IDENTIFIER,
+              statementInfo      ANY DEFINED BY statementId OPTIONAL}
+            
+
+ + The SemanticsInformation object. +
+                   SemanticsInformation ::= SEQUENCE {
+                     semanticsIdentifier        OBJECT IDENTIFIER   OPTIONAL,
+                     nameRegistrationAuthorities NameRegistrationAuthorities
+                                                                     OPTIONAL }
+                     (WITH COMPONENTS {..., semanticsIdentifier PRESENT}|
+                      WITH COMPONENTS {..., nameRegistrationAuthorities PRESENT})
+            
+                 NameRegistrationAuthorities ::=  SEQUENCE SIZE (1..MAX) OF
+                     GeneralName
+             
+
+ + The TypeOfBiometricData object. +
+             TypeOfBiometricData ::= CHOICE {
+               predefinedBiometricType   PredefinedBiometricType,
+               biometricDataOid          OBJECT IDENTIFIER }
+            
+             PredefinedBiometricType ::= INTEGER {
+               picture(0),handwritten-signature(1)}
+               (picture|handwritten-signature)
+             
+
+ + The ReasonFlags object. +
+            ReasonFlags ::= BIT STRING {
+               unused(0),
+               keyCompromise(1),
+               cACompromise(2),
+               affiliationChanged(3),
+               superseded(4),
+               cessationOfOperation(5),
+               certficateHold(6)
+            }
+            
+
+ + @param reasons - the bitwise OR of the Key Reason flags giving the + allowed uses for the key. + + + Implementation of the RoleSyntax object as specified by the RFC3281. + +
+             RoleSyntax ::= SEQUENCE {
+                             roleAuthority  [0] GeneralNames OPTIONAL,
+                             roleName       [1] GeneralName
+                       }
+             
+
+ + RoleSyntax factory method. + @param obj the object used to construct an instance of + RoleSyntax. It must be an instance of RoleSyntax + or Asn1Sequence. + @return the instance of RoleSyntax built from the + supplied object. + @throws java.lang.ArgumentException if the object passed + to the factory is not an instance of RoleSyntax or + Asn1Sequence. + + + Constructor. + @param roleAuthority the role authority of this RoleSyntax. + @param roleName the role name of this RoleSyntax. + + + Constructor. Invoking this constructor is the same as invoking + new RoleSyntax(null, roleName). + @param roleName the role name of this RoleSyntax. + + + Utility constructor. Takes a string argument representing + the role name, builds a GeneralName to hold the role name + and calls the constructor that takes a GeneralName. + @param roleName + + + Constructor that builds an instance of RoleSyntax by + extracting the encoded elements from the Asn1Sequence + object supplied. + @param seq an instance of Asn1Sequence that holds + the encoded elements used to build this RoleSyntax. + + + Gets the role authority of this RoleSyntax. + @return an instance of GeneralNames holding the + role authority of this RoleSyntax. + + + Gets the role name of this RoleSyntax. + @return an instance of GeneralName holding the + role name of this RoleSyntax. + + + Gets the role name as a java.lang.string object. + @return the role name of this RoleSyntax represented as a + string object. + + + Gets the role authority as a string[] object. + @return the role authority of this RoleSyntax represented as a + string[] array. + + + Implementation of the method ToAsn1Object as + required by the superclass ASN1Encodable. + +
+             RoleSyntax ::= SEQUENCE {
+                             roleAuthority  [0] GeneralNames OPTIONAL,
+                             roleName       [1] GeneralName
+                       }
+             
+
+ + This outputs the key in Pkcs1v2 format. +
+                 RSAPublicKey ::= Sequence {
+                                     modulus Integer, -- n
+                                     publicExponent Integer, -- e
+                                 }
+            
+
+ + Structure for a name or pseudonym. + +
+                  NameOrPseudonym ::= CHOICE {
+                	   surAndGivenName SEQUENCE {
+                	     surName DirectoryString,
+                	     givenName SEQUENCE OF DirectoryString 
+                    },
+                	   pseudonym DirectoryString 
+                  }
+            
+ + @see org.bouncycastle.asn1.x509.sigi.PersonalData + +
+ + Constructor from DERString. +

+ The sequence is of type NameOrPseudonym: +

+

+                  NameOrPseudonym ::= CHOICE {
+                	   surAndGivenName SEQUENCE {
+                	     surName DirectoryString,
+                	     givenName SEQUENCE OF DirectoryString
+                    },
+                	   pseudonym DirectoryString
+                  }
+            
+ @param pseudonym pseudonym value to use. +
+ + Constructor from Asn1Sequence. +

+ The sequence is of type NameOrPseudonym: +

+

+                   NameOrPseudonym ::= CHOICE {
+                 	   surAndGivenName SEQUENCE {
+                 	     surName DirectoryString,
+                 	     givenName SEQUENCE OF DirectoryString
+                     },
+                 	   pseudonym DirectoryString
+                   }
+             
+ + @param seq The ASN.1 sequence. +
+ + Constructor from a given details. + + @param pseudonym The pseudonym. + + + Constructor from a given details. + + @param surname The surname. + @param givenName A sequence of directory strings making up the givenName + + + Produce an object suitable for an Asn1OutputStream. +

+ Returns: +

+

+                   NameOrPseudonym ::= CHOICE {
+                 	   surAndGivenName SEQUENCE {
+                 	     surName DirectoryString,
+                 	     givenName SEQUENCE OF DirectoryString
+                     },
+                 	   pseudonym DirectoryString
+                   }
+             
+ + @return an Asn1Object +
+ + Contains personal data for the otherName field in the subjectAltNames + extension. +

+

+                 PersonalData ::= SEQUENCE {
+                   nameOrPseudonym NameOrPseudonym,
+                   nameDistinguisher [0] INTEGER OPTIONAL,
+                   dateOfBirth [1] GeneralizedTime OPTIONAL,
+                   placeOfBirth [2] DirectoryString OPTIONAL,
+                   gender [3] PrintableString OPTIONAL,
+                   postalAddress [4] DirectoryString OPTIONAL
+                   }
+             
+ + @see org.bouncycastle.asn1.x509.sigi.NameOrPseudonym + @see org.bouncycastle.asn1.x509.sigi.SigIObjectIdentifiers +
+ + Constructor from Asn1Sequence. +

+ The sequence is of type NameOrPseudonym: +

+

+                 PersonalData ::= SEQUENCE {
+                   nameOrPseudonym NameOrPseudonym,
+                   nameDistinguisher [0] INTEGER OPTIONAL,
+                   dateOfBirth [1] GeneralizedTime OPTIONAL,
+                   placeOfBirth [2] DirectoryString OPTIONAL,
+                   gender [3] PrintableString OPTIONAL,
+                   postalAddress [4] DirectoryString OPTIONAL
+                   }
+             
+ + @param seq The ASN.1 sequence. +
+ + Constructor from a given details. + + @param nameOrPseudonym Name or pseudonym. + @param nameDistinguisher Name distinguisher. + @param dateOfBirth Date of birth. + @param placeOfBirth Place of birth. + @param gender Gender. + @param postalAddress Postal Address. + + + Produce an object suitable for an Asn1OutputStream. +

+ Returns: +

+

+                 PersonalData ::= SEQUENCE {
+                   nameOrPseudonym NameOrPseudonym,
+                   nameDistinguisher [0] INTEGER OPTIONAL,
+                   dateOfBirth [1] GeneralizedTime OPTIONAL,
+                   placeOfBirth [2] DirectoryString OPTIONAL,
+                   gender [3] PrintableString OPTIONAL,
+                   postalAddress [4] DirectoryString OPTIONAL
+                   }
+             
+ + @return an Asn1Object +
+ + Object Identifiers of SigI specifciation (German Signature Law + Interoperability specification). + + + Key purpose IDs for German SigI (Signature Interoperability + Specification) + + + Certificate policy IDs for German SigI (Signature Interoperability + Specification) + + + Other Name IDs for German SigI (Signature Interoperability Specification) + + + To be used for for the generation of directory service certificates. + + + ID for PersonalData + + + Certificate is conform to german signature law. + + + This extension may contain further X.500 attributes of the subject. See also + RFC 3039. + +
+                 SubjectDirectoryAttributes ::= Attributes
+                 Attributes ::= SEQUENCE SIZE (1..MAX) OF Attribute
+                 Attribute ::= SEQUENCE
+                 {
+                   type AttributeType
+                   values SET OF AttributeValue
+                 }
+            
+                 AttributeType ::= OBJECT IDENTIFIER
+                 AttributeValue ::= ANY DEFINED BY AttributeType
+             
+ + @see org.bouncycastle.asn1.x509.X509Name for AttributeType ObjectIdentifiers. +
+ + Constructor from Asn1Sequence. + + The sequence is of type SubjectDirectoryAttributes: + +
+                  SubjectDirectoryAttributes ::= Attributes
+                  Attributes ::= SEQUENCE SIZE (1..MAX) OF Attribute
+                  Attribute ::= SEQUENCE
+                  {
+                    type AttributeType
+                    values SET OF AttributeValue
+                  }
+            
+                  AttributeType ::= OBJECT IDENTIFIER
+                  AttributeValue ::= ANY DEFINED BY AttributeType
+             
+ + @param seq + The ASN.1 sequence. +
+ + Constructor from an ArrayList of attributes. + + The ArrayList consists of attributes of type {@link Attribute Attribute} + + @param attributes The attributes. + + + + Produce an object suitable for an Asn1OutputStream. + + Returns: + +
+                  SubjectDirectoryAttributes ::= Attributes
+                  Attributes ::= SEQUENCE SIZE (1..MAX) OF Attribute
+                  Attribute ::= SEQUENCE
+                  {
+                    type AttributeType
+                    values SET OF AttributeValue
+                  }
+            
+                  AttributeType ::= OBJECT IDENTIFIER
+                  AttributeValue ::= ANY DEFINED BY AttributeType
+             
+ + @return a DERObject +
+ + @return Returns the attributes. + + + The SubjectKeyIdentifier object. +
+            SubjectKeyIdentifier::= OCTET STRING
+            
+
+ + Calculates the keyIdentifier using a SHA1 hash over the BIT STRING + from SubjectPublicKeyInfo as defined in RFC3280. + + @param spki the subject public key info. + + + Return a RFC 3280 type 1 key identifier. As in: +
+            (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the
+            value of the BIT STRING subjectPublicKey (excluding the tag,
+            length, and number of unused bits).
+            
+ @param keyInfo the key info object containing the subjectPublicKey field. + @return the key identifier. +
+ + Return a RFC 3280 type 2 key identifier. As in: +
+            (2) The keyIdentifier is composed of a four bit type field with
+            the value 0100 followed by the least significant 60 bits of the
+            SHA-1 hash of the value of the BIT STRING subjectPublicKey.
+            
+ @param keyInfo the key info object containing the subjectPublicKey field. + @return the key identifier. +
+ + The object that contains the public key stored in a certficate. +

+ The GetEncoded() method in the public keys in the JCE produces a DER + encoded one of these.

+
+ + for when the public key is an encoded object - if the bitstring + can't be decoded this routine raises an IOException. + + @exception IOException - if the bit string doesn't represent a Der + encoded object. + + + for when the public key is raw bits... + + + Produce an object suitable for an Asn1OutputStream. +
+            SubjectPublicKeyInfo ::= Sequence {
+                                     algorithm AlgorithmIdentifier,
+                                     publicKey BIT STRING }
+            
+
+ + Target structure used in target information extension for attribute + certificates from RFC 3281. + +
+                Target  ::= CHOICE {
+                  targetName          [0] GeneralName,
+                  targetGroup         [1] GeneralName,
+                  targetCert          [2] TargetCert
+                }
+            
+ +

+ The targetCert field is currently not supported and must not be used + according to RFC 3281.

+
+ + Creates an instance of a Target from the given object. +

+ obj can be a Target or a {@link Asn1TaggedObject}

+ + @param obj The object. + @return A Target instance. + @throws ArgumentException if the given object cannot be + interpreted as Target. +
+ + Constructor from Asn1TaggedObject. + + @param tagObj The tagged object. + @throws ArgumentException if the encoding is wrong. + + + Constructor from given details. +

+ Exactly one of the parameters must be not null.

+ + @param type the choice type to apply to the name. + @param name the general name. + @throws ArgumentException if type is invalid. +
+ + @return Returns the targetGroup. + + + @return Returns the targetName. + + + Produce an object suitable for an Asn1OutputStream. + + Returns: + +
+                Target  ::= CHOICE {
+                  targetName          [0] GeneralName,
+                  targetGroup         [1] GeneralName,
+                  targetCert          [2] TargetCert
+                }
+            
+ + @return an Asn1Object +
+ + Target information extension for attributes certificates according to RFC + 3281. + +
+                      SEQUENCE OF Targets
+            
+ +
+ + Creates an instance of a TargetInformation from the given object. +

+ obj can be a TargetInformation or a {@link Asn1Sequence}

+ + @param obj The object. + @return A TargetInformation instance. + @throws ArgumentException if the given object cannot be interpreted as TargetInformation. +
+ + Constructor from a Asn1Sequence. + + @param seq The Asn1Sequence. + @throws ArgumentException if the sequence does not contain + correctly encoded Targets elements. + + + Returns the targets in this target information extension. +

+ The ArrayList is cloned before it is returned.

+ + @return Returns the targets. +
+ + Constructs a target information from a single targets element. + According to RFC 3281 only one targets element must be produced. + + @param targets A Targets instance. + + + According to RFC 3281 only one targets element must be produced. If + multiple targets are given they must be merged in + into one targets element. + + @param targets An array with {@link Targets}. + + + Produce an object suitable for an Asn1OutputStream. + + Returns: + +
+                     SEQUENCE OF Targets
+            
+ +

+ According to RFC 3281 only one targets element must be produced. If + multiple targets are given in the constructor they are merged into one + targets element. If this was produced from a + {@link Org.BouncyCastle.Asn1.Asn1Sequence} the encoding is kept.

+ + @return an Asn1Object +
+ + Targets structure used in target information extension for attribute + certificates from RFC 3281. + +
+                       Targets ::= SEQUENCE OF Target
+                      
+                       Target  ::= CHOICE {
+                         targetName          [0] GeneralName,
+                         targetGroup         [1] GeneralName,
+                         targetCert          [2] TargetCert
+                       }
+                      
+                       TargetCert  ::= SEQUENCE {
+                         targetCertificate    IssuerSerial,
+                         targetName           GeneralName OPTIONAL,
+                         certDigestInfo       ObjectDigestInfo OPTIONAL
+                       }
+            
+ + @see org.bouncycastle.asn1.x509.Target + @see org.bouncycastle.asn1.x509.TargetInformation +
+ + Creates an instance of a Targets from the given object. +

+ obj can be a Targets or a {@link Asn1Sequence}

+ + @param obj The object. + @return A Targets instance. + @throws ArgumentException if the given object cannot be interpreted as Target. +
+ + Constructor from Asn1Sequence. + + @param targets The ASN.1 SEQUENCE. + @throws ArgumentException if the contents of the sequence are + invalid. + + + Constructor from given targets. +

+ The ArrayList is copied.

+ + @param targets An ArrayList of {@link Target}s. + @see Target + @throws ArgumentException if the ArrayList contains not only Targets. +
+ + Returns the targets in an ArrayList. +

+ The ArrayList is cloned before it is returned.

+ + @return Returns the targets. +
+ + Produce an object suitable for an Asn1OutputStream. + + Returns: + +
+                       Targets ::= SEQUENCE OF Target
+            
+ + @return an Asn1Object +
+ + The TbsCertificate object. +
+            TbsCertificate ::= Sequence {
+                 version          [ 0 ]  Version DEFAULT v1(0),
+                 serialNumber            CertificateSerialNumber,
+                 signature               AlgorithmIdentifier,
+                 issuer                  Name,
+                 validity                Validity,
+                 subject                 Name,
+                 subjectPublicKeyInfo    SubjectPublicKeyInfo,
+                 issuerUniqueID    [ 1 ] IMPLICIT UniqueIdentifier OPTIONAL,
+                 subjectUniqueID   [ 2 ] IMPLICIT UniqueIdentifier OPTIONAL,
+                 extensions        [ 3 ] Extensions OPTIONAL
+                 }
+            
+

+ Note: issuerUniqueID and subjectUniqueID are both deprecated by the IETF. This class + will parse them, but you really shouldn't be creating new ones.

+
+ + PKIX RFC-2459 - TbsCertList object. +
+            TbsCertList  ::=  Sequence  {
+                 version                 Version OPTIONAL,
+                                              -- if present, shall be v2
+                 signature               AlgorithmIdentifier,
+                 issuer                  Name,
+                 thisUpdate              Time,
+                 nextUpdate              Time OPTIONAL,
+                 revokedCertificates     Sequence OF Sequence  {
+                      userCertificate         CertificateSerialNumber,
+                      revocationDate          Time,
+                      crlEntryExtensions      Extensions OPTIONAL
+                                                    -- if present, shall be v2
+                                           }  OPTIONAL,
+                 crlExtensions           [0]  EXPLICIT Extensions OPTIONAL
+                                                    -- if present, shall be v2
+                                           }
+            
+
+ + creates a time object from a given date - if the date is between 1950 + and 2049 a UTCTime object is Generated, otherwise a GeneralizedTime + is used. + + + + Return our time as DateTime. + + A date time. + + + Produce an object suitable for an Asn1OutputStream. +
+            Time ::= CHOICE {
+                        utcTime        UTCTime,
+                        generalTime    GeneralizedTime }
+            
+
+ + UserNotice class, used in + CertificatePolicies X509 extensions (in policy + qualifiers). +
+             UserNotice ::= Sequence {
+                  noticeRef        NoticeReference OPTIONAL,
+                  explicitText     DisplayText OPTIONAL}
+            
+             
+ + @see PolicyQualifierId + @see PolicyInformation +
+ + Creates a new UserNotice instance. + + @param noticeRef a NoticeReference value + @param explicitText a DisplayText value + + + Creates a new UserNotice instance. + + @param noticeRef a NoticeReference value + @param str the explicitText field as a string. + + + Creates a new UserNotice instance. +

Useful from reconstructing a UserNotice instance + from its encodable/encoded form. + + @param as an ASN1Sequence value obtained from either + calling @{link toASN1Object()} for a UserNotice + instance or from parsing it from a DER-encoded stream.

+
+ + Generator for Version 1 TbsCertificateStructures. +
+             TbsCertificate ::= Sequence {
+                  version          [ 0 ]  Version DEFAULT v1(0),
+                  serialNumber            CertificateSerialNumber,
+                  signature               AlgorithmIdentifier,
+                  issuer                  Name,
+                  validity                Validity,
+                  subject                 Name,
+                  subjectPublicKeyInfo    SubjectPublicKeyInfo,
+                  }
+             
+ +
+ + Generator for Version 2 AttributeCertificateInfo +
+             AttributeCertificateInfo ::= Sequence {
+                   version              AttCertVersion -- version is v2,
+                   holder               Holder,
+                   issuer               AttCertIssuer,
+                   signature            AlgorithmIdentifier,
+                   serialNumber         CertificateSerialNumber,
+                   attrCertValidityPeriod   AttCertValidityPeriod,
+                   attributes           Sequence OF Attr,
+                   issuerUniqueID       UniqueIdentifier OPTIONAL,
+                   extensions           Extensions OPTIONAL
+             }
+             
+ +
+ + @param attribute + + + Produce an object suitable for an Asn1OutputStream. +
+             V2Form ::= Sequence {
+                  issuerName            GeneralNames  OPTIONAL,
+                  baseCertificateID     [0] IssuerSerial  OPTIONAL,
+                  objectDigestInfo      [1] ObjectDigestInfo  OPTIONAL
+                    -- issuerName MUST be present in this profile
+                    -- baseCertificateID and objectDigestInfo MUST NOT
+                    -- be present in this profile
+             }
+            
+
+ + Generator for Version 2 TbsCertList structures. +
+              TbsCertList  ::=  Sequence  {
+                   version                 Version OPTIONAL,
+                                                -- if present, shall be v2
+                   signature               AlgorithmIdentifier,
+                   issuer                  Name,
+                   thisUpdate              Time,
+                   nextUpdate              Time OPTIONAL,
+                   revokedCertificates     Sequence OF Sequence  {
+                        userCertificate         CertificateSerialNumber,
+                        revocationDate          Time,
+                        crlEntryExtensions      Extensions OPTIONAL
+                                                      -- if present, shall be v2
+                                             }  OPTIONAL,
+                   crlExtensions           [0]  EXPLICIT Extensions OPTIONAL
+                                                      -- if present, shall be v2
+                                             }
+             
+ + Note: This class may be subject to change +
+ + Generator for Version 3 TbsCertificateStructures. +
+             TbsCertificate ::= Sequence {
+                  version          [ 0 ]  Version DEFAULT v1(0),
+                  serialNumber            CertificateSerialNumber,
+                  signature               AlgorithmIdentifier,
+                  issuer                  Name,
+                  validity                Validity,
+                  subject                 Name,
+                  subjectPublicKeyInfo    SubjectPublicKeyInfo,
+                  issuerUniqueID    [ 1 ] IMPLICIT UniqueIdentifier OPTIONAL,
+                  subjectUniqueID   [ 2 ] IMPLICIT UniqueIdentifier OPTIONAL,
+                  extensions        [ 3 ] Extensions OPTIONAL
+                  }
+             
+ +
+ + an X509Certificate structure. +
+             Certificate ::= Sequence {
+                 tbsCertificate          TbsCertificate,
+                 signatureAlgorithm      AlgorithmIdentifier,
+                 signature               BIT STRING
+             }
+            
+
+ + The default converter for X509 DN entries when going from their + string value to ASN.1 strings. + + + Apply default conversion for the given value depending on the oid + and the character range of the value. + + @param oid the object identifier for the DN entry + @param value the value associated with it + @return the ASN.1 equivalent for the string value. + + + an object for the elements in the X.509 V3 extension block. + + + Convert the value of the passed in extension to an object. + The extension to parse. + The object the value string contains. + If conversion is not possible. + + + Subject Directory Attributes + + + Subject Key Identifier + + + Key Usage + + + Private Key Usage Period + + + Subject Alternative Name + + + Issuer Alternative Name + + + Basic Constraints + + + CRL Number + + + Reason code + + + Hold Instruction Code + + + Invalidity Date + + + Delta CRL indicator + + + Issuing Distribution Point + + + Certificate Issuer + + + Name Constraints + + + CRL Distribution Points + + + Certificate Policies + + + Policy Mappings + + + Authority Key Identifier + + + Policy Constraints + + + Extended Key Usage + + + Freshest CRL + + + Inhibit Any Policy + + + Authority Info Access + + + Subject Info Access + + + Logo Type + + + BiometricInfo + + + QCStatements + + + Audit identity extension in attribute certificates. + + + NoRevAvail extension in attribute certificates. + + + TargetInformation extension in attribute certificates. + + + Constructor from Asn1Sequence. + + the extensions are a list of constructed sequences, either with (Oid, OctetString) or (Oid, Boolean, OctetString) + + + constructor from a table of extensions. +

+ it's is assumed the table contains Oid/string pairs.

+
+ + Constructor from a table of extensions with ordering. +

+ It's is assumed the table contains Oid/string pairs.

+
+ + Constructor from two vectors + + @param objectIDs an ArrayList of the object identifiers. + @param values an ArrayList of the extension values. + + + return an Enumeration of the extension field's object ids. + + + return the extension represented by the object identifier + passed in. + + @return the extension if it's present, null otherwise. + + +
+                 Extensions        ::=   SEQUENCE SIZE (1..MAX) OF Extension
+            
+                 Extension         ::=   SEQUENCE {
+                    extnId            EXTENSION.&id ({ExtensionSet}),
+                    critical          BOOLEAN DEFAULT FALSE,
+                    extnValue         OCTET STRING }
+             
+
+ + Generator for X.509 extensions + + + Reset the generator + + + + Add an extension with the given oid and the passed in value to be included + in the OCTET STRING associated with the extension. + + OID for the extension. + True if critical, false otherwise. + The ASN.1 object to be included in the extension. + + + + Add an extension with the given oid and the passed in byte array to be wrapped + in the OCTET STRING associated with the extension. + + OID for the extension. + True if critical, false otherwise. + The byte array to be wrapped. + + + Return true if there are no extension present in this generator. + True if empty, false otherwise + + + Generate an X509Extensions object based on the current state of the generator. + An X509Extensions object + + +
+                 RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
+            
+                 RelativeDistinguishedName ::= SET SIZE (1..MAX) OF AttributeTypeAndValue
+            
+                 AttributeTypeAndValue ::= SEQUENCE {
+                                               type  OBJECT IDENTIFIER,
+                                               value ANY }
+             
+
+ + country code - StringType(SIZE(2)) + + + organization - StringType(SIZE(1..64)) + + + organizational unit name - StringType(SIZE(1..64)) + + + Title + + + common name - StringType(SIZE(1..64)) + + + street - StringType(SIZE(1..64)) + + + device serial number name - StringType(SIZE(1..64)) + + + locality name - StringType(SIZE(1..64)) + + + state, or province name - StringType(SIZE(1..64)) + + + Naming attributes of type X520name + + + businessCategory - DirectoryString(SIZE(1..128) + + + postalCode - DirectoryString(SIZE(1..40) + + + dnQualifier - DirectoryString(SIZE(1..64) + + + RFC 3039 Pseudonym - DirectoryString(SIZE(1..64) + + + RFC 3039 DateOfBirth - GeneralizedTime - YYYYMMDD000000Z + + + RFC 3039 PlaceOfBirth - DirectoryString(SIZE(1..128) + + + RFC 3039 DateOfBirth - PrintableString (SIZE(1)) -- "M", "F", "m" or "f" + + + RFC 3039 CountryOfCitizenship - PrintableString (SIZE (2)) -- ISO 3166 + codes only + + + RFC 3039 CountryOfCitizenship - PrintableString (SIZE (2)) -- ISO 3166 + codes only + + + ISIS-MTT NameAtBirth - DirectoryString(SIZE(1..64) + + + RFC 3039 PostalAddress - SEQUENCE SIZE (1..6) OF + DirectoryString(SIZE(1..30)) + + + RFC 2256 dmdName + + + id-at-telephoneNumber + + + id-at-name + + + Email address (RSA PKCS#9 extension) - IA5String. +

Note: if you're trying to be ultra orthodox, don't use this! It shouldn't be in here.

+
+ + more from PKCS#9 + + + email address in Verisign certificates + + + LDAP User id. + + + determines whether or not strings should be processed and printed + from back to front. + + + default look up table translating OID values into their common symbols following + the convention in RFC 2253 with a few extras + + + look up table translating OID values into their common symbols following the convention in RFC 2253 + + + look up table translating OID values into their common symbols following the convention in RFC 1779 + + + + look up table translating common symbols into their OIDS. + + + Return a X509Name based on the passed in tagged object. + + @param obj tag object holding name. + @param explicitly true if explicitly tagged false otherwise. + @return the X509Name + + + Constructor from Asn1Sequence + + the principal will be a list of constructed sets, each containing an (OID, string) pair. + + + Constructor from a table of attributes with ordering. +

+ it's is assumed the table contains OID/string pairs, and the contents + of the table are copied into an internal table as part of the + construction process. The ordering ArrayList should contain the OIDs + in the order they are meant to be encoded or printed in ToString.

+
+ + Constructor from a table of attributes with ordering. +

+ it's is assumed the table contains OID/string pairs, and the contents + of the table are copied into an internal table as part of the + construction process. The ordering ArrayList should contain the OIDs + in the order they are meant to be encoded or printed in ToString.

+

+ The passed in converter will be used to convert the strings into their + ASN.1 counterparts.

+
+ + Takes two vectors one of the oids and the other of the values. + + + Takes two vectors one of the oids and the other of the values. +

+ The passed in converter will be used to convert the strings into their + ASN.1 counterparts.

+
+ + Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or + some such, converting it into an ordered set of name attributes. + + + Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or + some such, converting it into an ordered set of name attributes with each + string value being converted to its associated ASN.1 type using the passed + in converter. + + + Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or + some such, converting it into an ordered set of name attributes. If reverse + is true, create the encoded version of the sequence starting from the + last element in the string. + + + Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or + some such, converting it into an ordered set of name attributes with each + string value being converted to its associated ASN.1 type using the passed + in converter. If reverse is true the ASN.1 sequence representing the DN will + be built by starting at the end of the string, rather than the start. + + + Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or + some such, converting it into an ordered set of name attributes. lookUp + should provide a table of lookups, indexed by lowercase only strings and + yielding a DerObjectIdentifier, other than that OID. and numeric oids + will be processed automatically. +
+ If reverse is true, create the encoded version of the sequence + starting from the last element in the string. + @param reverse true if we should start scanning from the end (RFC 2553). + @param lookUp table of names and their oids. + @param dirName the X.500 string to be parsed. +
+ + Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or + some such, converting it into an ordered set of name attributes. lookUp + should provide a table of lookups, indexed by lowercase only strings and + yielding a DerObjectIdentifier, other than that OID. and numeric oids + will be processed automatically. The passed in converter is used to convert the + string values to the right of each equals sign to their ASN.1 counterparts. +
+ @param reverse true if we should start scanning from the end, false otherwise. + @param lookUp table of names and oids. + @param dirName the string dirName + @param converter the converter to convert string values into their ASN.1 equivalents +
+ + return an IList of the oids in the name, in the order they were found. + + + return an IList of the values found in the name, in the order they + were found. + + + return an IList of the values found in the name, in the order they + were found, with the DN label corresponding to passed in oid. + + + The X509Name object to test equivalency against. + If true, the order of elements must be the same, + as well as the values associated with each element. + + + test for equivalence - note: case is ignored. + + + convert the structure to a string - if reverse is true the + oids and values are listed out starting with the last element + in the sequence (ala RFC 2253), otherwise the string will begin + with the first element of the structure. If no string definition + for the oid is found in oidSymbols the string value of the oid is + added. Two standard symbol tables are provided DefaultSymbols, and + RFC2253Symbols as part of this class. + + @param reverse if true start at the end of the sequence and work back. + @param oidSymbols look up table strings for oids. + + + * It turns out that the number of standard ways the fields in a DN should be + * encoded into their ASN.1 counterparts is rapidly approaching the + * number of machines on the internet. By default the X509Name class + * will produce UTF8Strings in line with the current recommendations (RFC 3280). + *

+ * An example of an encoder look like below: + *

+                 * public class X509DirEntryConverter
+                 *     : X509NameEntryConverter
+                 * {
+                 *     public Asn1Object GetConvertedValue(
+                 *         DerObjectIdentifier  oid,
+                 *         string               value)
+                 *     {
+                 *         if (str.Length() != 0 && str.charAt(0) == '#')
+                 *         {
+                 *             return ConvertHexEncoded(str, 1);
+                 *         }
+                 *         if (oid.Equals(EmailAddress))
+                 *         {
+                 *             return new DerIA5String(str);
+                 *         }
+                 *         else if (CanBePrintable(str))
+                 *         {
+                 *             return new DerPrintableString(str);
+                 *         }
+                 *         else if (CanBeUTF8(str))
+                 *         {
+                 *             return new DerUtf8String(str);
+                 *         }
+                 *         else
+                 *         {
+                 *             return new DerBmpString(str);
+                 *         }
+                 *     }
+                 * }
+            	 * 
+ *

+
+ + Convert an inline encoded hex string rendition of an ASN.1 + object back into its corresponding ASN.1 object. + + @param str the hex encoded object + @param off the index at which the encoding starts + @return the decoded object + + + return true if the passed in string can be represented without + loss as a PrintableString, false otherwise. + + + Convert the passed in string value into the appropriate ASN.1 + encoded object. + + @param oid the oid associated with the value in the DN. + @param value the value of the particular DN component. + @return the ASN.1 equivalent for the value. + + + class for breaking up an X500 Name into it's component tokens, ala + java.util.StringTokenizer. We need this class as some of the + lightweight Java environment don't support classes like + StringTokenizer. + + + ASN.1 def for Diffie-Hellman key exchange KeySpecificInfo structure. See + RFC 2631, or X9.42, for further details. + + + Produce an object suitable for an Asn1OutputStream. +
+             KeySpecificInfo ::= Sequence {
+                 algorithm OBJECT IDENTIFIER,
+                 counter OCTET STRING SIZE (4..4)
+             }
+            
+
+ + ANS.1 def for Diffie-Hellman key exchange OtherInfo structure. See + RFC 2631, or X9.42, for further details. + + + Produce an object suitable for an Asn1OutputStream. +
+             OtherInfo ::= Sequence {
+                 keyInfo KeySpecificInfo,
+                 partyAInfo [0] OCTET STRING OPTIONAL,
+                 suppPubInfo [2] OCTET STRING
+             }
+            
+
+ + table of the current named curves defined in X.962 EC-DSA. + + + return the X9ECParameters object for the named curve represented by + the passed in object identifier. Null if the curve isn't present. + + @param oid an object identifier representing a named curve, if present. + + + return the object identifier signified by the passed in name. Null + if there is no object identifier associated with name. + + @return the object identifier associated with name, if present. + + + return the named curve name represented by the given object identifier. + + + returns an enumeration containing the name strings for curves + contained in this structure. + + + Produce an object suitable for an Asn1OutputStream. +
+            Parameters ::= CHOICE {
+               ecParameters ECParameters,
+               namedCurve   CURVES.&id({CurveNames}),
+               implicitlyCA Null
+            }
+            
+
+ + ASN.1 def for Elliptic-Curve Curve structure. See + X9.62, for further details. + + + Produce an object suitable for an Asn1OutputStream. +
+             Curve ::= Sequence {
+                 a               FieldElement,
+                 b               FieldElement,
+                 seed            BIT STRING      OPTIONAL
+             }
+            
+
+ + ASN.1 def for Elliptic-Curve ECParameters structure. See + X9.62, for further details. + + + Produce an object suitable for an Asn1OutputStream. +
+             ECParameters ::= Sequence {
+                 version         Integer { ecpVer1(1) } (ecpVer1),
+                 fieldID         FieldID {{FieldTypes}},
+                 curve           X9Curve,
+                 base            X9ECPoint,
+                 order           Integer,
+                 cofactor        Integer OPTIONAL
+             }
+            
+
+ + class for describing an ECPoint as a Der object. + + + Produce an object suitable for an Asn1OutputStream. +
+             ECPoint ::= OCTET STRING
+            
+

+ Octet string produced using ECPoint.GetEncoded().

+
+ + Class for processing an ECFieldElement as a DER object. + + + Produce an object suitable for an Asn1OutputStream. +
+             FieldElement ::= OCTET STRING
+            
+

+

    +
  1. if q is an odd prime then the field element is + processed as an Integer and converted to an octet string + according to x 9.62 4.3.1.
  2. +
  3. if q is 2m then the bit string + contained in the field element is converted into an octet + string with the same ordering padded at the front if necessary. +
  4. +
+

+
+ + ASN.1 def for Elliptic-Curve Field ID structure. See + X9.62, for further details. + + + Constructor for elliptic curves over prime fields + F2. + @param primeP The prime p defining the prime field. + + + Constructor for elliptic curves over binary fields + F2m. + @param m The exponent m of + F2m. + @param k1 The integer k1 where xm + + xk3 + xk2 + xk1 + 1 + represents the reduction polynomial f(z). + @param k2 The integer k2 where xm + + xk3 + xk2 + xk1 + 1 + represents the reduction polynomial f(z). + @param k3 The integer k3 where xm + + xk3 + xk2 + xk1 + 1 + represents the reduction polynomial f(z).. + + + Produce a Der encoding of the following structure. +
+             FieldID ::= Sequence {
+                 fieldType       FIELD-ID.&id({IOSet}),
+                 parameters      FIELD-ID.&Type({IOSet}{@fieldType})
+             }
+            
+
+ + id-dsa-with-sha1 OBJECT IDENTIFIER ::= { iso(1) member-body(2) + us(840) x9-57 (10040) x9cm(4) 3 } + + + X9.63 + + + X9.42 + + + reader for Base64 armored objects - read the headers and then start returning + bytes when the data is reached. An IOException is thrown if the CRC check + fails. + + + decode the base 64 encoded input data. + + @return the offset the data starts in out. + + + Create a stream for reading a PGP armoured message, parsing up to a header + and then reading the data that follows. + + @param input + + + Create an armoured input stream which will assume the data starts + straight away, or parse for headers first depending on the value of + hasHeaders. + + @param input + @param hasHeaders true if headers are to be looked for, false otherwise. + + + @return true if we are inside the clear text section of a PGP + signed message. + + + @return true if the stream is actually at end of file. + + + Return the armor header line (if there is one) + @return the armor header line, null if none present. + + + Return the armor headers (the lines after the armor header line), + @return an array of armor headers, null if there aren't any. + + + Basic output stream. + + + encode the input data producing a base 64 encoded byte array. + + + Set an additional header entry. + + @param name the name of the header entry. + @param v the value of the header entry. + + + Reset the headers to only contain a Version string. + + + Start a clear text signed message. + @param hashAlgorithm + + + Note: Dispose does nor Dispose the underlying stream. So it is possible to write + multiple objects using armoring to a single stream. + + + Basic type for a image attribute packet. + + + Reader for PGP objects. + + + Returns the next packet tag in the stream. + + + + A stream that overlays our input stream, allowing the user to only read a segment of it. + NB: dataLength will be negative if the segment length is in the upper range above 2**31. + + + + Base class for a PGP object. + + + Basic output stream. + + + Create a stream representing a general packet. + Output stream to write to. + + + Create a stream representing an old style partial object. + Output stream to write to. + The packet tag for the object. + + + Create a stream representing a general packet. + Output stream to write to. + Packet tag. + Size of chunks making up the packet. + If true, the header is written out in old format. + + + Create a new style partial input stream buffered into chunks. + Output stream to write to. + Packet tag. + Size of chunks making up the packet. + + + Create a new style partial input stream buffered into chunks. + Output stream to write to. + Packet tag. + Buffer to use for collecting chunks. + + + Flush the underlying stream. + + + Finish writing out the current packet without closing the underlying stream. + + + Generic compressed data object. + + + The algorithm tag value. + + + Basic tags for compression algorithms. + + + Basic type for a PGP packet. + + + Base class for a DSA public key. + + + The stream to read the packet from. + + + The format, as a string, always "PGP". + + + Return the standard PGP encoding of the key. + + + Base class for a DSA secret key. + + + @param in + + + The format, as a string, always "PGP". + + + Return the standard PGP encoding of the key. + + + @return x + + + Base class for an ElGamal public key. + + + The format, as a string, always "PGP". + + + Return the standard PGP encoding of the key. + + + Base class for an ElGamal secret key. + + + @param in + + + @param x + + + The format, as a string, always "PGP". + + + Return the standard PGP encoding of the key. + + + Basic packet for an experimental packet. + + + Basic tags for hash algorithms. + + + Base interface for a PGP key. + + + + The base format for this key - in the case of the symmetric keys it will generally + be raw indicating that the key is just a straight byte representation, for an asymmetric + key the format will be PGP, indicating the key is a string of MPIs encoded in PGP format. + + "RAW" or "PGP". + + + Note: you can only read from this once... + + + Generic literal data packet. + + + The format tag value. + + + The modification time of the file in milli-seconds (since Jan 1, 1970 UTC) + + + Basic type for a marker packet. + + + Basic packet for a modification detection code packet. + + + A multiple precision integer + + + Generic signature object + + + The encryption algorithm tag. + + + The hash algorithm tag. + + + Basic PGP packet tag types. + + + Public Key Algorithm tag numbers. + + + Basic packet for a PGP public key. + + + Basic packet for a PGP public key. + + + Construct a version 4 public key packet. + + + Basic packet for a PGP public subkey + + + Construct a version 4 public subkey packet. + + + Base class for an RSA public key. + + + Construct an RSA public key from the passed in stream. + + + The modulus. + The public exponent. + + + The format, as a string, always "PGP". + + + Return the standard PGP encoding of the key. + + + Base class for an RSA secret (or priate) key. + + + The format, as a string, always "PGP". + + + Return the standard PGP encoding of the key. + + + The string to key specifier class. + + + The hash algorithm. + + + The IV for the key generation algorithm. + + + The iteration count + + + The protection mode - only if GnuDummyS2K + + + Basic packet for a PGP secret key. + + + Basic packet for a PGP secret key. + + + Generic signature packet. + + + Generate a version 4 signature packet. + + @param signatureType + @param keyAlgorithm + @param hashAlgorithm + @param hashedData + @param unhashedData + @param fingerprint + @param signature + + + Generate a version 2/3 signature packet. + + @param signatureType + @param keyAlgorithm + @param hashAlgorithm + @param fingerprint + @param signature + + + return the keyId + @return the keyId that created the signature. + + + return the signature trailer that must be included with the data + to reconstruct the signature + + @return byte[] + + + * return the signature as a set of integers - note this is normalised to be the + * ASN.1 encoding of what appears in the signature packet. + + + Return the byte encoding of the signature section. + @return uninterpreted signature bytes. + + + Return the creation time in milliseconds since 1 Jan., 1970 UTC. + + + Basic type for a PGP Signature sub-packet. + + + Return the generic data making up the packet. + + + reader for signature sub-packets + + + Basic PGP signature sub-packet tag types. + + + Packet embedded signature + + + packet giving signature creation time. + + + packet giving signature creation time. + + + packet giving time after creation at which the key expires. + + + Return the number of seconds after creation time a key is valid for. + + @return second count for key validity. + + + Packet holding the key flag values. + + + + Return the flag values contained in the first 4 octets (note: at the moment + the standard only uses the first one). + + + + Class provided a NotationData object according to + RFC2440, Chapter 5.2.3.15. Notation Data + + + packet giving signature creation time. + + + packet giving whether or not the signature is signed using the primary user ID for the key. + + + packet giving whether or not is revocable. + + + packet giving signature creation time. + + + packet giving signature expiration time. + + + return time in seconds before signature expires after creation time. + + + packet giving the User ID of the signer. + + + packet giving trust. + + + + Represents revocation key OpenPGP signature sub packet. + + + + + Represents revocation reason OpenPGP signature sub packet. + + + + Basic type for a symmetric key encrypted packet. + + + Basic tags for symmetric key algorithms + + + Basic type for a symmetric encrypted session key packet + + + @return int + + + @return S2k + + + @return byte[] + + + @return int + + + Basic type for a trust packet. + + + Basic type for a user attribute packet. + + + Basic type for a user attribute sub-packet. + + + return the generic data making up the packet. + + + reader for user attribute sub-packets + + + Basic PGP user attribute sub-packet tag types. + + + Basic type for a user ID packet. + + + Compressed data objects + + + The algorithm used for compression + + + Get the raw input stream contained in the object. + + + Return an uncompressed input stream which allows reading of the compressed data. + + + Class for producing compressed data packets. + + + +

+ Return an output stream which will save the data being written to + the compressed object. +

+

+ The stream created can be closed off by either calling Close() + on the stream or Close() on the generator. Closing the returned + stream does not close off the Stream parameter outStr. +

+
+ Stream to be used for output. + A Stream for output of the compressed data. + + + +
+ + +

+ Return an output stream which will compress the data as it is written to it. + The stream will be written out in chunks according to the size of the passed in buffer. +

+

+ The stream created can be closed off by either calling Close() + on the stream or Close() on the generator. Closing the returned + stream does not close off the Stream parameter outStr. +

+

+ Note: if the buffer is not a power of 2 in length only the largest power of 2 + bytes worth of the buffer will be used. +

+

+ Note: using this may break compatibility with RFC 1991 compliant tools. + Only recent OpenPGP implementations are capable of accepting these streams. +

+
+ Stream to be used for output. + The buffer to use. + A Stream for output of the compressed data. + + + + +
+ + Close the compressed object.summary> + + + + Thrown if the IV at the start of a data stream indicates the wrong key is being used. + + + + Return the raw input stream for the data stream. + + + Return true if the message is integrity protected. + True, if there is a modification detection code namespace associated + with this stream. + + + Note: This can only be called after the message has been read. + True, if the message verifies, false otherwise + + + Generator for encrypted objects. + + + Existing SecureRandom constructor. + The symmetric algorithm to use. + Source of randomness. + + + Creates a cipher stream which will have an integrity packet associated with it. + + + Base constructor. + The symmetric algorithm to use. + Source of randomness. + PGP 2.6.x compatibility required. + + + + Add a PBE encryption method to the encrypted object using the default algorithm (S2K_SHA1). + + + + Add a PBE encryption method to the encrypted object. + + + Add a public key encrypted session key to the encrypted object. + + + +

+ If buffer is non null stream assumed to be partial, otherwise the length will be used + to output a fixed length packet. +

+

+ The stream created can be closed off by either calling Close() + on the stream or Close() on the generator. Closing the returned + stream does not close off the Stream parameter outStr. +

+
+
+ + +

+ Return an output stream which will encrypt the data as it is written to it. +

+

+ The stream created can be closed off by either calling Close() + on the stream or Close() on the generator. Closing the returned + stream does not close off the Stream parameter outStr. +

+
+
+ + +

+ Return an output stream which will encrypt the data as it is written to it. + The stream will be written out in chunks according to the size of the passed in buffer. +

+

+ The stream created can be closed off by either calling Close() + on the stream or Close() on the generator. Closing the returned + stream does not close off the Stream parameter outStr. +

+

+ Note: if the buffer is not a power of 2 in length only the largest power of 2 + bytes worth of the buffer will be used. +

+
+
+ + +

+ Close off the encrypted object - this is equivalent to calling Close() on the stream + returned by the Open() method. +

+

+ Note: This does not close the underlying output stream, only the stream on top of + it created by the Open() method. +

+
+
+ + A holder for a list of PGP encryption method packets. + + + Generic exception class for PGP encoding/decoding problems. + + + Key flag values for the KeyFlags subpacket. + + + + General class to handle JCA key pairs and convert them into OpenPGP ones. +

+ A word for the unwary, the KeyId for an OpenPGP public key is calculated from + a hash that includes the time of creation, if you pass a different date to the + constructor below with the same public private key pair the KeyIs will not be the + same as for previous generations of the key, so ideally you only want to do + this once. +

+
+
+ + Create a key pair from a PgpPrivateKey and a PgpPublicKey. + The public key. + The private key. + + + The keyId associated with this key pair. + + + + Generator for a PGP master and subkey ring. + This class will generate both the secret and public key rings + + + + + Create a new key ring generator using old style checksumming. It is recommended to use + SHA1 checksumming where possible. + + The certification level for keys on this ring. + The master key pair. + The id to be associated with the ring. + The algorithm to be used to protect secret keys. + The passPhrase to be used to protect secret keys. + Packets to be included in the certification hash. + Packets to be attached unhashed to the certification. + input secured random. + + + + Create a new key ring generator. + + The certification level for keys on this ring. + The master key pair. + The id to be associated with the ring. + The algorithm to be used to protect secret keys. + The passPhrase to be used to protect secret keys. + Checksum the secret keys with SHA1 rather than the older 16 bit checksum. + Packets to be included in the certification hash. + Packets to be attached unhashed to the certification. + input secured random. + + + Add a subkey to the key ring to be generated with default certification. + + + + Add a subkey with specific hashed and unhashed packets associated with it and + default certification. + + Public/private key pair. + Hashed packet values to be included in certification. + Unhashed packets values to be included in certification. + + + + Return the secret key ring. + + + Return the public key ring that corresponds to the secret key ring. + + + + Thrown if the key checksum is invalid. + + + + Class for processing literal data objects. + + + The special name indicating a "for your eyes only" packet. + + + The format of the data stream - Binary or Text + + + The file name that's associated with the data stream. + + + Return the file name as an unintrepreted byte array. + + + The modification time for the file. + + + The raw input stream for the data stream. + + + The input stream representing the data stream. + + + Class for producing literal data packets. + + + The special name indicating a "for your eyes only" packet. + + + + Generates literal data objects in the old format. + This is important if you need compatibility with PGP 2.6.x. + + If true, uses old format. + + + +

+ Open a literal data packet, returning a stream to store the data inside the packet. +

+

+ The stream created can be closed off by either calling Close() + on the stream or Close() on the generator. Closing the returned + stream does not close off the Stream parameter outStr. +

+
+ The stream we want the packet in. + The format we are using. + The name of the 'file'. + The length of the data we will write. + The time of last modification we want stored. +
+ + +

+ Open a literal data packet, returning a stream to store the data inside the packet, + as an indefinite length stream. The stream is written out as a series of partial + packets with a chunk size determined by the size of the passed in buffer. +

+

+ The stream created can be closed off by either calling Close() + on the stream or Close() on the generator. Closing the returned + stream does not close off the Stream parameter outStr. +

+

+ Note: if the buffer is not a power of 2 in length only the largest power of 2 + bytes worth of the buffer will be used.

+
+ The stream we want the packet in. + The format we are using. + The name of the 'file'. + The time of last modification we want stored. + The buffer to use for collecting data to put into chunks. +
+ + + Close the literal data packet - this is equivalent to calling Close() + on the stream returned by the Open() method. + + + + + A PGP marker packet - in general these should be ignored other than where + the idea is to preserve the original input stream. + + + + + General class for reading a PGP object stream. +

+ Note: if this class finds a PgpPublicKey or a PgpSecretKey it + will create a PgpPublicKeyRing, or a PgpSecretKeyRing for each + key found. If all you are trying to do is read a key ring file use + either PgpPublicKeyRingBundle or PgpSecretKeyRingBundle.

+
+
+ + Return the next object in the stream, or null if the end is reached. + On a parse error + + + + Return all available objects in a list. + + An IList containing all objects from this factory, in order. + + + A one pass signature object. + + + Initialise the signature object for verification. + + + Verify the calculated signature against the passed in PgpSignature. + + + Holder for a list of PgpOnePassSignature objects. + + + A password based encryption object. + + + Return the raw input stream for the data stream. + + + Return the decrypted input stream, using the passed in passphrase. + + + General class to contain a private key for use with other OpenPGP objects. + + + + Create a PgpPrivateKey from a regular private key and the ID of its + associated public key. + + Private key to use. + ID of the corresponding public key. + + + The keyId associated with the contained private key. + + + The contained private key. + + + General class to handle a PGP public key object. + + + + Create a PgpPublicKey from the passed in lightweight one. + + + Note: the time passed in affects the value of the key's keyId, so you probably only want + to do this once for a lightweight key, or make sure you keep track of the time you used. + + Asymmetric algorithm type representing the public key. + Actual public key to associate. + Date of creation. + If pubKey is not public. + On key creation problem. + + + Constructor for a sub-key. + + + Copy constructor. + The public key to copy. + + + The version of this key. + + + The creation time of this key. + + + The number of valid days from creation time - zero means no expiry. + + + Return the trust data associated with the public key, if present. + A byte array with trust data, null otherwise. + + + The number of valid seconds from creation time - zero means no expiry. + + + The keyId associated with the public key. + + + The fingerprint of the key + + + + Check if this key has an algorithm type that makes it suitable to use for encryption. + + + Note: with version 4 keys KeyFlags subpackets should also be considered when present for + determining the preferred use of the key. + + + true if this key algorithm is suitable for encryption. + + + + True, if this is a master key. + + + The algorithm code associated with the public key. + + + The strength of the key in bits. + + + The public key contained in the object. + A lightweight public key. + If the key algorithm is not recognised. + + + Allows enumeration of any user IDs associated with the key. + An IEnumerable of string objects. + + + Allows enumeration of any user attribute vectors associated with the key. + An IEnumerable of PgpUserAttributeSubpacketVector objects. + + + Allows enumeration of any signatures associated with the passed in id. + The ID to be matched. + An IEnumerable of PgpSignature objects. + + + Allows enumeration of signatures associated with the passed in user attributes. + The vector of user attributes to be matched. + An IEnumerable of PgpSignature objects. + + + Allows enumeration of signatures of the passed in type that are on this key. + The type of the signature to be returned. + An IEnumerable of PgpSignature objects. + + + Allows enumeration of all signatures/certifications associated with this key. + An IEnumerable with all signatures/certifications. + + + Check whether this (sub)key has a revocation signature on it. + True, if this (sub)key has been revoked. + + + Add a certification for an id to the given public key. + The key the certification is to be added to. + The ID the certification is associated with. + The new certification. + The re-certified key. + + + Add a certification for the given UserAttributeSubpackets to the given public key. + The key the certification is to be added to. + The attributes the certification is associated with. + The new certification. + The re-certified key. + + + + Remove any certifications associated with a user attribute subpacket on a key. + + The key the certifications are to be removed from. + The attributes to be removed. + + The re-certified key, or null if the user attribute subpacket was not found on the key. + + + + Remove any certifications associated with a given ID on a key. + The key the certifications are to be removed from. + The ID that is to be removed. + The re-certified key, or null if the ID was not found on the key. + + + Remove a certification associated with a given ID on a key. + The key the certifications are to be removed from. + The ID that the certfication is to be removed from. + The certfication to be removed. + The re-certified key, or null if the certification was not found. + + + Remove a certification associated with a given user attributes on a key. + The key the certifications are to be removed from. + The user attributes that the certfication is to be removed from. + The certification to be removed. + The re-certified key, or null if the certification was not found. + + + Add a revocation or some other key certification to a key. + The key the revocation is to be added to. + The key signature to be added. + The new changed public key object. + + + Remove a certification from the key. + The key the certifications are to be removed from. + The certfication to be removed. + The modified key, null if the certification was not found. + + + A public key encrypted data object. + + + The key ID for the key used to encrypt the data. + + + + Return the algorithm code for the symmetric algorithm used to encrypt the data. + + + + Return the decrypted data stream for the packet. + + + + Class to hold a single master public key and its subkeys. +

+ Often PGP keyring files consist of multiple master keys, if you are trying to process + or construct one of these you should use the PgpPublicKeyRingBundle class. +

+
+
+ + Return the first public key in the ring. + + + Return the public key referred to by the passed in key ID if it is present. + + + Allows enumeration of all the public keys. + An IEnumerable of PgpPublicKey objects. + + + + Returns a new key ring with the public key passed in either added or + replacing an existing one. + + The public key ring to be modified. + The public key to be inserted. + A new PgpPublicKeyRing + + + Returns a new key ring with the public key passed in removed from the key ring. + The public key ring to be modified. + The public key to be removed. + A new PgpPublicKeyRing, or null if pubKey is not found. + + + + Often a PGP key ring file is made up of a succession of master/sub-key key rings. + If you want to read an entire public key file in one hit this is the class for you. + + + + Build a PgpPublicKeyRingBundle from the passed in input stream. + Input stream containing data. + If a problem parsing the stream occurs. + If an object is encountered which isn't a PgpPublicKeyRing. + + + Return the number of key rings in this collection. + + + Allow enumeration of the public key rings making up this collection. + + + Allow enumeration of the key rings associated with the passed in userId. + The user ID to be matched. + An IEnumerable of key rings which matched (possibly none). + + + Allow enumeration of the key rings associated with the passed in userId. + The user ID to be matched. + If true, userId need only be a substring of an actual ID string to match. + An IEnumerable of key rings which matched (possibly none). + + + Allow enumeration of the key rings associated with the passed in userId. + The user ID to be matched. + If true, userId need only be a substring of an actual ID string to match. + If true, case is ignored in user ID comparisons. + An IEnumerable of key rings which matched (possibly none). + + + Return the PGP public key associated with the given key id. + The ID of the public key to return. + + + Return the public key ring which contains the key referred to by keyId + key ID to match against + + + + Return true if a key matching the passed in key ID is present, false otherwise. + + key ID to look for. + + + + Return a new bundle containing the contents of the passed in bundle and + the passed in public key ring. + + The PgpPublicKeyRingBundle the key ring is to be added to. + The key ring to be added. + A new PgpPublicKeyRingBundle merging the current one with the passed in key ring. + If the keyId for the passed in key ring is already present. + + + + Return a new bundle containing the contents of the passed in bundle with + the passed in public key ring removed. + + The PgpPublicKeyRingBundle the key ring is to be removed from. + The key ring to be removed. + A new PgpPublicKeyRingBundle not containing the passed in key ring. + If the keyId for the passed in key ring is not present. + + + General class to handle a PGP secret key object. + + + + Check if this key has an algorithm type that makes it suitable to use for signing. + + + Note: with version 4 keys KeyFlags subpackets should also be considered when present for + determining the preferred use of the key. + + + true if this key algorithm is suitable for use with signing. + + + + True, if this is a master key. + + + The algorithm the key is encrypted with. + + + The key ID of the public key associated with this key. + + + The public key associated with this key. + + + Allows enumeration of any user IDs associated with the key. + An IEnumerable of string objects. + + + Allows enumeration of any user attribute vectors associated with the key. + An IEnumerable of string objects. + + + Extract a PgpPrivateKey from this secret key's encrypted contents. + + + + Return a copy of the passed in secret key, encrypted using a new password + and the passed in algorithm. + + The PgpSecretKey to be copied. + The current password for the key. + The new password for the key. + The algorithm to be used for the encryption. + Source of randomness. + + + Replace the passed the public key on the passed in secret key. + Secret key to change. + New public key. + A new secret key. + If KeyId's do not match. + + + + Class to hold a single master secret key and its subkeys. +

+ Often PGP keyring files consist of multiple master keys, if you are trying to process + or construct one of these you should use the PgpSecretKeyRingBundle class. +

+
+
+ + Return the public key for the master key. + + + Return the master private key. + + + Allows enumeration of the secret keys. + An IEnumerable of PgpSecretKey objects. + + + + Return an iterator of the public keys in the secret key ring that + have no matching private key. At the moment only personal certificate data + appears in this fashion. + + An IEnumerable of unattached, or extra, public keys. + + + + Replace the public key set on the secret ring with the corresponding key off the public ring. + + Secret ring to be changed. + Public ring containing the new public key set. + + + + Return a copy of the passed in secret key ring, with the master key and sub keys encrypted + using a new password and the passed in algorithm. + + The PgpSecretKeyRing to be copied. + The current password for key. + The new password for the key. + The algorithm to be used for the encryption. + Source of randomness. + + + + Returns a new key ring with the secret key passed in either added or + replacing an existing one with the same key ID. + + The secret key ring to be modified. + The secret key to be inserted. + A new PgpSecretKeyRing + + + Returns a new key ring with the secret key passed in removed from the key ring. + The secret key ring to be modified. + The secret key to be removed. + A new PgpSecretKeyRing, or null if secKey is not found. + + + + Often a PGP key ring file is made up of a succession of master/sub-key key rings. + If you want to read an entire secret key file in one hit this is the class for you. + + + + Build a PgpSecretKeyRingBundle from the passed in input stream. + Input stream containing data. + If a problem parsing the stream occurs. + If an object is encountered which isn't a PgpSecretKeyRing. + + + Return the number of rings in this collection. + + + Allow enumeration of the secret key rings making up this collection. + + + Allow enumeration of the key rings associated with the passed in userId. + The user ID to be matched. + An IEnumerable of key rings which matched (possibly none). + + + Allow enumeration of the key rings associated with the passed in userId. + The user ID to be matched. + If true, userId need only be a substring of an actual ID string to match. + An IEnumerable of key rings which matched (possibly none). + + + Allow enumeration of the key rings associated with the passed in userId. + The user ID to be matched. + If true, userId need only be a substring of an actual ID string to match. + If true, case is ignored in user ID comparisons. + An IEnumerable of key rings which matched (possibly none). + + + Return the PGP secret key associated with the given key id. + The ID of the secret key to return. + + + Return the secret key ring which contains the key referred to by keyId + The ID of the secret key + + + + Return true if a key matching the passed in key ID is present, false otherwise. + + key ID to look for. + + + + Return a new bundle containing the contents of the passed in bundle and + the passed in secret key ring. + + The PgpSecretKeyRingBundle the key ring is to be added to. + The key ring to be added. + A new PgpSecretKeyRingBundle merging the current one with the passed in key ring. + If the keyId for the passed in key ring is already present. + + + + Return a new bundle containing the contents of the passed in bundle with + the passed in secret key ring removed. + + The PgpSecretKeyRingBundle the key ring is to be removed from. + The key ring to be removed. + A new PgpSecretKeyRingBundle not containing the passed in key ring. + If the keyId for the passed in key ring is not present. + + + A PGP signature object. + + + The OpenPGP version number for this signature. + + + The key algorithm associated with this signature. + + + The hash algorithm associated with this signature. + + + + Verify the signature as certifying the passed in public key as associated + with the passed in user attributes. + + User attributes the key was stored under. + The key to be verified. + True, if the signature matches, false otherwise. + + + + Verify the signature as certifying the passed in public key as associated + with the passed in ID. + + ID the key was stored under. + The key to be verified. + True, if the signature matches, false otherwise. + + + Verify a certification for the passed in key against the passed in master key. + The key we are verifying against. + The key we are verifying. + True, if the certification is valid, false otherwise. + + + Verify a key certification, such as revocation, for the passed in key. + The key we are checking. + True, if the certification is valid, false otherwise. + + + The ID of the key that created the signature. + + + The creation time of this signature. + + + + Return true if the signature has either hashed or unhashed subpackets. + + + + Generator for PGP signatures. + + + Create a generator for the passed in keyAlgorithm and hashAlgorithm codes. + + + Initialise the generator for signing. + + + Initialise the generator for signing. + + + Return the one pass header associated with the current signature. + + + Return a signature object containing the current signature state. + + + Generate a certification for the passed in ID and key. + The ID we are certifying against the public key. + The key we are certifying against the ID. + The certification. + + + Generate a certification for the passed in userAttributes. + The ID we are certifying against the public key. + The key we are certifying against the ID. + The certification. + + + Generate a certification for the passed in key against the passed in master key. + The key we are certifying against. + The key we are certifying. + The certification. + + + Generate a certification, such as a revocation, for the passed in key. + The key we are certifying. + The certification. + + + A list of PGP signatures - normally in the signature block after literal data. + + + Generator for signature subpackets. + + + + Add a TrustSignature packet to the signature. The values for depth and trust are largely + installation dependent but there are some guidelines in RFC 4880 - 5.2.3.13. + + true if the packet is critical. + depth level. + trust amount. + + + + Set the number of seconds a key is valid for after the time of its creation. + A value of zero means the key never expires. + + True, if should be treated as critical, false otherwise. + The number of seconds the key is valid, or zero if no expiry. + + + + Set the number of seconds a signature is valid for after the time of its creation. + A value of zero means the signature never expires. + + True, if should be treated as critical, false otherwise. + The number of seconds the signature is valid, or zero if no expiry. + + + + Set the creation time for the signature. +

+ Note: this overrides the generation of a creation time when the signature + is generated.

+
+
+ + + Sets revocation reason sub packet + + + + + Sets revocation key sub packet + + + + + Sets issuer key sub packet + + + + Container for a list of signature subpackets. + + + Return true if a particular subpacket type exists. + + @param type type to look for. + @return true if present, false otherwise. + + + Return all signature subpackets of the passed in type. + @param type subpacket type code + @return an array of zero or more matching subpackets. + + + + Return the number of seconds a signature is valid for after its creation date. + A value of zero means the signature never expires. + + Seconds a signature is valid for. + + + + Return the number of seconds a key is valid for after its creation date. + A value of zero means the key never expires. + + Seconds a signature is valid for. + + + Return the number of packets this vector contains. + + + Container for a list of user attribute subpackets. + + + Basic utility class. + + + + Return either an ArmoredInputStream or a BcpgInputStream based on whether + the initial characters of the stream are binary PGP encodings or not. + + + + Generator for old style PGP V3 Signatures. + + + Create a generator for the passed in keyAlgorithm and hashAlgorithm codes. + + + Initialise the generator for signing. + + + Initialise the generator for signing. + + + Return the one pass header associated with the current signature. + + + Return a V3 signature object containing the current signature state. + + + + The 'Signature' parameter is only available when generating unsigned attributes. + + + + containing class for an CMS Authenticated Data object + + + return the object identifier for the content MAC algorithm. + + + return a store of the intended recipients for this message + + + return the ContentInfo + + + return a table of the digested attributes indexed by + the OID of the attribute. + + + return a table of the undigested attributes indexed by + the OID of the attribute. + + + return the ASN.1 encoded representation of this object. + + + General class for generating a CMS authenticated-data message. + + A simple example of usage. + +
+                  CMSAuthenticatedDataGenerator  fact = new CMSAuthenticatedDataGenerator();
+            
+                  fact.addKeyTransRecipient(cert);
+            
+                  CMSAuthenticatedData         data = fact.generate(content, algorithm, "BC");
+             
+
+ + base constructor + + + constructor allowing specific source of randomness + @param rand instance of SecureRandom to use + + + generate an enveloped object that contains an CMS Enveloped Data + object using the given provider and the passed in key generator. + + + generate an authenticated object that contains an CMS Authenticated Data object + + + Parsing class for an CMS Authenticated Data object from an input stream. +

+ Note: that because we are in a streaming mode only one recipient can be tried and it is important + that the methods on the parser are called in the appropriate order. +

+

+ Example of use - assuming the first recipient matches the private key we have. +

+                  CMSAuthenticatedDataParser     ad = new CMSAuthenticatedDataParser(inputStream);
+            
+                  RecipientInformationStore  recipients = ad.getRecipientInfos();
+            
+                  Collection  c = recipients.getRecipients();
+                  Iterator    it = c.iterator();
+            
+                  if (it.hasNext())
+                  {
+                      RecipientInformation   recipient = (RecipientInformation)it.next();
+            
+                      CMSTypedStream recData = recipient.getContentStream(privateKey, "BC");
+            
+                      processDataStream(recData.getContentStream());
+            
+                      if (!Arrays.equals(ad.getMac(), recipient.getMac())
+                      {
+                          System.err.println("Data corrupted!!!!");
+                      }
+                  }
+              
+ Note: this class does not introduce buffering - if you are processing large files you should create + the parser with: +
+                      CMSAuthenticatedDataParser     ep = new CMSAuthenticatedDataParser(new BufferedInputStream(inputStream, bufSize));
+              
+ where bufSize is a suitably large buffer size. +

+
+ + return the object identifier for the mac algorithm. + + + return the ASN.1 encoded encryption algorithm parameters, or null if + there aren't any. + + + return a store of the intended recipients for this message + + + return a table of the unauthenticated attributes indexed by + the OID of the attribute. + @exception java.io.IOException + + + return a table of the unauthenticated attributes indexed by + the OID of the attribute. + @exception java.io.IOException + + + General class for generating a CMS authenticated-data message stream. +

+ A simple example of usage. +

+                  CMSAuthenticatedDataStreamGenerator edGen = new CMSAuthenticatedDataStreamGenerator();
+            
+                  edGen.addKeyTransRecipient(cert);
+            
+                  ByteArrayOutputStream  bOut = new ByteArrayOutputStream();
+            
+                  OutputStream out = edGen.open(
+                                          bOut, CMSAuthenticatedDataGenerator.AES128_CBC, "BC");*
+                  out.write(data);
+            
+                  out.close();
+             
+

+
+ + base constructor + + + constructor allowing specific source of randomness + @param rand instance of SecureRandom to use + + + Set the underlying string size for encapsulated data + + @param bufferSize length of octet strings to buffer the data. + + + Use a BER Set to store the recipient information + + + generate an enveloped object that contains an CMS Enveloped Data + object using the given provider and the passed in key generator. + @throws java.io.IOException + + + generate an enveloped object that contains an CMS Enveloped Data object + + + generate an enveloped object that contains an CMS Enveloped Data object + + + base constructor + + + constructor allowing specific source of randomness + + @param rand instance of SecureRandom to use + + + containing class for an CMS AuthEnveloped Data object + + + containing class for an CMS Compressed Data object + + + Return the uncompressed content. + + @return the uncompressed content + @throws CmsException if there is an exception uncompressing the data. + + + Return the uncompressed content, throwing an exception if the data size + is greater than the passed in limit. If the content is exceeded getCause() + on the CMSException will contain a StreamOverflowException + + @param limit maximum number of bytes to read + @return the content read + @throws CMSException if there is an exception uncompressing the data. + + + return the ContentInfo + + + return the ASN.1 encoded representation of this object. + + + * General class for generating a compressed CMS message. + *

+ * A simple example of usage.

+ *

+ *

+                *      CMSCompressedDataGenerator fact = new CMSCompressedDataGenerator();
+                *      CMSCompressedData data = fact.Generate(content, algorithm);
+                * 
+ *

+
+ + Generate an object that contains an CMS Compressed Data + + + Class for reading a CMS Compressed Data stream. +
+                 CMSCompressedDataParser cp = new CMSCompressedDataParser(inputStream);
+            
+                 process(cp.GetContent().GetContentStream());
+             
+ Note: this class does not introduce buffering - if you are processing large files you should create + the parser with: +
+                  CMSCompressedDataParser     ep = new CMSCompressedDataParser(new BufferedInputStream(inputStream, bufSize));
+              
+ where bufSize is a suitably large buffer size. +
+ + General class for generating a compressed CMS message stream. +

+ A simple example of usage. +

+
+                  CMSCompressedDataStreamGenerator gen = new CMSCompressedDataStreamGenerator();
+            
+                  Stream cOut = gen.Open(outputStream, CMSCompressedDataStreamGenerator.ZLIB);
+            
+                  cOut.Write(data);
+            
+                  cOut.Close();
+             
+
+ + base constructor + + + Set the underlying string size for encapsulated data + + @param bufferSize length of octet strings to buffer the data. + + + Close the underlying data stream. + @throws IOException if the close fails. + + + containing class for an CMS Enveloped Data object + + + return the object identifier for the content encryption algorithm. + + + return a store of the intended recipients for this message + + + return the ContentInfo + + + return a table of the unprotected attributes indexed by + the OID of the attribute. + + + return the ASN.1 encoded representation of this object. + + + + General class for generating a CMS enveloped-data message. + + A simple example of usage. + +
+                  CmsEnvelopedDataGenerator  fact = new CmsEnvelopedDataGenerator();
+            
+                  fact.AddKeyTransRecipient(cert);
+            
+                  CmsEnvelopedData         data = fact.Generate(content, algorithm);
+             
+
+
+ + Constructor allowing specific source of randomness + Instance of SecureRandom to use. + + + + Generate an enveloped object that contains a CMS Enveloped Data + object using the passed in key generator. + + + + Generate an enveloped object that contains an CMS Enveloped Data object. + + + Generate an enveloped object that contains an CMS Enveloped Data object. + + + Parsing class for an CMS Enveloped Data object from an input stream. +

+ Note: that because we are in a streaming mode only one recipient can be tried and it is important + that the methods on the parser are called in the appropriate order. +

+

+ Example of use - assuming the first recipient matches the private key we have. +

+                  CmsEnvelopedDataParser     ep = new CmsEnvelopedDataParser(inputStream);
+            
+                  RecipientInformationStore  recipients = ep.GetRecipientInfos();
+            
+                  Collection  c = recipients.getRecipients();
+                  Iterator    it = c.iterator();
+            
+                  if (it.hasNext())
+                  {
+                      RecipientInformation   recipient = (RecipientInformation)it.next();
+            
+                      CMSTypedStream recData = recipient.getContentStream(privateKey);
+            
+                      processDataStream(recData.getContentStream());
+                  }
+              
+ Note: this class does not introduce buffering - if you are processing large files you should create + the parser with: +
+                      CmsEnvelopedDataParser     ep = new CmsEnvelopedDataParser(new BufferedInputStream(inputStream, bufSize));
+              
+ where bufSize is a suitably large buffer size. +

+
+ + return the object identifier for the content encryption algorithm. + + + return the ASN.1 encoded encryption algorithm parameters, or null if + there aren't any. + + + return a store of the intended recipients for this message + + + return a table of the unprotected attributes indexed by + the OID of the attribute. + @throws IOException + + + General class for generating a CMS enveloped-data message stream. +

+ A simple example of usage. +

+                  CmsEnvelopedDataStreamGenerator edGen = new CmsEnvelopedDataStreamGenerator();
+            
+                  edGen.AddKeyTransRecipient(cert);
+            
+                  MemoryStream  bOut = new MemoryStream();
+            
+                  Stream out = edGen.Open(
+                                          bOut, CMSEnvelopedDataGenerator.AES128_CBC);*
+                  out.Write(data);
+            
+                  out.Close();
+             
+

+
+ + Constructor allowing specific source of randomness + Instance of SecureRandom to use. + + + Set the underlying string size for encapsulated data. + Length of octet strings to buffer the data. + + + Use a BER Set to store the recipient information. + + + + Generate an enveloped object that contains an CMS Enveloped Data + object using the passed in key generator. + + + + generate an enveloped object that contains an CMS Enveloped Data object + @throws IOException + + + generate an enveloped object that contains an CMS Enveloped Data object + @throws IOException + + + General class for generating a CMS enveloped-data message. + + A simple example of usage. + +
+                  CMSEnvelopedDataGenerator  fact = new CMSEnvelopedDataGenerator();
+            
+                  fact.addKeyTransRecipient(cert);
+            
+                  CMSEnvelopedData         data = fact.generate(content, algorithm, "BC");
+             
+
+ + Constructor allowing specific source of randomness + Instance of SecureRandom to use. + + + add a recipient. + + @param cert recipient's public key certificate + @exception ArgumentException if there is a problem with the certificate + + + add a recipient + + @param key the public key used by the recipient + @param subKeyId the identifier for the recipient's public key + @exception ArgumentException if there is a problem with the key + + + add a KEK recipient. + @param key the secret key to use for wrapping + @param keyIdentifier the byte string that identifies the key + + + add a KEK recipient. + @param key the secret key to use for wrapping + @param keyIdentifier the byte string that identifies the key + + + Add a key agreement based recipient. + + @param agreementAlgorithm key agreement algorithm to use. + @param senderPrivateKey private key to initialise sender side of agreement with. + @param senderPublicKey sender public key to include with message. + @param recipientCert recipient's public key certificate. + @param cekWrapAlgorithm OID for key wrapping algorithm to use. + @exception SecurityUtilityException if the algorithm requested cannot be found + @exception InvalidKeyException if the keys are inappropriate for the algorithm specified + + + Add multiple key agreement based recipients (sharing a single KeyAgreeRecipientInfo structure). + + @param agreementAlgorithm key agreement algorithm to use. + @param senderPrivateKey private key to initialise sender side of agreement with. + @param senderPublicKey sender public key to include with message. + @param recipientCerts recipients' public key certificates. + @param cekWrapAlgorithm OID for key wrapping algorithm to use. + @exception SecurityUtilityException if the algorithm requested cannot be found + @exception InvalidKeyException if the keys are inappropriate for the algorithm specified + + + + Generic routine to copy out the data we want processed. + + + This routine may be called multiple times. + + + + a holding class for a byte array of data to be processed. + + + A clone of the byte array + + + general class for handling a pkcs7-signature message. + + A simple example of usage - note, in the example below the validity of + the certificate isn't verified, just the fact that one of the certs + matches the given signer... + +
+              IX509Store              certs = s.GetCertificates();
+              SignerInformationStore  signers = s.GetSignerInfos();
+            
+              foreach (SignerInformation signer in signers.GetSigners())
+              {
+                  ArrayList       certList = new ArrayList(certs.GetMatches(signer.SignerID));
+                  X509Certificate cert = (X509Certificate) certList[0];
+            
+                  if (signer.Verify(cert.GetPublicKey()))
+                  {
+                      verified++;
+                  }
+              }
+             
+
+ + Content with detached signature, digests precomputed + + @param hashes a map of precomputed digests for content indexed by name of hash. + @param sigBlock the signature object. + + + base constructor - content with detached signature. + + @param signedContent the content that was signed. + @param sigData the signature object. + + + base constructor - with encapsulated content + + + Return the version number for this object. + + + return the collection of signers that are associated with the + signatures for the message. + + + return a X509Store containing the attribute certificates, if any, contained + in this message. + + @param type type of store to create + @return a store of attribute certificates + @exception NoSuchStoreException if the store type isn't available. + @exception CmsException if a general exception prevents creation of the X509Store + + + return a X509Store containing the public key certificates, if any, contained + in this message. + + @param type type of store to create + @return a store of public key certificates + @exception NoSuchStoreException if the store type isn't available. + @exception CmsException if a general exception prevents creation of the X509Store + + + return a X509Store containing CRLs, if any, contained + in this message. + + @param type type of store to create + @return a store of CRLs + @exception NoSuchStoreException if the store type isn't available. + @exception CmsException if a general exception prevents creation of the X509Store + + + + Return the DerObjectIdentifier associated with the encapsulated + content info structure carried in the signed data. + + + + return the ContentInfo + + + return the ASN.1 encoded representation of this object. + + + Replace the signerinformation store associated with this + CmsSignedData object with the new one passed in. You would + probably only want to do this if you wanted to change the unsigned + attributes associated with a signer, or perhaps delete one. + + @param signedData the signed data object to be used as a base. + @param signerInformationStore the new signer information store to use. + @return a new signed data object. + + + Replace the certificate and CRL information associated with this + CmsSignedData object with the new one passed in. + + @param signedData the signed data object to be used as a base. + @param x509Certs the new certificates to be used. + @param x509Crls the new CRLs to be used. + @return a new signed data object. + @exception CmsException if there is an error processing the stores + + + * general class for generating a pkcs7-signature message. + *

+ * A simple example of usage. + * + *

+                 *      IX509Store certs...
+                 *      IX509Store crls...
+                 *      CmsSignedDataGenerator gen = new CmsSignedDataGenerator();
+                 *
+                 *      gen.AddSigner(privKey, cert, CmsSignedGenerator.DigestSha1);
+                 *      gen.AddCertificates(certs);
+                 *      gen.AddCrls(crls);
+                 *
+                 *      CmsSignedData data = gen.Generate(content);
+                 * 
+ *

+
+ + Constructor allowing specific source of randomness + Instance of SecureRandom to use. + + + * add a signer - no attributes other than the default ones will be + * provided here. + * + * @param key signing key to use + * @param cert certificate containing corresponding public key + * @param digestOID digest algorithm OID + + + add a signer, specifying the digest encryption algorithm to use - no attributes other than the default ones will be + provided here. + + @param key signing key to use + @param cert certificate containing corresponding public key + @param encryptionOID digest encryption algorithm OID + @param digestOID digest algorithm OID + + + add a signer - no attributes other than the default ones will be + provided here. + + + add a signer, specifying the digest encryption algorithm to use - no attributes other than the default ones will be + provided here. + + + * add a signer with extra signed/unsigned attributes. + * + * @param key signing key to use + * @param cert certificate containing corresponding public key + * @param digestOID digest algorithm OID + * @param signedAttr table of attributes to be included in signature + * @param unsignedAttr table of attributes to be included as unsigned + + + add a signer, specifying the digest encryption algorithm, with extra signed/unsigned attributes. + + @param key signing key to use + @param cert certificate containing corresponding public key + @param encryptionOID digest encryption algorithm OID + @param digestOID digest algorithm OID + @param signedAttr table of attributes to be included in signature + @param unsignedAttr table of attributes to be included as unsigned + + + * add a signer with extra signed/unsigned attributes. + * + * @param key signing key to use + * @param subjectKeyID subjectKeyID of corresponding public key + * @param digestOID digest algorithm OID + * @param signedAttr table of attributes to be included in signature + * @param unsignedAttr table of attributes to be included as unsigned + + + add a signer, specifying the digest encryption algorithm, with extra signed/unsigned attributes. + + @param key signing key to use + @param subjectKeyID subjectKeyID of corresponding public key + @param encryptionOID digest encryption algorithm OID + @param digestOID digest algorithm OID + @param signedAttr table of attributes to be included in signature + @param unsignedAttr table of attributes to be included as unsigned + + + add a signer with extra signed/unsigned attributes based on generators. + + + add a signer, specifying the digest encryption algorithm, with extra signed/unsigned attributes based on generators. + + + add a signer with extra signed/unsigned attributes based on generators. + + + add a signer, including digest encryption algorithm, with extra signed/unsigned attributes based on generators. + + + generate a signed object that for a CMS Signed Data object + + + generate a signed object that for a CMS Signed Data + object - if encapsulate is true a copy + of the message will be included in the signature. The content type + is set according to the OID represented by the string signedContentType. + + + generate a signed object that for a CMS Signed Data + object - if encapsulate is true a copy + of the message will be included in the signature with the + default content type "data". + + + generate a set of one or more SignerInformation objects representing counter signatures on + the passed in SignerInformation object. + + @param signer the signer to be countersigned + @param sigProvider the provider to be used for counter signing. + @return a store containing the signers. + + + Parsing class for an CMS Signed Data object from an input stream. +

+ Note: that because we are in a streaming mode only one signer can be tried and it is important + that the methods on the parser are called in the appropriate order. +

+

+ A simple example of usage for an encapsulated signature. +

+

+ Two notes: first, in the example below the validity of + the certificate isn't verified, just the fact that one of the certs + matches the given signer, and, second, because we are in a streaming + mode the order of the operations is important. +

+
+                  CmsSignedDataParser     sp = new CmsSignedDataParser(encapSigData);
+            
+                  sp.GetSignedContent().Drain();
+            
+                  IX509Store              certs = sp.GetCertificates();
+                  SignerInformationStore  signers = sp.GetSignerInfos();
+            
+                  foreach (SignerInformation signer in signers.GetSigners())
+                  {
+                      ArrayList       certList = new ArrayList(certs.GetMatches(signer.SignerID));
+                      X509Certificate cert = (X509Certificate) certList[0];
+            
+                      Console.WriteLine("verify returns: " + signer.Verify(cert));
+                  }
+             
+ Note also: this class does not introduce buffering - if you are processing large files you should create + the parser with: +
+                      CmsSignedDataParser     ep = new CmsSignedDataParser(new BufferedInputStream(encapSigData, bufSize));
+              
+ where bufSize is a suitably large buffer size. +
+ + base constructor - with encapsulated content + + + base constructor + + @param signedContent the content that was signed. + @param sigData the signature object. + + + Return the version number for the SignedData object + + @return the version number + + + return the collection of signers that are associated with the + signatures for the message. + @throws CmsException + + + return a X509Store containing the attribute certificates, if any, contained + in this message. + + @param type type of store to create + @return a store of attribute certificates + @exception org.bouncycastle.x509.NoSuchStoreException if the store type isn't available. + @exception CmsException if a general exception prevents creation of the X509Store + + + return a X509Store containing the public key certificates, if any, contained + in this message. + + @param type type of store to create + @return a store of public key certificates + @exception NoSuchStoreException if the store type isn't available. + @exception CmsException if a general exception prevents creation of the X509Store + + + return a X509Store containing CRLs, if any, contained + in this message. + + @param type type of store to create + @return a store of CRLs + @exception NoSuchStoreException if the store type isn't available. + @exception CmsException if a general exception prevents creation of the X509Store + + + + Return the DerObjectIdentifier associated with the encapsulated + content info structure carried in the signed data. + + + + Replace the signerinformation store associated with the passed + in message contained in the stream original with the new one passed in. + You would probably only want to do this if you wanted to change the unsigned + attributes associated with a signer, or perhaps delete one. +

+ The output stream is returned unclosed. +

+ @param original the signed data stream to be used as a base. + @param signerInformationStore the new signer information store to use. + @param out the stream to Write the new signed data object to. + @return out. +
+ + Replace the certificate and CRL information associated with this + CMSSignedData object with the new one passed in. +

+ The output stream is returned unclosed. +

+ @param original the signed data stream to be used as a base. + @param certsAndCrls the new certificates and CRLs to be used. + @param out the stream to Write the new signed data object to. + @return out. + @exception CmsException if there is an error processing the CertStore +
+ + General class for generating a pkcs7-signature message stream. +

+ A simple example of usage. +

+
+                  IX509Store                   certs...
+                  CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator();
+            
+                  gen.AddSigner(privateKey, cert, CmsSignedDataStreamGenerator.DIGEST_SHA1);
+            
+                  gen.AddCertificates(certs);
+            
+                  Stream sigOut = gen.Open(bOut);
+            
+                  sigOut.Write(Encoding.UTF8.GetBytes("Hello World!"));
+            
+                  sigOut.Close();
+             
+
+ + Constructor allowing specific source of randomness + Instance of SecureRandom to use. + + + Set the underlying string size for encapsulated data + + @param bufferSize length of octet strings to buffer the data. + + + add a signer - no attributes other than the default ones will be + provided here. + @throws NoSuchAlgorithmException + @throws InvalidKeyException + + + add a signer, specifying the digest encryption algorithm - no attributes other than the default ones will be + provided here. + @throws NoSuchProviderException + @throws NoSuchAlgorithmException + @throws InvalidKeyException + + + add a signer with extra signed/unsigned attributes. + @throws NoSuchAlgorithmException + @throws InvalidKeyException + + + add a signer with extra signed/unsigned attributes - specifying digest + encryption algorithm. + @throws NoSuchProviderException + @throws NoSuchAlgorithmException + @throws InvalidKeyException + + + add a signer - no attributes other than the default ones will be + provided here. + @throws NoSuchAlgorithmException + @throws InvalidKeyException + + + add a signer - no attributes other than the default ones will be + provided here. + @throws NoSuchProviderException + @throws NoSuchAlgorithmException + @throws InvalidKeyException + + + add a signer with extra signed/unsigned attributes. + @throws NoSuchAlgorithmException + @throws InvalidKeyException + + + generate a signed object that for a CMS Signed Data object + + + generate a signed object that for a CMS Signed Data + object - if encapsulate is true a copy + of the message will be included in the signature with the + default content type "data". + + + generate a signed object that for a CMS Signed Data + object using the given provider - if encapsulate is true a copy + of the message will be included in the signature with the + default content type "data". If dataOutputStream is non null the data + being signed will be written to the stream as it is processed. + @param out stream the CMS object is to be written to. + @param encapsulate true if data should be encapsulated. + @param dataOutputStream output stream to copy the data being signed to. + + + generate a signed object that for a CMS Signed Data + object - if encapsulate is true a copy + of the message will be included in the signature. The content type + is set according to the OID represented by the string signedContentType. + + + generate a signed object that for a CMS Signed Data + object using the given provider - if encapsulate is true a copy + of the message will be included in the signature. The content type + is set according to the OID represented by the string signedContentType. + @param out stream the CMS object is to be written to. + @param signedContentType OID for data to be signed. + @param encapsulate true if data should be encapsulated. + @param dataOutputStream output stream to copy the data being signed to. + + + Default type for the signed data. + + + Constructor allowing specific source of randomness + Instance of SecureRandom to use. + + + Add the attribute certificates contained in the passed in store to the + generator. + + @param store a store of Version 2 attribute certificates + @throws CmsException if an error occurse processing the store. + + + Add a store of precalculated signers to the generator. + + @param signerStore store of signers + + + Return a map of oids and byte arrays representing the digests calculated on the content during + the last generate. + + @return a map of oids (as String objects) and byte[] representing digests. + + + Return the digest algorithm using one of the standard JCA string + representations rather than the algorithm identifier (if possible). + + + Return the digest encryption algorithm using one of the standard + JCA string representations rather than the algorithm identifier (if + possible). + + + Default authenticated attributes generator. + + + Initialise to use all defaults + + + Initialise with some extra attributes or overrides. + + @param attributeTable initial attribute table to use. + + + Create a standard attribute table from the passed in parameters - this will + normally include contentType and messageDigest. If the constructor + using an AttributeTable was used, entries in it for contentType and + messageDigest will override the generated ones. + + @param parameters source parameters for table generation. + + @return a filled in IDictionary of attributes. + + + @param parameters source parameters + @return the populated attribute table + + + Default signed attributes generator. + + + Initialise to use all defaults + + + Initialise with some extra attributes or overrides. + + @param attributeTable initial attribute table to use. + + + Create a standard attribute table from the passed in parameters - this will + normally include contentType, signingTime, and messageDigest. If the constructor + using an AttributeTable was used, entries in it for contentType, signingTime, and + messageDigest will override the generated ones. + + @param parameters source parameters for table generation. + + @return a filled in Hashtable of attributes. + + + @param parameters source parameters + @return the populated attribute table + + + the RecipientInfo class for a recipient who has been sent a message + encrypted using a secret key known to the other side. + + + decrypt the content and return an input stream. + + + the RecipientInfo class for a recipient who has been sent a message + encrypted using key agreement. + + + decrypt the content and return an input stream. + + + the KeyTransRecipientInformation class for a recipient who has been sent a secret + key encrypted using their public key that needs to be used to + extract the message. + + + decrypt the content and return it as a byte array. + + + a basic index for an originator. + + + the RecipientInfo class for a recipient who has been sent a message + encrypted using a password. + + + return the object identifier for the key derivation algorithm, or null + if there is none present. + + @return OID for key derivation algorithm, if present. + + + decrypt the content and return an input stream. + + + + PKCS5 scheme-2 - password converted to bytes assuming ASCII. + + + + PKCS5 scheme-2 - password converted to bytes using UTF-8. + + + + Generate a RecipientInfo object for the given key. + + + A + + + A + + + A + + + + + * return the object identifier for the key encryption algorithm. + * + * @return OID for key encryption algorithm. + + + * return the ASN.1 encoded key encryption algorithm parameters, or null if + * there aren't any. + * + * @return ASN.1 encoding of key encryption algorithm parameters. + + + Return the MAC calculated for the content stream. Note: this call is only meaningful once all + the content has been read. + + @return byte array containing the mac. + + + Return the first RecipientInformation object that matches the + passed in selector. Null if there are no matches. + + @param selector to identify a recipient + @return a single RecipientInformation object. Null if none matches. + + + Return the number of recipients in the collection. + + @return number of recipients identified. + + + Return all recipients in the collection + + @return a collection of recipients. + + + Return possible empty collection with recipients matching the passed in RecipientID + + @param selector a recipient id to select against. + @return a collection of RecipientInformation objects. + + + a basic index for a signer. + + + an expanded SignerInfo block from a CMS Signed message + + + return the version number for this objects underlying SignerInfo structure. + + + return the object identifier for the signature. + + + return the signature parameters, or null if there aren't any. + + + return the content digest that was calculated during verification. + + + return the object identifier for the signature. + + + return the signature/encryption algorithm parameters, or null if + there aren't any. + + + return a table of the signed attributes - indexed by + the OID of the attribute. + + + return a table of the unsigned attributes indexed by + the OID of the attribute. + + + return the encoded signature + + + Return a SignerInformationStore containing the counter signatures attached to this + signer. If no counter signatures are present an empty store is returned. + + + return the DER encoding of the signed attributes. + @throws IOException if an encoding error occurs. + + + verify that the given public key successfully handles and confirms the + signature associated with this signer. + + + verify that the given certificate successfully handles and confirms + the signature associated with this signer and, if a signingTime + attribute is available, that the certificate was valid at the time the + signature was generated. + + + Return the base ASN.1 CMS structure that this object contains. + + @return an object containing a CMS SignerInfo structure. + + + Return a signer information object with the passed in unsigned + attributes replacing the ones that are current associated with + the object passed in. + + @param signerInformation the signerInfo to be used as the basis. + @param unsignedAttributes the unsigned attributes to add. + @return a copy of the original SignerInformationObject with the changed attributes. + + + Return a signer information object with passed in SignerInformationStore representing counter + signatures attached as an unsigned attribute. + + @param signerInformation the signerInfo to be used as the basis. + @param counterSigners signer info objects carrying counter signature. + @return a copy of the original SignerInformationObject with the changed attributes. + + + Return the first SignerInformation object that matches the + passed in selector. Null if there are no matches. + + @param selector to identify a signer + @return a single SignerInformation object. Null if none matches. + + + The number of signers in the collection. + + + An ICollection of all signers in the collection + + + Return possible empty collection with signers matching the passed in SignerID + + @param selector a signer id to select against. + @return a collection of SignerInformation objects. + + + Basic generator that just returns a preconstructed attribute table + + + a Diffie-Hellman key exchange engine. +

+ note: This uses MTI/A0 key agreement in order to make the key agreement + secure against passive attacks. If you're doing Diffie-Hellman and both + parties have long term public keys you should look at using this. For + further information have a look at RFC 2631.

+

+ It's possible to extend this to more than two parties as well, for the moment + that is left as an exercise for the reader.

+
+ + calculate our initial message. + + + given a message from a given party and the corresponding public key + calculate the next message in the agreement sequence. In this case + this will represent the shared secret. + + + a Diffie-Hellman key agreement class. +

+ note: This is only the basic algorithm, it doesn't take advantage of + long term public keys if they are available. See the DHAgreement class + for a "better" implementation.

+
+ + given a short term public key from a given party calculate the next + message in the agreement sequence. + + + P1363 7.2.1 ECSVDP-DH + + ECSVDP-DH is Elliptic Curve Secret Value Derivation Primitive, + Diffie-Hellman version. It is based on the work of [DH76], [Mil86], + and [Kob87]. This primitive derives a shared secret value from one + party's private key and another party's public key, where both have + the same set of EC domain parameters. If two parties correctly + execute this primitive, they will produce the same output. This + primitive can be invoked by a scheme to derive a shared secret key; + specifically, it may be used with the schemes ECKAS-DH1 and + DL/ECKAS-DH2. It assumes that the input keys are valid (see also + Section 7.2.2). + + + P1363 7.2.2 ECSVDP-DHC + + ECSVDP-DHC is Elliptic Curve Secret Value Derivation Primitive, + Diffie-Hellman version with cofactor multiplication. It is based on + the work of [DH76], [Mil86], [Kob87], [LMQ98] and [Kal98a]. This + primitive derives a shared secret value from one party's private key + and another party's public key, where both have the same set of EC + domain parameters. If two parties correctly execute this primitive, + they will produce the same output. This primitive can be invoked by a + scheme to derive a shared secret key; specifically, it may be used + with the schemes ECKAS-DH1 and DL/ECKAS-DH2. It does not assume the + validity of the input public key (see also Section 7.2.1). +

+ Note: As stated P1363 compatibility mode with ECDH can be preset, and + in this case the implementation doesn't have a ECDH compatibility mode + (if you want that just use ECDHBasicAgreement and note they both implement + BasicAgreement!).

+
+ + RFC 2631 Diffie-hellman KEK derivation function. + + + X9.63 based key derivation function for ECDH CMS. + + + Implements the client side SRP-6a protocol. Note that this class is stateful, and therefore NOT threadsafe. + This implementation of SRP is based on the optimized message sequence put forth by Thomas Wu in the paper + "SRP-6: Improvements and Refinements to the Secure Remote Password Protocol, 2002" + + + Initialises the client to begin new authentication attempt + @param N The safe prime associated with the client's verifier + @param g The group parameter associated with the client's verifier + @param digest The digest algorithm associated with the client's verifier + @param random For key generation + + + Generates client's credentials given the client's salt, identity and password + @param salt The salt used in the client's verifier. + @param identity The user's identity (eg. username) + @param password The user's password + @return Client's public value to send to server + + + Generates client's verification message given the server's credentials + @param serverB The server's credentials + @return Client's verification message for the server + @throws CryptoException If server's credentials are invalid + + + Implements the server side SRP-6a protocol. Note that this class is stateful, and therefore NOT threadsafe. + This implementation of SRP is based on the optimized message sequence put forth by Thomas Wu in the paper + "SRP-6: Improvements and Refinements to the Secure Remote Password Protocol, 2002" + + + Initialises the server to accept a new client authentication attempt + @param N The safe prime associated with the client's verifier + @param g The group parameter associated with the client's verifier + @param v The client's verifier + @param digest The digest algorithm associated with the client's verifier + @param random For key generation + + + Generates the server's credentials that are to be sent to the client. + @return The server's public value to the client + + + Processes the client's credentials. If valid the shared secret is generated and returned. + @param clientA The client's credentials + @return A shared secret BigInteger + @throws CryptoException If client's credentials are invalid + + + Generates new SRP verifier for user + + + Initialises generator to create new verifiers + @param N The safe prime to use (see DHParametersGenerator) + @param g The group parameter to use (see DHParametersGenerator) + @param digest The digest to use. The same digest type will need to be used later for the actual authentication + attempt. Also note that the final session key size is dependent on the chosen digest. + + + Creates a new SRP verifier + @param salt The salt to use, generally should be large and random + @param identity The user's identifying information (eg. username) + @param password The user's password + @return A new verifier for use in future SRP authentication + + + a holding class for public/private parameter pairs. + + + basic constructor. + + @param publicParam a public key parameters object. + @param privateParam the corresponding private key parameters. + + + return the public key parameters. + + @return the public key parameters. + + + return the private key parameters. + + @return the private key parameters. + + + The AEAD block ciphers already handle buffering internally, so this class + just takes care of implementing IBufferedCipher methods. + + + initialise the cipher. + + @param forEncryption if true the cipher is initialised for + encryption, if false for decryption. + @param param the key and other data required by the cipher. + @exception ArgumentException if the parameters argument is + inappropriate. + + + return the blocksize for the underlying cipher. + + @return the blocksize for the underlying cipher. + + + return the size of the output buffer required for an update + an input of len bytes. + + @param len the length of the input. + @return the space required to accommodate a call to update + with len bytes of input. + + + return the size of the output buffer required for an update plus a + doFinal with an input of len bytes. + + @param len the length of the input. + @return the space required to accommodate a call to update and doFinal + with len bytes of input. + + + process a single byte, producing an output block if neccessary. + + @param in the input byte. + @param out the space for any output that might be produced. + @param outOff the offset from which the output will be copied. + @return the number of output bytes copied to out. + @exception DataLengthException if there isn't enough space in out. + @exception InvalidOperationException if the cipher isn't initialised. + + + process an array of bytes, producing output if necessary. + + @param in the input byte array. + @param inOff the offset at which the input data starts. + @param len the number of bytes to be copied out of the input array. + @param out the space for any output that might be produced. + @param outOff the offset from which the output will be copied. + @return the number of output bytes copied to out. + @exception DataLengthException if there isn't enough space in out. + @exception InvalidOperationException if the cipher isn't initialised. + + + Process the last block in the buffer. + + @param out the array the block currently being held is copied into. + @param outOff the offset at which the copying starts. + @return the number of output bytes copied to out. + @exception DataLengthException if there is insufficient space in out for + the output, or the input is not block size aligned and should be. + @exception InvalidOperationException if the underlying cipher is not + initialised. + @exception InvalidCipherTextException if padding is expected and not found. + @exception DataLengthException if the input is not block size + aligned. + + + Reset the buffer and cipher. After resetting the object is in the same + state as it was after the last init (if there was one). + + + a buffer wrapper for an asymmetric block cipher, allowing input + to be accumulated in a piecemeal fashion until final processing. + + + base constructor. + + @param cipher the cipher this buffering object wraps. + + + return the amount of data sitting in the buffer. + + @return the amount of data sitting in the buffer. + + + initialise the buffer and the underlying cipher. + + @param forEncryption if true the cipher is initialised for + encryption, if false for decryption. + @param param the key and other data required by the cipher. + + + process the contents of the buffer using the underlying + cipher. + + @return the result of the encryption/decryption process on the + buffer. + @exception InvalidCipherTextException if we are given a garbage block. + + + Reset the buffer + + + A wrapper class that allows block ciphers to be used to process data in + a piecemeal fashion. The BufferedBlockCipher outputs a block only when the + buffer is full and more data is being added, or on a doFinal. +

+ Note: in the case where the underlying cipher is either a CFB cipher or an + OFB one the last block may not be a multiple of the block size. +

+
+ + constructor for subclasses + + + Create a buffered block cipher without padding. + + @param cipher the underlying block cipher this buffering object wraps. + false otherwise. + + + initialise the cipher. + + @param forEncryption if true the cipher is initialised for + encryption, if false for decryption. + @param param the key and other data required by the cipher. + @exception ArgumentException if the parameters argument is + inappropriate. + + + return the blocksize for the underlying cipher. + + @return the blocksize for the underlying cipher. + + + return the size of the output buffer required for an update + an input of len bytes. + + @param len the length of the input. + @return the space required to accommodate a call to update + with len bytes of input. + + + return the size of the output buffer required for an update plus a + doFinal with an input of len bytes. + + @param len the length of the input. + @return the space required to accommodate a call to update and doFinal + with len bytes of input. + + + process a single byte, producing an output block if neccessary. + + @param in the input byte. + @param out the space for any output that might be produced. + @param outOff the offset from which the output will be copied. + @return the number of output bytes copied to out. + @exception DataLengthException if there isn't enough space in out. + @exception InvalidOperationException if the cipher isn't initialised. + + + process an array of bytes, producing output if necessary. + + @param in the input byte array. + @param inOff the offset at which the input data starts. + @param len the number of bytes to be copied out of the input array. + @param out the space for any output that might be produced. + @param outOff the offset from which the output will be copied. + @return the number of output bytes copied to out. + @exception DataLengthException if there isn't enough space in out. + @exception InvalidOperationException if the cipher isn't initialised. + + + Process the last block in the buffer. + + @param out the array the block currently being held is copied into. + @param outOff the offset at which the copying starts. + @return the number of output bytes copied to out. + @exception DataLengthException if there is insufficient space in out for + the output, or the input is not block size aligned and should be. + @exception InvalidOperationException if the underlying cipher is not + initialised. + @exception InvalidCipherTextException if padding is expected and not found. + @exception DataLengthException if the input is not block size + aligned. + + + Reset the buffer and cipher. After resetting the object is in the same + state as it was after the last init (if there was one). + + + The base class for symmetric, or secret, cipher key generators. + + + initialise the key generator. + + @param param the parameters to be used for key generation + + + Generate a secret key. + + @return a byte array containing the key value. + + + this exception is thrown if a buffer that is meant to have output + copied into it turns out to be too short, or if we've been given + insufficient input. In general this exception will Get thrown rather + than an ArrayOutOfBounds exception. + + + base constructor. + + + create a DataLengthException with the given message. + + @param message the message to be carried with the exception. + + + base implementation of MD4 family style digest as outlined in + "Handbook of Applied Cryptography", pages 344 - 347. + + + implementation of GOST R 34.11-94 + + + Standard constructor + + + Constructor to allow use of a particular sbox with GOST28147 + @see GOST28147Engine#getSBox(String) + + + Copy constructor. This will copy the state of the provided + message digest. + + + reset the chaining variables to the IV values. + + + Base class for SHA-384 and SHA-512. + + + Constructor for variable length word + + + Copy constructor. We are using copy constructors in place + of the object.Clone() interface as this interface is not + supported by J2ME. + + + adjust the byte counts so that byteCount2 represents the + upper long (less 3 bits) word of the byte count. + + + implementation of MD2 + as outlined in RFC1319 by B.Kaliski from RSA Laboratories April 1992 + + + return the algorithm name + + @return the algorithm name + + + Close the digest, producing the final digest value. The doFinal + call leaves the digest reset. + + @param out the array the digest is to be copied into. + @param outOff the offset into the out array the digest is to start at. + + + reset the digest back to it's initial state. + + + update the message digest with a single byte. + + @param in the input byte to be entered. + + + update the message digest with a block of bytes. + + @param in the byte array containing the data. + @param inOff the offset into the byte array where the data starts. + @param len the length of the data. + + + implementation of MD4 as RFC 1320 by R. Rivest, MIT Laboratory for + Computer Science and RSA Data Security, Inc. +

+ NOTE: This algorithm is only included for backwards compatibility + with legacy applications, it's not secure, don't use it for anything new!

+
+ + Standard constructor + + + Copy constructor. This will copy the state of the provided + message digest. + + + reset the chaining variables to the IV values. + + + implementation of MD5 as outlined in "Handbook of Applied Cryptography", pages 346 - 347. + + + Copy constructor. This will copy the state of the provided + message digest. + + + reset the chaining variables to the IV values. + + + implementation of RipeMD128 + + + Standard constructor + + + Copy constructor. This will copy the state of the provided + message digest. + + + reset the chaining variables to the IV values. + + + implementation of RipeMD see, + http://www.esat.kuleuven.ac.be/~bosselae/ripemd160.html + + + Standard constructor + + + Copy constructor. This will copy the state of the provided + message digest. + + + reset the chaining variables to the IV values. + + + +

Implementation of RipeMD256.

+

Note: this algorithm offers the same level of security as RipeMD128.

+
+
+ + Standard constructor + + + Copy constructor. This will copy the state of the provided + message digest. + + + + reset the chaining variables to the IV values. + + + +

Implementation of RipeMD 320.

+

Note: this algorithm offers the same level of security as RipeMD160.

+
+
+ + Standard constructor + + + Copy constructor. This will copy the state of the provided + message digest. + + + + reset the chaining variables to the IV values. + + + implementation of SHA-1 as outlined in "Handbook of Applied Cryptography", pages 346 - 349. + + It is interesting to ponder why the, apart from the extra IV, the other difference here from MD5 + is the "endienness" of the word processing! + + + Copy constructor. This will copy the state of the provided + message digest. + + + reset the chaining variables + + + SHA-224 as described in RFC 3874 +
+                    block  word  digest
+            SHA-1   512    32    160
+            SHA-224 512    32    224
+            SHA-256 512    32    256
+            SHA-384 1024   64    384
+            SHA-512 1024   64    512
+            
+
+ + Standard constructor + + + Copy constructor. This will copy the state of the provided + message digest. + + + reset the chaining variables + + + Draft FIPS 180-2 implementation of SHA-256. Note: As this is + based on a draft this implementation is subject to change. + +
+                     block  word  digest
+             SHA-1   512    32    160
+             SHA-256 512    32    256
+             SHA-384 1024   64    384
+             SHA-512 1024   64    512
+             
+
+ + Copy constructor. This will copy the state of the provided + message digest. + + + reset the chaining variables + + + Draft FIPS 180-2 implementation of SHA-384. Note: As this is + based on a draft this implementation is subject to change. + +
+                     block  word  digest
+             SHA-1   512    32    160
+             SHA-256 512    32    256
+             SHA-384 1024   64    384
+             SHA-512 1024   64    512
+             
+
+ + Copy constructor. This will copy the state of the provided + message digest. + + + reset the chaining variables + + + Draft FIPS 180-2 implementation of SHA-512. Note: As this is + based on a draft this implementation is subject to change. + +
+                     block  word  digest
+             SHA-1   512    32    160
+             SHA-256 512    32    256
+             SHA-384 1024   64    384
+             SHA-512 1024   64    512
+             
+
+ + Copy constructor. This will copy the state of the provided + message digest. + + + reset the chaining variables + + + Wrapper class that reduces the output length of a particular digest to + only the first n bytes of the digest function. + + + Base constructor. + + @param baseDigest underlying digest to use. + @param length length in bytes of the output of doFinal. + @exception ArgumentException if baseDigest is null, or length is greater than baseDigest.GetDigestSize(). + + + implementation of Tiger based on: + + http://www.cs.technion.ac.il/~biham/Reports/Tiger + + + Standard constructor + + + Copy constructor. This will copy the state of the provided + message digest. + + + reset the chaining variables + + + Implementation of WhirlpoolDigest, based on Java source published by Barreto + and Rijmen. + + + + Copy constructor. This will copy the state of the provided message + digest. + + + Reset the chaining variables + + + ISO 9796-1 padding. Note in the light of recent results you should + only use this with RSA (rather than the "simpler" Rabin keys) and you + should never use it with anything other than a hash (ie. even if the + message is small don't sign the message, sign it's hash) or some "random" + value. See your favorite search engine for details. + + + return the input block size. The largest message we can process + is (key_size_in_bits + 3)/16, which in our world comes to + key_size_in_bytes / 2. + + + return the maximum possible size for the output. + + + set the number of bits in the next message to be treated as + pad bits. + + + retrieve the number of pad bits in the last decoded message. + + + @exception InvalidCipherTextException if the decrypted block is not a valid ISO 9796 bit string + + + Optimal Asymmetric Encryption Padding (OAEP) - see PKCS 1 V 2. + + + @exception InvalidCipherTextException if the decrypted block turns out to + be badly formatted. + + + int to octet string. + + + mask generator function, as described in PKCS1v2. + + + this does your basic Pkcs 1 v1.5 padding - whether or not you should be using this + depends on your application - see Pkcs1 Version 2 for details. + + + some providers fail to include the leading zero in PKCS1 encoded blocks. If you need to + work with one of these set the system property Org.BouncyCastle.Pkcs1.Strict to false. + + + The same effect can be achieved by setting the static property directly +

+ The static property is checked during construction of the encoding object, it is set to + true by default. +

+
+ + Basic constructor. + @param cipher + + + @exception InvalidCipherTextException if the decrypted block is not in Pkcs1 format. + + + an implementation of the AES (Rijndael), from FIPS-197. +

+ For further details see: http://csrc.nist.gov/encryption/aes/. + + This implementation is based on optimizations from Dr. Brian Gladman's paper and C code at + http://fp.gladman.plus.com/cryptography_technology/rijndael/ + + There are three levels of tradeoff of speed vs memory + Because java has no preprocessor, they are written as three separate classes from which to choose + + The fastest uses 8Kbytes of static tables to precompute round calculations, 4 256 word tables for encryption + and 4 for decryption. + + The middle performance version uses only one 256 word table for each, for a total of 2Kbytes, + adding 12 rotate operations per round to compute the values contained in the other tables from + the contents of the first. + + The slowest version uses no static tables at all and computes the values in each round. +

+

+ This file contains the middle performance version with 2Kbytes of static tables for round precomputation. +

+
+ + Calculate the necessary round keys + The number of calculations depends on key size and block size + AES specified a fixed block size of 128 bits and key sizes 128/192/256 bits + This code is written assuming those are the only possible values + + + default constructor - 128 bit block size. + + + initialise an AES cipher. + + @param forEncryption whether or not we are for encryption. + @param parameters the parameters required to set up the cipher. + @exception ArgumentException if the parameters argument is + inappropriate. + + + an implementation of the AES (Rijndael)), from FIPS-197. +

+ For further details see: http://csrc.nist.gov/encryption/aes/. + + This implementation is based on optimizations from Dr. Brian Gladman's paper and C code at + http://fp.gladman.plus.com/cryptography_technology/rijndael/ + + There are three levels of tradeoff of speed vs memory + Because java has no preprocessor), they are written as three separate classes from which to choose + + The fastest uses 8Kbytes of static tables to precompute round calculations), 4 256 word tables for encryption + and 4 for decryption. + + The middle performance version uses only one 256 word table for each), for a total of 2Kbytes), + adding 12 rotate operations per round to compute the values contained in the other tables from + the contents of the first + + The slowest version uses no static tables at all and computes the values in each round +

+

+ This file contains the fast version with 8Kbytes of static tables for round precomputation +

+
+ + Calculate the necessary round keys + The number of calculations depends on key size and block size + AES specified a fixed block size of 128 bits and key sizes 128/192/256 bits + This code is written assuming those are the only possible values + + + default constructor - 128 bit block size. + + + initialise an AES cipher. + + @param forEncryption whether or not we are for encryption. + @param parameters the parameters required to set up the cipher. + @exception ArgumentException if the parameters argument is + inappropriate. + + + an implementation of the AES (Rijndael), from FIPS-197. +

+ For further details see: http://csrc.nist.gov/encryption/aes/. + + This implementation is based on optimizations from Dr. Brian Gladman's paper and C code at + http://fp.gladman.plus.com/cryptography_technology/rijndael/ + + There are three levels of tradeoff of speed vs memory + Because java has no preprocessor, they are written as three separate classes from which to choose + + The fastest uses 8Kbytes of static tables to precompute round calculations, 4 256 word tables for encryption + and 4 for decryption. + + The middle performance version uses only one 256 word table for each, for a total of 2Kbytes, + adding 12 rotate operations per round to compute the values contained in the other tables from + the contents of the first + + The slowest version uses no static tables at all and computes the values + in each round. +

+

+ This file contains the slowest performance version with no static tables + for round precomputation, but it has the smallest foot print. +

+
+ + Calculate the necessary round keys + The number of calculations depends on key size and block size + AES specified a fixed block size of 128 bits and key sizes 128/192/256 bits + This code is written assuming those are the only possible values + + + default constructor - 128 bit block size. + + + initialise an AES cipher. + + @param forEncryption whether or not we are for encryption. + @param parameters the parameters required to set up the cipher. + @exception ArgumentException if the parameters argument is + inappropriate. + + + + An implementation of the AES Key Wrapper from the NIST Key Wrap Specification. +

+ For further details see: http://csrc.nist.gov/encryption/kms/key-wrap.pdf. + + + + A class that provides Blowfish key encryption operations, + such as encoding data and generating keys. + All the algorithms herein are from Applied Cryptography + and implement a simplified cryptography interface. + + + initialise a Blowfish cipher. + + @param forEncryption whether or not we are for encryption. + @param parameters the parameters required to set up the cipher. + @exception ArgumentException if the parameters argument is + inappropriate. + + + apply the encryption cycle to each value pair in the table. + + + Encrypt the given input starting at the given offset and place + the result in the provided buffer starting at the given offset. + The input will be an exact multiple of our blocksize. + + + Decrypt the given input starting at the given offset and place + the result in the provided buffer starting at the given offset. + The input will be an exact multiple of our blocksize. + + + Camellia - based on RFC 3713. + + + Camellia - based on RFC 3713, smaller implementation, about half the size of CamelliaEngine. + + + + An implementation of the Camellia key wrapper based on RFC 3657/RFC 3394. +

+ For further details see: http://www.ietf.org/rfc/rfc3657.txt. + + + + A class that provides CAST key encryption operations, + such as encoding data and generating keys. + + All the algorithms herein are from the Internet RFC's + + RFC2144 - Cast5 (64bit block, 40-128bit key) + RFC2612 - CAST6 (128bit block, 128-256bit key) + + and implement a simplified cryptography interface. + + + initialise a CAST cipher. + + @param forEncryption whether or not we are for encryption. + @param parameters the parameters required to set up the cipher. + @exception ArgumentException if the parameters argument is + inappropriate. + + + Encrypt the given input starting at the given offset and place + the result in the provided buffer starting at the given offset. + + @param src The plaintext buffer + @param srcIndex An offset into src + @param dst The ciphertext buffer + @param dstIndex An offset into dst + + + Decrypt the given input starting at the given offset and place + the result in the provided buffer starting at the given offset. + + @param src The plaintext buffer + @param srcIndex An offset into src + @param dst The ciphertext buffer + @param dstIndex An offset into dst + + + The first of the three processing functions for the + encryption and decryption. + + @param D the input to be processed + @param Kmi the mask to be used from Km[n] + @param Kri the rotation value to be used + + + + The second of the three processing functions for the + encryption and decryption. + + @param D the input to be processed + @param Kmi the mask to be used from Km[n] + @param Kri the rotation value to be used + + + + The third of the three processing functions for the + encryption and decryption. + + @param D the input to be processed + @param Kmi the mask to be used from Km[n] + @param Kri the rotation value to be used + + + + Does the 16 rounds to encrypt the block. + + @param L0 the LH-32bits of the plaintext block + @param R0 the RH-32bits of the plaintext block + + + A class that provides CAST6 key encryption operations, + such as encoding data and generating keys. + + All the algorithms herein are from the Internet RFC + + RFC2612 - CAST6 (128bit block, 128-256bit key) + + and implement a simplified cryptography interface. + + + Encrypt the given input starting at the given offset and place + the result in the provided buffer starting at the given offset. + + @param src The plaintext buffer + @param srcIndex An offset into src + @param dst The ciphertext buffer + @param dstIndex An offset into dst + + + Decrypt the given input starting at the given offset and place + the result in the provided buffer starting at the given offset. + + @param src The plaintext buffer + @param srcIndex An offset into src + @param dst The ciphertext buffer + @param dstIndex An offset into dst + + + Does the 12 quad rounds rounds to encrypt the block. + + @param A the 00-31 bits of the plaintext block + @param B the 32-63 bits of the plaintext block + @param C the 64-95 bits of the plaintext block + @param D the 96-127 bits of the plaintext block + @param result the resulting ciphertext + + + Does the 12 quad rounds rounds to decrypt the block. + + @param A the 00-31 bits of the ciphertext block + @param B the 32-63 bits of the ciphertext block + @param C the 64-95 bits of the ciphertext block + @param D the 96-127 bits of the ciphertext block + @param result the resulting plaintext + + + A class that provides a basic DESede (or Triple DES) engine. + + + initialise a DESede cipher. + + @param forEncryption whether or not we are for encryption. + @param parameters the parameters required to set up the cipher. + @exception ArgumentException if the parameters argument is + inappropriate. + + + * Wrap keys according to + * + * draft-ietf-smime-key-wrap-01.txt. + *

+ * Note: + *

    + *
  • this is based on a draft, and as such is subject to change - don't use this class for anything requiring long term storage.
  • + *
  • if you are using this to wrap triple-des keys you need to set the + * parity bits on the key and, if it's a two-key triple-des key, pad it + * yourself.
  • + *
+ *

+
+ + Field engine + + + Field param + + + Field paramPlusIV + + + Field iv + + + Field forWrapping + + + Field IV2 + + + Method init + + @param forWrapping + @param param + + + Method GetAlgorithmName + + @return + + + Method wrap + + @param in + @param inOff + @param inLen + @return + + + Method unwrap + + @param in + @param inOff + @param inLen + @return + @throws InvalidCipherTextException + + + Some key wrap algorithms make use of the Key Checksum defined + in CMS [CMS-Algorithms]. This is used to provide an integrity + check value for the key being wrapped. The algorithm is + + - Compute the 20 octet SHA-1 hash on the key being wrapped. + - Use the first 8 octets of this hash as the checksum value. + + @param key + @return + @throws Exception + @see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum + + + @param key + @param checksum + @return + @see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum + + + A class that provides a basic DES engine. + + + initialise a DES cipher. + + @param forEncryption whether or not we are for encryption. + @param parameters the parameters required to set up the cipher. + @exception ArgumentException if the parameters argument is + inappropriate. + + + what follows is mainly taken from "Applied Cryptography", by + Bruce Schneier, however it also bears great resemblance to Richard + Outerbridge's D3DES... + + + Generate an integer based working key based on our secret key + and what we processing we are planning to do. + + Acknowledgements for this routine go to James Gillogly and Phil Karn. + (whoever, and wherever they are!). + + + the DES engine. + + + this does your basic ElGamal algorithm. + + + initialise the ElGamal engine. + + @param forEncryption true if we are encrypting, false otherwise. + @param param the necessary ElGamal key parameters. + + + Return the maximum size for an input block to this engine. + For ElGamal this is always one byte less than the size of P on + encryption, and twice the length as the size of P on decryption. + + @return maximum size for an input block. + + + Return the maximum size for an output block to this engine. + For ElGamal this is always one byte less than the size of P on + decryption, and twice the length as the size of P on encryption. + + @return maximum size for an output block. + + + Process a single block using the basic ElGamal algorithm. + + @param in the input array. + @param inOff the offset into the input buffer where the data starts. + @param length the length of the data to be processed. + @return the result of the ElGamal process. + @exception DataLengthException the input block is too large. + + + implementation of GOST 28147-89 + + + standard constructor. + + + initialise an Gost28147 cipher. + + @param forEncryption whether or not we are for encryption. + @param parameters the parameters required to set up the cipher. + @exception ArgumentException if the parameters argument is inappropriate. + + + Return the S-Box associated with SBoxName + @param sBoxName name of the S-Box + @return byte array representing the S-Box + + + HC-128 is a software-efficient stream cipher created by Hongjun Wu. It + generates keystream from a 128-bit secret key and a 128-bit initialization + vector. +

+ http://www.ecrypt.eu.org/stream/p3ciphers/hc/hc128_p3.pdf +

+ It is a third phase candidate in the eStream contest, and is patent-free. + No attacks are known as of today (April 2007). See + + http://www.ecrypt.eu.org/stream/hcp3.html +

+
+ + Initialise a HC-128 cipher. + + @param forEncryption whether or not we are for encryption. Irrelevant, as + encryption and decryption are the same. + @param params the parameters required to set up the cipher. + @throws ArgumentException if the params argument is + inappropriate (ie. the key is not 128 bit long). + + + HC-256 is a software-efficient stream cipher created by Hongjun Wu. It + generates keystream from a 256-bit secret key and a 256-bit initialization + vector. +

+ http://www.ecrypt.eu.org/stream/p3ciphers/hc/hc256_p3.pdf +

+ Its brother, HC-128, is a third phase candidate in the eStream contest. + The algorithm is patent-free. No attacks are known as of today (April 2007). + See + + http://www.ecrypt.eu.org/stream/hcp3.html +

+
+ + Initialise a HC-256 cipher. + + @param forEncryption whether or not we are for encryption. Irrelevant, as + encryption and decryption are the same. + @param params the parameters required to set up the cipher. + @throws ArgumentException if the params argument is + inappropriate (ie. the key is not 256 bit long). + + + support class for constructing intergrated encryption ciphers + for doing basic message exchanges on top of key agreement ciphers + + + set up for use with stream mode, where the key derivation function + is used to provide a stream of bytes to xor with the message. + + @param agree the key agreement used as the basis for the encryption + @param kdf the key derivation function used for byte generation + @param mac the message authentication code generator for the message + + + set up for use in conjunction with a block cipher to handle the + message. + + @param agree the key agreement used as the basis for the encryption + @param kdf the key derivation function used for byte generation + @param mac the message authentication code generator for the message + @param cipher the cipher to used for encrypting the message + + + Initialise the encryptor. + + @param forEncryption whether or not this is encryption/decryption. + @param privParam our private key parameters + @param pubParam the recipient's/sender's public key parameters + @param param encoding and derivation parameters. + + + Implementation of Bob Jenkin's ISAAC (Indirection Shift Accumulate Add and Count). + see: http://www.burtleburtle.net/bob/rand/isaacafa.html + + + initialise an ISAAC cipher. + + @param forEncryption whether or not we are for encryption. + @param params the parameters required to set up the cipher. + @exception ArgumentException if the params argument is + inappropriate. + + + NaccacheStern Engine. For details on this cipher, please see + http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf + + + Initializes this algorithm. Must be called before all other Functions. + + @see org.bouncycastle.crypto.AsymmetricBlockCipher#init(bool, + org.bouncycastle.crypto.CipherParameters) + + + Returns the input block size of this algorithm. + + @see org.bouncycastle.crypto.AsymmetricBlockCipher#GetInputBlockSize() + + + Returns the output block size of this algorithm. + + @see org.bouncycastle.crypto.AsymmetricBlockCipher#GetOutputBlockSize() + + + Process a single Block using the Naccache-Stern algorithm. + + @see org.bouncycastle.crypto.AsymmetricBlockCipher#ProcessBlock(byte[], + int, int) + + + Encrypts a BigInteger aka Plaintext with the public key. + + @param plain + The BigInteger to encrypt + @return The byte[] representation of the encrypted BigInteger (i.e. + crypted.toByteArray()) + + + Adds the contents of two encrypted blocks mod sigma + + @param block1 + the first encrypted block + @param block2 + the second encrypted block + @return encrypt((block1 + block2) mod sigma) + @throws InvalidCipherTextException + + + Convenience Method for data exchange with the cipher. + + Determines blocksize and splits data to blocksize. + + @param data the data to be processed + @return the data after it went through the NaccacheSternEngine. + @throws InvalidCipherTextException + + + Computes the integer x that is expressed through the given primes and the + congruences with the chinese remainder theorem (CRT). + + @param congruences + the congruences c_i + @param primes + the primes p_i + @return an integer x for that x % p_i == c_i + + + A Noekeon engine, using direct-key mode. + + + Create an instance of the Noekeon encryption algorithm + and set some defaults + + + initialise + + @param forEncryption whether or not we are for encryption. + @param params the parameters required to set up the cipher. + @exception ArgumentException if the params argument is + inappropriate. + + + Re-key the cipher. + + @param key the key to be used + + + The no-op engine that just copies bytes through, irrespective of whether encrypting and decrypting. + Provided for the sake of completeness. + + + an implementation of RC2 as described in RFC 2268 + "A Description of the RC2(r) Encryption Algorithm" R. Rivest. + + + initialise a RC2 cipher. + + @param forEncryption whether or not we are for encryption. + @param parameters the parameters required to set up the cipher. + @exception ArgumentException if the parameters argument is + inappropriate. + + + return the result rotating the 16 bit number in x left by y + + + Wrap keys according to RFC 3217 - RC2 mechanism + + + Field engine + + + Field param + + + Field paramPlusIV + + + Field iv + + + Field forWrapping + + + Field IV2 + + + Method init + + @param forWrapping + @param param + + + Method GetAlgorithmName + + @return + + + Method wrap + + @param in + @param inOff + @param inLen + @return + + + Method unwrap + + @param in + @param inOff + @param inLen + @return + @throws InvalidCipherTextException + + + Some key wrap algorithms make use of the Key Checksum defined + in CMS [CMS-Algorithms]. This is used to provide an integrity + check value for the key being wrapped. The algorithm is + + - Compute the 20 octet SHA-1 hash on the key being wrapped. + - Use the first 8 octets of this hash as the checksum value. + + @param key + @return + @throws Exception + @see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum + + + @param key + @param checksum + @return + @see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum + + + initialise a RC4 cipher. + + @param forEncryption whether or not we are for encryption. + @param parameters the parameters required to set up the cipher. + @exception ArgumentException if the parameters argument is + inappropriate. + + + The specification for RC5 came from the RC5 Encryption Algorithm + publication in RSA CryptoBytes, Spring of 1995. + http://www.rsasecurity.com/rsalabs/cryptobytes. +

+ This implementation has a word size of 32 bits.

+
+ + Create an instance of the RC5 encryption algorithm + and set some defaults + + + initialise a RC5-32 cipher. + + @param forEncryption whether or not we are for encryption. + @param parameters the parameters required to set up the cipher. + @exception ArgumentException if the parameters argument is + inappropriate. + + + Re-key the cipher. + + @param key the key to be used + + + Encrypt the given block starting at the given offset and place + the result in the provided buffer starting at the given offset. + + @param in in byte buffer containing data to encrypt + @param inOff offset into src buffer + @param out out buffer where encrypted data is written + @param outOff offset into out buffer + + + Perform a left "spin" of the word. The rotation of the given + word x is rotated left by y bits. + Only the lg(32) low-order bits of y + are used to determine the rotation amount. Here it is + assumed that the wordsize used is a power of 2. + + @param x word to rotate + @param y number of bits to rotate % 32 + + + Perform a right "spin" of the word. The rotation of the given + word x is rotated left by y bits. + Only the lg(32) low-order bits of y + are used to determine the rotation amount. Here it is + assumed that the wordsize used is a power of 2. + + @param x word to rotate + @param y number of bits to rotate % 32 + + + The specification for RC5 came from the RC5 Encryption Algorithm + publication in RSA CryptoBytes, Spring of 1995. + http://www.rsasecurity.com/rsalabs/cryptobytes. +

+ This implementation is set to work with a 64 bit word size.

+
+ + Create an instance of the RC5 encryption algorithm + and set some defaults + + + initialise a RC5-64 cipher. + + @param forEncryption whether or not we are for encryption. + @param parameters the parameters required to set up the cipher. + @exception ArgumentException if the parameters argument is + inappropriate. + + + Re-key the cipher. + + @param key the key to be used + + + Encrypt the given block starting at the given offset and place + the result in the provided buffer starting at the given offset. + + @param in in byte buffer containing data to encrypt + @param inOff offset into src buffer + @param out out buffer where encrypted data is written + @param outOff offset into out buffer + + + Perform a left "spin" of the word. The rotation of the given + word x is rotated left by y bits. + Only the lg(wordSize) low-order bits of y + are used to determine the rotation amount. Here it is + assumed that the wordsize used is a power of 2. + + @param x word to rotate + @param y number of bits to rotate % wordSize + + + Perform a right "spin" of the word. The rotation of the given + word x is rotated left by y bits. + Only the lg(wordSize) low-order bits of y + are used to determine the rotation amount. Here it is + assumed that the wordsize used is a power of 2. + + @param x word to rotate + @param y number of bits to rotate % wordSize + + + An RC6 engine. + + + Create an instance of the RC6 encryption algorithm + and set some defaults + + + initialise a RC5-32 cipher. + + @param forEncryption whether or not we are for encryption. + @param parameters the parameters required to set up the cipher. + @exception ArgumentException if the parameters argument is + inappropriate. + + + Re-key the cipher. + + @param inKey the key to be used + + + Perform a left "spin" of the word. The rotation of the given + word x is rotated left by y bits. + Only the lg(wordSize) low-order bits of y + are used to determine the rotation amount. Here it is + assumed that the wordsize used is a power of 2. + + @param x word to rotate + @param y number of bits to rotate % wordSize + + + Perform a right "spin" of the word. The rotation of the given + word x is rotated left by y bits. + Only the lg(wordSize) low-order bits of y + are used to determine the rotation amount. Here it is + assumed that the wordsize used is a power of 2. + + @param x word to rotate + @param y number of bits to rotate % wordSize + + + an implementation of the RFC 3211 Key Wrap + Specification. + + + + An implementation of the AES Key Wrapper from the NIST Key Wrap + Specification as described in RFC 3394. +

+ For further details see: http://www.ietf.org/rfc/rfc3394.txt + and http://csrc.nist.gov/encryption/kms/key-wrap.pdf. + + + + an implementation of Rijndael, based on the documentation and reference implementation + by Paulo Barreto, Vincent Rijmen, for v2.0 August '99. +

+ Note: this implementation is based on information prior to readonly NIST publication. +

+
+ + multiply two elements of GF(2^m) + needed for MixColumn and InvMixColumn + + + xor corresponding text input and round key input bytes + + + Row 0 remains unchanged + The other three rows are shifted a variable amount + + + Replace every byte of the input by the byte at that place + in the nonlinear S-box + + + Mix the bytes of every column in a linear way + + + Mix the bytes of every column in a linear way + This is the opposite operation of Mixcolumn + + + Calculate the necessary round keys + The number of calculations depends on keyBits and blockBits + + + default constructor - 128 bit block size. + + + basic constructor - set the cipher up for a given blocksize + + @param blocksize the blocksize in bits, must be 128, 192, or 256. + + + initialise a Rijndael cipher. + + @param forEncryption whether or not we are for encryption. + @param parameters the parameters required to set up the cipher. + @exception ArgumentException if the parameters argument is + inappropriate. + + + this does your basic RSA algorithm with blinding + + + initialise the RSA engine. + + @param forEncryption true if we are encrypting, false otherwise. + @param param the necessary RSA key parameters. + + + Return the maximum size for an input block to this engine. + For RSA this is always one byte less than the key size on + encryption, and the same length as the key size on decryption. + + @return maximum size for an input block. + + + Return the maximum size for an output block to this engine. + For RSA this is always one byte less than the key size on + decryption, and the same length as the key size on encryption. + + @return maximum size for an output block. + + + Process a single block using the basic RSA algorithm. + + @param inBuf the input array. + @param inOff the offset into the input buffer where the data starts. + @param inLen the length of the data to be processed. + @return the result of the RSA process. + @exception DataLengthException the input block is too large. + + + This does your basic RSA Chaum's blinding and unblinding as outlined in + "Handbook of Applied Cryptography", page 475. You need to use this if you are + trying to get another party to generate signatures without them being aware + of the message they are signing. + + + Initialise the blinding engine. + + @param forEncryption true if we are encrypting (blinding), false otherwise. + @param param the necessary RSA key parameters. + + + Return the maximum size for an input block to this engine. + For RSA this is always one byte less than the key size on + encryption, and the same length as the key size on decryption. + + @return maximum size for an input block. + + + Return the maximum size for an output block to this engine. + For RSA this is always one byte less than the key size on + decryption, and the same length as the key size on encryption. + + @return maximum size for an output block. + + + Process a single block using the RSA blinding algorithm. + + @param in the input array. + @param inOff the offset into the input buffer where the data starts. + @param inLen the length of the data to be processed. + @return the result of the RSA process. + @throws DataLengthException the input block is too large. + + + this does your basic RSA algorithm. + + + initialise the RSA engine. + + @param forEncryption true if we are encrypting, false otherwise. + @param param the necessary RSA key parameters. + + + Return the maximum size for an input block to this engine. + For RSA this is always one byte less than the key size on + encryption, and the same length as the key size on decryption. + + @return maximum size for an input block. + + + Return the maximum size for an output block to this engine. + For RSA this is always one byte less than the key size on + decryption, and the same length as the key size on encryption. + + @return maximum size for an output block. + + + this does your basic RSA algorithm. + + + initialise the RSA engine. + + @param forEncryption true if we are encrypting, false otherwise. + @param param the necessary RSA key parameters. + + + Return the maximum size for an input block to this engine. + For RSA this is always one byte less than the key size on + encryption, and the same length as the key size on decryption. + + @return maximum size for an input block. + + + Return the maximum size for an output block to this engine. + For RSA this is always one byte less than the key size on + decryption, and the same length as the key size on encryption. + + @return maximum size for an output block. + + + Process a single block using the basic RSA algorithm. + + @param inBuf the input array. + @param inOff the offset into the input buffer where the data starts. + @param inLen the length of the data to be processed. + @return the result of the RSA process. + @exception DataLengthException the input block is too large. + + + Implementation of Daniel J. Bernstein's Salsa20 stream cipher, Snuffle 2005 + + + Constants + + + initialise a Salsa20 cipher. + + @param forEncryption whether or not we are for encryption. + @param params the parameters required to set up the cipher. + @exception ArgumentException if the params argument is + inappropriate. + + + Implementation of the SEED algorithm as described in RFC 4009 + + + + An implementation of the SEED key wrapper based on RFC 4010/RFC 3394. +

+ For further details see: http://www.ietf.org/rfc/rfc4010.txt. + + + + * Serpent is a 128-bit 32-round block cipher with variable key lengths, + * including 128, 192 and 256 bit keys conjectured to be at least as + * secure as three-key triple-DES. + *

+ * Serpent was designed by Ross Anderson, Eli Biham and Lars Knudsen as a + * candidate algorithm for the NIST AES Quest.> + *

+ *

+ * For full details see the The Serpent home page + *

+
+ + initialise a Serpent cipher. + + @param forEncryption whether or not we are for encryption. + @param parameters the parameters required to set up the cipher. + @exception ArgumentException if the parameters argument is + inappropriate. + + + Process one block of input from the array in and write it to + the out array. + + @param in the array containing the input data. + @param inOff offset into the in array the data starts at. + @param out the array the output data will be copied into. + @param outOff the offset into the out array the output will start at. + @exception DataLengthException if there isn't enough data in in, or + space in out. + @exception InvalidOperationException if the cipher isn't initialised. + @return the number of bytes processed and produced. + + + Expand a user-supplied key material into a session key. + + @param key The user-key bytes (multiples of 4) to use. + @exception ArgumentException + + + Encrypt one block of plaintext. + + @param in the array containing the input data. + @param inOff offset into the in array the data starts at. + @param out the array the output data will be copied into. + @param outOff the offset into the out array the output will start at. + + + Decrypt one block of ciphertext. + + @param in the array containing the input data. + @param inOff offset into the in array the data starts at. + @param out the array the output data will be copied into. + @param outOff the offset into the out array the output will start at. + + + S0 - { 3, 8,15, 1,10, 6, 5,11,14,13, 4, 2, 7, 0, 9,12 } - 15 terms. + + + InvSO - {13, 3,11, 0,10, 6, 5,12, 1,14, 4, 7,15, 9, 8, 2 } - 15 terms. + + + S1 - {15,12, 2, 7, 9, 0, 5,10, 1,11,14, 8, 6,13, 3, 4 } - 14 terms. + + + InvS1 - { 5, 8, 2,14,15, 6,12, 3,11, 4, 7, 9, 1,13,10, 0 } - 14 steps. + + + S2 - { 8, 6, 7, 9, 3,12,10,15,13, 1,14, 4, 0,11, 5, 2 } - 16 terms. + + + InvS2 - {12, 9,15, 4,11,14, 1, 2, 0, 3, 6,13, 5, 8,10, 7 } - 16 steps. + + + S3 - { 0,15,11, 8,12, 9, 6, 3,13, 1, 2, 4,10, 7, 5,14 } - 16 terms. + + + InvS3 - { 0, 9,10, 7,11,14, 6,13, 3, 5,12, 2, 4, 8,15, 1 } - 15 terms + + + S4 - { 1,15, 8, 3,12, 0,11, 6, 2, 5, 4,10, 9,14, 7,13 } - 15 terms. + + + InvS4 - { 5, 0, 8, 3,10, 9, 7,14, 2,12,11, 6, 4,15,13, 1 } - 15 terms. + + + S5 - {15, 5, 2,11, 4,10, 9,12, 0, 3,14, 8,13, 6, 7, 1 } - 16 terms. + + + InvS5 - { 8,15, 2, 9, 4, 1,13,14,11, 6, 5, 3, 7,12,10, 0 } - 16 terms. + + + S6 - { 7, 2,12, 5, 8, 4, 6,11,14, 9, 1,15,13, 3,10, 0 } - 15 terms. + + + InvS6 - {15,10, 1,13, 5, 3, 6, 0, 4, 9,14, 7, 2,12, 8,11 } - 15 terms. + + + S7 - { 1,13,15, 0,14, 8, 2,11, 7, 4,12,10, 9, 3, 5, 6 } - 16 terms. + + + InvS7 - { 3, 0, 6,13, 9,14,15, 8, 5,12,11, 7,10, 1, 4, 2 } - 17 terms. + + + Apply the linear transformation to the register set. + + + Apply the inverse of the linear transformation to the register set. + + + a class that provides a basic SKIPJACK engine. + + + initialise a SKIPJACK cipher. + + @param forEncryption whether or not we are for encryption. + @param parameters the parameters required to set up the cipher. + @exception ArgumentException if the parameters argument is + inappropriate. + + + The G permutation + + + the inverse of the G permutation. + + + An TEA engine. + + + Create an instance of the TEA encryption algorithm + and set some defaults + + + initialise + + @param forEncryption whether or not we are for encryption. + @param params the parameters required to set up the cipher. + @exception ArgumentException if the params argument is + inappropriate. + + + Re-key the cipher. + + @param key the key to be used + + + A class that provides Twofish encryption operations. + + This Java implementation is based on the Java reference + implementation provided by Bruce Schneier and developed + by Raif S. Naffah. + + + Define the fixed p0/p1 permutations used in keyed S-box lookup. + By changing the following constant definitions, the S-boxes will + automatically Get changed in the Twofish engine. + + + gSubKeys[] and gSBox[] are eventually used in the + encryption and decryption methods. + + + initialise a Twofish cipher. + + @param forEncryption whether or not we are for encryption. + @param parameters the parameters required to set up the cipher. + @exception ArgumentException if the parameters argument is + inappropriate. + + + Encrypt the given input starting at the given offset and place + the result in the provided buffer starting at the given offset. + The input will be an exact multiple of our blocksize. + + encryptBlock uses the pre-calculated gSBox[] and subKey[] + arrays. + + + Decrypt the given input starting at the given offset and place + the result in the provided buffer starting at the given offset. + The input will be an exact multiple of our blocksize. + + + Use (12, 8) Reed-Solomon code over GF(256) to produce + a key S-box 32-bit entity from 2 key material 32-bit + entities. + + @param k0 first 32-bit entity + @param k1 second 32-bit entity + @return Remainder polynomial Generated using RS code + + + * Reed-Solomon code parameters: (12,8) reversible code: + *

+ *

+                    * G(x) = x^4 + (a+1/a)x^3 + ax^2 + (a+1/a)x + 1
+                    * 
+ * where a = primitive root of field generator 0x14D + *

+
+ + initialise a VMPC cipher. + + @param forEncryption + whether or not we are for encryption. + @param params + the parameters required to set up the cipher. + @exception ArgumentException + if the params argument is inappropriate. + + + An XTEA engine. + + + Create an instance of the TEA encryption algorithm + and set some defaults + + + initialise + + @param forEncryption whether or not we are for encryption. + @param params the parameters required to set up the cipher. + @exception ArgumentException if the params argument is + inappropriate. + + + Re-key the cipher. + + @param key the key to be used + + + Basic KDF generator for derived keys and ivs as defined by IEEE P1363a/ISO 18033 +
+ This implementation is based on ISO 18033/P1363a. +
+ + Construct a KDF Parameters generator. + + @param counterStart value of counter. + @param digest the digest to be used as the source of derived keys. + + + return the underlying digest. + + + fill len bytes of the output buffer with bytes generated from + the derivation function. + + @throws ArgumentException if the size of the request will cause an overflow. + @throws DataLengthException if the out buffer is too small. + + + initialise the key generator - if strength is set to zero + the key Generated will be 192 bits in size, otherwise + strength can be 128 or 192 (or 112 or 168 if you don't count + parity bits), depending on whether you wish to do 2-key or 3-key + triple DES. + + @param param the parameters to be used for key generation + + + initialise the key generator - if strength is set to zero + the key generated will be 64 bits in size, otherwise + strength can be 64 or 56 bits (if you don't count the parity bits). + + @param param the parameters to be used for key generation + + + a basic Diffie-Hellman key pair generator. + + This generates keys consistent for use with the basic algorithm for + Diffie-Hellman. + + + a Diffie-Hellman key pair generator. + + This generates keys consistent for use in the MTI/A0 key agreement protocol + as described in "Handbook of Applied Cryptography", Pages 516-519. + + + which Generates the p and g values from the given parameters, + returning the DHParameters object. +

+ Note: can take a while...

+
+ + * a DSA key pair generator. + * + * This Generates DSA keys in line with the method described + * in FIPS 186-3 B.1 FFC Key Pair Generation. + + + Generate suitable parameters for DSA, in line with FIPS 186-2. + + + initialise the key generator. + + @param size size of the key (range 2^512 -> 2^1024 - 64 bit increments) + @param certainty measure of robustness of prime (for FIPS 186-2 compliance this should be at least 80). + @param random random byte source. + + + which Generates the p and g values from the given parameters, + returning the DsaParameters object. +

+ Note: can take a while...

+
+ + generate suitable parameters for DSA, in line with + FIPS 186-3 A.1 Generation of the FFC Primes p and q. + + + Given the domain parameters this routine Generates an EC key + pair in accordance with X9.62 section 5.2.1 pages 26, 27. + + + a ElGamal key pair generator. +

+ This Generates keys consistent for use with ElGamal as described in + page 164 of "Handbook of Applied Cryptography".

+
+ + * which Generates the p and g values from the given parameters, + * returning the ElGamalParameters object. + *

+ * Note: can take a while... + *

+
+ + a GOST3410 key pair generator. + This generates GOST3410 keys in line with the method described + in GOST R 34.10-94. + + + generate suitable parameters for GOST3410. + + + initialise the key generator. + + @param size size of the key + @param typeProcedure type procedure A,B = 1; A',B' - else + @param random random byte source. + + + Procedure C + procedure generates the a value from the given p,q, + returning the a value. + + + which generates the p , q and a values from the given parameters, + returning the Gost3410Parameters object. + + + KFD2 generator for derived keys and ivs as defined by IEEE P1363a/ISO 18033 +
+ This implementation is based on IEEE P1363/ISO 18033. +
+ + Construct a KDF1 byte generator. + + @param digest the digest to be used as the source of derived keys. + + + KDF2 generator for derived keys and ivs as defined by IEEE P1363a/ISO 18033 +
+ This implementation is based on IEEE P1363/ISO 18033. +
+ + Construct a KDF2 bytes generator. Generates key material + according to IEEE P1363 or ISO 18033 depending on the initialisation. + + @param digest the digest to be used as the source of derived keys. + + + Generator for MGF1 as defined in Pkcs 1v2 + + + @param digest the digest to be used as the source of Generated bytes + + + return the underlying digest. + + + int to octet string. + + + fill len bytes of the output buffer with bytes Generated from + the derivation function. + + @throws DataLengthException if the out buffer is too small. + + + Key generation parameters for NaccacheStern cipher. For details on this cipher, please see + + http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf + + + Generates a permuted ArrayList from the original one. The original List + is not modified + + @param arr + the ArrayList to be permuted + @param rand + the source of Randomness for permutation + @return a new ArrayList with the permuted elements. + + + Finds the first 'count' primes starting with 3 + + @param count + the number of primes to find + @return a vector containing the found primes as Integer + + + Generator for PBE derived keys and ivs as usd by OpenSSL. +

+ The scheme is a simple extension of PKCS 5 V2.0 Scheme 1 using MD5 with an + iteration count of 1. +

+
+ + Construct a OpenSSL Parameters generator. + + + Initialise - note the iteration count for this algorithm is fixed at 1. + + @param password password to use. + @param salt salt to use. + + + the derived key function, the ith hash of the password and the salt. + + + Generate a key parameter derived from the password, salt, and iteration + count we are currently initialised with. + + @param keySize the size of the key we want (in bits) + @return a KeyParameter object. + @exception ArgumentException if the key length larger than the base hash size. + + + Generate a key with initialisation vector parameter derived from + the password, salt, and iteration count we are currently initialised + with. + + @param keySize the size of the key we want (in bits) + @param ivSize the size of the iv we want (in bits) + @return a ParametersWithIV object. + @exception ArgumentException if keySize + ivSize is larger than the base hash size. + + + Generate a key parameter for use with a MAC derived from the password, + salt, and iteration count we are currently initialised with. + + @param keySize the size of the key we want (in bits) + @return a KeyParameter object. + @exception ArgumentException if the key length larger than the base hash size. + + + Generator for Pbe derived keys and ivs as defined by Pkcs 12 V1.0. +

+ The document this implementation is based on can be found at + + RSA's Pkcs12 Page +

+
+ + Construct a Pkcs 12 Parameters generator. + + @param digest the digest to be used as the source of derived keys. + @exception ArgumentException if an unknown digest is passed in. + + + add a + b + 1, returning the result in a. The a value is treated + as a BigInteger of length (b.Length * 8) bits. The result is + modulo 2^b.Length in case of overflow. + + + generation of a derived key ala Pkcs12 V1.0. + + + Generate a key parameter derived from the password, salt, and iteration + count we are currently initialised with. + + @param keySize the size of the key we want (in bits) + @return a KeyParameter object. + + + Generate a key with initialisation vector parameter derived from + the password, salt, and iteration count we are currently initialised + with. + + @param keySize the size of the key we want (in bits) + @param ivSize the size of the iv we want (in bits) + @return a ParametersWithIV object. + + + Generate a key parameter for use with a MAC derived from the password, + salt, and iteration count we are currently initialised with. + + @param keySize the size of the key we want (in bits) + @return a KeyParameter object. + + + Generator for Pbe derived keys and ivs as defined by Pkcs 5 V2.0 Scheme 1. + Note this generator is limited to the size of the hash produced by the + digest used to drive it. +

+ The document this implementation is based on can be found at + + RSA's Pkcs5 Page +

+
+ + Construct a Pkcs 5 Scheme 1 Parameters generator. + + @param digest the digest to be used as the source of derived keys. + + + the derived key function, the ith hash of the mPassword and the mSalt. + + + Generate a key parameter derived from the mPassword, mSalt, and iteration + count we are currently initialised with. + + @param keySize the size of the key we want (in bits) + @return a KeyParameter object. + @exception ArgumentException if the key length larger than the base hash size. + + + Generate a key with initialisation vector parameter derived from + the mPassword, mSalt, and iteration count we are currently initialised + with. + + @param keySize the size of the key we want (in bits) + @param ivSize the size of the iv we want (in bits) + @return a ParametersWithIV object. + @exception ArgumentException if keySize + ivSize is larger than the base hash size. + + + Generate a key parameter for use with a MAC derived from the mPassword, + mSalt, and iteration count we are currently initialised with. + + @param keySize the size of the key we want (in bits) + @return a KeyParameter object. + @exception ArgumentException if the key length larger than the base hash size. + + + Generator for Pbe derived keys and ivs as defined by Pkcs 5 V2.0 Scheme 2. + This generator uses a SHA-1 HMac as the calculation function. +

+ The document this implementation is based on can be found at + + RSA's Pkcs5 Page

+
+ + construct a Pkcs5 Scheme 2 Parameters generator. + + + Generate a key parameter derived from the password, salt, and iteration + count we are currently initialised with. + + @param keySize the size of the key we want (in bits) + @return a KeyParameter object. + + + Generate a key with initialisation vector parameter derived from + the password, salt, and iteration count we are currently initialised + with. + + @param keySize the size of the key we want (in bits) + @param ivSize the size of the iv we want (in bits) + @return a ParametersWithIV object. + + + Generate a key parameter for use with a MAC derived from the password, + salt, and iteration count we are currently initialised with. + + @param keySize the size of the key we want (in bits) + @return a KeyParameter object. + + + Generate a random factor suitable for use with RSA blind signatures + as outlined in Chaum's blinding and unblinding as outlined in + "Handbook of Applied Cryptography", page 475. + + + Initialise the factor generator + + @param param the necessary RSA key parameters. + + + Generate a suitable blind factor for the public key the generator was initialised with. + + @return a random blind factor + + + an RSA key pair generator. + + + Base interface for a public/private key block cipher. + + + The name of the algorithm this cipher implements. + + + Initialise the cipher. + Initialise for encryption if true, for decryption if false. + The key or other data required by the cipher. + + + The maximum size, in bytes, an input block may be. + + + The maximum size, in bytes, an output block will be. + + + Process a block. + The input buffer. + The offset into inBuf that the input block begins. + The length of the input block. + Input decrypts improperly. + Input is too large for the cipher. + + + interface that a public/private key pair generator should conform to. + + + intialise the key pair generator. + + @param the parameters the key pair is to be initialised with. + + + return an AsymmetricCipherKeyPair containing the Generated keys. + + @return an AsymmetricCipherKeyPair containing the Generated keys. + + + The basic interface that basic Diffie-Hellman implementations + conforms to. + + + initialise the agreement engine. + + + given a public key from a given party calculate the next + message in the agreement sequence. + + + Base interface for a symmetric key block cipher. + + + The name of the algorithm this cipher implements. + + + Initialise the cipher. + Initialise for encryption if true, for decryption if false. + The key or other data required by the cipher. + + + The block size for this cipher, in bytes. + + + Indicates whether this cipher can handle partial blocks. + + + Process a block. + The input buffer. + The offset into inBuf that the input block begins. + The output buffer. + The offset into outBuf to write the output block. + If input block is wrong size, or outBuf too small. + The number of bytes processed and produced. + + + + Reset the cipher to the same state as it was after the last init (if there was one). + + + + Block cipher engines are expected to conform to this interface. + + + The name of the algorithm this cipher implements. + + + Initialise the cipher. + If true the cipher is initialised for encryption, + if false for decryption. + The key and other data required by the cipher. + + + + Reset the cipher. After resetting the cipher is in the same state + as it was after the last init (if there was one). + + + + all parameter classes implement this. + + + base interface for general purpose byte derivation functions. + + + return the message digest used as the basis for the function + + + Parameters for key/byte stream derivation classes + + + interface that a message digest conforms to. + + + return the algorithm name + + @return the algorithm name + + + return the size, in bytes, of the digest produced by this message digest. + + @return the size, in bytes, of the digest produced by this message digest. + + + return the size, in bytes, of the internal buffer used by this digest. + + @return the size, in bytes, of the internal buffer used by this digest. + + + update the message digest with a single byte. + + @param inByte the input byte to be entered. + + + update the message digest with a block of bytes. + + @param input the byte array containing the data. + @param inOff the offset into the byte array where the data starts. + @param len the length of the data. + + + Close the digest, producing the final digest value. The doFinal + call leaves the digest reset. + + @param output the array the digest is to be copied into. + @param outOff the offset into the out array the digest is to start at. + + + reset the digest back to it's initial state. + + + interface for classes implementing the Digital Signature Algorithm + + + initialise the signer for signature generation or signature + verification. + + @param forSigning true if we are generating a signature, false + otherwise. + @param param key parameters for signature generation. + + + sign the passed in message (usually the output of a hash function). + + @param message the message to be signed. + @return two big integers representing the r and s values respectively. + + + verify the message message against the signature values r and s. + + @param message the message that was supposed to have been signed. + @param r the r signature value. + @param s the s signature value. + + + The base interface for implementations of message authentication codes (MACs). + + + Initialise the MAC. + + @param param the key and other data required by the MAC. + @exception ArgumentException if the parameters argument is + inappropriate. + + + Return the name of the algorithm the MAC implements. + + @return the name of the algorithm the MAC implements. + + + Return the block size for this MAC (in bytes). + + @return the block size for this MAC in bytes. + + + add a single byte to the mac for processing. + + @param in the byte to be processed. + @exception InvalidOperationException if the MAC is not initialised. + + + @param in the array containing the input. + @param inOff the index in the array the data begins at. + @param len the length of the input starting at inOff. + @exception InvalidOperationException if the MAC is not initialised. + @exception DataLengthException if there isn't enough data in in. + + + Compute the final stage of the MAC writing the output to the out + parameter. +

+ doFinal leaves the MAC in the same state it was after the last init. +

+ @param out the array the MAC is to be output to. + @param outOff the offset into the out buffer the output is to start at. + @exception DataLengthException if there isn't enough space in out. + @exception InvalidOperationException if the MAC is not initialised. +
+ + Reset the MAC. At the end of resetting the MAC should be in the + in the same state it was after the last init (if there was one). + + + this exception is thrown whenever we find something we don't expect in a + message. + + + base constructor. + + + create a InvalidCipherTextException with the given message. + + @param message the message to be carried with the exception. + + + Return the name of the algorithm the signer implements. + + @return the name of the algorithm the signer implements. + + + Initialise the signer for signing or verification. + + @param forSigning true if for signing, false otherwise + @param param necessary parameters. + + + update the internal digest with the byte b + + + update the internal digest with the byte array in + + + Generate a signature for the message we've been loaded with using + the key we were initialised with. + + + return true if the internal state represents the signature described + in the passed in array. + + + reset the internal state + + + Signer with message recovery. + + + Returns true if the signer has recovered the full message as + part of signature verification. + + @return true if full message recovered. + + + Returns a reference to what message was recovered (if any). + + @return full/partial message, null if nothing. + + + Perform an update with the recovered message before adding any other data. This must + be the first update method called, and calling it will result in the signer assuming + that further calls to update will include message content past what is recoverable. + + @param signature the signature that we are in the process of verifying. + @throws IllegalStateException + + + The interface stream ciphers conform to. + + + The name of the algorithm this cipher implements. + + + Initialise the cipher. + If true the cipher is initialised for encryption, + if false for decryption. + The key and other data required by the cipher. + + If the parameters argument is inappropriate. + + + + encrypt/decrypt a single byte returning the result. + the byte to be processed. + the result of processing the input byte. + + + + Process a block of bytes from input putting the result into output. + + The input byte array. + + The offset into input where the data to be processed starts. + + The number of bytes to be processed. + The output buffer the processed bytes go into. + + The offset into output the processed data starts at. + + If the output buffer is too small. + + + + Reset the cipher to the same state as it was after the last init (if there was one). + + + + The name of the algorithm this cipher implements. + + + The base class for parameters to key generators. + + + initialise the generator with a source of randomness + and a strength (in bits). + + @param random the random byte source. + @param strength the size, in bits, of the keys we want to produce. + + + return the random source associated with this + generator. + + @return the generators random source. + + + return the bit strength for keys produced by this generator, + + @return the strength of the keys this generator produces (in bits). + + + standard CBC Block Cipher MAC - if no padding is specified the default of + pad of zeroes is used. + + + create a standard MAC based on a CBC block cipher. This will produce an + authentication code half the length of the block size of the cipher. + + @param cipher the cipher to be used as the basis of the MAC generation. + + + create a standard MAC based on a CBC block cipher. This will produce an + authentication code half the length of the block size of the cipher. + + @param cipher the cipher to be used as the basis of the MAC generation. + @param padding the padding to be used to complete the last block. + + + create a standard MAC based on a block cipher with the size of the + MAC been given in bits. This class uses CBC mode as the basis for the + MAC generation. +

+ Note: the size of the MAC must be at least 24 bits (FIPS Publication 81), + or 16 bits if being used as a data authenticator (FIPS Publication 113), + and in general should be less than the size of the block cipher as it reduces + the chance of an exhaustive attack (see Handbook of Applied Cryptography). +

+ @param cipher the cipher to be used as the basis of the MAC generation. + @param macSizeInBits the size of the MAC in bits, must be a multiple of 8. +
+ + create a standard MAC based on a block cipher with the size of the + MAC been given in bits. This class uses CBC mode as the basis for the + MAC generation. +

+ Note: the size of the MAC must be at least 24 bits (FIPS Publication 81), + or 16 bits if being used as a data authenticator (FIPS Publication 113), + and in general should be less than the size of the block cipher as it reduces + the chance of an exhaustive attack (see Handbook of Applied Cryptography). +

+ @param cipher the cipher to be used as the basis of the MAC generation. + @param macSizeInBits the size of the MAC in bits, must be a multiple of 8. + @param padding the padding to be used to complete the last block. +
+ + Reset the mac generator. + + + implements a Cipher-FeedBack (CFB) mode on top of a simple cipher. + + + Basic constructor. + + @param cipher the block cipher to be used as the basis of the + feedback mode. + @param blockSize the block size in bits (note: a multiple of 8) + + + Initialise the cipher and, possibly, the initialisation vector (IV). + If an IV isn't passed as part of the parameter, the IV will be all zeros. + An IV which is too short is handled in FIPS compliant fashion. + + @param param the key and other data required by the cipher. + @exception ArgumentException if the parameters argument is + inappropriate. + + + return the algorithm name and mode. + + @return the name of the underlying algorithm followed by "/CFB" + and the block size in bits. + + + return the block size we are operating at. + + @return the block size we are operating at (in bytes). + + + Process one block of input from the array in and write it to + the out array. + + @param in the array containing the input data. + @param inOff offset into the in array the data starts at. + @param out the array the output data will be copied into. + @param outOff the offset into the out array the output will start at. + @exception DataLengthException if there isn't enough data in in, or + space in out. + @exception InvalidOperationException if the cipher isn't initialised. + @return the number of bytes processed and produced. + + + reset the chaining vector back to the IV and reset the underlying + cipher. + + + create a standard MAC based on a CFB block cipher. This will produce an + authentication code half the length of the block size of the cipher, with + the CFB mode set to 8 bits. + + @param cipher the cipher to be used as the basis of the MAC generation. + + + create a standard MAC based on a CFB block cipher. This will produce an + authentication code half the length of the block size of the cipher, with + the CFB mode set to 8 bits. + + @param cipher the cipher to be used as the basis of the MAC generation. + @param padding the padding to be used. + + + create a standard MAC based on a block cipher with the size of the + MAC been given in bits. This class uses CFB mode as the basis for the + MAC generation. +

+ Note: the size of the MAC must be at least 24 bits (FIPS Publication 81), + or 16 bits if being used as a data authenticator (FIPS Publication 113), + and in general should be less than the size of the block cipher as it reduces + the chance of an exhaustive attack (see Handbook of Applied Cryptography). +

+ @param cipher the cipher to be used as the basis of the MAC generation. + @param cfbBitSize the size of an output block produced by the CFB mode. + @param macSizeInBits the size of the MAC in bits, must be a multiple of 8. +
+ + create a standard MAC based on a block cipher with the size of the + MAC been given in bits. This class uses CFB mode as the basis for the + MAC generation. +

+ Note: the size of the MAC must be at least 24 bits (FIPS Publication 81), + or 16 bits if being used as a data authenticator (FIPS Publication 113), + and in general should be less than the size of the block cipher as it reduces + the chance of an exhaustive attack (see Handbook of Applied Cryptography). +

+ @param cipher the cipher to be used as the basis of the MAC generation. + @param cfbBitSize the size of an output block produced by the CFB mode. + @param macSizeInBits the size of the MAC in bits, must be a multiple of 8. + @param padding a padding to be used. +
+ + Reset the mac generator. + + + CMAC - as specified at www.nuee.nagoya-u.ac.jp/labs/tiwata/omac/omac.html +

+ CMAC is analogous to OMAC1 - see also en.wikipedia.org/wiki/CMAC +

+ CMAC is a NIST recomendation - see + csrc.nist.gov/CryptoToolkit/modes/800-38_Series_Publications/SP800-38B.pdf +

+ CMAC/OMAC1 is a blockcipher-based message authentication code designed and + analyzed by Tetsu Iwata and Kaoru Kurosawa. +

+ CMAC/OMAC1 is a simple variant of the CBC MAC (Cipher Block Chaining Message + Authentication Code). OMAC stands for One-Key CBC MAC. +

+ It supports 128- or 64-bits block ciphers, with any key size, and returns + a MAC with dimension less or equal to the block size of the underlying + cipher. +

+
+ + create a standard MAC based on a CBC block cipher (64 or 128 bit block). + This will produce an authentication code the length of the block size + of the cipher. + + @param cipher the cipher to be used as the basis of the MAC generation. + + + create a standard MAC based on a block cipher with the size of the + MAC been given in bits. +

+ Note: the size of the MAC must be at least 24 bits (FIPS Publication 81), + or 16 bits if being used as a data authenticator (FIPS Publication 113), + and in general should be less than the size of the block cipher as it reduces + the chance of an exhaustive attack (see Handbook of Applied Cryptography). + + @param cipher the cipher to be used as the basis of the MAC generation. + @param macSizeInBits the size of the MAC in bits, must be a multiple of 8 and @lt;= 128. + + + Reset the mac generator. + + + implementation of GOST 28147-89 MAC + + + HMAC implementation based on RFC2104 + + H(K XOR opad, H(K XOR ipad, text)) + + + Reset the mac generator. + + + DES based CBC Block Cipher MAC according to ISO9797, algorithm 3 (ANSI X9.19 Retail MAC) + + This could as well be derived from CBCBlockCipherMac, but then the property mac in the base + class must be changed to protected + + + create a Retail-MAC based on a CBC block cipher. This will produce an + authentication code of the length of the block size of the cipher. + + @param cipher the cipher to be used as the basis of the MAC generation. This must + be DESEngine. + + + create a Retail-MAC based on a CBC block cipher. This will produce an + authentication code of the length of the block size of the cipher. + + @param cipher the cipher to be used as the basis of the MAC generation. + @param padding the padding to be used to complete the last block. + + + create a Retail-MAC based on a block cipher with the size of the + MAC been given in bits. This class uses single DES CBC mode as the basis for the + MAC generation. +

+ Note: the size of the MAC must be at least 24 bits (FIPS Publication 81), + or 16 bits if being used as a data authenticator (FIPS Publication 113), + and in general should be less than the size of the block cipher as it reduces + the chance of an exhaustive attack (see Handbook of Applied Cryptography). +

+ @param cipher the cipher to be used as the basis of the MAC generation. + @param macSizeInBits the size of the MAC in bits, must be a multiple of 8. +
+ + create a standard MAC based on a block cipher with the size of the + MAC been given in bits. This class uses single DES CBC mode as the basis for the + MAC generation. The final block is decrypted and then encrypted using the + middle and right part of the key. +

+ Note: the size of the MAC must be at least 24 bits (FIPS Publication 81), + or 16 bits if being used as a data authenticator (FIPS Publication 113), + and in general should be less than the size of the block cipher as it reduces + the chance of an exhaustive attack (see Handbook of Applied Cryptography). +

+ @param cipher the cipher to be used as the basis of the MAC generation. + @param macSizeInBits the size of the MAC in bits, must be a multiple of 8. + @param padding the padding to be used to complete the last block. +
+ + Reset the mac generator. + + + + This exception is thrown whenever a cipher requires a change of key, iv + or similar after x amount of bytes enciphered + + + + implements Cipher-Block-Chaining (CBC) mode on top of a simple cipher. + + + Basic constructor. + + @param cipher the block cipher to be used as the basis of chaining. + + + return the underlying block cipher that we are wrapping. + + @return the underlying block cipher that we are wrapping. + + + Initialise the cipher and, possibly, the initialisation vector (IV). + If an IV isn't passed as part of the parameter, the IV will be all zeros. + + @param forEncryption if true the cipher is initialised for + encryption, if false for decryption. + @param param the key and other data required by the cipher. + @exception ArgumentException if the parameters argument is + inappropriate. + + + return the algorithm name and mode. + + @return the name of the underlying algorithm followed by "/CBC". + + + return the block size of the underlying cipher. + + @return the block size of the underlying cipher. + + + Process one block of input from the array in and write it to + the out array. + + @param in the array containing the input data. + @param inOff offset into the in array the data starts at. + @param out the array the output data will be copied into. + @param outOff the offset into the out array the output will start at. + @exception DataLengthException if there isn't enough data in in, or + space in out. + @exception InvalidOperationException if the cipher isn't initialised. + @return the number of bytes processed and produced. + + + reset the chaining vector back to the IV and reset the underlying + cipher. + + + Do the appropriate chaining step for CBC mode encryption. + + @param in the array containing the data to be encrypted. + @param inOff offset into the in array the data starts at. + @param out the array the encrypted data will be copied into. + @param outOff the offset into the out array the output will start at. + @exception DataLengthException if there isn't enough data in in, or + space in out. + @exception InvalidOperationException if the cipher isn't initialised. + @return the number of bytes processed and produced. + + + Do the appropriate chaining step for CBC mode decryption. + + @param in the array containing the data to be decrypted. + @param inOff offset into the in array the data starts at. + @param out the array the decrypted data will be copied into. + @param outOff the offset into the out array the output will start at. + @exception DataLengthException if there isn't enough data in in, or + space in out. + @exception InvalidOperationException if the cipher isn't initialised. + @return the number of bytes processed and produced. + + + * Implements the Counter with Cipher Block Chaining mode (CCM) detailed in + * NIST Special Publication 800-38C. + *

+ * Note: this mode is a packet mode - it needs all the data up front. + *

+
+ + Basic constructor. + + @param cipher the block cipher to be used. + + + return the underlying block cipher that we are wrapping. + + @return the underlying block cipher that we are wrapping. + + + Returns a byte array containing the mac calculated as part of the + last encrypt or decrypt operation. + + @return the last mac calculated. + + + implements a Cipher-FeedBack (CFB) mode on top of a simple cipher. + + + Basic constructor. + + @param cipher the block cipher to be used as the basis of the + feedback mode. + @param blockSize the block size in bits (note: a multiple of 8) + + + return the underlying block cipher that we are wrapping. + + @return the underlying block cipher that we are wrapping. + + + Initialise the cipher and, possibly, the initialisation vector (IV). + If an IV isn't passed as part of the parameter, the IV will be all zeros. + An IV which is too short is handled in FIPS compliant fashion. + + @param forEncryption if true the cipher is initialised for + encryption, if false for decryption. + @param param the key and other data required by the cipher. + @exception ArgumentException if the parameters argument is + inappropriate. + + + return the algorithm name and mode. + + @return the name of the underlying algorithm followed by "/CFB" + and the block size in bits. + + + return the block size we are operating at. + + @return the block size we are operating at (in bytes). + + + Process one block of input from the array in and write it to + the out array. + + @param in the array containing the input data. + @param inOff offset into the in array the data starts at. + @param out the array the output data will be copied into. + @param outOff the offset into the out array the output will start at. + @exception DataLengthException if there isn't enough data in in, or + space in out. + @exception InvalidOperationException if the cipher isn't initialised. + @return the number of bytes processed and produced. + + + Do the appropriate processing for CFB mode encryption. + + @param in the array containing the data to be encrypted. + @param inOff offset into the in array the data starts at. + @param out the array the encrypted data will be copied into. + @param outOff the offset into the out array the output will start at. + @exception DataLengthException if there isn't enough data in in, or + space in out. + @exception InvalidOperationException if the cipher isn't initialised. + @return the number of bytes processed and produced. + + + Do the appropriate processing for CFB mode decryption. + + @param in the array containing the data to be decrypted. + @param inOff offset into the in array the data starts at. + @param out the array the encrypted data will be copied into. + @param outOff the offset into the out array the output will start at. + @exception DataLengthException if there isn't enough data in in, or + space in out. + @exception InvalidOperationException if the cipher isn't initialised. + @return the number of bytes processed and produced. + + + reset the chaining vector back to the IV and reset the underlying + cipher. + + + A Cipher Text Stealing (CTS) mode cipher. CTS allows block ciphers to + be used to produce cipher text which is the same outLength as the plain text. + + + Create a buffered block cipher that uses Cipher Text Stealing + + @param cipher the underlying block cipher this buffering object wraps. + + + return the size of the output buffer required for an update of 'length' bytes. + + @param length the outLength of the input. + @return the space required to accommodate a call to update + with length bytes of input. + + + return the size of the output buffer required for an update plus a + doFinal with an input of length bytes. + + @param length the outLength of the input. + @return the space required to accommodate a call to update and doFinal + with length bytes of input. + + + process a single byte, producing an output block if neccessary. + + @param in the input byte. + @param out the space for any output that might be produced. + @param outOff the offset from which the output will be copied. + @return the number of output bytes copied to out. + @exception DataLengthException if there isn't enough space in out. + @exception InvalidOperationException if the cipher isn't initialised. + + + process an array of bytes, producing output if necessary. + + @param in the input byte array. + @param inOff the offset at which the input data starts. + @param length the number of bytes to be copied out of the input array. + @param out the space for any output that might be produced. + @param outOff the offset from which the output will be copied. + @return the number of output bytes copied to out. + @exception DataLengthException if there isn't enough space in out. + @exception InvalidOperationException if the cipher isn't initialised. + + + Process the last block in the buffer. + + @param out the array the block currently being held is copied into. + @param outOff the offset at which the copying starts. + @return the number of output bytes copied to out. + @exception DataLengthException if there is insufficient space in out for + the output. + @exception InvalidOperationException if the underlying cipher is not + initialised. + @exception InvalidCipherTextException if cipher text decrypts wrongly (in + case the exception will never Get thrown). + + + A Two-Pass Authenticated-Encryption Scheme Optimized for Simplicity and + Efficiency - by M. Bellare, P. Rogaway, D. Wagner. + + http://www.cs.ucdavis.edu/~rogaway/papers/eax.pdf + + EAX is an AEAD scheme based on CTR and OMAC1/CMAC, that uses a single block + cipher to encrypt and authenticate data. It's on-line (the length of a + message isn't needed to begin processing it), has good performances, it's + simple and provably secure (provided the underlying block cipher is secure). + + Of course, this implementations is NOT thread-safe. + + + Constructor that accepts an instance of a block cipher engine. + + @param cipher the engine to use + + + + Implements the Galois/Counter mode (GCM) detailed in + NIST Special Publication 800-38D. + + + + implements the GOST 28147 OFB counter mode (GCTR). + + + Basic constructor. + + @param cipher the block cipher to be used as the basis of the + counter mode (must have a 64 bit block size). + + + return the underlying block cipher that we are wrapping. + + @return the underlying block cipher that we are wrapping. + + + Initialise the cipher and, possibly, the initialisation vector (IV). + If an IV isn't passed as part of the parameter, the IV will be all zeros. + An IV which is too short is handled in FIPS compliant fashion. + + @param encrypting if true the cipher is initialised for + encryption, if false for decryption. + @param parameters the key and other data required by the cipher. + @exception ArgumentException if the parameters argument is inappropriate. + + + return the algorithm name and mode. + + @return the name of the underlying algorithm followed by "/GCTR" + and the block size in bits + + + return the block size we are operating at (in bytes). + + @return the block size we are operating at (in bytes). + + + Process one block of input from the array in and write it to + the out array. + + @param in the array containing the input data. + @param inOff offset into the in array the data starts at. + @param out the array the output data will be copied into. + @param outOff the offset into the out array the output will start at. + @exception DataLengthException if there isn't enough data in in, or + space in out. + @exception InvalidOperationException if the cipher isn't initialised. + @return the number of bytes processed and produced. + + + reset the feedback vector back to the IV and reset the underlying + cipher. + + + + A block cipher mode that includes authenticated encryption with a streaming mode + and optional associated data. + + + + The name of the algorithm this cipher implements. + + + Initialise the cipher. + Parameter can either be an AeadParameters or a ParametersWithIV object. + Initialise for encryption if true, for decryption if false. + The key or other data required by the cipher. + + + The block size for this cipher, in bytes. + + + Encrypt/decrypt a single byte. + + @param input the byte to be processed. + @param outBytes the output buffer the processed byte goes into. + @param outOff the offset into the output byte array the processed data starts at. + @return the number of bytes written to out. + @exception DataLengthException if the output buffer is too small. + + + Process a block of bytes from in putting the result into out. + + @param inBytes the input byte array. + @param inOff the offset into the in array where the data to be processed starts. + @param len the number of bytes to be processed. + @param outBytes the output buffer the processed bytes go into. + @param outOff the offset into the output byte array the processed data starts at. + @return the number of bytes written to out. + @exception DataLengthException if the output buffer is too small. + + + Finish the operation either appending or verifying the MAC at the end of the data. + + @param outBytes space for any resulting output data. + @param outOff offset into out to start copying the data at. + @return number of bytes written into out. + @throws InvalidOperationException if the cipher is in an inappropriate state. + @throws InvalidCipherTextException if the MAC fails to match. + + + Return the value of the MAC associated with the last stream processed. + + @return MAC for plaintext data. + + + Return the size of the output buffer required for a ProcessBytes + an input of len bytes. + + @param len the length of the input. + @return the space required to accommodate a call to ProcessBytes + with len bytes of input. + + + Return the size of the output buffer required for a ProcessBytes plus a + DoFinal with an input of len bytes. + + @param len the length of the input. + @return the space required to accommodate a call to ProcessBytes and DoFinal + with len bytes of input. + + + + Reset the cipher to the same state as it was after the last init (if there was one). + + + + implements a Output-FeedBack (OFB) mode on top of a simple cipher. + + + Basic constructor. + + @param cipher the block cipher to be used as the basis of the + feedback mode. + @param blockSize the block size in bits (note: a multiple of 8) + + + return the underlying block cipher that we are wrapping. + + @return the underlying block cipher that we are wrapping. + + + Initialise the cipher and, possibly, the initialisation vector (IV). + If an IV isn't passed as part of the parameter, the IV will be all zeros. + An IV which is too short is handled in FIPS compliant fashion. + + @param forEncryption if true the cipher is initialised for + encryption, if false for decryption. + @param param the key and other data required by the cipher. + @exception ArgumentException if the parameters argument is + inappropriate. + + + return the algorithm name and mode. + + @return the name of the underlying algorithm followed by "/OFB" + and the block size in bits + + + return the block size we are operating at (in bytes). + + @return the block size we are operating at (in bytes). + + + Process one block of input from the array in and write it to + the out array. + + @param in the array containing the input data. + @param inOff offset into the in array the data starts at. + @param out the array the output data will be copied into. + @param outOff the offset into the out array the output will start at. + @exception DataLengthException if there isn't enough data in in, or + space in out. + @exception InvalidOperationException if the cipher isn't initialised. + @return the number of bytes processed and produced. + + + reset the feedback vector back to the IV and reset the underlying + cipher. + + + * Implements OpenPGP's rather strange version of Cipher-FeedBack (CFB) mode + * on top of a simple cipher. This class assumes the IV has been prepended + * to the data stream already, and just accomodates the reset after + * (blockSize + 2) bytes have been read. + *

+ * For further info see RFC 2440. + *

+
+ + Basic constructor. + + @param cipher the block cipher to be used as the basis of the + feedback mode. + + + return the underlying block cipher that we are wrapping. + + @return the underlying block cipher that we are wrapping. + + + return the algorithm name and mode. + + @return the name of the underlying algorithm followed by "/PGPCFB" + and the block size in bits. + + + return the block size we are operating at. + + @return the block size we are operating at (in bytes). + + + Process one block of input from the array in and write it to + the out array. + + @param in the array containing the input data. + @param inOff offset into the in array the data starts at. + @param out the array the output data will be copied into. + @param outOff the offset into the out array the output will start at. + @exception DataLengthException if there isn't enough data in in, or + space in out. + @exception InvalidOperationException if the cipher isn't initialised. + @return the number of bytes processed and produced. + + + reset the chaining vector back to the IV and reset the underlying + cipher. + + + Initialise the cipher and, possibly, the initialisation vector (IV). + If an IV isn't passed as part of the parameter, the IV will be all zeros. + An IV which is too short is handled in FIPS compliant fashion. + + @param forEncryption if true the cipher is initialised for + encryption, if false for decryption. + @param parameters the key and other data required by the cipher. + @exception ArgumentException if the parameters argument is + inappropriate. + + + Encrypt one byte of data according to CFB mode. + @param data the byte to encrypt + @param blockOff offset in the current block + @returns the encrypted byte + + + Do the appropriate processing for CFB IV mode encryption. + + @param in the array containing the data to be encrypted. + @param inOff offset into the in array the data starts at. + @param out the array the encrypted data will be copied into. + @param outOff the offset into the out array the output will start at. + @exception DataLengthException if there isn't enough data in in, or + space in out. + @exception InvalidOperationException if the cipher isn't initialised. + @return the number of bytes processed and produced. + + + Do the appropriate processing for CFB IV mode decryption. + + @param in the array containing the data to be decrypted. + @param inOff offset into the in array the data starts at. + @param out the array the encrypted data will be copied into. + @param outOff the offset into the out array the output will start at. + @exception DataLengthException if there isn't enough data in in, or + space in out. + @exception InvalidOperationException if the cipher isn't initialised. + @return the number of bytes processed and produced. + + + Implements the Segmented Integer Counter (SIC) mode on top of a simple + block cipher. + + + Basic constructor. + + @param c the block cipher to be used. + + + return the underlying block cipher that we are wrapping. + + @return the underlying block cipher that we are wrapping. + + + Block cipher padders are expected to conform to this interface + + + Initialise the padder. + + @param param parameters, if any required. + + + Return the name of the algorithm the cipher implements. + + @return the name of the algorithm the cipher implements. + + + add the pad bytes to the passed in block, returning the + number of bytes added. + + + return the number of pad bytes present in the block. + @exception InvalidCipherTextException if the padding is badly formed + or invalid. + + + A padder that adds ISO10126-2 padding to a block. + + + Initialise the padder. + + @param random a SecureRandom if available. + + + Return the name of the algorithm the cipher implements. + + @return the name of the algorithm the cipher implements. + + + add the pad bytes to the passed in block, returning the + number of bytes added. + + + return the number of pad bytes present in the block. + + + A padder that adds the padding according to the scheme referenced in + ISO 7814-4 - scheme 2 from ISO 9797-1. The first byte is 0x80, rest is 0x00 + + + Initialise the padder. + + @param random - a SecureRandom if available. + + + Return the name of the algorithm the padder implements. + + @return the name of the algorithm the padder implements. + + + add the pad bytes to the passed in block, returning the + number of bytes added. + + + return the number of pad bytes present in the block. + + + A wrapper class that allows block ciphers to be used to process data in + a piecemeal fashion with padding. The PaddedBufferedBlockCipher + outputs a block only when the buffer is full and more data is being added, + or on a doFinal (unless the current block in the buffer is a pad block). + The default padding mechanism used is the one outlined in Pkcs5/Pkcs7. + + + Create a buffered block cipher with the desired padding. + + @param cipher the underlying block cipher this buffering object wraps. + @param padding the padding type. + + + Create a buffered block cipher Pkcs7 padding + + @param cipher the underlying block cipher this buffering object wraps. + + + initialise the cipher. + + @param forEncryption if true the cipher is initialised for + encryption, if false for decryption. + @param param the key and other data required by the cipher. + @exception ArgumentException if the parameters argument is + inappropriate. + + + return the minimum size of the output buffer required for an update + plus a doFinal with an input of len bytes. + + @param len the length of the input. + @return the space required to accommodate a call to update and doFinal + with len bytes of input. + + + return the size of the output buffer required for an update + an input of len bytes. + + @param len the length of the input. + @return the space required to accommodate a call to update + with len bytes of input. + + + process a single byte, producing an output block if neccessary. + + @param in the input byte. + @param out the space for any output that might be produced. + @param outOff the offset from which the output will be copied. + @return the number of output bytes copied to out. + @exception DataLengthException if there isn't enough space in out. + @exception InvalidOperationException if the cipher isn't initialised. + + + process an array of bytes, producing output if necessary. + + @param in the input byte array. + @param inOff the offset at which the input data starts. + @param len the number of bytes to be copied out of the input array. + @param out the space for any output that might be produced. + @param outOff the offset from which the output will be copied. + @return the number of output bytes copied to out. + @exception DataLengthException if there isn't enough space in out. + @exception InvalidOperationException if the cipher isn't initialised. + + + Process the last block in the buffer. If the buffer is currently + full and padding needs to be added a call to doFinal will produce + 2 * GetBlockSize() bytes. + + @param out the array the block currently being held is copied into. + @param outOff the offset at which the copying starts. + @return the number of output bytes copied to out. + @exception DataLengthException if there is insufficient space in out for + the output or we are decrypting and the input is not block size aligned. + @exception InvalidOperationException if the underlying cipher is not + initialised. + @exception InvalidCipherTextException if padding is expected and not found. + + + A padder that adds Pkcs7/Pkcs5 padding to a block. + + + Initialise the padder. + + @param random - a SecureRandom if available. + + + Return the name of the algorithm the cipher implements. + + @return the name of the algorithm the cipher implements. + + + add the pad bytes to the passed in block, returning the + number of bytes added. + + + return the number of pad bytes present in the block. + + + A padder that adds Trailing-Bit-Compliment padding to a block. +

+ This padding pads the block out compliment of the last bit + of the plain text. +

+
+
+ + Return the name of the algorithm the cipher implements. + the name of the algorithm the cipher implements. + + + + Initialise the padder. + - a SecureRandom if available. + + + + add the pad bytes to the passed in block, returning the + number of bytes added. +

+ Note: this assumes that the last block of plain text is always + passed to it inside in. i.e. if inOff is zero, indicating the + entire block is to be overwritten with padding the value of in + should be the same as the last block of plain text. +

+
+
+ + return the number of pad bytes present in the block. + + + A padder that adds X9.23 padding to a block - if a SecureRandom is + passed in random padding is assumed, otherwise padding with zeros is used. + + + Initialise the padder. + + @param random a SecureRandom if one is available. + + + Return the name of the algorithm the cipher implements. + + @return the name of the algorithm the cipher implements. + + + add the pad bytes to the passed in block, returning the + number of bytes added. + + + return the number of pad bytes present in the block. + + + A padder that adds Null byte padding to a block. + + + Return the name of the algorithm the cipher implements. + + + the name of the algorithm the cipher implements. + + + + Initialise the padder. + + + - a SecureRandom if available. + + + + add the pad bytes to the passed in block, returning the + number of bytes added. + + + + return the number of pad bytes present in the block. + + + Base constructor. + + @param key key to be used by underlying cipher + @param macSize macSize in bits + @param nonce nonce to be used + @param associatedText associated text, if any + + + Base constructor. + + @param key key to be used by underlying cipher + @param macSize macSize in bits + @param nonce nonce to be used + @param associatedText associated text, if any + + + return true if the passed in key is a DES-EDE weak key. + + @param key bytes making up the key + @param offset offset into the byte array the key starts at + @param length number of bytes making up the key + + + return true if the passed in key is a DES-EDE weak key. + + @param key bytes making up the key + @param offset offset into the byte array the key starts at + + + DES has 16 weak keys. This method will check + if the given DES key material is weak or semi-weak. + Key material that is too short is regarded as weak. +

+ See "Applied + Cryptography" by Bruce Schneier for more information. +

+ @return true if the given DES key material is weak or semi-weak, + false otherwise. +
+ + DES Keys use the LSB as the odd parity bit. This can + be used to check for corrupt keys. + + @param bytes the byte array to set the parity on. + + + The minimum bitlength of the private value. + + + The bitlength of the private value. + + + return the generator - g + + + return private value limit - l + + + parameters for using an integrated cipher in stream mode. + + + @param derivation the derivation parameter for the KDF function. + @param encoding the encoding parameter for the KDF function. + @param macKeySize the size of the MAC key (in bits). + + + @param derivation the derivation parameter for the KDF function. + @param encoding the encoding parameter for the KDF function. + @param macKeySize the size of the MAC key (in bits). + @param cipherKeySize the size of the associated Cipher key (in bits). + + + parameters for Key derivation functions for ISO-18033 + + + parameters for Key derivation functions for IEEE P1363a + + + Parameters for mask derivation functions. + + + Parameters for NaccacheStern public private key generation. For details on + this cipher, please see + + http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf + + + Parameters for generating a NaccacheStern KeyPair. + + @param random + The source of randomness + @param strength + The desired strength of the Key in Bits + @param certainty + the probability that the generated primes are not really prime + as integer: 2^(-certainty) is then the probability + @param countSmallPrimes + How many small key factors are desired + + + Parameters for a NaccacheStern KeyPair. + + @param random + The source of randomness + @param strength + The desired strength of the Key in Bits + @param certainty + the probability that the generated primes are not really prime + as integer: 2^(-certainty) is then the probability + @param cntSmallPrimes + How many small key factors are desired + @param debug + Turn debugging on or off (reveals secret information, use with + caution) + + + @return Returns the certainty. + + + @return Returns the countSmallPrimes. + + + Public key parameters for NaccacheStern cipher. For details on this cipher, + please see + + http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf + + + @param privateKey + + + @return Returns the g. + + + @return Returns the lowerSigmaBound. + + + @return Returns the n. + + + Private key parameters for NaccacheStern cipher. For details on this cipher, + please see + + http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf + + + Constructs a NaccacheSternPrivateKey + + @param g + the public enryption parameter g + @param n + the public modulus n = p*q + @param lowerSigmaBound + the public lower sigma bound up to which data can be encrypted + @param smallPrimes + the small primes, of which sigma is constructed in the right + order + @param phi_n + the private modulus phi(n) = (p-1)(q-1) + + + Cipher parameters with a fixed salt value associated with them. + + + super class for all Password Based Encyrption (Pbe) parameter generator classes. + + + base constructor. + + + initialise the Pbe generator. + + @param password the password converted into bytes (see below). + @param salt the salt to be mixed with the password. + @param iterationCount the number of iterations the "mixing" function + is to be applied for. + + + return the password byte array. + + @return the password byte array. + + + return the salt byte array. + + @return the salt byte array. + + + return the iteration count. + + @return the iteration count. + + + Generate derived parameters for a key of length keySize. + + @param keySize the length, in bits, of the key required. + @return a parameters object representing a key. + + + Generate derived parameters for a key of length keySize, and + an initialisation vector (IV) of length ivSize. + + @param keySize the length, in bits, of the key required. + @param ivSize the length, in bits, of the iv required. + @return a parameters object representing a key and an IV. + + + Generate derived parameters for a key of length keySize, specifically + for use with a MAC. + + @param keySize the length, in bits, of the key required. + @return a parameters object representing a key. + + + converts a password to a byte array according to the scheme in + Pkcs5 (ascii, no padding) + + @param password a character array representing the password. + @return a byte array representing the password. + + + converts a password to a byte array according to the scheme in + PKCS5 (UTF-8, no padding) + + @param password a character array representing the password. + @return a byte array representing the password. + + + converts a password to a byte array according to the scheme in + Pkcs12 (unicode, big endian, 2 zero pad bytes at the end). + + @param password a character array representing the password. + @return a byte array representing the password. + + + Random generation based on the digest with counter. Calling AddSeedMaterial will + always increase the entropy of the hash. +

+ Internal access to the digest is synchronized so a single one of these can be shared. +

+
+ + Generic interface for objects generating random bytes. + + + Add more seed material to the generator. + A byte array to be mixed into the generator's state. + + + Add more seed material to the generator. + A long value to be mixed into the generator's state. + + + Fill byte array with random values. + Array to be filled. + + + Fill byte array with random values. + Array to receive bytes. + Index to start filling at. + Length of segment to fill. + + + + Takes bytes generated by an underling RandomGenerator and reverses the order in + each small window (of configurable size). +

+ Access to internals is synchronized so a single one of these can be shared. +

+
+
+ + Add more seed material to the generator. + A byte array to be mixed into the generator's state. + + + Add more seed material to the generator. + A long value to be mixed into the generator's state. + + + Fill byte array with random values. + Array to be filled. + + + Fill byte array with random values. + Array to receive bytes. + Index to start filling at. + Length of segment to fill. + + + A thread based seed generator - one source of randomness. +

+ Based on an idea from Marcus Lippert. +

+
+ + Generate seed bytes. Set fast to false for best quality. +

+ If fast is set to true, the code should be round about 8 times faster when + generating a long sequence of random bytes. 20 bytes of random values using + the fast mode take less than half a second on a Nokia e70. If fast is set to false, + it takes round about 2500 ms. +

+ @param numBytes the number of bytes to generate + @param fast true if fast mode should be used +
+ + + Permutation generated by code: + + // First 1850 fractional digit of Pi number. + byte[] key = new BigInteger("14159265358979323846...5068006422512520511").ToByteArray(); + s = 0; + P = new byte[256]; + for (int i = 0; i < 256; i++) + { + P[i] = (byte) i; + } + for (int m = 0; m < 768; m++) + { + s = P[(s + P[m & 0xff] + key[m % key.length]) & 0xff]; + byte temp = P[m & 0xff]; + P[m & 0xff] = P[s & 0xff]; + P[s & 0xff] = temp; + } + + + + Value generated in the same way as P. + + + update the internal digest with the byte b + + + update the internal digest with the byte array in + + + Generate a signature for the message we've been loaded with using + the key we were initialised with. + + + true if the internal state represents the signature described in the passed in array. + + + Reset the internal state + + + The Digital Signature Algorithm - as described in "Handbook of Applied + Cryptography", pages 452 - 453. + + + Generate a signature for the given message using the key we were + initialised with. For conventional DSA the message should be a SHA-1 + hash of the message of interest. + + @param message the message that will be verified later. + + + return true if the value r and s represent a DSA signature for + the passed in message for standard DSA the message should be a + SHA-1 hash of the real message to be verified. + + + EC-DSA as described in X9.62 + + + Generate a signature for the given message using the key we were + initialised with. For conventional DSA the message should be a SHA-1 + hash of the message of interest. + + @param message the message that will be verified later. + + + return true if the value r and s represent a DSA signature for + the passed in message (for standard DSA the message should be + a SHA-1 hash of the real message to be verified). + + + GOST R 34.10-2001 Signature Algorithm + + + generate a signature for the given message using the key we were + initialised with. For conventional GOST3410 the message should be a GOST3411 + hash of the message of interest. + + @param message the message that will be verified later. + + + return true if the value r and s represent a GOST3410 signature for + the passed in message (for standard GOST3410 the message should be + a GOST3411 hash of the real message to be verified). + + + EC-NR as described in IEEE 1363-2000 + + + generate a signature for the given message using the key we were + initialised with. Generally, the order of the curve should be at + least as long as the hash of the message of interest, and with + ECNR it *must* be at least as long. + + @param digest the digest to be signed. + @exception DataLengthException if the digest is longer than the key allows + + + return true if the value r and s represent a signature for the + message passed in. Generally, the order of the curve should be at + least as long as the hash of the message of interest, and with + ECNR, it *must* be at least as long. But just in case the signer + applied mod(n) to the longer digest, this implementation will + apply mod(n) during verification. + + @param digest the digest to be verified. + @param r the r value of the signature. + @param s the s value of the signature. + @exception DataLengthException if the digest is longer than the key allows + + + initialise the signer for signing or verification. + + @param forSigning + true if for signing, false otherwise + @param parameters + necessary parameters. + + + update the internal digest with the byte b + + + update the internal digest with the byte array in + + + Generate a signature for the message we've been loaded with using the key + we were initialised with. + + + return true if the internal state represents the signature described in + the passed in array. + + + update the internal digest with the byte b + + + update the internal digest with the byte array in + + + Generate a signature for the message we've been loaded with using + the key we were initialised with. + + + true if the internal state represents the signature described in the passed in array. + + + Reset the internal state + + + Gost R 34.10-94 Signature Algorithm + + + generate a signature for the given message using the key we were + initialised with. For conventional Gost3410 the message should be a Gost3411 + hash of the message of interest. + + @param message the message that will be verified later. + + + return true if the value r and s represent a Gost3410 signature for + the passed in message for standard Gost3410 the message should be a + Gost3411 hash of the real message to be verified. + + + ISO9796-2 - mechanism using a hash function with recovery (scheme 2 and 3). +

+ Note: the usual length for the salt is the length of the hash + function used in bytes.

+
+
+ + + Return a reference to the recoveredMessage message. + + The full/partial recoveredMessage message. + + + + + Generate a signer for the with either implicit or explicit trailers + for ISO9796-2, scheme 2 or 3. + + base cipher to use for signature creation/verification + digest to use. + length of salt in bytes. + whether or not the trailer is implicit or gives the hash. + + + Constructor for a signer with an explicit digest trailer. + + + cipher to use. + + digest to sign with. + + length of salt in bytes. + + + + Initialise the signer. + true if for signing, false if for verification. + parameters for signature generation/verification. If the + parameters are for generation they should be a ParametersWithRandom, + a ParametersWithSalt, or just an RsaKeyParameters object. If RsaKeyParameters + are passed in a SecureRandom will be created. + + if wrong parameter type or a fixed + salt is passed in which is the wrong length. + + + + compare two byte arrays - constant time. + + + clear possible sensitive data + + + update the internal digest with the byte b + + + update the internal digest with the byte array in + + + reset the internal state + + + Generate a signature for the loaded message using the key we were + initialised with. + + + + return true if the signature represents a ISO9796-2 signature + for the passed in message. + + + + + Return true if the full message was recoveredMessage. + + true on full message recovery, false otherwise, or if not sure. + + + + int to octet string. + int to octet string. + + + long to octet string. + + + mask generator function, as described in Pkcs1v2. + + + ISO9796-2 - mechanism using a hash function with recovery (scheme 1) + + + + Return a reference to the recoveredMessage message. + + The full/partial recoveredMessage message. + + + + + Generate a signer for the with either implicit or explicit trailers + for ISO9796-2. + + base cipher to use for signature creation/verification + digest to use. + whether or not the trailer is implicit or gives the hash. + + + Constructor for a signer with an explicit digest trailer. + + + cipher to use. + + digest to sign with. + + + + compare two byte arrays - constant time. + + + clear possible sensitive data + + + update the internal digest with the byte b + + + update the internal digest with the byte array in + + + reset the internal state + + + Generate a signature for the loaded message using the key we were + initialised with. + + + + return true if the signature represents a ISO9796-2 signature + for the passed in message. + + + + + Return true if the full message was recoveredMessage. + + true on full message recovery, false otherwise. + + + + RSA-PSS as described in Pkcs# 1 v 2.1. +

+ Note: the usual value for the salt length is the number of + bytes in the hash function.

+
+
+ + Basic constructor + the asymmetric cipher to use. + the digest to use. + the length of the salt to use (in bytes). + + + clear possible sensitive data + + + update the internal digest with the byte b + + + update the internal digest with the byte array in + + + reset the internal state + + + Generate a signature for the message we've been loaded with using + the key we were initialised with. + + + + return true if the internal state represents the signature described + in the passed in array. + + + + int to octet string. + + + mask generator function, as described in Pkcs1v2. + + + + Load oid table. + + + + Initialise the signer for signing or verification. + + @param forSigning true if for signing, false otherwise + @param param necessary parameters. + + + update the internal digest with the byte b + + + update the internal digest with the byte array in + + + Generate a signature for the message we've been loaded with using + the key we were initialised with. + + + return true if the internal state represents the signature described + in the passed in array. + + + a wrapper for block ciphers with a single byte block size, so that they + can be treated like stream ciphers. + + + basic constructor. + + @param cipher the block cipher to be wrapped. + @exception ArgumentException if the cipher has a block size other than + one. + + + initialise the underlying cipher. + + @param forEncryption true if we are setting up for encryption, false otherwise. + @param param the necessary parameters for the underlying cipher to be initialised. + + + return the name of the algorithm we are wrapping. + + @return the name of the algorithm we are wrapping. + + + encrypt/decrypt a single byte returning the result. + + @param in the byte to be processed. + @return the result of processing the input byte. + + + process a block of bytes from in putting the result into out. + + @param in the input byte array. + @param inOff the offset into the in array where the data to be processed starts. + @param len the number of bytes to be processed. + @param out the output buffer the processed bytes go into. + @param outOff the offset into the output byte array the processed data stars at. + @exception DataLengthException if the output buffer is too small. + + + reset the underlying cipher. This leaves it in the same state + it was at after the last init (if there was one). + + + + RFC 2246 7.2 + + + + + RFC 2246 7.2 + + + + + A certificate verifyer, that will always return true. +
+            DO NOT USE THIS FILE UNLESS YOU KNOW EXACTLY WHAT YOU ARE DOING.
+            
+
+
+ + Return true. + + + + A queue for bytes. +

+ This file could be more optimized. +

+
+
+ + The smallest number which can be written as 2^x which is bigger than i. + + + The initial size for our buffer. + + + The buffer where we store our data. + + + How many bytes at the beginning of the buffer are skipped. + + + How many bytes in the buffer are valid data. + + + Read data from the buffer. + The buffer where the read data will be copied to. + How many bytes to skip at the beginning of buf. + How many bytes to read at all. + How many bytes from our data to skip. + + + Add some data to our buffer. + A byte-array to read data from. + How many bytes to skip at the beginning of the array. + How many bytes to read from the array. + + + Remove some bytes from our data from the beginning. + How many bytes to remove. + + + The number of bytes which are available in this buffer. + + + A representation for a certificate chain. + + + The certificates. + + + Parse the ServerCertificate message. + + @param inStr The stream where to parse from. + @return A Certificate object with the certs, the server has sended. + @throws IOException If something goes wrong during parsing. + + + Encodes version of the ClientCertificate message + + @param outStr stream to write the message to + @throws IOException If something goes wrong + + + Private constructor from a cert array. + + @param certs The certs the chain should contain. + + + An array which contains the certs, this chain contains. + + + A of X509Name + + + + RFC 2246 A.5 + + + + + RFC 2246 7.4.4 + + + + A combined hash, which implements md5(m) || sha1(m). + + + + + + + + + + + + + + + + + + + + + + + + + RFC 2246 6.1 + + + + + RFC 2246 6.2.1 + + + + + + + + + + + + + + RFC 4492 5.4 + + + + Indicates the elliptic curve domain parameters are conveyed verbosely, and the + underlying finite field is a prime field. + + + Indicates the elliptic curve domain parameters are conveyed verbosely, and the + underlying finite field is a characteristic-2 field. + + + Indicates that a named curve is used. This option SHOULD be used when applicable. + + + + RFC 4492 5.1.2 + + + + + RFC 4366 2.3 + + + + + RFC 2246 7.4 + + + + + This should be implemented by any class which can find out, if a given + certificate chain is being accepted by an client. + + + + The certs, which are part of the chain. + True, if the chain is accepted, false otherwise + + + + A temporary class to wrap old CertificateVerifyer stuff for new TlsAuthentication. + + + + + A temporary class to use LegacyTlsAuthentication + + + + + RFC 4492 5.1.1 + The named curves defined here are those specified in SEC 2 [13]. Note that many of + these curves are also recommended in ANSI X9.62 [7] and FIPS 186-2 [11]. Values 0xFE00 + through 0xFEFF are reserved for private use. Values 0xFF01 and 0xFF02 indicate that the + client supports arbitrary prime and characteristic-2 curves, respectively (the curve + parameters must be encoded explicitly in ECParameters). + + + + An implementation of the TLS 1.0 record layer. + + + HMAC implementation based on original internet draft for HMAC (RFC 2104) + + The difference is that padding is concatentated versus XORed with the key + + H(K + opad, H(K + ipad, text)) + + + Base constructor for one of the standard digest algorithms that the byteLength of + the algorithm is know for. Behaviour is undefined for digests other than MD5 or SHA1. + + @param digest the digest. + + + Reset the mac generator. + + + + + + + Called by the protocol handler to report the server certificate. + + + This method is responsible for certificate verification and validation + + The server received + + + + + Return client credentials in response to server's certificate request + + + A containing server certificate request details + + + A to be used for client authentication + (or null for no client authentication) + + + + + + A generic TLS 1.0 block cipher. This can be used for AES or 3DES for example. + + + + + + + + + + + + + + Called at the start of a new TLS session, before any other methods. + + + A + + + + + Get the list of cipher suites that this client supports. + + + An array of , each specifying a supported cipher suite. + + + + + Get the list of compression methods that this client supports. + + + An array of , each specifying a supported compression method. + + + + + Get the (optional) table of client extensions to be included in (extended) client hello. + + + A ( -> byte[]). May be null. + + + + + + Reports the session ID once it has been determined. + + + A + + + + + Report the cipher suite that was selected by the server. + + + The protocol handler validates this value against the offered cipher suites + + + + A + + + + + Report the compression method that was selected by the server. + + + The protocol handler validates this value against the offered compression methods + + + + A + + + + + Report whether the server supports secure renegotiation + + + The protocol handler automatically processes the relevant extensions + + + A , true if the server supports secure renegotiation + + + + + + Report the extensions from an extended server hello. + + + Will only be called if we returned a non-null result from . + + + A ( -> byte[]) + + + + + Return an implementation of to negotiate the key exchange + part of the protocol. + + + A + + + + + + Return an implementation of to handle authentication + part of the protocol. + + + + + + Return an implementation of to handle record compression. + + + + + + Return an implementation of to use for encryption/decryption. + + + A + + + + + + TLS 1.0 DH key exchange. + + + + ECDHE key exchange (see RFC 4492) + + + ECDH key exchange (see RFC 4492) + + + + A generic interface for key exchange implementations in TLS 1.0. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + A generic TLS MAC implementation, which can be used with any kind of + IDigest to act as an HMAC. + + + + Generate a new instance of an TlsMac. + + @param digest The digest to use. + @param key_block A byte-array where the key for this mac is located. + @param offset The number of bytes to skip, before the key starts in the buffer. + @param len The length of the key. + + + @return the MAC write secret + + + @return the current write sequence number + + + Increment the current write sequence number + + + @return The Keysize of the mac. + + + Calculate the mac for some given data. +

+ TlsMac will keep track of the sequence number internally. + + @param type The message type of the message. + @param message A byte-buffer containing the message. + @param offset The number of bytes to skip, before the message starts. + @param len The length of the message. + @return A new byte-buffer containing the mac value. + + +

+ A NULL cipher suite, for use during handshake. + +
+ + An implementation of all high level protocols in TLS 1.0. + + + Both streams can be the same object + + + Both streams can be the same object + + + This method is called, when a change cipher spec message is received. + + @throws IOException If the message has an invalid content or the + handshake is not in the correct state. + + + Connects to the remote system. + Will be used when a certificate is received to verify + that this certificate is accepted by the client. + If handshake was not successful + + + Read data from the network. The method will return immediately, if there is + still some data left in the buffer, or block until some application + data has been read from the network. + + @param buf The buffer where the data will be copied to. + @param offset The position where the data will be placed in the buffer. + @param len The maximum number of bytes to read. + @return The number of bytes read. + @throws IOException If something goes wrong during reading data. + + + Send some application data to the remote system. +

+ The method will handle fragmentation internally. + + @param buf The buffer with the data. + @param offset The position in the buffer where the data is placed. + @param len The length of the data. + @throws IOException If something goes wrong during sending. + + +

A Stream which can be used to send data. +
+ + A Stream which can be used to read data. + + + The secure bidirectional stream for this connection + + + Terminate this connection with an alert. +

+ Can be used for normal closure too. + + @param alertLevel The level of the alert, an be AlertLevel.fatal or AL_warning. + @param alertDescription The exact alert message. + @throws IOException If alert was fatal. + + +

Closes this connection + If something goes wrong during closing. +
+ + Make sure the Stream is now empty. Fail otherwise. + + @param is The Stream to check. + @throws IOException If is is not empty. + + + + TLS 1.0 RSA key exchange. + + + + + + + + TLS 1.1 SRP key exchange. + + + + Some helper fuctions for MicroTLS. + + + return a = a + b - b preserved. + + + unsigned comparison on two arrays - note the arrays may + start with leading zeros. + + + return z = x / y - done in place (z value preserved, x contains the + remainder) + + + return whether or not a BigInteger is probably prime with a + probability of 1 - (1/2)**certainty. +

From Knuth Vol 2, pg 395.

+
+ + Calculate the numbers u1, u2, and u3 such that: + + u1 * a + u2 * b = u3 + + where u3 is the greatest common divider of a and b. + a and b using the extended Euclid algorithm (refer p. 323 + of The Art of Computer Programming vol 2, 2nd ed). + This also seems to have the side effect of calculating + some form of multiplicative inverse. + + @param a First number to calculate gcd for + @param b Second number to calculate gcd for + @param u1Out the return object for the u1 value + @param u2Out the return object for the u2 value + @return The greatest common divisor of a and b + + + return w with w = x * x - w is assumed to have enough space. + + + return x with x = y * z - x is assumed to have enough space. + + + Calculate mQuote = -m^(-1) mod b with b = 2^32 (32 = word size) + + + Montgomery multiplication: a = x * y * R^(-1) mod m +
+ Based algorithm 14.36 of Handbook of Applied Cryptography. +
+
  • m, x, y should have length n
  • +
  • a should have length (n + 1)
  • +
  • b = 2^32, R = b^n
  • +
    + The result is put in x +
    + NOTE: the indices of x, y, m, a different in HAC and in Java +
    + + return x = x % y - done in place (y value preserved) + + + do a left shift - this returns a new array. + + + do a right shift - this does it in place. + + + do a right shift by one - this does it in place. + + + returns x = x - y - we assume x is >= y + + + Class representing a simple version of a big decimal. A + SimpleBigDecimal is basically a + {@link java.math.BigInteger BigInteger} with a few digits on the right of + the decimal point. The number of (binary) digits on the right of the decimal + point is called the scale of the SimpleBigDecimal. + Unlike in {@link java.math.BigDecimal BigDecimal}, the scale is not adjusted + automatically, but must be set manually. All SimpleBigDecimals + taking part in the same arithmetic operation must have equal scale. The + result of a multiplication of two SimpleBigDecimals returns a + SimpleBigDecimal with double scale. + + + Returns a SimpleBigDecimal representing the same numerical + value as value. + @param value The value of the SimpleBigDecimal to be + created. + @param scale The scale of the SimpleBigDecimal to be + created. + @return The such created SimpleBigDecimal. + + + Constructor for SimpleBigDecimal. The value of the + constructed SimpleBigDecimal Equals bigInt / + 2scale. + @param bigInt The bigInt value parameter. + @param scale The scale of the constructed SimpleBigDecimal. + + + Class holding methods for point multiplication based on the window + τ-adic nonadjacent form (WTNAF). The algorithms are based on the + paper "Improved Algorithms for Arithmetic on Anomalous Binary Curves" + by Jerome A. Solinas. The paper first appeared in the Proceedings of + Crypto 1997. + + + The window width of WTNAF. The standard value of 4 is slightly less + than optimal for running time, but keeps space requirements for + precomputation low. For typical curves, a value of 5 or 6 results in + a better running time. When changing this value, the + αu's must be computed differently, see + e.g. "Guide to Elliptic Curve Cryptography", Darrel Hankerson, + Alfred Menezes, Scott Vanstone, Springer-Verlag New York Inc., 2004, + p. 121-122 + + + 24 + + + The αu's for a=0 as an array + of ZTauElements. + + + The αu's for a=0 as an array + of TNAFs. + + + The αu's for a=1 as an array + of ZTauElements. + + + The αu's for a=1 as an array + of TNAFs. + + + Computes the norm of an element λ of + Z[τ]. + @param mu The parameter μ of the elliptic curve. + @param lambda The element λ of + Z[τ]. + @return The norm of λ. + + + Computes the norm of an element λ of + R[τ], where λ = u + vτ + and u and u are real numbers (elements of + R). + @param mu The parameter μ of the elliptic curve. + @param u The real part of the element λ of + R[τ]. + @param v The τ-adic part of the element + λ of R[τ]. + @return The norm of λ. + + + Rounds an element λ of R[τ] + to an element of Z[τ], such that their difference + has minimal norm. λ is given as + λ = λ0 + λ1τ. + @param lambda0 The component λ0. + @param lambda1 The component λ1. + @param mu The parameter μ of the elliptic curve. Must + equal 1 or -1. + @return The rounded element of Z[τ]. + @throws ArgumentException if lambda0 and + lambda1 do not have same scale. + + + Approximate division by n. For an integer + k, the value λ = s k / n is + computed to c bits of accuracy. + @param k The parameter k. + @param s The curve parameter s0 or + s1. + @param vm The Lucas Sequence element Vm. + @param a The parameter a of the elliptic curve. + @param m The bit length of the finite field + Fm. + @param c The number of bits of accuracy, i.e. the scale of the returned + SimpleBigDecimal. + @return The value λ = s k / n computed to + c bits of accuracy. + + + Computes the τ-adic NAF (non-adjacent form) of an + element λ of Z[τ]. + @param mu The parameter μ of the elliptic curve. + @param lambda The element λ of + Z[τ]. + @return The τ-adic NAF of λ. + + + Applies the operation τ() to an + F2mPoint. + @param p The F2mPoint to which τ() is applied. + @return τ(p) + + + Returns the parameter μ of the elliptic curve. + @param curve The elliptic curve from which to obtain μ. + The curve must be a Koblitz curve, i.e. a Equals + 0 or 1 and b Equals + 1. + @return μ of the elliptic curve. + @throws ArgumentException if the given ECCurve is not a Koblitz + curve. + + + Calculates the Lucas Sequence elements Uk-1 and + Uk or Vk-1 and + Vk. + @param mu The parameter μ of the elliptic curve. + @param k The index of the second element of the Lucas Sequence to be + returned. + @param doV If set to true, computes Vk-1 and + Vk, otherwise Uk-1 and + Uk. + @return An array with 2 elements, containing Uk-1 + and Uk or Vk-1 + and Vk. + + + Computes the auxiliary value tw. If the width is + 4, then for mu = 1, tw = 6 and for + mu = -1, tw = 10 + @param mu The parameter μ of the elliptic curve. + @param w The window width of the WTNAF. + @return the auxiliary value tw + + + Computes the auxiliary values s0 and + s1 used for partial modular reduction. + @param curve The elliptic curve for which to compute + s0 and s1. + @throws ArgumentException if curve is not a + Koblitz curve (Anomalous Binary Curve, ABC). + + + Partial modular reduction modulo + m - 1)/(τ - 1). + @param k The integer to be reduced. + @param m The bitlength of the underlying finite field. + @param a The parameter a of the elliptic curve. + @param s The auxiliary values s0 and + s1. + @param mu The parameter μ of the elliptic curve. + @param c The precision (number of bits of accuracy) of the partial + modular reduction. + @return ρ := k partmod (τm - 1)/(τ - 1) + + + Multiplies a {@link org.bouncycastle.math.ec.F2mPoint F2mPoint} + by a BigInteger using the reduced τ-adic + NAF (RTNAF) method. + @param p The F2mPoint to Multiply. + @param k The BigInteger by which to Multiply p. + @return k * p + + + Multiplies a {@link org.bouncycastle.math.ec.F2mPoint F2mPoint} + by an element λ of Z[τ] + using the τ-adic NAF (TNAF) method. + @param p The F2mPoint to Multiply. + @param lambda The element λ of + Z[τ]. + @return λ * p + + + Multiplies a {@link org.bouncycastle.math.ec.F2mPoint F2mPoint} + by an element λ of Z[τ] + using the τ-adic NAF (TNAF) method, given the TNAF + of λ. + @param p The F2mPoint to Multiply. + @param u The the TNAF of λ.. + @return λ * p + + + Computes the [τ]-adic window NAF of an element + λ of Z[τ]. + @param mu The parameter μ of the elliptic curve. + @param lambda The element λ of + Z[τ] of which to compute the + [τ]-adic NAF. + @param width The window width of the resulting WNAF. + @param pow2w 2width. + @param tw The auxiliary value tw. + @param alpha The αu's for the window width. + @return The [τ]-adic window NAF of + λ. + + + Does the precomputation for WTNAF multiplication. + @param p The ECPoint for which to do the precomputation. + @param a The parameter a of the elliptic curve. + @return The precomputation array for p. + + + Class representing an element of Z[τ]. Let + λ be an element of Z[τ]. Then + λ is given as λ = u + vτ. The + components u and v may be used directly, there + are no accessor methods. + Immutable class. + + + The "real" part of λ. + + + The "τ-adic" part of λ. + + + Constructor for an element λ of + Z[τ]. + @param u The "real" part of λ. + @param v The "τ-adic" part of + λ. + + + Base class for an elliptic curve. + + + Decode a point on this curve from its ASN.1 encoding. The different + encodings are taken account of, including point compression for + Fp (X9.62 s 4.2.1 pg 17). + @return The decoded point. + + + Elliptic curve over Fp + + + Elliptic curves over F2m. The Weierstrass equation is given by + y2 + xy = x3 + ax2 + b. + + + The exponent m of F2m. + + + TPB: The integer k where xm + + xk + 1 represents the reduction polynomial + f(z).
    + PPB: The integer k1 where xm + + xk3 + xk2 + xk1 + 1 + represents the reduction polynomial f(z).
    +
    + + TPB: Always set to 0
    + PPB: The integer k2 where xm + + xk3 + xk2 + xk1 + 1 + represents the reduction polynomial f(z).
    +
    + + TPB: Always set to 0
    + PPB: The integer k3 where xm + + xk3 + xk2 + xk1 + 1 + represents the reduction polynomial f(z).
    +
    + + The order of the base point of the curve. + + + The cofactor of the curve. + + + The point at infinity on this curve. + + + The parameter μ of the elliptic curve if this is + a Koblitz curve. + + + The auxiliary values s0 and + s1 used for partial modular reduction for + Koblitz curves. + + + Constructor for Trinomial Polynomial Basis (TPB). + @param m The exponent m of + F2m. + @param k The integer k where xm + + xk + 1 represents the reduction + polynomial f(z). + @param a The coefficient a in the Weierstrass equation + for non-supersingular elliptic curves over + F2m. + @param b The coefficient b in the Weierstrass equation + for non-supersingular elliptic curves over + F2m. + + + Constructor for Trinomial Polynomial Basis (TPB). + @param m The exponent m of + F2m. + @param k The integer k where xm + + xk + 1 represents the reduction + polynomial f(z). + @param a The coefficient a in the Weierstrass equation + for non-supersingular elliptic curves over + F2m. + @param b The coefficient b in the Weierstrass equation + for non-supersingular elliptic curves over + F2m. + @param n The order of the main subgroup of the elliptic curve. + @param h The cofactor of the elliptic curve, i.e. + #Ea(F2m) = h * n. + + + Constructor for Pentanomial Polynomial Basis (PPB). + @param m The exponent m of + F2m. + @param k1 The integer k1 where xm + + xk3 + xk2 + xk1 + 1 + represents the reduction polynomial f(z). + @param k2 The integer k2 where xm + + xk3 + xk2 + xk1 + 1 + represents the reduction polynomial f(z). + @param k3 The integer k3 where xm + + xk3 + xk2 + xk1 + 1 + represents the reduction polynomial f(z). + @param a The coefficient a in the Weierstrass equation + for non-supersingular elliptic curves over + F2m. + @param b The coefficient b in the Weierstrass equation + for non-supersingular elliptic curves over + F2m. + + + Constructor for Pentanomial Polynomial Basis (PPB). + @param m The exponent m of + F2m. + @param k1 The integer k1 where xm + + xk3 + xk2 + xk1 + 1 + represents the reduction polynomial f(z). + @param k2 The integer k2 where xm + + xk3 + xk2 + xk1 + 1 + represents the reduction polynomial f(z). + @param k3 The integer k3 where xm + + xk3 + xk2 + xk1 + 1 + represents the reduction polynomial f(z). + @param a The coefficient a in the Weierstrass equation + for non-supersingular elliptic curves over + F2m. + @param b The coefficient b in the Weierstrass equation + for non-supersingular elliptic curves over + F2m. + @param n The order of the main subgroup of the elliptic curve. + @param h The cofactor of the elliptic curve, i.e. + #Ea(F2m) = h * n. + + + Returns true if this is a Koblitz curve (ABC curve). + @return true if this is a Koblitz curve (ABC curve), false otherwise + + + Returns the parameter μ of the elliptic curve. + @return μ of the elliptic curve. + @throws ArgumentException if the given ECCurve is not a + Koblitz curve. + + + @return the auxiliary values s0 and + s1 used for partial modular reduction for + Koblitz curves. + + + Solves a quadratic equation z2 + z = beta(X9.62 + D.1.6) The other solution is z + 1. + + @param beta + The value to solve the qradratic equation for. + @return the solution for z2 + z = beta or + null if no solution exists. + + + Return true if curve uses a Trinomial basis. + + @return true if curve Trinomial, false otherwise. + + + return the field name for this field. + + @return the string "Fp". + + + return a sqrt root - the routine verifies that the calculation + returns the right value - if none exists it returns null. + + + Class representing the Elements of the finite field + F2m in polynomial basis (PB) + representation. Both trinomial (Tpb) and pentanomial (Ppb) polynomial + basis representations are supported. Gaussian normal basis (GNB) + representation is not supported. + + + Indicates gaussian normal basis representation (GNB). Number chosen + according to X9.62. GNB is not implemented at present. + + + Indicates trinomial basis representation (Tpb). Number chosen + according to X9.62. + + + Indicates pentanomial basis representation (Ppb). Number chosen + according to X9.62. + + + Tpb or Ppb. + + + The exponent m of F2m. + + + Tpb: The integer k where xm + + xk + 1 represents the reduction polynomial + f(z).
    + Ppb: The integer k1 where xm + + xk3 + xk2 + xk1 + 1 + represents the reduction polynomial f(z).
    +
    + + Tpb: Always set to 0
    + Ppb: The integer k2 where xm + + xk3 + xk2 + xk1 + 1 + represents the reduction polynomial f(z).
    +
    + + Tpb: Always set to 0
    + Ppb: The integer k3 where xm + + xk3 + xk2 + xk1 + 1 + represents the reduction polynomial f(z).
    +
    + + The IntArray holding the bits. + + + The number of ints required to hold m bits. + + + Constructor for Ppb. + @param m The exponent m of + F2m. + @param k1 The integer k1 where xm + + xk3 + xk2 + xk1 + 1 + represents the reduction polynomial f(z). + @param k2 The integer k2 where xm + + xk3 + xk2 + xk1 + 1 + represents the reduction polynomial f(z). + @param k3 The integer k3 where xm + + xk3 + xk2 + xk1 + 1 + represents the reduction polynomial f(z). + @param x The BigInteger representing the value of the field element. + + + Constructor for Tpb. + @param m The exponent m of + F2m. + @param k The integer k where xm + + xk + 1 represents the reduction + polynomial f(z). + @param x The BigInteger representing the value of the field element. + + + Checks, if the ECFieldElements a and b + are elements of the same field F2m + (having the same representation). + @param a field element. + @param b field element to be compared. + @throws ArgumentException if a and b + are not elements of the same field + F2m (having the same + representation). + + + @return the representation of the field + F2m, either of + {@link F2mFieldElement.Tpb} (trinomial + basis representation) or + {@link F2mFieldElement.Ppb} (pentanomial + basis representation). + + + @return the degree m of the reduction polynomial + f(z). + + + @return Tpb: The integer k where xm + + xk + 1 represents the reduction polynomial + f(z).
    + Ppb: The integer k1 where xm + + xk3 + xk2 + xk1 + 1 + represents the reduction polynomial f(z).
    +
    + + @return Tpb: Always returns 0
    + Ppb: The integer k2 where xm + + xk3 + xk2 + xk1 + 1 + represents the reduction polynomial f(z).
    +
    + + @return Tpb: Always set to 0
    + Ppb: The integer k3 where xm + + xk3 + xk2 + xk1 + 1 + represents the reduction polynomial f(z).
    +
    + + base class for points on elliptic curves. + + + Sets the PreCompInfo. Used by ECMultipliers + to save the precomputation for this ECPoint to store the + precomputation result for use by subsequent multiplication. + @param preCompInfo The values precomputed by the + ECMultiplier. + + + Sets the appropriate ECMultiplier, unless already set. + + + return the field element encoded with point compression. (S 4.3.6) + + + Multiplies this ECPoint by the given number. + @param k The multiplicator. + @return k * this. + + + Elliptic curve points over Fp + + + Create a point which encodes with point compression. + + @param curve the curve to use + @param x affine x co-ordinate + @param y affine y co-ordinate + + + Create a point that encodes with or without point compresion. + + @param curve the curve to use + @param x affine x co-ordinate + @param y affine y co-ordinate + @param withCompression if true encode with point compression + + + Sets the default ECMultiplier, unless already set. + + + Elliptic curve points over F2m + + + @param curve base curve + @param x x point + @param y y point + + + @param curve base curve + @param x x point + @param y y point + @param withCompression true if encode with point compression. + + + Constructor for point at infinity + + + Check, if two ECPoints can be added or subtracted. + @param a The first ECPoint to check. + @param b The second ECPoint to check. + @throws IllegalArgumentException if a and b + cannot be added. + + + Adds another ECPoints.F2m to this without + checking if both points are on the same curve. Used by multiplication + algorithms, because there all points are a multiple of the same point + and hence the checks can be omitted. + @param b The other ECPoints.F2m to add to + this. + @return this + b + + + Subtracts another ECPoints.F2m from this + without checking if both points are on the same curve. Used by + multiplication algorithms, because there all points are a multiple + of the same point and hence the checks can be omitted. + @param b The other ECPoints.F2m to subtract from + this. + @return this - b + + + Sets the appropriate ECMultiplier, unless already set. + + + Interface for classes encapsulating a point multiplication algorithm + for ECPoints. + + + Multiplies the ECPoint p by k, i.e. + p is added k times to itself. + @param p The ECPoint to be multiplied. + @param k The factor by which p i multiplied. + @return p multiplied by k. + + + Class implementing the NAF (Non-Adjacent Form) multiplication algorithm. + + + D.3.2 pg 101 + @see org.bouncycastle.math.ec.multiplier.ECMultiplier#multiply(org.bouncycastle.math.ec.ECPoint, java.math.BigInteger) + + + Interface for classes storing precomputation data for multiplication + algorithms. Used as a Memento (see GOF patterns) for + WNafMultiplier. + + + Simple shift-and-add multiplication. Serves as reference implementation + to verify (possibly faster) implementations in + {@link org.bouncycastle.math.ec.ECPoint ECPoint}. + + @param p The point to multiply. + @param k The factor by which to multiply. + @return The result of the point multiplication k * p. + + + Class implementing the WNAF (Window Non-Adjacent Form) multiplication + algorithm. + + + Computes the Window NAF (non-adjacent Form) of an integer. + @param width The width w of the Window NAF. The width is + defined as the minimal number w, such that for any + w consecutive digits in the resulting representation, at + most one is non-zero. + @param k The integer of which the Window NAF is computed. + @return The Window NAF of the given width, such that the following holds: + k = −i=0l-1 ki2i + , where the ki denote the elements of the + returned sbyte[]. + + + Multiplies this by an integer k using the + Window NAF method. + @param k The integer by which this is multiplied. + @return A new ECPoint which equals this + multiplied by k. + + + Class holding precomputation data for the WNAF (Window Non-Adjacent Form) + algorithm. + + + Array holding the precomputed ECPoints used for the Window + NAF multiplication in + {@link org.bouncycastle.math.ec.multiplier.WNafMultiplier.multiply() + WNafMultiplier.multiply()}. + + + Holds an ECPoint representing twice(this). Used for the + Window NAF multiplication in + {@link org.bouncycastle.math.ec.multiplier.WNafMultiplier.multiply() + WNafMultiplier.multiply()}. + + + Class implementing the WTNAF (Window + τ-adic Non-Adjacent Form) algorithm. + + + Multiplies a {@link org.bouncycastle.math.ec.F2mPoint F2mPoint} + by k using the reduced τ-adic NAF (RTNAF) + method. + @param p The F2mPoint to multiply. + @param k The integer by which to multiply k. + @return p multiplied by k. + + + Multiplies a {@link org.bouncycastle.math.ec.F2mPoint F2mPoint} + by an element λ of Z[τ] using + the τ-adic NAF (TNAF) method. + @param p The F2mPoint to multiply. + @param lambda The element λ of + Z[τ] of which to compute the + [τ]-adic NAF. + @return p multiplied by λ. + + + Multiplies a {@link org.bouncycastle.math.ec.F2mPoint F2mPoint} + by an element λ of Z[τ] + using the window τ-adic NAF (TNAF) method, given the + WTNAF of λ. + @param p The F2mPoint to multiply. + @param u The the WTNAF of λ.. + @return λ * p + + + Class holding precomputation data for the WTNAF (Window + τ-adic Non-Adjacent Form) algorithm. + + + Array holding the precomputed F2mPoints used for the + WTNAF multiplication in + {@link org.bouncycastle.math.ec.multiplier.WTauNafMultiplier.multiply() + WTauNafMultiplier.multiply()}. + + + Constructor for WTauNafPreCompInfo + @param preComp Array holding the precomputed F2mPoints + used for the WTNAF multiplication in + {@link org.bouncycastle.math.ec.multiplier.WTauNafMultiplier.multiply() + WTauNafMultiplier.multiply()}. + + + @return the array holding the precomputed F2mPoints + used for the WTNAF multiplication in + {@link org.bouncycastle.math.ec.multiplier.WTauNafMultiplier.multiply() + WTauNafMultiplier.multiply()}. + + + + + BasicOcspResponse ::= SEQUENCE { + tbsResponseData ResponseData, + signatureAlgorithm AlgorithmIdentifier, + signature BIT STRING, + certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL + } + + + + + The DER encoding of the tbsResponseData field. + In the event of an encoding error. + + + The certificates, if any, associated with the response. + In the event of an encoding error. + + + + Verify the signature against the tbsResponseData object we contain. + + + + The ASN.1 encoded representation of this object. + + + Generator for basic OCSP response objects. + + + basic constructor + + + construct with the responderID to be the SHA-1 keyHash of the passed in public key. + + + Add a response for a particular Certificate ID. + + @param certID certificate ID details + @param certStatus status of the certificate - null if okay + + + Add a response for a particular Certificate ID. + + @param certID certificate ID details + @param certStatus status of the certificate - null if okay + @param singleExtensions optional extensions + + + Add a response for a particular Certificate ID. + + @param certID certificate ID details + @param nextUpdate date when next update should be requested + @param certStatus status of the certificate - null if okay + @param singleExtensions optional extensions + + + Add a response for a particular Certificate ID. + + @param certID certificate ID details + @param thisUpdate date this response was valid on + @param nextUpdate date when next update should be requested + @param certStatus status of the certificate - null if okay + @param singleExtensions optional extensions + + + Set the extensions for the response. + + @param responseExtensions the extension object to carry. + + + Return an IEnumerable of the signature names supported by the generator. + + @return an IEnumerable containing recognised names. + + + create from an issuer certificate and the serial number of the + certificate it signed. + @exception OcspException if any problems occur creating the id fields. + + + return the serial number for the certificate associated + with this request. + + + Create a new CertificateID for a new serial number derived from a previous one + calculated for the same CA certificate. + + @param original the previously calculated CertificateID for the CA. + @param newSerialNumber the serial number for the new certificate of interest. + + @return a new CertificateID for newSerialNumber + + +
    +             OcspRequest     ::=     SEQUENCE {
    +                   tbsRequest                  TBSRequest,
    +                   optionalSignature   [0]     EXPLICIT Signature OPTIONAL }
    +            
    +               TBSRequest      ::=     SEQUENCE {
    +                   version             [0]     EXPLICIT Version DEFAULT v1,
    +                   requestorName       [1]     EXPLICIT GeneralName OPTIONAL,
    +                   requestList                 SEQUENCE OF Request,
    +                   requestExtensions   [2]     EXPLICIT Extensions OPTIONAL }
    +            
    +               Signature       ::=     SEQUENCE {
    +                   signatureAlgorithm      AlgorithmIdentifier,
    +                   signature               BIT STRING,
    +                   certs               [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL}
    +            
    +               Version         ::=             INTEGER  {  v1(0) }
    +            
    +               Request         ::=     SEQUENCE {
    +                   reqCert                     CertID,
    +                   singleRequestExtensions     [0] EXPLICIT Extensions OPTIONAL }
    +            
    +               CertID          ::=     SEQUENCE {
    +                   hashAlgorithm       AlgorithmIdentifier,
    +                   issuerNameHash      OCTET STRING, -- Hash of Issuer's DN
    +                   issuerKeyHash       OCTET STRING, -- Hash of Issuers public key
    +                   serialNumber        CertificateSerialNumber }
    +             
    +
    + + Return the DER encoding of the tbsRequest field. + @return DER encoding of tbsRequest + @throws OcspException in the event of an encoding error. + + + return the object identifier representing the signature algorithm + + + If the request is signed return a possibly empty CertStore containing the certificates in the + request. If the request is not signed the method returns null. + + @return null if not signed, a CertStore otherwise + @throws OcspException + + + Return whether or not this request is signed. + + @return true if signed false otherwise. + + + Verify the signature against the TBSRequest object we contain. + + + return the ASN.1 encoded representation of this object. + + + Add a request for the given CertificateID. + + @param certId certificate ID of interest + + + Add a request with extensions + + @param certId certificate ID of interest + @param singleRequestExtensions the extensions to attach to the request + + + Set the requestor name to the passed in X509Principal + + @param requestorName a X509Principal representing the requestor name. + + + Generate an unsigned request + + @return the OcspReq + @throws OcspException + + + Return an IEnumerable of the signature names supported by the generator. + + @return an IEnumerable containing recognised names. + + + return the ASN.1 encoded representation of this object. + + + base generator for an OCSP response - at the moment this only supports the + generation of responses containing BasicOCSP responses. + + + note 4 is not used. + + + Carrier for a ResponderID. + + + wrapper for the RevokedInfo object + + + return the revocation reason. Note: this field is optional, test for it + with hasRevocationReason() first. + @exception InvalidOperationException if a reason is asked for and none is avaliable + + + Return the status object for the response - null indicates good. + + @return the status object for the response, null if it is good. + + + return the NextUpdate value - note: this is an optional field so may + be returned as null. + + @return nextUpdate, or null if not present. + + + wrapper for the UnknownInfo object + + + + Utility class for creating IBasicAgreement objects from their names/Oids + + + + + Cipher Utility class contains methods that can not be specifically grouped into other classes. + + + + + Returns a ObjectIdentifier for a give encoding. + + A string representation of the encoding. + A DerObjectIdentifier, null if the Oid is not available. + + + + Utility class for creating IDigest objects from their names/Oids + + + + + Returns a ObjectIdentifier for a given digest mechanism. + + A string representation of the digest meanism. + A DerObjectIdentifier, null if the Oid is not available. + + + + Utility class for creating HMac object from their names/Oids + + + + + + + + + + Returns a ObjectIdentifier for a give encoding. + + A string representation of the encoding. + A DerObjectIdentifier, null if the Oid is not available. + + + Use the specified instance of IRandomGenerator as random source. + + This constructor performs no seeding of either the IRandomGenerator or the + constructed SecureRandom. It is the responsibility of the client to provide + proper seed material as necessary/appropriate for the given IRandomGenerator + implementation. + + The source to generate all random bytes from. + + + base constructor. + + + create a SecurityUtilityException with the given message. + + @param message the message to be carried with the exception. + + + + Signer Utility class contains methods that can not be specifically grouped into other classes. + + + + + Returns a ObjectIdentifier for a give encoding. + + A string representation of the encoding. + A DerObjectIdentifier, null if the Oid is not available. + + + + Utility class for creating IWrapper objects from their names/Oids + + + + PEM generator for the original set of PEM objects used in Open SSL. + + + Class for reading OpenSSL PEM encoded streams containing + X509 certificates, PKCS8 encoded keys and PKCS7 objects. +

    + In the case of PKCS7 objects the reader will return a CMS ContentInfo object. Keys and + Certificates will be returned using the appropriate java.security type.

    +
    + + Create a new PemReader + + @param reader the Reader + + + Create a new PemReader with a password finder + + @param reader the Reader + @param pFinder the password finder + + + Reads in a X509Certificate. + + @return the X509Certificate + @throws IOException if an I/O error occured + + + Reads in a X509CRL. + + @return the X509Certificate + @throws IOException if an I/O error occured + + + Reads in a PKCS10 certification request. + + @return the certificate request. + @throws IOException if an I/O error occured + + + Reads in a X509 Attribute Certificate. + + @return the X509 Attribute Certificate + @throws IOException if an I/O error occured + + + Reads in a PKCS7 object. This returns a ContentInfo object suitable for use with the CMS + API. + + @return the X509Certificate + @throws IOException if an I/O error occured + + + Read a Key Pair + + + General purpose writer for OpenSSL PEM objects. + + + The TextWriter object to write the output to. + + + Constructor for an unencrypted private key PEM object. + + @param key private key to be encoded. + + + Constructor for an encrypted private key PEM object. + + @param key private key to be encoded + @param algorithm encryption algorithm to use + @param provider provider to use + @throws NoSuchAlgorithmException if algorithm/mode cannot be found + + + + A class for verifying and creating Pkcs10 Certification requests. + + + CertificationRequest ::= Sequence { + certificationRequestInfo CertificationRequestInfo, + signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }}, + signature BIT STRING + } + + CertificationRequestInfo ::= Sequence { + version Integer { v1(0) } (v1,...), + subject Name, + subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }}, + attributes [0] Attributes{{ CRIAttributes }} + } + + Attributes { ATTRIBUTE:IOSet } ::= Set OF Attr{{ IOSet }} + + Attr { ATTRIBUTE:IOSet } ::= Sequence { + type ATTRIBUTE.&id({IOSet}), + values Set SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{\@type}) + } + + see + + + + Instantiate a Pkcs10CertificationRequest object with the necessary credentials. + + Name of Sig Alg. + X509Name of subject eg OU="My unit." O="My Organisatioin" C="au" + Public Key to be included in cert reqest. + ASN1Set of Attributes. + Matching Private key for nominated (above) public key to be used to sign the request. + + + + Get the public key. + + The public key. + + + + Verify Pkcs10 Cert Request is valid. + + true = valid. + + + + A class for creating and verifying Pkcs10 Certification requests (this is an extension on ). + The requests are made using delay signing. This is useful for situations where + the private key is in another environment and not directly accessible (e.g. HSM) + So the first step creates the request, then the signing is done outside this + object and the signature is then used to complete the request. + + + CertificationRequest ::= Sequence { + certificationRequestInfo CertificationRequestInfo, + signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }}, + signature BIT STRING + } + + CertificationRequestInfo ::= Sequence { + version Integer { v1(0) } (v1,...), + subject Name, + subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }}, + attributes [0] Attributes{{ CRIAttributes }} + } + + Attributes { ATTRIBUTE:IOSet } ::= Set OF Attr{{ IOSet }} + + Attr { ATTRIBUTE:IOSet } ::= Sequence { + type ATTRIBUTE.&id({IOSet}), + values Set SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{\@type}) + } + + see + + + + Instantiate a Pkcs10CertificationRequest object with the necessary credentials. + + Name of Sig Alg. + X509Name of subject eg OU="My unit." O="My Organisatioin" C="au" + Public Key to be included in cert reqest. + ASN1Set of Attributes. + + After the object is constructed use the and finally the + SignRequest methods to finalize the request. + + + + simply return the cert entry for the private key + + + Utility class for reencoding PKCS#12 files to definite length. + + + Just re-encode the outer layer of the PKCS#12 file to definite length encoding. + + @param berPKCS12File - original PKCS#12 file + @return a byte array representing the DER encoding of the PFX structure + @throws IOException + + + Re-encode the PKCS#12 structure to definite length encoding at the inner layer + as well, recomputing the MAC accordingly. + + @param berPKCS12File - original PKCS12 file. + @param provider - provider to use for MAC calculation. + @return a byte array representing the DER encoding of the PFX structure. + @throws IOException on parsing, encoding errors. + + + + Returns the revocationDate. + + + + + Returns the certStatus. + + + + Returns an immutable Set of X.509 attribute certificate + extensions that this PkixAttrCertChecker supports or + null if no extensions are supported. +

    + Each element of the set is a String representing the + Object Identifier (OID) of the X.509 extension that is supported. +

    +

    + All X.509 attribute certificate extensions that a + PkixAttrCertChecker might possibly be able to process + should be included in the set. +

    + + @return an immutable Set of X.509 extension OIDs (in + String format) supported by this + PkixAttrCertChecker, or null if no + extensions are supported +
    + + Performs checks on the specified attribute certificate. Every handled + extension is rmeoved from the unresolvedCritExts + collection. + + @param attrCert The attribute certificate to be checked. + @param certPath The certificate path which belongs to the attribute + certificate issuer public key certificate. + @param holderCertPath The certificate path which belongs to the holder + certificate. + @param unresolvedCritExts a Collection of OID strings + representing the current set of unresolved critical extensions + @throws CertPathValidatorException if the specified attribute certificate + does not pass the check. + + + Returns a clone of this object. + + @return a copy of this PkixAttrCertChecker + + + Build and validate a CertPath using the given parameter. + + @param params PKIXBuilderParameters object containing all information to + build the CertPath + + + CertPathValidatorSpi implementation for X.509 Attribute Certificates la RFC 3281. + + @see org.bouncycastle.x509.ExtendedPkixParameters + + + Validates an attribute certificate with the given certificate path. + +

    + params must be an instance of + ExtendedPkixParameters. +

    + The target constraints in the params must be an + X509AttrCertStoreSelector with at least the attribute + certificate criterion set. Obey that also target informations may be + necessary to correctly validate this attribute certificate. +

    + The attribute certificate issuer must be added to the trusted attribute + issuers with {@link ExtendedPkixParameters#setTrustedACIssuers(Set)}. +

    + @param certPath The certificate path which belongs to the attribute + certificate issuer public key certificate. + @param params The PKIX parameters. + @return A PKIXCertPathValidatorResult of the result of + validating the certPath. + @throws InvalidAlgorithmParameterException if params is + inappropriate for this validator. + @throws CertPathValidatorException if the verification fails. +
    + + + Summary description for PkixBuilderParameters. + + + + Returns an instance of PkixBuilderParameters. +

    + This method can be used to get a copy from other + PKIXBuilderParameters, PKIXParameters, + and ExtendedPKIXParameters instances. +

    + + @param pkixParams The PKIX parameters to create a copy of. + @return An PkixBuilderParameters instance. +
    + + + Excluded certificates are not used for building a certification path. + + the excluded certificates. + + + + Sets the excluded certificates which are not used for building a + certification path. If the ISet is null an + empty set is assumed. + + + The given set is cloned to protect it against subsequent modifications. + + The excluded certificates to set. + + + Can alse handle ExtendedPKIXBuilderParameters and + PKIXBuilderParameters. + + @param params Parameters to set. + @see org.bouncycastle.x509.ExtendedPKIXParameters#setParams(java.security.cert.PKIXParameters) + + + Makes a copy of this PKIXParameters object. Changes to the + copy will not affect the original and vice versa. + + @return a copy of this PKIXParameters object + + + An immutable sequence of certificates (a certification path).
    +
    + This is an abstract class that defines the methods common to all CertPaths. + Subclasses can handle different kinds of certificates (X.509, PGP, etc.).
    +
    + All CertPath objects have a type, a list of Certificates, and one or more + supported encodings. Because the CertPath class is immutable, a CertPath + cannot change in any externally visible way after being constructed. This + stipulation applies to all public fields and methods of this class and any + added or overridden by subclasses.
    +
    + The type is a string that identifies the type of Certificates in the + certification path. For each certificate cert in a certification path + certPath, cert.getType().equals(certPath.getType()) must be true.
    +
    + The list of Certificates is an ordered List of zero or more Certificates. + This List and all of the Certificates contained in it must be immutable.
    +
    + Each CertPath object must support one or more encodings so that the object + can be translated into a byte array for storage or transmission to other + parties. Preferably, these encodings should be well-documented standards + (such as PKCS#7). One of the encodings supported by a CertPath is considered + the default encoding. This encoding is used if no encoding is explicitly + requested (for the {@link #getEncoded()} method, for instance).
    +
    + All CertPath objects are also Serializable. CertPath objects are resolved + into an alternate {@link CertPathRep} object during serialization. This + allows a CertPath object to be serialized into an equivalent representation + regardless of its underlying implementation.
    +
    + CertPath objects can be created with a CertificateFactory or they can be + returned by other classes, such as a CertPathBuilder.
    +
    + By convention, X.509 CertPaths (consisting of X509Certificates), are ordered + starting with the target certificate and ending with a certificate issued by + the trust anchor. That is, the issuer of one certificate is the subject of + the following one. The certificate representing the + {@link TrustAnchor TrustAnchor} should not be included in the certification + path. Unvalidated X.509 CertPaths may not follow these conventions. PKIX + CertPathValidators will detect any departure from these conventions that + cause the certification path to be invalid and throw a + CertPathValidatorException.
    +
    + Concurrent Access
    +
    + All CertPath objects must be thread-safe. That is, multiple threads may + concurrently invoke the methods defined in this class on a single CertPath + object (or more than one) with no ill effects. This is also true for the List + returned by CertPath.getCertificates.
    +
    + Requiring CertPath objects to be immutable and thread-safe allows them to be + passed around to various pieces of code without worrying about coordinating + access. Providing this thread-safety is generally not difficult, since the + CertPath and List objects in question are immutable. + + @see CertificateFactory + @see CertPathBuilder + + CertPath implementation for X.509 certificates. + +
    + + @param certs + + + Creates a CertPath of the specified type. + This constructor is protected because most users should use + a CertificateFactory to create CertPaths. + @param type the standard name of the type of Certificatesin this path + + + + Creates a CertPath of the specified type. + This constructor is protected because most users should use + a CertificateFactory to create CertPaths. + + @param type the standard name of the type of Certificatesin this path + + + + Returns an iteration of the encodings supported by this + certification path, with the default encoding + first. Attempts to modify the returned Iterator via its + remove method result in an UnsupportedOperationException. + + @return an Iterator over the names of the supported encodings (as Strings) + + + + Compares this certification path for equality with the specified object. + Two CertPaths are equal if and only if their types are equal and their + certificate Lists (and by implication the Certificates in those Lists) + are equal. A CertPath is never equal to an object that is not a CertPath.
    +
    + This algorithm is implemented by this method. If it is overridden, the + behavior specified here must be maintained. + + @param other + the object to test for equality with this certification path + + @return true if the specified object is equal to this certification path, + false otherwise + + @see Object#hashCode() Object.hashCode() +
    + + Returns the encoded form of this certification path, using + the default encoding. + + @return the encoded bytes + @exception CertificateEncodingException if an encoding error occurs + + + + Returns the encoded form of this certification path, using + the specified encoding. + + @param encoding the name of the encoding to use + @return the encoded bytes + @exception CertificateEncodingException if an encoding error + occurs or the encoding requested is not supported + + + + + Returns the list of certificates in this certification + path. + + + + Return a DERObject containing the encoded certificate. + + @param cert the X509Certificate object to be encoded + + @return the DERObject + + + + Implements the PKIX CertPathBuilding algorithm for BouncyCastle. + + @see CertPathBuilderSpi + + + Build and validate a CertPath using the given parameter. + + @param params PKIXBuilderParameters object containing all information to + build the CertPath + + + + Summary description for PkixCertPathBuilderException. + + + + + Summary description for PkixCertPathBuilderResult. + + + + * Initializes the internal state of this PKIXCertPathChecker. + *

    + * The forward flag specifies the order that certificates + * will be passed to the {@link #check check} method (forward or reverse). A + * PKIXCertPathChecker must support reverse checking + * and may support forward checking. + *

    + * + * @param forward + * the order that certificates are presented to the + * check method. If true, + * certificates are presented from target to most-trusted CA + * (forward); if false, from most-trusted CA to + * target (reverse). + * @exception CertPathValidatorException + * if this PKIXCertPathChecker is unable to + * check certificates in the specified order; it should never + * be thrown if the forward flag is false since reverse + * checking must be supported +
    + + Indicates if forward checking is supported. Forward checking refers to + the ability of the PKIXCertPathChecker to perform its + checks when certificates are presented to the check method + in the forward direction (from target to most-trusted CA). + + @return true if forward checking is supported, + false otherwise + + + * Returns an immutable Set of X.509 certificate extensions + * that this PKIXCertPathChecker supports (i.e. recognizes, + * is able to process), or null if no extensions are + * supported. + *

    + * Each element of the set is a String representing the + * Object Identifier (OID) of the X.509 extension that is supported. The OID + * is represented by a set of nonnegative integers separated by periods. + *

    + * All X.509 certificate extensions that a PKIXCertPathChecker + * might possibly be able to process should be included in the set. + *

    + * + * @return an immutable Set of X.509 extension OIDs (in + * String format) supported by this + * PKIXCertPathChecker, or null if no + * extensions are supported +
    + + Performs the check(s) on the specified certificate using its internal + state and removes any critical extensions that it processes from the + specified collection of OID strings that represent the unresolved + critical extensions. The certificates are presented in the order + specified by the init method. + + @param cert + the Certificate to be checked + @param unresolvedCritExts + a Collection of OID strings representing the + current set of unresolved critical extensions + @exception CertPathValidatorException + if the specified certificate does not pass the check + + + Returns a clone of this object. Calls the Object.clone() + method. All subclasses which maintain state must support and override + this method, if necessary. + + @return a copy of this PKIXCertPathChecker + + + The Service Provider Interface (SPI) + for the {@link CertPathValidator CertPathValidator} class. All + CertPathValidator implementations must include a class (the + SPI class) that extends this class (CertPathValidatorSpi) + and implements all of its methods. In general, instances of this class + should only be accessed through the CertPathValidator class. + For details, see the Java Cryptography Architecture.
    +
    + Concurrent Access
    +
    + Instances of this class need not be protected against concurrent + access from multiple threads. Threads that need to access a single + CertPathValidatorSpi instance concurrently should synchronize + amongst themselves and provide the necessary locking before calling the + wrapping CertPathValidator object.
    +
    + However, implementations of CertPathValidatorSpi may still + encounter concurrency issues, since multiple threads each + manipulating a different CertPathValidatorSpi instance need not + synchronize. + + CertPathValidatorSpi implementation for X.509 Certificate validation a la RFC + 3280. + +
    + + An exception indicating one of a variety of problems encountered when + validating a certification path.
    +
    + A CertPathValidatorException provides support for wrapping + exceptions. The {@link #getCause getCause} method returns the throwable, + if any, that caused this exception to be thrown.
    +
    + A CertPathValidatorException may also include the + certification path that was being validated when the exception was thrown + and the index of the certificate in the certification path that caused the + exception to be thrown. Use the {@link #getCertPath getCertPath} and + {@link #getIndex getIndex} methods to retrieve this information.
    +
    + Concurrent Access
    +
    + Unless otherwise specified, the methods defined in this class are not + thread-safe. Multiple threads that need to access a single + object concurrently should synchronize amongst themselves and + provide the necessary locking. Multiple threads each manipulating + separate objects need not synchronize. + + @see CertPathValidator + +
    + + + Creates a PkixCertPathValidatorException with the given detail + message. A detail message is a String that describes this + particular exception. + + the detail message + + + + Creates a PkixCertPathValidatorException with the specified + detail message and cause. + + the detail message + the cause (which is saved for later retrieval by the + {@link #getCause getCause()} method). (A null + value is permitted, and indicates that the cause is + nonexistent or unknown.) + + + + Creates a PkixCertPathValidatorException with the specified + detail message, cause, certification path, and index. + + the detail message (or null if none) + the cause (or null if none) + the certification path that was in the process of being + validated when the error was encountered + the index of the certificate in the certification path that * + + + + Returns the detail message for this CertPathValidatorException. + + the detail message, or null if neither the message nor cause were specified + + + Returns the certification path that was being validated when the + exception was thrown. + + @return the CertPath that was being validated when the + exception was thrown (or null if not specified) + + + Returns the index of the certificate in the certification path that + caused the exception to be thrown. Note that the list of certificates in + a CertPath is zero based. If no index has been set, -1 is + returned. + + @return the index that has been set, or -1 if none has been set + + + + Summary description for PkixCertPathValidatorResult. + + + + + Summary description for PkixCertPathValidatorUtilities. + + + + + key usage bits + + + + + Search the given Set of TrustAnchor's for one that is the + issuer of the given X509 certificate. + + the X509 certificate + a Set of TrustAnchor's + the TrustAnchor object if found or + null if not. + + @exception + + + + Returns the issuer of an attribute certificate or certificate. + + The attribute certificate or certificate. + The issuer as X500Principal. + + + Return the next working key inheriting DSA parameters if necessary. +

    + This methods inherits DSA parameters from the indexed certificate or + previous certificates in the certificate chain to the returned + PublicKey. The list is searched upwards, meaning the end + certificate is at position 0 and previous certificates are following. +

    +

    + If the indexed certificate does not contain a DSA key this method simply + returns the public key. If the DSA key already contains DSA parameters + the key is also only returned. +

    + + @param certs The certification path. + @param index The index of the certificate which contains the public key + which should be extended with DSA parameters. + @return The public key of the certificate in list position + index extended with DSA parameters if applicable. + @throws Exception if DSA parameters cannot be inherited. +
    + + + Return a Collection of all certificates or attribute certificates found + in the X509Store's that are matching the certSelect criteriums. + + a {@link Selector} object that will be used to select + the certificates + a List containing only X509Store objects. These + are used to search for certificates. + a Collection of all found or + org.bouncycastle.x509.X509AttributeCertificate objects. + May be empty but never null. + + + + Add the CRL issuers from the cRLIssuer field of the distribution point or + from the certificate if not given to the issuer criterion of the + selector. +

    + The issuerPrincipals are a collection with a single + X500Principal for X509Certificates. For + {@link X509AttributeCertificate}s the issuer may contain more than one + X500Principal. +

    + + @param dp The distribution point. + @param issuerPrincipals The issuers of the certificate or attribute + certificate which contains the distribution point. + @param selector The CRL selector. + @param pkixParams The PKIX parameters containing the cert stores. + @throws Exception if an exception occurs while processing. + @throws ClassCastException if issuerPrincipals does not + contain only X500Principals. +
    + + Fetches complete CRLs according to RFC 3280. + + @param dp The distribution point for which the complete CRL + @param cert The X509Certificate or + {@link org.bouncycastle.x509.X509AttributeCertificate} for + which the CRL should be searched. + @param currentDate The date for which the delta CRLs must be valid. + @param paramsPKIX The extended PKIX parameters. + @return A Set of X509CRLs with complete + CRLs. + @throws Exception if an exception occurs while picking the CRLs + or no CRLs are found. + + + Fetches delta CRLs according to RFC 3280 section 5.2.4. + + @param currentDate The date for which the delta CRLs must be valid. + @param paramsPKIX The extended PKIX parameters. + @param completeCRL The complete CRL the delta CRL is for. + @return A Set of X509CRLs with delta CRLs. + @throws Exception if an exception occurs while picking the delta + CRLs. + + + Find the issuer certificates of a given certificate. + + @param cert + The certificate for which an issuer should be found. + @param pkixParams + @return A Collection object containing the issuer + X509Certificates. Never null. + + @exception Exception + if an error occurs. + + + + Extract the value of the given extension, if it exists. + + The extension object. + The object identifier to obtain. + Asn1Object + if the extension cannot be read. + + + + crl checking + Return a Collection of all CRLs found in the X509Store's that are + matching the crlSelect criteriums. + + a {@link X509CRLStoreSelector} object that will be used + to select the CRLs + a List containing only {@link org.bouncycastle.x509.X509Store + X509Store} objects. These are used to search for CRLs + a Collection of all found {@link X509CRL X509CRL} objects. May be + empty but never null. + + + + Returns the intersection of the permitted IP ranges in + permitted with ip. + + @param permitted A Set of permitted IP addresses with + their subnet mask as byte arrays. + @param ips The IP address with its subnet mask. + @return The Set of permitted IP ranges intersected with + ip. + + + Returns the union of the excluded IP ranges in excluded + with ip. + + @param excluded A Set of excluded IP addresses with their + subnet mask as byte arrays. + @param ip The IP address with its subnet mask. + @return The Set of excluded IP ranges unified with + ip as byte arrays. + + + Calculates the union if two IP ranges. + + @param ipWithSubmask1 The first IP address with its subnet mask. + @param ipWithSubmask2 The second IP address with its subnet mask. + @return A Set with the union of both addresses. + + + Calculates the interesction if two IP ranges. + + @param ipWithSubmask1 The first IP address with its subnet mask. + @param ipWithSubmask2 The second IP address with its subnet mask. + @return A Set with the single IP address with its subnet + mask as a byte array or an empty Set. + + + Concatenates the IP address with its subnet mask. + + @param ip The IP address. + @param subnetMask Its subnet mask. + @return The concatenated IP address with its subnet mask. + + + Splits the IP addresses and their subnet mask. + + @param ipWithSubmask1 The first IP address with the subnet mask. + @param ipWithSubmask2 The second IP address with the subnet mask. + @return An array with two elements. Each element contains the IP address + and the subnet mask in this order. + + + Based on the two IP addresses and their subnet masks the IP range is + computed for each IP address - subnet mask pair and returned as the + minimum IP address and the maximum address of the range. + + @param ip1 The first IP address. + @param subnetmask1 The subnet mask of the first IP address. + @param ip2 The second IP address. + @param subnetmask2 The subnet mask of the second IP address. + @return A array with two elements. The first/second element contains the + min and max IP address of the first/second IP address and its + subnet mask. + + + Checks if the IP ip is included in the permitted ISet + permitted. + + @param permitted A Set of permitted IP addresses with + their subnet mask as byte arrays. + @param ip The IP address. + @throws PkixNameConstraintValidatorException + if the IP is not permitted. + + + Checks if the IP ip is included in the excluded ISet + excluded. + + @param excluded A Set of excluded IP addresses with their + subnet mask as byte arrays. + @param ip The IP address. + @throws PkixNameConstraintValidatorException + if the IP is excluded. + + + Checks if the IP address ip is constrained by + constraint. + + @param ip The IP address. + @param constraint The constraint. This is an IP address concatenated with + its subnetmask. + @return true if constrained, false + otherwise. + + + The common part of email1 and email2 is + added to the union union. If email1 and + email2 have nothing in common they are added both. + + @param email1 Email address constraint 1. + @param email2 Email address constraint 2. + @param union The union. + + + The most restricting part from email1 and + email2 is added to the intersection intersect. + + @param email1 Email address constraint 1. + @param email2 Email address constraint 2. + @param intersect The intersection. + + + Checks if the given GeneralName is in the permitted ISet. + + @param name The GeneralName + @throws PkixNameConstraintValidatorException + If the name + + + Check if the given GeneralName is contained in the excluded ISet. + + @param name The GeneralName. + @throws PkixNameConstraintValidatorException + If the name is + excluded. + + + Updates the permitted ISet of these name constraints with the intersection + with the given subtree. + + @param permitted The permitted subtrees + + + Adds a subtree to the excluded ISet of these name constraints. + + @param subtree A subtree with an excluded GeneralName. + + + Returns the maximum IP address. + + @param ip1 The first IP address. + @param ip2 The second IP address. + @return The maximum IP address. + + + Returns the minimum IP address. + + @param ip1 The first IP address. + @param ip2 The second IP address. + @return The minimum IP address. + + + Compares IP address ip1 with ip2. If ip1 + is equal to ip2 0 is returned. If ip1 is bigger 1 is returned, -1 + otherwise. + + @param ip1 The first IP address. + @param ip2 The second IP address. + @return 0 if ip1 is equal to ip2, 1 if ip1 is bigger, -1 otherwise. + + + Returns the logical OR of the IP addresses ip1 and + ip2. + + @param ip1 The first IP address. + @param ip2 The second IP address. + @return The OR of ip1 and ip2. + + + Stringifies an IPv4 or v6 address with subnet mask. + + @param ip The IP with subnet mask. + @return The stringified IP address. + + + + Summary description for PkixParameters. + + + + This is the default PKIX validity model. Actually there are two variants + of this: The PKIX model and the modified PKIX model. The PKIX model + verifies that all involved certificates must have been valid at the + current time. The modified PKIX model verifies that all involved + certificates were valid at the signing time. Both are indirectly choosen + with the {@link PKIXParameters#setDate(java.util.Date)} method, so this + methods sets the Date when all certificates must have been + valid. + + + This model uses the following validity model. Each certificate must have + been valid at the moment where is was used. That means the end + certificate must have been valid at the time the signature was done. The + CA certificate which signed the end certificate must have been valid, + when the end certificate was signed. The CA (or Root CA) certificate must + have been valid, when the CA certificate was signed and so on. So the + {@link PKIXParameters#setDate(java.util.Date)} method sets the time, when + the end certificate must have been valid.

    It is used e.g. + in the German signature law. + + + Creates an instance of PKIXParameters with the specified Set of + most-trusted CAs. Each element of the set is a TrustAnchor.
    +
    + Note that the Set is copied to protect against subsequent modifications. + + @param trustAnchors + a Set of TrustAnchors + + @exception InvalidAlgorithmParameterException + if the specified Set is empty + (trustAnchors.isEmpty() == true) + @exception NullPointerException + if the specified Set is null + @exception ClassCastException + if any of the elements in the Set are not of type + java.security.cert.TrustAnchor +
    + + Returns the required constraints on the target certificate. The + constraints are returned as an instance of CertSelector. If + null, no constraints are defined.
    +
    + Note that the CertSelector returned is cloned to protect against + subsequent modifications. + + @return a CertSelector specifying the constraints on the target + certificate (or null) + + @see #setTargetCertConstraints(CertSelector) +
    + + Sets the required constraints on the target certificate. The constraints + are specified as an instance of CertSelector. If null, no constraints are + defined.
    +
    + Note that the CertSelector specified is cloned to protect against + subsequent modifications. + + @param selector + a CertSelector specifying the constraints on the target + certificate (or null) + + @see #getTargetCertConstraints() +
    + + Returns an immutable Set of initial policy identifiers (OID strings), + indicating that any one of these policies would be acceptable to the + certificate user for the purposes of certification path processing. The + default return value is an empty Set, which is + interpreted as meaning that any policy would be acceptable. + + @return an immutable Set of initial policy OIDs in String + format, or an empty Set (implying any policy is + acceptable). Never returns null. + + @see #setInitialPolicies(java.util.Set) + + + Sets the Set of initial policy identifiers (OID strings), + indicating that any one of these policies would be acceptable to the + certificate user for the purposes of certification path processing. By + default, any policy is acceptable (i.e. all policies), so a user that + wants to allow any policy as acceptable does not need to call this + method, or can call it with an empty Set (or + null).
    +
    + Note that the Set is copied to protect against subsequent modifications.
    +
    + + @param initialPolicies + a Set of initial policy OIDs in String format (or + null) + + @exception ClassCastException + if any of the elements in the set are not of type String + + @see #getInitialPolicies() +
    + + Sets a List of additional certification path checkers. If + the specified List contains an object that is not a PKIXCertPathChecker, + it is ignored.
    +
    + Each PKIXCertPathChecker specified implements additional + checks on a certificate. Typically, these are checks to process and + verify private extensions contained in certificates. Each + PKIXCertPathChecker should be instantiated with any + initialization parameters needed to execute the check.
    +
    + This method allows sophisticated applications to extend a PKIX + CertPathValidator or CertPathBuilder. Each + of the specified PKIXCertPathCheckers will be called, in turn, by a PKIX + CertPathValidator or CertPathBuilder for + each certificate processed or validated.
    +
    + Regardless of whether these additional PKIXCertPathCheckers are set, a + PKIX CertPathValidator or CertPathBuilder + must perform all of the required PKIX checks on each certificate. The one + exception to this rule is if the RevocationEnabled flag is set to false + (see the {@link #setRevocationEnabled(boolean) setRevocationEnabled} + method).
    +
    + Note that the List supplied here is copied and each PKIXCertPathChecker + in the list is cloned to protect against subsequent modifications. + + @param checkers + a List of PKIXCertPathCheckers. May be null, in which case no + additional checkers will be used. + @exception ClassCastException + if any of the elements in the list are not of type + java.security.cert.PKIXCertPathChecker + @see #getCertPathCheckers() +
    + + Returns the List of certification path checkers. Each PKIXCertPathChecker + in the returned IList is cloned to protect against subsequent modifications. + + @return an immutable List of PKIXCertPathCheckers (may be empty, but not + null) + + @see #setCertPathCheckers(java.util.List) + + + Adds a PKIXCertPathChecker to the list of certification + path checkers. See the {@link #setCertPathCheckers setCertPathCheckers} + method for more details. +

    + Note that the PKIXCertPathChecker is cloned to protect + against subsequent modifications.

    + + @param checker a PKIXCertPathChecker to add to the list of + checks. If null, the checker is ignored (not added to list). +
    + + Method to support Clone() under J2ME. + super.Clone() does not exist and fields are not copied. + + @param params Parameters to set. If this are + ExtendedPkixParameters they are copied to. + + + Whether delta CRLs should be used for checking the revocation status. + Defaults to false. + + + The validity model. + @see #CHAIN_VALIDITY_MODEL + @see #PKIX_VALIDITY_MODEL + + + Sets the Bouncy Castle Stores for finding CRLs, certificates, attribute + certificates or cross certificates. +

    + The IList is cloned. +

    + + @param stores A list of stores to use. + @see #getStores + @throws ClassCastException if an element of stores is not + a {@link Store}. +
    + + Adds a Bouncy Castle {@link Store} to find CRLs, certificates, attribute + certificates or cross certificates. +

    + This method should be used to add local stores, like collection based + X.509 stores, if available. Local stores should be considered first, + before trying to use additional (remote) locations, because they do not + need possible additional network traffic. +

    + If store is null it is ignored. +

    + + @param store The store to add. + @see #getStores +
    + + Adds an additional Bouncy Castle {@link Store} to find CRLs, certificates, + attribute certificates or cross certificates. +

    + You should not use this method. This method is used for adding additional + X.509 stores, which are used to add (remote) locations, e.g. LDAP, found + during X.509 object processing, e.g. in certificates or CRLs. This method + is used in PKIX certification path processing. +

    + If store is null it is ignored. +

    + + @param store The store to add. + @see #getStores() +
    + + Returns an IList of additional Bouncy Castle + Stores used for finding CRLs, certificates, attribute + certificates or cross certificates. + + @return an immutable IList of additional Bouncy Castle + Stores. Never null. + + @see #addAddionalStore(Store) + + + Returns an IList of Bouncy Castle + Stores used for finding CRLs, certificates, attribute + certificates or cross certificates. + + @return an immutable IList of Bouncy Castle + Stores. Never null. + + @see #setStores(IList) + + + Returns if additional {@link X509Store}s for locations like LDAP found + in certificates or CRLs should be used. + + @return Returns true if additional stores are used. + + + Sets if additional {@link X509Store}s for locations like LDAP found in + certificates or CRLs should be used. + + @param enabled true if additional stores are used. + + + Returns the required constraints on the target certificate or attribute + certificate. The constraints are returned as an instance of + IX509Selector. If null, no constraints are + defined. + +

    + The target certificate in a PKIX path may be a certificate or an + attribute certificate. +

    + Note that the IX509Selector returned is cloned to protect + against subsequent modifications. +

    + @return a IX509Selector specifying the constraints on the + target certificate or attribute certificate (or null) + @see #setTargetConstraints + @see X509CertStoreSelector + @see X509AttributeCertStoreSelector +
    + + Sets the required constraints on the target certificate or attribute + certificate. The constraints are specified as an instance of + IX509Selector. If null, no constraints are + defined. +

    + The target certificate in a PKIX path may be a certificate or an + attribute certificate. +

    + Note that the IX509Selector specified is cloned to protect + against subsequent modifications. +

    + + @param selector a IX509Selector specifying the constraints on + the target certificate or attribute certificate (or + null) + @see #getTargetConstraints + @see X509CertStoreSelector + @see X509AttributeCertStoreSelector +
    + + Returns the trusted attribute certificate issuers. If attribute + certificates is verified the trusted AC issuers must be set. +

    + The returned ISet consists of TrustAnchors. +

    + The returned ISet is immutable. Never null +

    + + @return Returns an immutable set of the trusted AC issuers. +
    + + Sets the trusted attribute certificate issuers. If attribute certificates + is verified the trusted AC issuers must be set. +

    + The trustedACIssuers must be a ISet of + TrustAnchor +

    + The given set is cloned. +

    + + @param trustedACIssuers The trusted AC issuers to set. Is never + null. + @throws ClassCastException if an element of stores is not + a TrustAnchor. +
    + + Returns the neccessary attributes which must be contained in an attribute + certificate. +

    + The returned ISet is immutable and contains + Strings with the OIDs. +

    + + @return Returns the necessary AC attributes. +
    + + Sets the neccessary which must be contained in an attribute certificate. +

    + The ISet must contain Strings with the + OIDs. +

    + The set is cloned. +

    + + @param necessaryACAttributes The necessary AC attributes to set. + @throws ClassCastException if an element of + necessaryACAttributes is not a + String. +
    + + Returns the attribute certificates which are not allowed. +

    + The returned ISet is immutable and contains + Strings with the OIDs. +

    + + @return Returns the prohibited AC attributes. Is never null. +
    + + Sets the attribute certificates which are not allowed. +

    + The ISet must contain Strings with the + OIDs. +

    + The set is cloned. +

    + + @param prohibitedACAttributes The prohibited AC attributes to set. + @throws ClassCastException if an element of + prohibitedACAttributes is not a + String. +
    + + Returns the attribute certificate checker. The returned set contains + {@link PKIXAttrCertChecker}s and is immutable. + + @return Returns the attribute certificate checker. Is never + null. + + + Sets the attribute certificate checkers. +

    + All elements in the ISet must a {@link PKIXAttrCertChecker}. +

    +

    + The given set is cloned. +

    + + @param attrCertCheckers The attribute certificate checkers to set. Is + never null. + @throws ClassCastException if an element of attrCertCheckers + is not a PKIXAttrCertChecker. +
    + + + Summary description for PkixPolicyNode. + + + + Constructors + + + + This class helps to handle CRL revocation reasons mask. Each CRL handles a + certain set of revocation reasons. + + + + + Constructs are reason mask with the reasons. + + The reasons. + + + + A reason mask with no reason. + + + + + A mask with all revocation reasons. + + + + Adds all reasons from the reasons mask to this mask. + + @param mask The reasons mask to add. + + + + Returns true if this reasons mask contains all possible + reasons. + + true if this reasons mask contains all possible reasons. + + + + + Intersects this mask with the given reasons mask. + + mask The mask to intersect with. + The intersection of this and teh given mask. + + + + Returns true if the passed reasons mask has new reasons. + + The reasons mask which should be tested for new reasons. + true if the passed reasons mask has new reasons. + + + + Returns the reasons in this mask. + + + + If the complete CRL includes an issuing distribution point (IDP) CRL + extension check the following: +

    + (i) If the distribution point name is present in the IDP CRL extension + and the distribution field is present in the DP, then verify that one of + the names in the IDP matches one of the names in the DP. If the + distribution point name is present in the IDP CRL extension and the + distribution field is omitted from the DP, then verify that one of the + names in the IDP matches one of the names in the cRLIssuer field of the + DP. +

    +

    + (ii) If the onlyContainsUserCerts boolean is asserted in the IDP CRL + extension, verify that the certificate does not include the basic + constraints extension with the cA boolean asserted. +

    +

    + (iii) If the onlyContainsCACerts boolean is asserted in the IDP CRL + extension, verify that the certificate includes the basic constraints + extension with the cA boolean asserted. +

    +

    + (iv) Verify that the onlyContainsAttributeCerts boolean is not asserted. +

    + + @param dp The distribution point. + @param cert The certificate. + @param crl The CRL. + @throws AnnotatedException if one of the conditions is not met or an error occurs. +
    + + If the DP includes cRLIssuer, then verify that the issuer field in the + complete CRL matches cRLIssuer in the DP and that the complete CRL + contains an + g distribution point extension with the indirectCRL + boolean asserted. Otherwise, verify that the CRL issuer matches the + certificate issuer. + + @param dp The distribution point. + @param cert The certificate ot attribute certificate. + @param crl The CRL for cert. + @throws AnnotatedException if one of the above conditions does not apply or an error + occurs. + + + Obtain and validate the certification path for the complete CRL issuer. + If a key usage extension is present in the CRL issuer's certificate, + verify that the cRLSign bit is set. + + @param crl CRL which contains revocation information for the certificate + cert. + @param cert The attribute certificate or certificate to check if it is + revoked. + @param defaultCRLSignCert The issuer certificate of the certificate cert. + @param defaultCRLSignKey The public key of the issuer certificate + defaultCRLSignCert. + @param paramsPKIX paramsPKIX PKIX parameters. + @param certPathCerts The certificates on the certification path. + @return A Set with all keys of possible CRL issuer + certificates. + @throws AnnotatedException if the CRL is not valid or the status cannot be checked or + some error occurs. + + + Checks a distribution point for revocation information for the + certificate cert. + + @param dp The distribution point to consider. + @param paramsPKIX PKIX parameters. + @param cert Certificate to check if it is revoked. + @param validDate The date when the certificate revocation status should be + checked. + @param defaultCRLSignCert The issuer certificate of the certificate cert. + @param defaultCRLSignKey The public key of the issuer certificate + defaultCRLSignCert. + @param certStatus The current certificate revocation status. + @param reasonMask The reasons mask which is already checked. + @param certPathCerts The certificates of the certification path. + @throws AnnotatedException if the certificate is revoked or the status cannot be checked + or some error occurs. + + + Checks a certificate if it is revoked. + + @param paramsPKIX PKIX parameters. + @param cert Certificate to check if it is revoked. + @param validDate The date when the certificate revocation status should be + checked. + @param sign The issuer certificate of the certificate cert. + @param workingPublicKey The public key of the issuer certificate sign. + @param certPathCerts The certificates of the certification path. + @throws AnnotatedException if the certificate is revoked or the status cannot be checked + or some error occurs. + + + If use-deltas is set, verify the issuer and scope of the delta CRL. + + @param deltaCRL The delta CRL. + @param completeCRL The complete CRL. + @param pkixParams The PKIX paramaters. + @throws AnnotatedException if an exception occurs. + + + Checks if an attribute certificate is revoked. + + @param attrCert Attribute certificate to check if it is revoked. + @param paramsPKIX PKIX parameters. + @param issuerCert The issuer certificate of the attribute certificate + attrCert. + @param validDate The date when the certificate revocation status should + be checked. + @param certPathCerts The certificates of the certification path to be + checked. + + @throws CertPathValidatorException if the certificate is revoked or the + status cannot be checked or some error occurs. + + + Searches for a holder public key certificate and verifies its + certification path. + + @param attrCert the attribute certificate. + @param pkixParams The PKIX parameters. + @return The certificate path of the holder certificate. + @throws Exception if +
      +
    • no public key certificate can be found although holder + information is given by an entity name or a base certificate + ID
    • +
    • support classes cannot be created
    • +
    • no certification path for the public key certificate can + be built
    • +
    +
    + + + Checks a distribution point for revocation information for the + certificate attrCert. + + @param dp The distribution point to consider. + @param attrCert The attribute certificate which should be checked. + @param paramsPKIX PKIX parameters. + @param validDate The date when the certificate revocation status should + be checked. + @param issuerCert Certificate to check if it is revoked. + @param reasonMask The reasons mask which is already checked. + @param certPathCerts The certificates of the certification path to be + checked. + @throws Exception if the certificate is revoked or the status + cannot be checked or some error occurs. + + + + A trust anchor or most-trusted Certification Authority (CA). + + This class represents a "most-trusted CA", which is used as a trust anchor + for validating X.509 certification paths. A most-trusted CA includes the + public key of the CA, the CA's name, and any constraints upon the set of + paths which may be validated using this key. These parameters can be + specified in the form of a trusted X509Certificate or as individual + parameters. + + + + + Creates an instance of TrustAnchor with the specified X509Certificate and + optional name constraints, which are intended to be used as additional + constraints when validating an X.509 certification path. + The name constraints are specified as a byte array. This byte array + should contain the DER encoded form of the name constraints, as they + would appear in the NameConstraints structure defined in RFC 2459 and + X.509. The ASN.1 definition of this structure appears below. + +
    +            	NameConstraints ::= SEQUENCE {
    +            		permittedSubtrees       [0]     GeneralSubtrees OPTIONAL,
    +            		excludedSubtrees        [1]     GeneralSubtrees OPTIONAL }
    +            	   
    +             GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
    +             
    +            		GeneralSubtree ::= SEQUENCE {
    +            		base                    GeneralName,
    +            		minimum         [0]     BaseDistance DEFAULT 0,
    +            		maximum         [1]     BaseDistance OPTIONAL }
    +            		
    +            		BaseDistance ::= INTEGER (0..MAX)
    +            
    +            		GeneralName ::= CHOICE {
    +            		otherName                       [0]     OtherName,
    +            		rfc822Name                      [1]     IA5String,
    +            		dNSName                         [2]     IA5String,
    +            		x400Address                     [3]     ORAddress,
    +            		directoryName                   [4]     Name,
    +            		ediPartyName                    [5]     EDIPartyName,
    +            		uniformResourceIdentifier       [6]     IA5String,
    +            		iPAddress                       [7]     OCTET STRING,
    +            		registeredID                    [8]     OBJECT IDENTIFIER}
    +            	
    + + Note that the name constraints byte array supplied is cloned to protect + against subsequent modifications. +
    + a trusted X509Certificate + a byte array containing the ASN.1 DER encoding of a + NameConstraints extension to be used for checking name + constraints. Only the value of the extension is included, not + the OID or criticality flag. Specify null to omit the + parameter. + if the specified X509Certificate is null +
    + + + Creates an instance of TrustAnchor where the + most-trusted CA is specified as an X500Principal and public key. + + +

    + Name constraints are an optional parameter, and are intended to be used + as additional constraints when validating an X.509 certification path. +

    + The name constraints are specified as a byte array. This byte array + contains the DER encoded form of the name constraints, as they + would appear in the NameConstraints structure defined in RFC 2459 + and X.509. The ASN.1 notation for this structure is supplied in the + documentation for the other constructors. +

    + Note that the name constraints byte array supplied here is cloned to + protect against subsequent modifications. +

    +
    + the name of the most-trusted CA as X509Name + the public key of the most-trusted CA + + a byte array containing the ASN.1 DER encoding of a NameConstraints extension to + be used for checking name constraints. Only the value of the extension is included, + not the OID or criticality flag. Specify null to omit the parameter. + + + if caPrincipal or pubKey is null + +
    + + + Creates an instance of TrustAnchor where the most-trusted + CA is specified as a distinguished name and public key. Name constraints + are an optional parameter, and are intended to be used as additional + constraints when validating an X.509 certification path. +
    + The name constraints are specified as a byte array. This byte array + contains the DER encoded form of the name constraints, as they would + appear in the NameConstraints structure defined in RFC 2459 and X.509. +
    + the X.500 distinguished name of the most-trusted CA in RFC + 2253 string format + the public key of the most-trusted CA + a byte array containing the ASN.1 DER encoding of a + NameConstraints extension to be used for checking name + constraints. Only the value of the extension is included, not + the OID or criticality flag. Specify null to omit the + parameter. + throws NullPointerException, IllegalArgumentException +
    + + + Returns the most-trusted CA certificate. + + + + + Returns the name of the most-trusted CA as an X509Name. + + + + + Returns the name of the most-trusted CA in RFC 2253 string format. + + + + + Returns the public key of the most-trusted CA. + + + + + Decode the name constraints and clone them if not null. + + + + + Returns a formatted string describing the TrustAnchor. + + a formatted string describing the TrustAnchor + + + Base class for an RFC 3161 Time Stamp Request. + + + Create a TimeStampRequest from the past in byte array. + + @param req byte array containing the request. + @throws IOException if the request is malformed. + + + Create a TimeStampRequest from the past in input stream. + + @param in input stream containing the request. + @throws IOException if the request is malformed. + + + Validate the timestamp request, checking the digest to see if it is of an + accepted type and whether it is of the correct length for the algorithm specified. + + @param algorithms a set of string OIDS giving accepted algorithms. + @param policies if non-null a set of policies we are willing to sign under. + @param extensions if non-null a set of extensions we are willing to accept. + @throws TspException if the request is invalid, or processing fails. + + + return the ASN.1 encoded representation of this object. + + + Generator for RFC 3161 Time Stamp Request objects. + + + add a given extension field for the standard extensions tag (tag 3) + @throws IOException + + + add a given extension field for the standard extensions tag + The value parameter becomes the contents of the octet string associated + with the extension. + + + add a given extension field for the standard extensions tag (tag 3) + @throws IOException + + + add a given extension field for the standard extensions tag + The value parameter becomes the contents of the octet string associated + with the extension. + + + Base class for an RFC 3161 Time Stamp Response object. + + + Create a TimeStampResponse from a byte array containing an ASN.1 encoding. + + @param resp the byte array containing the encoded response. + @throws TspException if the response is malformed. + @throws IOException if the byte array doesn't represent an ASN.1 encoding. + + + Create a TimeStampResponse from an input stream containing an ASN.1 encoding. + + @param input the input stream containing the encoded response. + @throws TspException if the response is malformed. + @throws IOException if the stream doesn't represent an ASN.1 encoding. + + + Check this response against to see if it a well formed response for + the passed in request. Validation will include checking the time stamp + token if the response status is GRANTED or GRANTED_WITH_MODS. + + @param request the request to be checked against + @throws TspException if the request can not match this response. + + + return the ASN.1 encoded representation of this object. + + + Generator for RFC 3161 Time Stamp Responses. + + + Return an appropriate TimeStampResponse. +

    + If genTime is null a timeNotAvailable error response will be returned. + + @param request the request this response is for. + @param serialNumber serial number for the response token. + @param genTime generation time for the response token. + @param provider provider to use for signature calculation. + @return + @throws NoSuchAlgorithmException + @throws NoSuchProviderException + @throws TSPException +

    +
    + + Generate a TimeStampResponse with chosen status and FailInfoField. + + @param status the PKIStatus to set. + @param failInfoField the FailInfoField to set. + @param statusString an optional string describing the failure. + @return a TimeStampResponse with a failInfoField and optional statusString + @throws TSPException in case the response could not be created + + + Validate the time stamp token. +

    + To be valid the token must be signed by the passed in certificate and + the certificate must be the one referred to by the SigningCertificate + attribute included in the hashed attributes of the token. The + certificate must also have the ExtendedKeyUsageExtension with only + KeyPurposeID.IdKPTimeStamping and have been valid at the time the + timestamp was created. +

    +

    + A successful call to validate means all the above are true. +

    +
    + + Return the underlying CmsSignedData object. + + @return the underlying CMS structure. + + + Return a ASN.1 encoded byte stream representing the encoded object. + + @throws IOException if encoding fails. + + + basic creation - only the default attributes will be included here. + + + create with a signer with extra signed/unsigned attributes. + + + @return the nonce value, null if there isn't one. + + + Recognised hash algorithms for the time stamp protocol. + + + Fetches the signature time-stamp attributes from a SignerInformation object. + Checks that the MessageImprint for each time-stamp matches the signature field. + (see RFC 3161 Appendix A). + + @param signerInfo a SignerInformation to search for time-stamps + @return a collection of TimeStampToken objects + @throws TSPValidationException + + + Validate the passed in certificate as being of the correct type to be used + for time stamping. To be valid it must have an ExtendedKeyUsage extension + which has a key purpose identifier of id-kp-timeStamping. + + @param cert the certificate of interest. + @throws TspValidationException if the certicate fails on one of the check points. + + + + Return the digest algorithm using one of the standard JCA string + representations rather than the algorithm identifier (if possible). + + + + Exception thrown if a TSP request or response fails to validate. +

    + If a failure code is associated with the exception it can be retrieved using + the getFailureCode() method.

    +
    + + Return the failure code associated with this exception - if one is set. + + @return the failure code if set, -1 otherwise. + + + General array utilities. + + + + Are two arrays equal. + + Left side. + Right side. + True if equal. + + + + A constant time equals comparison - does not terminate early if + test will fail. + + first array + second array + true if arrays equal, false otherwise. + + + BigInteger utilities. + + + Return the passed in value as an unsigned byte array. + + @param value value to be converted. + @return a byte array without a leading zero byte if present in the signed encoding. + + + Return a random BigInteger not less than 'min' and not greater than 'max' + + @param min the least value that may be generated + @param max the greatest value that may be generated + @param random the source of randomness + @return a random BigInteger value in the range [min,max] + + + + Return the number of milliseconds since the Unix epoch (1 Jan., 1970 UTC) for a given DateTime value. + + A UTC DateTime value not before epoch. + Number of whole milliseconds after epoch. + 'dateTime' is before epoch. + + + + Create a DateTime value from the number of milliseconds since the Unix epoch (1 Jan., 1970 UTC). + + Number of milliseconds since the epoch. + A UTC DateTime value + + + + Return the current number of milliseconds since the Unix epoch (1 Jan., 1970 UTC). + + + + encode the input data producing a base 64 encoded byte array. + + @return a byte array containing the base 64 encoded data. + + + Encode the byte data to base 64 writing it to the given output stream. + + @return the number of bytes produced. + + + Encode the byte data to base 64 writing it to the given output stream. + + @return the number of bytes produced. + + + decode the base 64 encoded input data. It is assumed the input data is valid. + + @return a byte array representing the decoded data. + + + decode the base 64 encoded string data - whitespace will be ignored. + + @return a byte array representing the decoded data. + + + decode the base 64 encoded string data writing it to the given output stream, + whitespace characters will be ignored. + + @return the number of bytes produced. + + + encode the input data producing a base 64 output stream. + + @return the number of bytes produced. + + + decode the base 64 encoded byte data writing it to the given output stream, + whitespace characters will be ignored. + + @return the number of bytes produced. + + + decode the base 64 encoded string data writing it to the given output stream, + whitespace characters will be ignored. + + @return the number of bytes produced. + + + + A buffering class to allow translation from one format to another to + be done in discrete chunks. + + + + + Create a buffered Decoder. + + The translater to use. + The size of the buffer. + + + + Process one byte of data. + + Data in. + Byte array for the output. + The offset in the output byte array to start writing from. + The amount of output bytes. + + + + Process data from a byte array. + + The input data. + Start position within input data array. + Amount of data to process from input data array. + Array to store output. + Position in output array to start writing from. + The amount of output bytes. + + + + A class that allows encoding of data using a specific encoder to be processed in chunks. + + + + + Create. + + The translator to use. + Size of the chunks. + + + + Process one byte of data. + + The byte. + An array to store output in. + Offset within output array to start writing from. + + + + + Process data from a byte array. + + Input data Byte array containing data to be processed. + Start position within input data array. + Amount of input data to be processed. + Output data array. + Offset within output data array to start writing to. + The amount of data written. + + + + Class to decode and encode Hex. + + + + encode the input data producing a Hex encoded byte array. + + @return a byte array containing the Hex encoded data. + + + encode the input data producing a Hex encoded byte array. + + @return a byte array containing the Hex encoded data. + + + Hex encode the byte data writing it to the given output stream. + + @return the number of bytes produced. + + + Hex encode the byte data writing it to the given output stream. + + @return the number of bytes produced. + + + decode the Hex encoded input data. It is assumed the input data is valid. + + @return a byte array representing the decoded data. + + + decode the Hex encoded string data - whitespace will be ignored. + + @return a byte array representing the decoded data. + + + decode the Hex encoded string data writing it to the given output stream, + whitespace characters will be ignored. + + @return the number of bytes produced. + + + encode the input data producing a Hex output stream. + + @return the number of bytes produced. + + + decode the Hex encoded byte data writing it to the given output stream, + whitespace characters will be ignored. + + @return the number of bytes produced. + + + decode the Hex encoded string data writing it to the given output stream, + whitespace characters will be ignored. + + @return the number of bytes produced. + + + + A hex translator. + + + + + Return encoded block size. + + 2 + + + + Encode some data. + + Input data array. + Start position within input data array. + The amount of data to process. + The output data array. + The offset within the output data array to start writing from. + Amount of data encoded. + + + + Returns the decoded block size. + + 1 + + + + Decode data from a byte array. + + The input data array. + Start position within input data array. + The amounty of data to process. + The output data array. + The position within the output data array to start writing from. + The amount of data written. + + + Encode and decode byte arrays (typically from binary to 7-bit ASCII + encodings). + + + + Translator interface. + + + + Convert binary data to and from UrlBase64 encoding. This is identical to + Base64 encoding, except that the padding character is "." and the other + non-alphanumeric characters are "-" and "_" instead of "+" and "/". +

    + The purpose of UrlBase64 encoding is to provide a compact encoding of binary + data that is safe for use as an URL parameter. Base64 encoding does not + produce encoded values that are safe for use in URLs, since "/" can be + interpreted as a path delimiter; "+" is the encoded form of a space; and + "=" is used to separate a name from the corresponding value in an URL + parameter. +

    +
    + + Encode the input data producing a URL safe base 64 encoded byte array. + + @return a byte array containing the URL safe base 64 encoded data. + + + Encode the byte data writing it to the given output stream. + + @return the number of bytes produced. + + + Decode the URL safe base 64 encoded input data - white space will be ignored. + + @return a byte array representing the decoded data. + + + decode the URL safe base 64 encoded byte data writing it to the given output stream, + whitespace characters will be ignored. + + @return the number of bytes produced. + + + decode the URL safe base 64 encoded string data - whitespace will be ignored. + + @return a byte array representing the decoded data. + + + Decode the URL safe base 64 encoded string data writing it to the given output stream, + whitespace characters will be ignored. + + @return the number of bytes produced. + + + Convert binary data to and from UrlBase64 encoding. This is identical to + Base64 encoding, except that the padding character is "." and the other + non-alphanumeric characters are "-" and "_" instead of "+" and "/". +

    + The purpose of UrlBase64 encoding is to provide a compact encoding of binary + data that is safe for use as an URL parameter. Base64 encoding does not + produce encoded values that are safe for use in URLs, since "/" can be + interpreted as a path delimiter; "+" is the encoded form of a space; and + "=" is used to separate a name from the corresponding value in an URL + parameter. +

    +
    + + + A + + + + + + A + + + A + + + + + + A + + + + + A generic PEM writer, based on RFC 1421 + + + Base constructor. + + @param out output stream to use. + + + Return the number of bytes or characters required to contain the + passed in object if it is PEM encoded. + + @param obj pem object to be output + @return an estimate of the number of bytes + + + + Pipe all bytes from inStr to outStr, throwing StreamFlowException if greater + than limit bytes in inStr. + + + A + + + A + + + A + + The number of bytes actually transferred, if not greater than limit + + + + Validate the given IPv4 or IPv6 address. + + @param address the IP address as a string. + + @return true if a valid address, false otherwise + + + Validate the given IPv4 or IPv6 address and netmask. + + @param address the IP address as a string. + + @return true if a valid address with netmask, false otherwise + + + Validate the given IPv4 address. + + @param address the IP address as a string. + + @return true if a valid IPv4 address, false otherwise + + + Validate the given IPv6 address. + + @param address the IP address as a string. + + @return true if a valid IPv4 address, false otherwise + + + General string utilities. + + + + Summary description for DeflaterOutputStream. + + + + + Summary description for DeflaterOutputStream. + + + + + The Holder object. +
    +            Holder ::= SEQUENCE {
    +            	baseCertificateID   [0] IssuerSerial OPTIONAL,
    +            		-- the issuer and serial number of
    +            		-- the holder's Public Key Certificate
    +            	entityName          [1] GeneralNames OPTIONAL,
    +            		-- the name of the claimant or role
    +            	objectDigestInfo    [2] ObjectDigestInfo OPTIONAL
    +            		-- used to directly authenticate the holder,
    +            		-- for example, an executable
    +            }
    +            
    +
    +
    + + Constructs a holder for v2 attribute certificates with a hash value for + some type of object. +

    + digestedObjectType can be one of the following: +

      +
    • 0 - publicKey - A hash of the public key of the holder must be + passed.
    • +
    • 1 - publicKeyCert - A hash of the public key certificate of the + holder must be passed.
    • +
    • 2 - otherObjectDigest - A hash of some other object type must be + passed. otherObjectTypeID must not be empty.
    • +
    +

    +

    This cannot be used if a v1 attribute certificate is used.

    + + @param digestedObjectType The digest object type. + @param digestAlgorithm The algorithm identifier for the hash. + @param otherObjectTypeID The object type ID if + digestedObjectType is + otherObjectDigest. + @param objectDigest The hash value. +
    + + Returns the digest object type if an object digest info is used. +

    +

      +
    • 0 - publicKey - A hash of the public key of the holder must be + passed.
    • +
    • 1 - publicKeyCert - A hash of the public key certificate of the + holder must be passed.
    • +
    • 2 - otherObjectDigest - A hash of some other object type must be + passed. otherObjectTypeID must not be empty.
    • +
    +

    + + @return The digest object type or -1 if no object digest info is set. +
    + + Returns the other object type ID if an object digest info is used. + + @return The other object type ID or null if no object + digest info is set. + + + Returns the hash if an object digest info is used. + + @return The hash or null if no object digest info is set. + + + Returns the digest algorithm ID if an object digest info is used. + + @return The digest algorithm ID or null if no object + digest info is set. + + + Return any principal objects inside the attribute certificate holder entity names field. + + @return an array of IPrincipal objects (usually X509Name), null if no entity names field is set. + + + Return the principals associated with the issuer attached to this holder + + @return an array of principals, null if no BaseCertificateID is set. + + + Return the serial number associated with the issuer attached to this holder. + + @return the certificate serial number, null if no BaseCertificateID is set. + + + Carrying class for an attribute certificate issuer. + + + Set the issuer directly with the ASN.1 structure. + + @param issuer The issuer + + + Return any principal objects inside the attribute certificate issuer object. + An array of IPrincipal objects (usually X509Principal). + + + A high level authority key identifier. + + + Constructor which will take the byte[] returned from getExtensionValue() + + @param encodedValue a DER octet encoded string with the extension structure in it. + @throws IOException on parsing errors. + + + Create an AuthorityKeyIdentifier using the passed in certificate's public + key, issuer and serial number. + + @param certificate the certificate providing the information. + @throws CertificateParsingException if there is a problem processing the certificate + + + Create an AuthorityKeyIdentifier using just the hash of the + public key. + + @param pubKey the key to generate the hash from. + @throws InvalidKeyException if there is a problem using the key. + + + A high level subject key identifier. + + + Constructor which will take the byte[] returned from getExtensionValue() + + @param encodedValue a DER octet encoded string with the extension structure in it. + @throws IOException on parsing errors. + + + Interface for an X.509 Attribute Certificate. + + + The version number for the certificate. + + + The serial number for the certificate. + + + The UTC DateTime before which the certificate is not valid. + + + The UTC DateTime after which the certificate is not valid. + + + The holder of the certificate. + + + The issuer details for the certificate. + + + Return the attributes contained in the attribute block in the certificate. + An array of attributes. + + + Return the attributes with the same type as the passed in oid. + The object identifier we wish to match. + An array of matched attributes, null if there is no match. + + + Return an ASN.1 encoded byte array representing the attribute certificate. + An ASN.1 encoded byte array. + If the certificate cannot be encoded. + + + + Get all critical extension values, by oid + + IDictionary with string (OID) keys and Asn1OctetString values + + + + Get all non-critical extension values, by oid + + IDictionary with string (OID) keys and Asn1OctetString values + + + + A utility class that will extract X509Principal objects from X.509 certificates. +

    + Use this in preference to trying to recreate a principal from a string, not all + DNs are what they should be, so it's best to leave them encoded where they + can be.

    +
    +
    + + Return the issuer of the given cert as an X509Principal. + + + Return the subject of the given cert as an X509Principal. + + + Return the issuer of the given CRL as an X509Principal. + + + This class is an Selector like implementation to select + attribute certificates from a given set of criteria. + + @see org.bouncycastle.x509.X509AttributeCertificate + @see org.bouncycastle.x509.X509Store + + + + Decides if the given attribute certificate should be selected. + + The attribute certificate to be checked. + true if the object matches this selector. + + + The attribute certificate which must be matched. + If null is given, any will do. + + + The criteria for validity + If null is given any will do. + + + The holder. + If null is given any will do. + + + The issuer. + If null is given any will do. + + + The serial number. + If null is given any will do. + + + Adds a target name criterion for the attribute certificate to the target + information extension criteria. The X509AttributeCertificate + must contain at least one of the specified target names. +

    + Each attribute certificate may contain a target information extension + limiting the servers where this attribute certificate can be used. If + this extension is not present, the attribute certificate is not targeted + and may be accepted by any server. +

    + + @param name The name as a GeneralName (not null) +
    + + Adds a target name criterion for the attribute certificate to the target + information extension criteria. The X509AttributeCertificate + must contain at least one of the specified target names. +

    + Each attribute certificate may contain a target information extension + limiting the servers where this attribute certificate can be used. If + this extension is not present, the attribute certificate is not targeted + and may be accepted by any server. +

    + + @param name a byte array containing the name in ASN.1 DER encoded form of a GeneralName + @throws IOException if a parsing error occurs. +
    + + Adds a collection with target names criteria. If null is + given any will do. +

    + The collection consists of either GeneralName objects or byte[] arrays representing + DER encoded GeneralName structures. +

    + + @param names A collection of target names. + @throws IOException if a parsing error occurs. + @see #AddTargetName(byte[]) + @see #AddTargetName(GeneralName) +
    + + Gets the target names. The collection consists of Lists + made up of an Integer in the first entry and a DER encoded + byte array or a String in the second entry. +

    The returned collection is immutable.

    + + @return The collection of target names + @see #setTargetNames(Collection) +
    + + Adds a target group criterion for the attribute certificate to the target + information extension criteria. The X509AttributeCertificate + must contain at least one of the specified target groups. +

    + Each attribute certificate may contain a target information extension + limiting the servers where this attribute certificate can be used. If + this extension is not present, the attribute certificate is not targeted + and may be accepted by any server. +

    + + @param group The group as GeneralName form (not null) +
    + + Adds a target group criterion for the attribute certificate to the target + information extension criteria. The X509AttributeCertificate + must contain at least one of the specified target groups. +

    + Each attribute certificate may contain a target information extension + limiting the servers where this attribute certificate can be used. If + this extension is not present, the attribute certificate is not targeted + and may be accepted by any server. +

    + + @param name a byte array containing the group in ASN.1 DER encoded form of a GeneralName + @throws IOException if a parsing error occurs. +
    + + Adds a collection with target groups criteria. If null is + given any will do. +

    + The collection consists of GeneralName objects or byte[] + representing DER encoded GeneralNames. +

    + + @param names A collection of target groups. + @throws IOException if a parsing error occurs. + @see #AddTargetGroup(byte[]) + @see #AddTargetGroup(GeneralName) +
    + + Gets the target groups. The collection consists of Lists + made up of an Integer in the first entry and a DER encoded + byte array or a String in the second entry. +

    The returned collection is immutable.

    + + @return The collection of target groups. + @see #setTargetGroups(Collection) +
    + + + This class is an IX509Selector implementation to select + certificate pairs, which are e.g. used for cross certificates. The set of + criteria is given from two X509CertStoreSelector objects, + each of which, if present, must match the respective component of a pair. + + + + The certificate pair which is used for testing on equality. + + + The certificate selector for the forward part. + + + The certificate selector for the reverse part. + + + + Decides if the given certificate pair should be selected. If + obj is not a X509CertificatePair, this method + returns false. + + The X509CertificatePair to be tested. + true if the object matches this selector. + + + + An ISet of DerObjectIdentifier objects. + + + + A simple collection backed store. + + + Basic constructor. + + @param collection - initial contents for the store, this is copied. + + + Return the matches in the collection for the passed in selector. + + @param selector the selector to match against. + @return a possibly empty collection of matching objects. + + + This class contains a collection for collection based X509Stores. + + + + Constructor. +

    + The collection is copied. +

    +
    + The collection containing X.509 object types. + If collection is null. +
    + + Returns a copy of the ICollection. + + + Returns a formatted string describing the parameters. + + + + An ICollection of X509Name objects + + + + The attribute certificate being checked. This is not a criterion. + Rather, it is optional information that may help a {@link X509Store} find + CRLs that would be relevant when checking revocation for the specified + attribute certificate. If null is specified, then no such + optional information is provided. + + @param attrCert the IX509AttributeCertificate being checked (or + null) + @see #getAttrCertificateChecking() + + + If true only complete CRLs are returned. Defaults to + false. + + @return true if only complete CRLs are returned. + + + Returns if this selector must match CRLs with the delta CRL indicator + extension set. Defaults to false. + + @return Returns true if only CRLs with the delta CRL + indicator extension are selected. + + + The issuing distribution point. +

    + The issuing distribution point extension is a CRL extension which + identifies the scope and the distribution point of a CRL. The scope + contains among others information about revocation reasons contained in + the CRL. Delta CRLs and complete CRLs must have matching issuing + distribution points.

    +

    + The byte array is cloned to protect against subsequent modifications.

    +

    + You must also enable or disable this criteria with + {@link #setIssuingDistributionPointEnabled(bool)}.

    + + @param issuingDistributionPoint The issuing distribution point to set. + This is the DER encoded OCTET STRING extension value. + @see #getIssuingDistributionPoint() +
    + + Whether the issuing distribution point criteria should be applied. + Defaults to false. +

    + You may also set the issuing distribution point criteria if not a missing + issuing distribution point should be assumed.

    + + @return Returns if the issuing distribution point check is enabled. +
    + + The maximum base CRL number. Defaults to null. + + @return Returns the maximum base CRL number. + @see #setMaxBaseCRLNumber(BigInteger) + + + + A factory to produce Public Key Info Objects. + + + + + Create a Subject Public Key Info object for a given public key. + + One of ElGammalPublicKeyParameters, DSAPublicKeyParameter, DHPublicKeyParameters, RsaKeyParameters or ECPublicKeyParameters + A subject public key info object. + Throw exception if object provided is not one of the above. + + + + Create loading data from byte array. + + + + + + Create loading data from byte array. + + + + + Generates a certificate object and initializes it with the data + read from the input stream inStream. + + + Returns a (possibly empty) collection view of the certificates + read from the given input stream inStream. + + + Class for carrying the values in an X.509 Attribute. + + + @param at an object representing an attribute. + + + Create an X.509 Attribute with the type given by the passed in oid and + the value represented by an ASN.1 Set containing value. + + @param oid type of the attribute + @param value value object to go into the atribute's value set. + + + Create an X.59 Attribute with the type given by the passed in oid and the + value represented by an ASN.1 Set containing the objects in value. + + @param oid type of the attribute + @param value vector of values to go in the attribute's value set. + + + + An Object representing an X509 Certificate. + Has static methods for loading Certificates encoded in many forms that return X509Certificate Objects. + + + + + Return true if the current time is within the start and end times nominated on the certificate. + + true id certificate is valid for the current time. + + + + Return true if the nominated time is within the start and end times nominated on the certificate. + + The time to test validity against. + True if certificate is valid for nominated time. + + + + Checks if the current date is within certificate's validity period. + + + + + Checks if the given date is within certificate's validity period. + + if the certificate is expired by given date + if the certificate is not yet valid on given date + + + + Return the certificate's version. + + An integer whose value Equals the version of the cerficate. + + + + Return a BigInteger containing the serial number. + + The Serial number. + + + + Get the Issuer Distinguished Name. (Who signed the certificate.) + + And X509Object containing name and value pairs. + + + + Get the subject of this certificate. + + An X509Name object containing name and value pairs. + + + + The time that this certificate is valid from. + + A DateTime object representing that time in the local time zone. + + + + The time that this certificate is valid up to. + + A DateTime object representing that time in the local time zone. + + + + Return the Der encoded TbsCertificate data. + This is the certificate component less the signature. + To Get the whole certificate call the GetEncoded() member. + + A byte array containing the Der encoded Certificate component. + + + + The signature. + + A byte array containg the signature of the certificate. + + + + A meaningful version of the Signature Algorithm. (EG SHA1WITHRSA) + + A sting representing the signature algorithm. + + + + Get the Signature Algorithms Object ID. + + A string containg a '.' separated object id. + + + + Get the signature algorithms parameters. (EG DSA Parameters) + + A byte array containing the Der encoded version of the parameters or null if there are none. + + + + Get the issuers UID. + + A DerBitString. + + + + Get the subjects UID. + + A DerBitString. + + + + Get a key usage guidlines. + + + + + Get the public key of the subject of the certificate. + + The public key parameters. + + + + Return a Der encoded version of this certificate. + + A byte array. + + + + Verify the certificate's signature using the nominated public key. + + An appropriate public key parameter object, RsaPublicKeyParameters, DsaPublicKeyParameters or ECDsaPublicKeyParameters + True if the signature is valid. + If key submitted is not of the above nominated types. + + + + This class contains a cross certificate pair. Cross certificates pairs may + contain two cross signed certificates from two CAs. A certificate from the + other CA to this CA is contained in the forward certificate, the certificate + from this CA to the other CA is contained in the reverse certificate. + + + + Constructor + Certificate from the other CA to this CA. + Certificate from this CA to the other CA. + + + Constructor from a ASN.1 CertificatePair structure. + The CertificatePair ASN.1 object. + + + Returns the certificate from the other CA to this CA. + + + Returns the certificate from this CA to the other CA. + + + class for dealing with X509 certificates. +

    + At the moment this will deal with "-----BEGIN CERTIFICATE-----" to "-----END CERTIFICATE-----" + base 64 encoded certs, as well as the BER binaries of certificates and some classes of PKCS#7 + objects.

    +
    + + + Create loading data from byte array. + + + + + + Create loading data from byte array. + + + + + Generates a certificate object and initializes it with the data + read from the input stream inStream. + + + Returns a (possibly empty) collection view of the certificates + read from the given input stream inStream. + + + + Create loading data from byte array. + + + + + + Create loading data from byte array. + + + + + The following extensions are listed in RFC 2459 as relevant to CRLs + + Authority Key Identifier + Issuer Alternative Name + CRL Number + Delta CRL Indicator (critical) + Issuing Distribution Point (critical) + + + Returns a string representation of this CRL. + + @return a string representation of this CRL. + + + Checks whether the given certificate is on this CRL. + + @param cert the certificate to check for. + @return true if the given certificate is on this CRL, + false otherwise. + + + The following extensions are listed in RFC 2459 as relevant to CRL Entries + + ReasonCode Hode Instruction Code Invalidity Date Certificate Issuer + (critical) + + + Constructor for CRLEntries of indirect CRLs. If isIndirect + is false {@link #getCertificateIssuer()} will always + return null, previousCertificateIssuer is + ignored. If this isIndirect is specified and this CrlEntry + has no certificate issuer CRL entry extension + previousCertificateIssuer is returned by + {@link #getCertificateIssuer()}. + + @param c + TbsCertificateList.CrlEntry object. + @param isIndirect + true if the corresponding CRL is a indirect + CRL. + @param previousCertificateIssuer + Certificate issuer of the previous CrlEntry. + + + + Create loading data from byte array. + + + + + + Create loading data from byte array. + + + + + Generates a certificate revocation list (CRL) object and initializes + it with the data read from the input stream inStream. + + + Returns a (possibly empty) collection view of the CRLs read from + the given input stream inStream. + + The inStream may contain a sequence of DER-encoded CRLs, or + a PKCS#7 CRL set. This is a PKCS#7 SignedData object, with the + only significant field being crls. In particular the signature + and the contents are ignored. + + + + Get non critical extensions. + + A set of non critical extension oids. + + + + Get any critical extensions. + + A sorted list of critical entension. + + + + Get the value of a given extension. + + The object ID of the extension. + An Asn1OctetString object if that extension is found or null if not. + + + A holding class for constructing an X509 Key Usage extension. + +
    +                id-ce-keyUsage OBJECT IDENTIFIER ::=  { id-ce 15 }
    +            
    +                KeyUsage ::= BIT STRING {
    +                     digitalSignature        (0),
    +                     nonRepudiation          (1),
    +                     keyEncipherment         (2),
    +                     dataEncipherment        (3),
    +                     keyAgreement            (4),
    +                     keyCertSign             (5),
    +                     cRLSign                 (6),
    +                     encipherOnly            (7),
    +                     decipherOnly            (8) }
    +             
    +
    + + Basic constructor. + + @param usage - the bitwise OR of the Key Usage flags giving the + allowed uses for the key. + e.g. (X509KeyUsage.keyEncipherment | X509KeyUsage.dataEncipherment) + + + Return the digest algorithm using one of the standard JCA string + representations rather than the algorithm identifier (if possible). + + + + Class to Generate X509V1 Certificates. + + + + + Default Constructor. + + + + + Reset the generator. + + + + + Set the certificate's serial number. + + Make serial numbers long, if you have no serial number policy make sure the number is at least 16 bytes of secure random data. + You will be surprised how ugly a serial number collision can get. + The serial number. + + + + Set the issuer distinguished name. + The issuer is the entity whose private key is used to sign the certificate. + + The issuers DN. + + + + Set the date that this certificate is to be valid from. + + + + + + Set the date after which this certificate will no longer be valid. + + + + + + Set the subject distinguished name. + The subject describes the entity associated with the public key. + + + + + + Set the public key that this certificate identifies. + + + + + + Set the signature algorithm that will be used to sign this certificate. + This can be either a name or an OID, names are treated as case insensitive. + + string representation of the algorithm name + + + + Generate a new X509Certificate. + + The private key of the issuer used to sign this certificate. + An X509Certificate. + + + + Generate a new X509Certificate specifying a SecureRandom instance that you would like to use. + + The private key of the issuer used to sign this certificate. + The Secure Random you want to use. + An X509Certificate. + + + + Allows enumeration of the signature names supported by the generator. + + + + An implementation of a version 2 X.509 Attribute Certificate. + + + Class to produce an X.509 Version 2 AttributeCertificate. + + + Reset the generator + + + Set the Holder of this Attribute Certificate. + + + Set the issuer. + + + Set the serial number for the certificate. + + + + Set the signature algorithm. This can be either a name or an OID, names + are treated as case insensitive. + + The algorithm name. + + + Add an attribute. + + + Add a given extension field for the standard extensions tag. + + + + Add a given extension field for the standard extensions tag. + The value parameter becomes the contents of the octet string associated + with the extension. + + + + + Generate an X509 certificate, based on the current issuer and subject. + + + + + Generate an X509 certificate, based on the current issuer and subject, + using the supplied source of randomness, if required. + + + + + Allows enumeration of the signature names supported by the generator. + + + + class to produce an X.509 Version 2 CRL. + + + reset the generator + + + Set the issuer distinguished name - the issuer is the entity whose private key is used to sign the + certificate. + + + Reason being as indicated by CrlReason, i.e. CrlReason.KeyCompromise + or 0 if CrlReason is not to be used + + + + Add a CRL entry with an Invalidity Date extension as well as a CrlReason extension. + Reason being as indicated by CrlReason, i.e. CrlReason.KeyCompromise + or 0 if CrlReason is not to be used + + + + Add a CRL entry with extensions. + + + + Add the CRLEntry objects contained in a previous CRL. + + @param other the X509Crl to source the other entries from. + + + Set the signature algorithm. This can be either a name or an oid, names + are treated as case insensitive. + + @param signatureAlgorithm string representation of the algorithm name. + + + add a given extension field for the standard extensions tag (tag 0) + + + add a given extension field for the standard extensions tag (tag 0) + + + add a given extension field for the standard extensions tag (tag 0) + + + add a given extension field for the standard extensions tag (tag 0) + + + Generate an X509 CRL, based on the current issuer and subject. + The key used for signing. + + + Generate an X509 CRL, based on the current issuer and subject. + The key used for signing. + A user-defined source of randomness. + + + + Allows enumeration of the signature names supported by the generator. + + + + + A class to Generate Version 3 X509Certificates. + + + + + Reset the Generator. + + + + + Set the certificate's serial number. + + Make serial numbers long, if you have no serial number policy make sure the number is at least 16 bytes of secure random data. + You will be surprised how ugly a serial number collision can Get. + The serial number. + + + + Set the distinguished name of the issuer. + The issuer is the entity which is signing the certificate. + + The issuer's DN. + + + + Set the date that this certificate is to be valid from. + + + + + + Set the date after which this certificate will no longer be valid. + + + + + + Set the DN of the entity that this certificate is about. + + + + + + Set the public key that this certificate identifies. + + + + + + Set the signature algorithm that will be used to sign this certificate. + + + + + + Set the subject unique ID - note: it is very rare that it is correct to do this. + + + + + + Set the issuer unique ID - note: it is very rare that it is correct to do this. + + + + + + Add a given extension field for the standard extensions tag (tag 3). + + string containing a dotted decimal Object Identifier. + Is it critical. + The value. + + + + Add an extension to this certificate. + + Its Object Identifier. + Is it critical. + The value. + + + + Add an extension using a string with a dotted decimal OID. + + string containing a dotted decimal Object Identifier. + Is it critical. + byte[] containing the value of this extension. + + + + Add an extension to this certificate. + + Its Object Identifier. + Is it critical. + byte[] containing the value of this extension. + + + + Add a given extension field for the standard extensions tag (tag 3), + copying the extension value from another certificate. + + + + add a given extension field for the standard extensions tag (tag 3) + copying the extension value from another certificate. + @throws CertificateParsingException if the extension cannot be extracted. + + + + Generate an X509Certificate. + + The private key of the issuer that is signing this certificate. + An X509Certificate. + + + + Generate an X509Certificate using your own SecureRandom. + + The private key of the issuer that is signing this certificate. + You Secure Random instance. + An X509Certificate. + + + + Allows enumeration of the signature names supported by the generator. + + +
    +
    diff --git a/server/dao.xml b/server/dao.xml new file mode 100644 index 0000000..c04d224 --- /dev/null +++ b/server/dao.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file