Matrix multiplication

Does someone have a function of pseudo code to do matrix multiplication?
For instance, I want to do the following:
mastrix-I..........matrix-II output
a....b.......|......e....f................(a*e)+(b*g)........(a*f)+(b*h)
..............X..................=
c....d.......|......g....h................(c*e)+(d*g)........(c*f)+(d*h)
In real life I have a matrix (table) 14(columns) by 14(rows) which I want to multiply it my itself 12 times.
Any help will be greadly appreciated!
Thanks!
Edited by: theodora on Mar 8, 2010 8:58 AM

http://www.filebuzz.com/findsoftware/Symbian_Matrix_Calculator/1.html
http://www.getjar.com/mobile/35290/mobilemaths-for-nokia-5800-xpressmusic/
 jje

Similar Messages

  • Insufficient buffer error in LV for running CIN matrix multiplication

    We have developed a CIN for LabVIEW application in which we carry out matrix multiplication. We are able to carry out multiplication of 3x3 matrices in the LV environment using the CIN. The LV application gives error for higher order of matrices indicating insufficient buffer. However the c source code (from which the CIN  has been compiled) does not give any such error while executing higher order matrix multiplication in the C environment. How do we calculate and define the required Buffer memory in LV environment for such applications. Similar problems may arise in numerous other applications in LV environment. Pl. suggest ways and means to get over this problem.
    LabVIEW 6.1 professional development system  is our platform on windows-xp. 

    PNVK wrote:
    We have developed a CIN for
    LabVIEW application in which we carry out matrix multiplication.
    We are able to carry out multiplication of 3x3 matrices in the LV
    environment using the CIN. The LV application gives error for higher
    order of matrices indicating insufficient buffer. However the c
    source code (from which the CIN  has been compiled) does not give
    any such error while executing higher order matrix multiplication in
    the C environment. How do we calculate and define the required Buffer
    memory in LV environment for such applications. Similar problems may
    arise in numerous other applications in LV environment. Pl. suggest
    ways and means to get over this problem.
    LabVIEW 6.1 professional development system  is our platform on windows-xp. 
    It
    seems strange that only a 3*3 matrix would be possible. So the
    conclusion is you do something wrong in your CIN. This could be some
    difference in the CIN parameters for the CIN node in comparison to what
    the CIN actually does or it could be a bug in the CIN itself most
    probably in the adaption of your C type algorithme to the LabVIEW
    datatype parameters.
    Rolf Kalbermatter
    Rolf Kalbermatter
    CIT Engineering Netherlands
    a division of Test & Measurement Solutions

  • Price Matrix - Multiple Product Attributes

    Hi, I need to set prices for 1 product based on combination of selected multiple attributes. How can I do this?
    Product A
    Material
    Size
    Price
    material 1
    s
    10
    m
    12
    l
    15
    material 2
    s
    20
    m
    25
    l
    30
    xl
    35
    xxl
    63
    material 3
    l
    80
    xl
    100

    For more information on inventory control and setting product inventory for attributes, please refer to the following article : http://helpx.adobe.com/business-catalyst/partner/product-inventory.html
    Cheers,
    Aishvarya Raj Rastogi

  • Matrix multiple rows adding problem

    Hi all,
    In a SDK developed form, have a button "Add Row". When press Add Row a new row has to be added in the matrix.
    I' ve written the set of codes as
    Private Sub SBO_Application_ItemEvent(ByVal FormUID As String, ByRef pVal As SAPbouiCOM.ItemEvent, ByRef BubbleEvent As Boolean) Handles SBO_Application.ItemEvent
            Dim oitem As SAPbouiCOM.Item
            Try
                If (FormUID = "Frm_itemsupplier") Then
                    If (pVal.Before_Action = False) Then
                        'Add Row
                        If (pVal.ItemUID = "AddRow") And (pVal.EventType = SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED) Then
                            Dim f As SAPbouiCOM.Form
                            Dim oMatrix As SAPbouiCOM.Matrix
                            f = SBO_Application.Forms.Item(FormUID)
                            oMatrix = f.Items.Item("mat1").Specific
                            f.DataSources.DBDataSources.Item(1).Clear()
                            oMatrix.AddRow(1)
                        End If
    But at run time, when press Add row button first time this will add one row.  Then I cancel the form, open the same form then press add row Button, 1+1 rows are adding in the matrix. If I do the above(cancel and open the form again), keep on increasing rows additionally on every time.
    Let me get a solution how to solve the issue and I will be appreciated.
    Thanks & regards,
    Venkatesan g.

    try it as
    Private Sub SBO_Application_ItemEvent(ByVal FormUID As String, ByRef pVal As SAPbouiCOM.ItemEvent, ByRef BubbleEvent As Boolean) Handles SBO_Application.ItemEvent
    Dim oitem As SAPbouiCOM.Item
    Try
    If (FormUID = "Frm_itemsupplier") Then
    If (pVal.Before_Action = False) Then
    'Add Row
    If (pVal.ItemUID = "AddRow") And (pVal.EventType = SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED) Then
    Dim f As SAPbouiCOM.Form
    Dim oMatrix As SAPbouiCOM.Matrix
    f = SBO_Application.Forms.Item(FormUID)
    oMatrix = f.Items.Item("mat1").Specific
    f.DataSources.DBDataSources.Item(1).Clear()
                        Dim cell As SAPbouiCOM.Cell
                        Dim col As SAPbouiCOM.Column
                        Dim ed As SAPbouiCOM.EditText
                        col = omatrix1.Columns.Item(1)
                        cell = col.Cells.Item(1)
                        ed = cell.Specific
                        if ed.String <> "" then
    oMatrix.AddRow(1,0)
    end if
    End If
    this will test before addrow if there exist blank first row and in case that no, it will add new row. The sample test for column index 1 and first row.
    Hope it`s what you need.

  • Matrix multiple query report problem

    dear members i have serious problem regarding report as i m usin oracle 10g with developer 6i release2 and i m getting following error while executing teh report out:
    rep-1761: internal error <rgcaag-2> while processing group <g_item_code>
    plz any one hv idea regarding this error so share with me .
    thnx in advance
    Edited by: user581618 on Jul 14, 2012 1:48 AM

    Internal errors usually indicate a bug somewhere.
    What are your exact Reports version, database version and operating system? Developer 6i release2 and 10g are not the exact version numbers.

  • What's wrong with my multi-threaded Matrix Mult. code? 1 thread is fastest

    For some reason, 1 thread performs the best. What's wrong with my implementation?
    import java.util.Random;
    import java.util.Date;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.TimeUnit;
    public class Matrix {     
         private int values[][];
         private int rows;
         private int columns;
         public Matrix(int r, int c) {
              this.rows = r;
              this.columns = c;
              this.values = new int[r][c];
         private void randomize() {
              Random generator = new Random();
              for (int r = 0; r < this.rows; r++) {
                   for (int c = 0; c < this.columns; c++) {
                        this.values[r][c] = generator.nextInt(10);
         public String toString() {
              String out = "";
              for (int r = 0; r < this.rows; r++) {
                   for (int c = 0; c < this.columns; c++) {
                        if (c == 0) out += "[";
                        else out += "\t";
                        out += this.values[r][c];
                   out += "]\n";
              return out;
         public boolean equals(Object obj) {
              Matrix other = (Matrix) obj;
              if (this.columns != other.columns || this.rows != other.rows)  {
                   return false;
              for (int r = 0; r < this.rows; r++) {
                   for (int c = 0; c < this.columns; c++) {
                        if (this.values[r][c] != other.values[r][c]) {
                             return false;
              return true;
         // matrix multiplication using single thread
         public Matrix times(Matrix other) {
              assert(this.columns == other.rows);
              Matrix out = new Matrix(this.rows, other.columns);
              for (int r = 0; r < this.rows; r++) {
                   for (int c = 0; c < other.columns; c++) {
                        int dotProduct = 0;
                        for (int z = 0; z < this.columns; z++) {
                             dotProduct += this.values[r][z] * other.values[z][c];
                        out.values[r][c] = dotProduct;
              return out;
         // matrix multiplication with many threads
         public Matrix ptimes(Matrix other, int numberOfThreads) throws InterruptedException { // parallel
              assert(this.columns == other.rows);
              Matrix out = new Matrix(this.rows, other.columns);
              ExecutorService threadExecutor = Executors.newFixedThreadPool(numberOfThreads);
              for (int r = 0; r < this.rows; r++) {
                   for (int c = 0; c < other.columns; c++) {
                        threadExecutor.execute(new HelperThread(r, c, this, other, out));
              threadExecutor.shutdown();
              threadExecutor.awaitTermination(2, TimeUnit.DAYS);
              return out;
         private class HelperThread implements Runnable {
              private int row;
              private int col;
              private Matrix a;
              private Matrix b;
              private Matrix out;
              HelperThread(int r, int c, Matrix a, Matrix b, Matrix o) {
                   this.row = r;
                   this.col = c;
                   this.a = a;
                   this.b = b;
                   this.out = o;
              public void run() {
                   int dotProduct = 0;
                   for (int z = 0; z < a.columns; z++) {
                        dotProduct += this.a.values[row][z] * this.b.values[z][col];
                   this.out.values[row][col] = dotProduct;
         public static void main(String[] args) throws InterruptedException {
              int size = 100;
              Matrix a = new Matrix(size, size);
              a.randomize();     
              Matrix b = new Matrix(size, size);
              b.randomize();
              for (int t = 1; t < 15; t++) {
                   long start = new Date().getTime();
                   System.out.print(t + " threads: ");
                   Matrix c = a.ptimes(b, t);
                   //System.out.println(c);
                   long finish = new Date().getTime();
                   System.out.println((finish - start) + " milliseconds");
                   Matrix d = a.times(b);
                   assert(c.equals(d));
    }

    This one is even faster. On my dual core I get:
    Warmup
    Single Threaded
    5.20616 milliseconds
    5.52872 milliseconds
    5.12708 milliseconds
    5.59048 milliseconds
    5.16104 milliseconds
    5.1838 milliseconds
    5.37104 milliseconds
    5.1788 milliseconds
    5.18636 milliseconds
    5.15736 milliseconds
    Multi Threaded with 2 threads
    3.22184 milliseconds
    2.86552 milliseconds
    2.86284 milliseconds
    3.67032 milliseconds
    3.08032 milliseconds
    2.97388 milliseconds
    2.93084 milliseconds
    3.44012 milliseconds
    2.89744 milliseconds
    2.88136 milliseconds
    As you can see the Multi-Threaded versions are now faster.
        // matrix multiplication with many threads
        ExecutorService threadExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        public Matrix ptimes(Matrix other) throws InterruptedException, ExecutionException {
            assert (this.columns == other.rows);
            Matrix out = new Matrix(this.rows, other.columns);
            Future futures[] = new Future[rows];
            for (int r = 0; r < this.rows; r++) {
                futures[r] = threadExecutor.submit(new HelperThread(r, this, other, out));
            for(Future f : futures) {
                f.get();
            return out;
        private class HelperThread implements Callable<Object> {
            private int row;
            private Matrix a;
            private Matrix b;
            private Matrix out;
            HelperThread(int r, Matrix a, Matrix b, Matrix o) {
                this.row = r;
                this.a = a;
                this.b = b;
                this.out = o;
            public String call() throws Exception {
                int dotProduct = 0;
                for (int c = 0; c < b.columns; c++) {
                    for (int z = 0; z < a.columns; z++) {
                        dotProduct += this.a.values[row][z] * this.b.values[z][c];
                    this.out.values[row][c] = dotProduct;
                return null;
        public static void main(String[] args) throws InterruptedException, ExecutionException {
            int size = 100;
            Matrix a = new Matrix(size, size);
            a.randomize();
            Matrix b = new Matrix(size, size);
            b.randomize();
            System.out.println("Warmup");
            for (int t = 0; t < 1000; t++) {
                Matrix c = a.ptimes(b);
                Matrix d = a.times(b);
                assert (c.equals(d));
            System.out.println("Single Threaded");
            for (int t = 0; t < 10; t++) {
                long start = System.nanoTime();
                Matrix d = a.times(b);
                long finish = System.nanoTime();
                System.out.println((finish - start)/1000000.0 + " milliseconds");
            System.out.println("Multi Threaded with " + Runtime.getRuntime().availableProcessors() + " threads");
            for (int t = 0; t < 10; t++) {
                long start = System.nanoTime();
                Matrix c = a.ptimes(b);
                long finish = System.nanoTime();
                System.out.println((finish - start)/1000000.0 + " milliseconds");
                Matrix d = a.times(b);
                assert (c.equals(d));
            System.exit(0);
        }

  • Error in result of Matrix Multiplica​tion

    Multiplying complex A(3x3) with a vector (3x1), errorin output. details as attached. any solution?
    Attachments:
    Matrix Multiplication.PNG ‏10 KB
    Matrix Output Error.PNG ‏19 KB

    If the inputs to the matrix multiplication is same, and the multiply is configured for AXB then there is a n error generated!
    Attachments:
    Matrix Multiplication-Error Code.PNG ‏25 KB

  • VertexShader - Parameter / Matrix Issues

    I'm trying to implement a simple mask-shader for my 2D engine and I'm having multiple issues getting it to work.
    Basically the shader takes two images and two matrices and tries to map back the vertex position of the sprites vertex back to the local mask space position and then calculate the local uv-coordinates for the mask, but I'm stuck with some basic calculations here.
    Bug 1: Divisions in the material-vertex kernel don't work at all. That's why I have to put invertedMaskSize (which is 1.0 / 128.0) into the shader (but we already know that )
    Bug 2: interpolated vars have to be float4, float2 is not possible (That's a pretty old bug as well)
    I tried the following changes in the shader. The shader posted here, just tries to display the resulting uv-coordinates. No textures are used.
    Case 1:
    interpolatedMaskUV = float4((vertexPos.x + halfMaskSize.x) * invertedMaskSize.x, (vertexPoss.y + halfMaskSize.y) * invertedMaskSize.y, 0.0, 0.0);
    The output is this: http://dev.nulldesign.de/plain_uvcoords.png Just like you expect! Perfect, let's proceed.
    Case 2:
    Change the halfMaskSize and invertedMaskSize to float2 and set set the parameters as two vectors of length two of course in AS. The output: http://dev.nulldesign.de/float2_uvcoords.png
    Case 3:
    Masking Test, matrix multiplication. First calculating the world space position of the vertex:
    float4 worldSpacePos = float4(vertexPos.x, vertexPos.y, 0.0, 1.0) * objectToClipSpaceTransform;
    Then mapping it back to the local space of the mask:
    float4 localMaskSpacePos = worldSpacePos * maskObjectToClipSpaceTransform;
    And calculating the uv-coords:
    interpolatedMaskUV = float4((localMaskSpacePos.x + halfMaskSize.x) * invertedMaskSize.x, (localMaskSpacePos.y + halfMaskSize.y) * invertedMaskSize.y, 0.0, 0.0);
    For testing, I set the maskObjectToClipSpaceTransform to the inverse of the objectToClipSpaceTransform. In theory and on paper, this should work.
    But, I think, something gets out of order and maybe the maskObjectToClipSpaceTransform is screwed up in the shader, just like when I set the halfMaskSize and invertedMaskSize to float2. The result is this: http://dev.nulldesign.de/local_uvcoords.png and I have no idea how to fix this...
    <languageVersion : 1.0;>
    material kernel texture
    <
        namespace : "ND2D_Shader";
        vendor : "nulldesign";
        version : 1;
    >
        input vertex float2 uvCoord
        <
            id : "PB3D_UV";
        >;
        input vertex float2 vertexPos
        <
            id : "PB3D_POSITION";
        >;
        parameter float2 uvOffset;
        parameter float4x4 objectToClipSpaceTransform;
        parameter float4x4 maskObjectToClipSpaceTransform;
        // if set to float2, strange things happen
        parameter float4 halfMaskSize;
        parameter float4 invertedMaskSize;
        interpolated float4 interpolatedUV;
        interpolated float4 interpolatedMaskUV;
        void evaluateVertex()
            // not used in the current test ...
            interpolatedUV = float4(uvCoord.x + uvOffset.x, uvCoord.y + uvOffset.y, 0.0, 0.0);
            float4 worldSpacePos = float4(vertexPos.x, vertexPos.y, 0.0, 1.0) * objectToClipSpaceTransform;
            // doesn't work as expected
            float4 localMaskSpacePos = worldSpacePos * maskObjectToClipSpaceTransform;
            interpolatedMaskUV = float4((localMaskSpacePos.x + halfMaskSize.x) * invertedMaskSize.x,
                                        (localMaskSpacePos.y + halfMaskSize.y) * invertedMaskSize.y,
                                         0.0, 0.0);
        input image4 textureImage;
        input image4 textureMaskImage;
        parameter float4 color;
        output float4 result;
        void evaluateFragment()
              // just visualize the uv-coords
              result = float4(interpolatedMaskUV.x, interpolatedMaskUV.y, 0.0, 1.0);
            float4 texel = sample(textureImage, float2(interpolatedUV.x, interpolatedUV.y), PB3D_2D | PB3D_MIPNEAREST | PB3D_CLAMP);
            float4 texel2 = sample(textureMaskImage, float2(interpolatedMaskUV.x, interpolatedMaskUV.y), PB3D_2D | PB3D_MIPNEAREST | PB3D_CLAMP);
            result = float4(texel.r * color.r,
                            texel.g * color.g,
                            texel.b * color.b,
                            texel.a * color.a * texel2.a);
    I know that we're working with a four month old version of pb3d and I hope that a new version will be out soon and maybe all these bugs I encountered are already solved, but if not.... here's another shader to fix

    Ah that's interesting. I thought after compiling the three shaders with pixelbender, the two vertex kernels are merged and I can use the same parameters. This would mean, I have to push objectToClipSpaceTransform twice (with a different name)? So I would to waste four registers
    Here is the AGAL version of the shader, it's working as expected:
    vertex:
    m44 vt0, va0, vc0                   // vertex * clipspace
    m44 vt1, vt0, vc4                   // clipsace to local pos in mask
    add vt1.xy, vt1.xy, vc8.xy     // add half masksize to local pos
    div vt1.xy, vt1.xy, vc8.zw     // local pos / masksize
    mov v0, va1                         // copy uv
    mov v1, vt1                         // copy mask uv
    mov op, vt0                         // output position
    fragment:
    mov ft0, v0                                                   // get interpolated uv coords
    tex ft1, ft0, fs0 <2d,clamp,linear,nomip>      // sample texture
    mul ft1, ft1, fc0                                             // mult with color
    mov ft2, v1                                                   // get interpolated uv coords for mask
    tex ft3, ft2, fs1 <2d,clamp,linear,nomip>      // sample mask
    mul ft1, ft1, ft3                                             // mult mask color with tex color
    mov oc, ft1                                                   // output color
    The full source code here: https://github.com/nulldesign/nd2d/blob/master/src/de/nulldesign/nd2d/materials/Sprite2DMa skMaterial.as
    I'll try it with a different parameter name now. Thanks

  • Waveform to Matrix Multiplica​tion

    Hi All.
    I have a DAQ-MX file that brings in a 1-D array of waveforms. This will either have six, seven, or eight waveforms (depending on previous settings). Regardless of how many there are, I want to take the first six of these waveforms, and do a matrix multiplication.
    That is, if A is my 6x1 of the voltages read in by the DAQ, I want to multiply that matrix by B, a 6x6 of constants.
    Is this possible?
    Thanks,
    James
    Solved!
    Go to Solution.

    But I do want to perform matrix multiplication. See the image below.
    If these were the time-averages of the voltages or anything else then I would be fine in setting it up, I just can't figure out how to do it when they are waveforms.
    Thanks,
    James
    Attachments:
    matrix multiplication.png ‏24 KB

  • Re: Matrix Inversion

    I don't know if I've understood your problem :
    Given two matrix A and B we suppose that B verify that is possible obtain a inverse B^-1 that exists C matrix such :
    C = A x B^-1
    Your question is how can made for obtain C or B^-1 ?

    and no, not all encryption relies on Matrix multiplication....its just a common technique...and I really have always been interested in it since I first heard about it in Algebra II
    After I finish this project, i'll hopefully have a much better grasp on security and encryption

  • Matrix Raised to a Power in Excel

    To Whom it May Concern,
    I am working with matrices in Excel 2010 and happened upon a problem.  Excel can perform matrix multiplication (e.g. A1:B2 times A3:B4) by the mmult function and yields the correct answer.  However, there is a problem when attempting to raise a
    single matrix to a power - e.g. A^3 (for some array I refer to as A).
    Various fora online all suggest using the power function on an array (thus, using the ctrl + shift + enter).  This takes each entry of the matrix and raises it to the given power.  This is NOT the same as raising the matrix to the given power,
    and thus yields an incorrect result if the user is hoping to perform such an operation.  Effectively, I'm curious as to the existence of an excel function that uses the method of mmult for raising a matrix to a power.
    I'm not sure if this is an error in an excel function or something that exists in an add on.  Please let me know if there is a way to properly raise a matrix to a power in excel.
    Thanks,
    Louis

    Well, you can make your own simple matrix power function, like this;
    Function PowerMatrix(rngInp As Range, lngPow As Long) As Variant
    Dim i As Long
    PowerMatrix = rngInp
    If lngPow > 1 Then
    For i = 2 To lngPow
    PowerMatrix = Application.WorksheetFunction.MMult(rngInp, PowerMatrix)
    Next
    End If
    End Function
    Use it in a range like;
    =PowerMatrix(A1:B2,3)
    to get the matrix to the third power. Enter the function as an array formula.
    This simple function does not test for a square matrix (which you need if you are going to multiply a matrix by itself).
    Ed Ferrero
    www.edferrero.com
    I know this is an ancient post but there is a much better answer. If you want to raise the matrix to a large power (like 1 billion), the above will leave you waiting for a long time. Note that X^100 can be represented as (X^64)*(X^32)*(X^4) = (X^2^2) * (X^2^2^2^2^2)
    * (X^2^2^2^2^2^2). By repeatedly squaring and multiplying the squares by the output value you can drastically reduce the number multiplications required.
    Function PowerMatrix(Matrix As Range, Power As Long) As Variant
    Dim Result As Variant
    Dim Square As Variant
    Dim i As Long
    Square = Matrix
    For i = 0 To 31
    If (Power And 2 ^ i) Then
    If IsEmpty(Result) Then
    Result = Square
    Else
    Result = Application.WorksheetFunction.MMult(Square, Result)
    End If
    End If
    If 2 ^ i >= Power Then Exit For
    Square = Application.WorksheetFunction.MMult(Square, Square)
    Next
    PowerMatrix = Result
    End Function

  • How do i pass a variable in flex

    i've been looking all over google for how to pass a variable yet
    i've come up empty handed
    i have a C code and as3
    i've never been able to get a C program to compile on my own, this is from a tutorial im trying to understand about raycasting
    from what i can gather i think that the variables are passed threw this
    #######raycaster.c##########
    AS3_Val loop( void* self, AS3_Val args )
        AS3_ArrayValue(args,"IntType,IntType,IntType,IntType",&K_UP,&K_DOWN,&K_LEFT,&K_RIGHT);
        CastRay();
        int opos,j,i,jpos;
        for(j=0; j < resY; j++ ){
            jpos = resX*j;
            for(i=0; i < resX; i++ ){
                opos = (jpos+i);
                tBuffer[opos] = buffer[i][j];
            }//end of for
        }//end of for
        return 0;
    }//end of loop
    however not one of the values inside of AS3_ArrayValue is to be found on the Main.as
    this is the only function that comunicates with the C code, but i could be wrong
    ####Main.as######
            private function enterFrame(event:Event):void {
                alcRCLib.loop(upKey,downKey,leftKey,rightKey);
                alchemyMemory.position=alcScreenBufferPointer;
                screenBitmapData.setPixels(screenBitmapData.rect,alchemyMemory);
    the reason i want to do this, other than to know how, because that would be useful above all else, i've already written a as3 that comunicates with php
    to get a array of images  for a topdown game, and i wouldn't know how to load these variables to C from a HTTP request but if i can get flash to tell c what they are then every thing worked out
    heres both codes in full
    #####Main.as####
    *Alchemy Ray Caster
    *April 6, 2010
    *Bruce Jawn
    *http://bruce-lab.blogspot.com
    *Copyright (c) <2010> <Bruce Jawn>
    *This software is released under the MIT License
    *<http://www.opensource.org/licenses/mit-license.php>
    package {
    //    import cmodule.Ray_Caster._worldMap;
    //    import cmodule.Ray_Caster._worldMap;
        import cmodule.Ray_Caster.CLibInit;
    //    import cmodule.Ray_Caster.TextFieldI;
        import flash.display.*;
        import flash.text.*;
        import flash.events.*;
        import flash.geom.*;
        import flash.text.engine.TextBlock;
        import flash.text.engine.TextLine;
        import flash.text.TextField;
        import flash.utils.*;
        import flash.ui.*;
        [SWF(width="840", height="880")]
        public class Main extends Sprite {
            [Embed(source="../wolftex/barrel.png")]
            public static var barrelClass:Class;
            [Embed(source="../wolftex/bluestone.png")]
            public static var bluestoneClass:Class;
            [Embed(source="../wolftex/colorstone.png")]
            public static var colorstoneClass:Class;
            [Embed(source="../wolftex/eagle.png")]
            public static var eagleClass:Class;
            [Embed(source="../wolftex/greenlight.png")]
            public static var greenlightClass:Class;
            [Embed(source="../wolftex/greystone.png")]
            public static var greystoneClass:Class;
            [Embed(source="../wolftex/mossy.png")]
            public static var mossyClass:Class;
            [Embed(source="../wolftex/pillar.png")]
            public static var pillarClass:Class;
            [Embed(source="../wolftex/purplestone.png")]
            public static var purplestoneClass:Class;
            [Embed(source="../wolftex/redbrick.png")]
            public static var redbrickClass:Class;
            [Embed(source="../wolftex/wood.png")]
            public static var woodClass:Class;
            //Array to hold all the textures
            private var texs:Array=[];
            private var worldMap:Array = [];
            //private var worldMap[1]:Array=[];
            private static const SCREEN_WIDTH:int=640;
            private static const SCREEN_HEIGHT:int=480;
            private var screenBitmapData:BitmapData;
            private var screenBitmap:Bitmap;
            private var alchemyMemory:ByteArray;
            private var alcRCLib:Object;
            private var cLibInit:CLibInit;
            private var alcScreenBufferPointer:uint;
            private var alcTexPointer:uint;
            private var upKey:int=0;
            private var downKey:int=0;
            private var leftKey:int=0;
            private var rightKey:int=0;
            private var a:flash.text.TextField;
            public function Main() {
                stage.frameRate=60;
                stage.align=StageAlign.TOP_LEFT;
                stage.scaleMode=StageScaleMode.NO_SCALE;
                stage.fullScreenSourceRect=new Rectangle(0,0,SCREEN_WIDTH,SCREEN_HEIGHT);
                init();
                }//end of function Main
            private function init():void {
                initBitmaps();
                initAlchemy();
                initRendering();
            }//end of function init
            private function initBitmaps():void {
                texs.push(prepareBitmapData(new eagleClass().bitmapData  ));
                texs.push(prepareBitmapData(new redbrickClass().bitmapData  ));
                texs.push(prepareBitmapData(new purplestoneClass().bitmapData  ));
                texs.push(prepareBitmapData(new greystoneClass().bitmapData  ));
                texs.push(prepareBitmapData(new bluestoneClass().bitmapData  ));
                texs.push(prepareBitmapData(new mossyClass().bitmapData  ));
                texs.push(prepareBitmapData(new woodClass().bitmapData  ));
                texs.push(prepareBitmapData(new colorstoneClass().bitmapData  ));
                texs.push(prepareBitmapData(new barrelClass().bitmapData  ));
                texs.push(prepareBitmapData(new pillarClass().bitmapData  ));
                texs.push(prepareBitmapData(new greenlightClass().bitmapData  ));
                screenBitmapData=new BitmapData(SCREEN_WIDTH,SCREEN_HEIGHT,false,0);
                screenBitmap=new Bitmap(screenBitmapData);
                addChild(screenBitmap);
                worldMap[1] = (1,2,3,4);
                worldMap[2] = (1,2,3,4);
                worldMap[3] = (1,2,3,4);
                worldMap[4] = (1,2,3,4);
                worldMap[5] = (1,2,3,4);
                worldMap[6] = (1,2,3,4);
                worldMap[7] = (1,2,3,4);
                }//end of function initBitmaps
            //Prepare the bitmap once to take into account the lower-endianess of the alchemy code.
            private function prepareBitmapData(sourceMap:BitmapData):BitmapData {
                var outBitmapData:BitmapData=sourceMap.clone();
                outBitmapData=new BitmapData(outBitmapData.width,outBitmapData.height,true,0xFF000000);
                outBitmapData.copyChannel(sourceMap,outBitmapData.rect,outBitmapData.rect.topLeft,BitmapD ataChannel.ALPHA,BitmapDataChannel.BLUE);
                outBitmapData.copyChannel(sourceMap,outBitmapData.rect,outBitmapData.rect.topLeft,BitmapD ataChannel.RED,BitmapDataChannel.GREEN);
                outBitmapData.copyChannel(sourceMap,outBitmapData.rect,outBitmapData.rect.topLeft,BitmapD ataChannel.GREEN,BitmapDataChannel.RED);
                outBitmapData.copyChannel(sourceMap,outBitmapData.rect,outBitmapData.rect.topLeft,BitmapD ataChannel.BLUE,BitmapDataChannel.ALPHA);
                return outBitmapData;
            }//end of function prepareBitmapData
            private function initAlchemy():void {
                cLibInit=new CLibInit  ;
                alcRCLib=cLibInit.init();
                //Retrieve the "Alchemy Memory".
                var ns:Namespace=new Namespace("cmodule.Ray_Caster");
                alchemyMemory=ns::gstate.ds;
                //Allocate the buffers in Alchemy.
                alcScreenBufferPointer=alcRCLib.initializeScreenBuffer(SCREEN_WIDTH,SCREEN_HEIGHT);//Setu p a screenbuffer of size x,y;
                //Copy the textures to alchemy memory.
                for (var i:int=0; i<11; i++) {
                    var ba:ByteArray=texs[i].getPixels(texs[i].rect);
                    alcTexPointer=alcRCLib.initializeTexBuffer(i);
                    alchemyMemory.position=alcTexPointer;
                    alchemyMemory.writeBytes(ba,0,ba.length);
                }//end of for
            }//end of function initAlchemy
            private function initRendering():void {
                stage.addEventListener(KeyboardEvent.KEY_DOWN,key_pressed);
                stage.addEventListener(KeyboardEvent.KEY_UP,key_released);
                addEventListener(Event.ENTER_FRAME,enterFrame);
            }//end of function initRendering
            private function enterFrame(event:Event):void {
                alcRCLib.loop(upKey,downKey,leftKey,rightKey);
                alchemyMemory.position=alcScreenBufferPointer;
                screenBitmapData.setPixels(screenBitmapData.rect,alchemyMemory);
                }//end of function enterFrame
            private function key_pressed(e:KeyboardEvent):void {
                switch (e.keyCode) {
                    case Keyboard.UP :
                        upKey=1;
                        break;
                    case Keyboard.DOWN :
                        downKey=1;
                        break;
                    case Keyboard.LEFT :
                        leftKey=1;
                        break;
                    case Keyboard.RIGHT :
                        rightKey=1;
                        break;
                }//end of switch
                }//end of function key_pressed
            private function key_released(e:KeyboardEvent):void {
                switch (e.keyCode) {
                    case Keyboard.UP :
                        upKey=0;
                        break;
                    case Keyboard.DOWN :
                        downKey=0;
                        break;
                    case Keyboard.LEFT :
                        leftKey=0;
                        break;
                    case Keyboard.RIGHT :
                        rightKey=0;
                        break;               
                        }//end of switch
                }//end of function key_released
                }//end of class
    }//end of package
    ###raycaster####
    //Raycasting Engine from Lode's Computer Graphics Tutorial
    //http://www.student.kuleuven.be/~m0216922/CG/raycasting.html
    //Modified for Alchemy by Bruce Jawn
    //http://bruce-lab.blogspot.com
    #include "AS3.h"
    #include <math.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    //============================================================
    //============================================================
    enum bool {false=0,true=!false};
    #define screenWidth 1640
    #define screenHeight 1480
    #define texWidth 64
    #define texHeight 64
    #define mapWidth 24
    #define mapHeight 24
    //1D Screen Buffer
    int* tBuffer;
    int resX = 0;
    int resY = 0;
    //2D Screen Buffer
    int buffer[screenWidth][screenHeight];
    //1D Zbuffer
    double ZBuffer[screenWidth];
    //============================================================
    //============================================================
    //textures
    int texture[11][texWidth*texHeight];
    #define numSprites 19
    //arrays used to sort the sprites
    int spriteOrder[numSprites];
    double spriteDistance[numSprites];
    struct SSprite
      double x;
      double y;
      int texture;
    struct SSprite sprite[numSprites]=
      //green light in front of playerstart
      {20.5, 11.5, 10},
      //green lights in every room
      {18.5,4.5, 10},
      {10.0,4.5, 10},
      {10.0,12.5,10},
      {3.5, 6.5, 10},
      {3.5, 20.5,10},
      {3.5, 14.5,10},
      {14.5,20.5,10},
      //row of pillars in front of wall: fisheye test
      {18.5, 10.5, 9},
      {18.5, 11.5, 9},
      {18.5, 12.5, 9},
      //some barrels around the map
      {21.5, 1.5, 8},
      {15.5, 1.5, 8},
      {16.0, 1.8, 8},
      {16.2, 1.2, 8},
      {3.5,  2.5, 8},
      {9.5, 15.5, 8},
      {10.0, 15.1,8},
      {10.5, 15.8,8},
    //============================================================
    //============================================================
    //map
    int worldMap[mapWidth][mapHeight] =
      {8,8,8,8,8,8,8,8,8,8,8,4,4,6,4,4,6,4,6,4,4,4,6,4},
      {8,0,0,0,0,0,0,0,0,0,8,4,0,0,0,0,0,0,0,0,0,0,0,4},
      {8,0,3,3,0,0,0,0,0,8,8,4,0,0,0,0,0,0,0,0,0,0,0,6},
      {8,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,6},
      {8,0,3,3,0,0,0,0,0,8,8,4,0,0,0,0,0,0,0,0,0,0,0,4},
      {8,0,0,0,0,0,0,0,0,0,8,4,0,0,0,0,0,6,6,6,0,6,4,6},
      {8,8,8,8,0,8,8,8,8,8,8,4,4,4,4,4,4,6,0,0,0,0,0,6},
      {7,7,7,7,0,7,7,7,7,0,8,0,8,0,8,0,8,4,0,4,0,6,0,6},
      {7,7,0,0,0,0,0,0,7,8,0,8,0,8,0,8,8,6,0,0,0,0,0,6},
      {7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8,6,0,0,0,0,0,4},
      {7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8,6,0,6,0,6,0,6},
      {7,7,0,0,0,0,0,0,7,8,0,8,0,8,0,8,8,6,4,6,0,6,6,6},
      {7,7,7,7,0,7,7,7,7,8,8,4,0,6,8,4,8,3,3,3,0,3,3,3},
      {2,2,2,2,0,2,2,2,2,4,6,4,0,0,6,0,6,3,0,0,0,0,0,3},
      {2,2,0,0,0,0,0,2,2,4,0,0,0,0,0,0,4,3,0,0,0,0,0,3},
      {2,0,0,0,0,0,0,0,2,4,0,0,0,0,0,0,4,3,0,0,0,0,0,3},
      {1,0,0,0,0,0,0,0,1,4,4,4,4,4,6,0,6,3,3,0,0,0,3,3},
      {2,0,0,0,0,0,0,0,2,2,2,1,2,2,2,6,6,0,0,5,0,5,0,5},
      {2,2,0,0,0,0,0,2,2,2,0,0,0,2,2,0,5,0,5,0,0,0,5,5},
      {2,0,0,0,0,0,0,0,2,0,0,0,0,0,2,5,0,5,0,5,0,5,0,5},
      {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5},
      {2,0,0,0,0,0,0,0,2,0,0,0,0,0,2,5,0,5,0,5,0,5,0,5},
      {2,2,0,0,0,0,0,2,2,2,0,0,0,2,2,0,5,0,5,0,0,0,5,5},
      {2,2,2,2,1,2,2,2,2,2,2,1,2,2,2,5,5,5,5,5,5,5,5,5}
    //============================================================
    //============================================================
    double posX = 22.0, posY = 11.5; //x and y start position
    double dirX = -1.0, dirY = 0.0; //initial direction vector
    double planeX = 0.0, planeY = 0.66; //the 2d raycaster version of camera plane
    int K_LEFT=0;
    int K_RIGHT=0;
    int K_UP=0;
    int K_DOWN=0;
    //speed modifiers
    double moveSpeed =  .30; //the constant value is in squares/second
    double rotSpeed =   .20; //the constant value is in radians/second
    //============================================================
    //============================================================
    AS3_Val initializeScreenBuffer(void* self, AS3_Val args)
        AS3_ArrayValue(args, "IntType, IntType", &resX, &resY);
        tBuffer = malloc( resX * resY * sizeof(int) );
        return AS3_Ptr( tBuffer );
    }//end of initializeScreenBuffer
    //used to load some textures & sprite textures
    AS3_Val initializeTexBuffer(void* self, AS3_Val args)
        int index;
        AS3_ArrayValue(args, "IntType", &index);
        return AS3_Ptr( texture[index] );
    }//end of initializeTexBuffer
    //start the main loop
    AS3_Val loop( void* self, AS3_Val args )
        AS3_ArrayValue(args,"IntType,IntType,IntType,IntType",&K_UP,&K_DOWN,&K_LEFT,&K_RIGHT);
        CastRay();
        int opos,j,i,jpos;
        for(j=0; j < resY; j++ ){
            jpos = resX*j;
            for(i=0; i < resX; i++ ){
                opos = (jpos+i);
                tBuffer[opos] = buffer[i][j];
            }//end of for
        }//end of for
        return 0;
    }//end of loop
    int main()
        AS3_Val initializeScreenBufferMethod = AS3_Function( NULL,initializeScreenBuffer );
        AS3_Val loopMethod = AS3_Function( NULL,loop );
        AS3_Val initializeTexBufferMethod = AS3_Function( NULL,initializeTexBuffer );
        AS3_Val result = AS3_Object("initializeScreenBuffer:AS3ValType,loop:AS3ValType,initializeTexBuffer:AS3ValT ype"
                                    ,initializeScreenBufferMethod,loopMethod,initializeTexBufferMethod);
        AS3_Release( initializeScreenBufferMethod );
        AS3_Release( loopMethod );
        AS3_Release( initializeTexBufferMethod );
        AS3_LibInit( result );
        return 0;
    }//end of main
    //================================================================
    //================================================================
    void CastRay()
        printf ("Hello World!\n");
        int x;
        int y;
        int w=screenWidth;
        int h=screenHeight;
        for( x = 0; x < screenWidth; x++) for( y = 0; y < screenHeight; y++) {buffer[x][y] = 0;} //clear the buffer instead of cls()
        for(x = 0; x < w; x++)
          //calculate ray position and direction
          double cameraX = 2 * x / (double)(w) - 1; //x-coordinate in camera space    
          double rayPosX = posX;
          double rayPosY = posY;
          double rayDirX = dirX + planeX * cameraX;
          double rayDirY = dirY + planeY * cameraX;
          //which box of the map we're in 
          int mapX = (int)(rayPosX);
          int mapY = (int)(rayPosY);
          //length of ray from current position to next x or y-side
          double sideDistX;
          double sideDistY;
          //length of ray from one x or y-side to next x or y-side
          double deltaDistX = sqrt(1 + (rayDirY * rayDirY) / (rayDirX * rayDirX));
          double deltaDistY = sqrt(1 + (rayDirX * rayDirX) / (rayDirY * rayDirY));
          double perpWallDist;
          //what direction to step in x or y-direction (either +1 or -1)
          int stepX;
          int stepY;
          int hit = 0; //was there a wall hit?
          int side; //was a NS or a EW wall hit?
          //calculate step and initial sideDist
          if (rayDirX < 0)
            stepX = -1;
            sideDistX = (rayPosX - mapX) * deltaDistX;
          }//end of if (rayDirX < 0)
          else
            stepX = 1;
            sideDistX = (mapX + 1.0 - rayPosX) * deltaDistX;
          }//end of else
          if (rayDirY < 0)
            stepY = -1;
            sideDistY = (rayPosY - mapY) * deltaDistY;
          }//end of if (rayDirY < 0)
          else
            stepY = 1;
            sideDistY = (mapY + 1.0 - rayPosY) * deltaDistY;
          }//end of else
          //perform DDA
          while (hit == 0)
            //jump to next map square, OR in x-direction, OR in y-direction
            if (sideDistX < sideDistY)
              sideDistX += deltaDistX;
              mapX += stepX;
              side = 0;
            }//end of if (sideDistX < sideDistY)
            else
              sideDistY += deltaDistY;
              mapY += stepY;
              side = 1;
            }//end of else
            //Check if ray has hit a wall      
            if (worldMap[mapX][mapY] > 0) hit = 1;
          }//end of while (hit == 0)
          //Calculate distance of perpendicular ray (oblique distance will give fisheye effect!)   
          if (side == 0) perpWallDist = fabs((mapX - rayPosX + (1 - stepX) / 2) / rayDirX);
          else       perpWallDist = fabs((mapY - rayPosY + (1 - stepY) / 2) / rayDirY);
          //Calculate height of line to draw on screen      
          int lineHeight = abs((int)(h / perpWallDist));
          //calculate lowest and highest pixel to fill in current stripe
          int drawStart = -lineHeight / 2 + h / 2;
          if(drawStart < 0) drawStart = 0;
          int drawEnd = lineHeight / 2 + h / 2;
          if(drawEnd >= h) drawEnd = h - 1;
          //texturing calculations
          int texNum = worldMap[mapX][mapY] - 1; //1 subtracted from it so that texture 0 can be used!
          //calculate value of wallX
          double wallX; //where exactly the wall was hit
          if (side == 1) wallX = rayPosX + ((mapY - rayPosY + (1 - stepY) / 2) / rayDirY) * rayDirX;
          else       wallX = rayPosY + ((mapX - rayPosX + (1 - stepX) / 2) / rayDirX) * rayDirY;
          wallX -= floor((wallX));
          //x coordinate on the texture
          int texX = (int)(wallX * (double)(texWidth));
          if(side == 0 && rayDirX > 0) texX = texWidth - texX - 1;
          if(side == 1 && rayDirY < 0) texX = texWidth - texX - 1;
          int y;
          for(y = drawStart; y < drawEnd; y++)
            int d = y * 256 - h * 128 + lineHeight * 128; //256 and 128 factors to avoid floats
            int texY = ((d * texHeight) / lineHeight) / 256;
            int color = texture[texNum][texWidth * texY + texX];
            //make color darker for y-sides: R, G and B byte each divided through two with a "shift" and an "and"
            if(side == 1) color = (color >> 1) & 8355711;
            buffer[x][y] = color;
          }//end of for(y = drawStart; y < drawEnd; y++)
          //SET THE ZBUFFER FOR THE SPRITE CASTING
          ZBuffer[x] = perpWallDist; //perpendicular distance is used
          //FLOOR CASTING
          double floorXWall, floorYWall; //x, y position of the floor texel at the bottom of the wall
          //4 different wall directions possible
          if(side == 0 && rayDirX > 0)
            floorXWall = mapX;
            floorYWall = mapY + wallX;
          }//end of if(side == 0 && rayDirX > 0)
          else if(side == 0 && rayDirX < 0)
            floorXWall = mapX + 1.0;
            floorYWall = mapY + wallX;
          }//end of else if(side == 0 && rayDirX < 0)
          else if(side == 1 && rayDirY > 0)
            floorXWall = mapX + wallX;
            floorYWall = mapY;
          }//end of else if(side == 1 && rayDirY > 0)
          else
            floorXWall = mapX + wallX;
            floorYWall = mapY + 1.0;
          }//end of else
          double distWall, distPlayer, currentDist;
          distWall = perpWallDist;
          distPlayer = 0.0;
          if (drawEnd < 0) drawEnd = h; //becomes < 0 when the integer overflows
          //draw the floor from drawEnd to the bottom of the screen
          for(y = drawEnd + 1; y < h; y++)
            currentDist = h / (2.0 * y - h); //you could make a small lookup table for this instead
            double weight = (currentDist - distPlayer) / (distWall - distPlayer);
            double currentFloorX = weight * floorXWall + (1.0 - weight) * posX;
            double currentFloorY = weight * floorYWall + (1.0 - weight) * posY;
            int floorTexX, floorTexY;
            floorTexX = (int)(currentFloorX * texWidth) % texWidth;
            floorTexY = (int)(currentFloorY * texHeight) % texHeight;
            //floor
            buffer[x][y] = (texture[3][texWidth * floorTexY + floorTexX] >> 1) & 8355711;
            //ceiling (symmetrical!)
            buffer[x][h - y] = texture[6][texWidth * floorTexY + floorTexX];
          }//end of for(y = drawEnd + 1; y < h; y++)
        }//end of for(x = 0; x < w; x++)
        //SPRITE CASTING
        //sort sprites from far to close
        int i;
        for(i = 0; i < numSprites; i++)
          spriteOrder[i] = i;
          spriteDistance[i] = ((posX - sprite[i].x) * (posX - sprite[i].x) + (posY - sprite[i].y) * (posY - sprite[i].y)); //sqrt not taken, unneeded
        }//end of for(i = 0; i < numSprites; i++)
        combSort(spriteOrder, spriteDistance, numSprites);
        //after sorting the sprites, do the projection and draw them
        for(i = 0; i < numSprites; i++)
          //translate sprite position to relative to camera
          double spriteX = sprite[spriteOrder[i]].x - posX;
          double spriteY = sprite[spriteOrder[i]].y - posY;
          //transform sprite with the inverse camera matrix
          // [ planeX   dirX ] -1                                       [ dirY      -dirX ]
          // [               ]       =  1/(planeX*dirY-dirX*planeY) *   [                 ]
          // [ planeY   dirY ]                                          [ -planeY  planeX ]
          double invDet = 1.0 / (planeX * dirY - dirX * planeY); //required for correct matrix multiplication
          double transformX = invDet * (dirY * spriteX - dirX * spriteY);
          double transformY = invDet * (-planeY * spriteX + planeX * spriteY); //this is actually the depth inside the screen, that what Z is in 3D      
          int spriteScreenX = (int)((w / 2) * (1 + transformX / transformY));
          //parameters for scaling and moving the sprites
          #define uDiv 1
          #define vDiv 1
          #define vMove 0.0
          int vMoveScreen = (int)(vMove / transformY);
          //calculate height of the sprite on screen
          int spriteHeight = abs((int)(h / (transformY))) / vDiv; //using "transformY" instead of the real distance prevents fisheye
          //calculate lowest and highest pixel to fill in current stripe
          int drawStartY = -spriteHeight / 2 + h / 2 + vMoveScreen;
          if(drawStartY < 0) drawStartY = 0;
          int drawEndY = spriteHeight / 2 + h / 2 + vMoveScreen;
          if(drawEndY >= h) drawEndY = h - 1;
          //calculate width of the sprite
          int spriteWidth = abs( (int) (h / (transformY))) / uDiv;
          int drawStartX = -spriteWidth / 2 + spriteScreenX;
          if(drawStartX < 0) drawStartX = 0;
          int drawEndX = spriteWidth / 2 + spriteScreenX;
          if(drawEndX >= w) drawEndX = w - 1;
          //loop through every vertical stripe of the sprite on screen
          int stripe;
          for(stripe = drawStartX; stripe < drawEndX; stripe++)
            int texX = (int)(256 * (stripe - (-spriteWidth / 2 + spriteScreenX)) * texWidth / spriteWidth) / 256;
            //the conditions in the if are:
            //1) it's in front of camera plane so you don't see things behind you
            //2) it's on the screen (left)
            //3) it's on the screen (right)
            //4) ZBuffer, with perpendicular distance
            int y;
            if(transformY > 0 && stripe > 0 && stripe < w && transformY < ZBuffer[stripe])
            for(y = drawStartY; y < drawEndY; y++) //for every pixel of the current stripe
              int d = (y-vMoveScreen) * 256 - h * 128 + spriteHeight * 128; //256 and 128 factors to avoid floats
              int texY = ((d * texHeight) / spriteHeight) / 256;
              unsigned int color = texture[sprite[spriteOrder[i]].texture][texWidth * texY + texX]; //get current color from the texture//??????????????????
              if((color & 0x00FFFFFF) != 0) buffer[stripe][y] = color; //paint pixel if it isn't black, black is the invisible color
            }//end of for(y = drawStartY; y < drawEndY; y++)
          }//end of for(stripe = drawStartX; stripe < drawEndX; stripe++)
        }//end of for(i = 0; i < numSprites; i++)
        //readKeys
        //move forward if no wall in front of you
        if (K_UP)
          if(worldMap[(int)(posX + dirX * moveSpeed)][(int)(posY)] == false) posX += dirX * moveSpeed;
          if(worldMap[(int)(posX)][(int)(posY + dirY * moveSpeed)] == false) posY += dirY * moveSpeed;
        }//end of if (K_UP)
        //move backwards if no wall behind you
        if (K_DOWN)
          if(worldMap[(int)(posX - dirX * moveSpeed)][(int)(posY)] == false) posX -= dirX * moveSpeed;
          if(worldMap[(int)(posX)][(int)(posY - dirY * moveSpeed)] == false) posY -= dirY * moveSpeed;
        }//end of if (K_DOWN)
        //rotate to the right
        if (K_RIGHT)
          //both camera direction and camera plane must be rotated
          double oldDirX = dirX;
          dirX = dirX * cos(-rotSpeed) - dirY * sin(-rotSpeed);
          dirY = oldDirX * sin(-rotSpeed) + dirY * cos(-rotSpeed);
          double oldPlaneX = planeX;
          planeX = planeX * cos(-rotSpeed) - planeY * sin(-rotSpeed);
          planeY = oldPlaneX * sin(-rotSpeed) + planeY * cos(-rotSpeed);
        }//end of if (K_RIGHT)
        //rotate to the left
        if (K_LEFT)
          //both camera direction and camera plane must be rotated
          double oldDirX = dirX;
          dirX = dirX * cos(rotSpeed) - dirY * sin(rotSpeed);
          dirY = oldDirX * sin(rotSpeed) + dirY * cos(rotSpeed);
          double oldPlaneX = planeX;
          planeX = planeX * cos(rotSpeed) - planeY * sin(rotSpeed);
          planeY = oldPlaneX * sin(rotSpeed) + planeY * cos(rotSpeed);
        }//end of if (K_LEFT)
    }//end of CastRay
    //sort algorithm
    void combSort(int* order, double* dist, int amount)
      int gap = amount;
      enum bool swapped = false;
      while(gap > 1 || swapped)
        //shrink factor 1.3
        gap = (gap * 10) / 13;
        if(gap == 9 || gap == 10) gap = 11;
        if (gap < 1) gap = 1;
        swapped = false;
        int i;
        for (i = 0; i < amount - gap; i++)
          int j = i + gap;
          if (dist[i] < dist[j])
            double disttemp=dist[i];
            dist[i]=dist[j];
            dist[j]=disttemp;
            int ordertemp=order[i];
            order[i]=order[j];
            order[j]=ordertemp;
            swapped = true;
          }//end of if (dist[i] < dist[j])
        }//end of for (i = 0; i < amount - gap; i++)
      }//end of while(gap > 1 || swapped)
    }//end of combSort
    the sorce file can be found here http://bruce-lab.blogspot.com/2010/04/alchemy-ray-casting-engine-source-code.html

    RadioactiveLizard, you need adobe alchemy (http://labs.adobe.com/technologies/alchemy/) to compile the C code to a swc,
    not pass variables to C directly.

  • Random numbers in sumproduct function

      have no success with this:     e33 has 1,  f33 has 2,  g33 has 3.    k22 has 4,  k25 has 5,  k32 has 6.       expecting (1x4) + (2x5) + (3x6) = 4+10+18= 32
        it's the outer product in matrix algebra.     in apl it's 1 2 3 +.x 4 5 6 = 32       
         how is a random list or range  of  values entered?     thanks.     don mattern

    I could be wrong, but I do not believe numbers has the power to make matrix calculations.  I might suggest excel if that is an option.
    This is how I would say that you need to do matrix multiplication.  I am going to assume you know all the rules for multiplying matrices.  First you need to have 4 separate tables with no header rows, no footer rows, nor header columns.
    I will demonstrate with a (3x3)(3x3).  The first two tables are the Matrices that you are multiplying.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    9
    8
    7
    6
    5
    4
    3
    2
    1
    The third is the Transpose of Table 2.  In row 1 column A, place this formula =INDEX(TRANSPOSE(Table 2::$A$1:$C$3),ROW(),COLUMN()), and then fill it all the way out. And this is your result:
    9
    6
    3
    8
    5
    2
    7
    4
    1
    Now in the fourth table, in row 1 column A place this formula: =SUMPRODUCT(OFFSET(Table 1::$A$1,ROW()−1,0,1,3),OFFSET(Transpose of Table 2::$A$1,COLUMN()−1,0,1,3)) and fill out to the rest of the table.
    30
    24
    18
    84
    69
    54
    138
    114
    90
    This is a slight doozy, but I will explain when I have it written up in a few.

  • Multidimention array multiply

    Hi all,
    I have a problem to solve. I have an A matrix (col = 5, row = 5). If I want to calculate A power 100 by uusing method C=A*A*A*.....*A 100 times. What I should use and write in Java program. This is a fixed matrix.
    Any one could help, please help. Thanks.

    Writing a (square) matrix multiplication function isn't that difficult:
    double[][] matMul(double[][] a, double[][] b) {
       double[][] c= new double[a.length][a.length];
       for (int i= 0; i < a.length; i++)
          for (int j= 0; j < a.length; j++)
             for (k= 0; k < a.length) {
                c[i][j]+= a[i][k]*b[k][j];
       return c;
    }Note howerver that A**100 (** is exponentiation here) can be composed as
    A**64 * A**32 * A**4 so you don't need to invoke the function above 99 times:
    double[][] A4= matMul(A, A);
    A4= matMul(A4, A4);
    double[][] A32= matMul(A4, A4);
    A32= matMul(A32, A32);
    A32= matMul(A32, A32);
    double[][] A64= matMul(A32, A32)
    return matMul(A64, matMul(A32, A4));kind regards

  • Solving Riccati equation

    I have experience with Systembuild only.
    I saw that Xmath has a module with a function to solve the Riccati equation. How can I use this function in Systembuild?

    The Riccati equation can be solved in SystemBuild using a UserCodeBlock where internally the function XmathExecute is called to solve the Riccatti equation using Xmath.
    This Riccati equation solver could be placed in a slower periodic SuperBlock so that it is not recalculated every time step.
    Another UserCodeBlock (file scoped with the Ricatti solver UserCodeBlock) could return the new A and B matricies.
    But, the real problem is how to inject the new A and B matrix into your model.
    The SystemBuild StateSpace block A,B,C and D matricies can be only changed during simulation initialization.
    You would have to create your own StateSpace SuperBlock using the matrix multiple blocks, UserCodeBlock(returns new A,B), intergator block and summer blocks to calculate.
    Xdot = Ax + Bu;
    Y      = Cx + Du;
    It would be much easier if there were a StateSpace block that had the A and B matricies as inputs.
    Note: using SystemBuild the UserCodeBlocks and StateSpace SuperBlock dimensions are fixed and would have to be determined before hand.

Maybe you are looking for

  • How to create event trigger to kick off another report

    Hi i am having two reports, first report runs for 10 minutes , i want the second report to run automatically after first report is completed. how to do that?

  • Once I send 1 string, the rest are cut off, any ideas?

    Hello everyone. For some reason when I send my first string through the socket, everything works fine. But after that Its cutting off the first 2 or 3 characters of the string and I have no idea why because I'm flushing the output buffer before and a

  • Flash 8 objects created in Director 10.1.1

    OK, I'm pulling out my hair here. In Director MX2004, with Flash 7 movies, everything was dandy. I was able to create an object in Director and pass it into Flash and all was good: -- In Director myFlashObj = sprite(1).newObject("Object") myFlashObj.

  • Where clause causing a query to slow down in a cursor

    I have a table "the_table" with about 10,000 rows and four columns (id, description, inventory, and category). This query returns all rows immediately:     select id          , description          , inventory     from the_table     where category = 

  • Why does my Apple Mobile Device Support not uninstall?

    Why does my Apple Mobile Device Support not uninstall from the Control Panel?  It appears that my unsuccessful iTunes install requires that I clean up ALL Apple software,before trying again.