Monkey: box2d falling boxes

'----Includes----'
Import box2d.dynamics.b2world

'----Test Zone----'
Function Main()
  New Box2DLoop()
End Function

'----Main Loop----'
Class Box2DLoop Extends App

  Field _world:b2World

  Field RATIO:Float = 8

  Field _nextCrateIn:Int

  '--Main Methods----'

  Method OnCreate()

    ' 1. Set Up World
    setupWorld()
    ' Create Walls and Floors
    createWallsAndFloor()
    setupDebugDraw()
    _nextCrateIn = 0

    'Display Setup
    SetUpdateRate(60)

  End Method

  Method setupDebugDraw:Void()

      'Box2D Debug Settings       'Delete this section if you dont need to see the physical process in graphics.
    Local dbgDraw :b2DebugDraw = New b2DebugDraw()      

        dbgDraw.SetDrawScale(10.0)
        dbgDraw.SetFillAlpha(0.3)
        dbgDraw.SetLineThickness(1.0)
        dbgDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit)'| b2DebugDraw.e_pairBit)
        _world.SetDebugDraw(dbgDraw)

  End
  Method OnRender()
    Cls    

    _world.DrawDebugData()

  End Method

  Method OnUpdate()

    _world.TimeStep(1.0 /30,10,10)
    _world.ClearForces()

    _nextCrateIn = _nextCrateIn - 1

    If _nextCrateIn  <=0 And _world.m_bodyCount < 80 Then
      addARandomCrate()
      _nextCrateIn = 10
    Endif

  End Method

  Method setupWorld()

    ' Define gravity
    Local gravity:b2Vec2 = New b2Vec2(0,9.8)

    ' Ignore Sleeping Objects
    Local ignoresleeping:Bool = True

    _world = New b2World(gravity,ignoresleeping)

  End

  Method addARandomCrate()
    Local fd:b2FixtureDef = New b2FixtureDef()
    Local sd:b2PolygonShape = New b2PolygonShape()
    Local bd:b2BodyDef = New b2BodyDef();
    bd.type = b2Body.b2_Body

    fd.friction = 0.8
    fd.restitution = 0.3
    fd.density = 0.7
    fd.shape = sd

    sd.SetAsBox(randomInt(5,40) / RATIO, randomInt(5, 40) / RATIO)

    bd.position.Set(randomInt(15,530) / RATIO, randomInt(-100, -10) / RATIO)
    bd.angle = randomInt(0,360) * 3.14 / 180

    Local b:b2Body = _world.CreateBody(bd)
    b.CreateFixture(fd)

  End

  Method randomInt:Int(lowVal:Int, highVal:Int)

    If (lowVal <= highVal)

      Return lowVal + Floor(Rnd() * (highVal - lowVal + 1))

    Endif
  End

  Method createWallsAndFloor:Void()

    Local sd:b2PolygonShape = New b2PolygonShape()
    Local fd:b2FixtureDef = New b2FixtureDef()
    Local bd:b2BodyDef = New b2BodyDef()
    bd.type = b2Body.b2_staticBody

    sd.SetAsArray([New b2Vec2(0,0),New b2Vec2(550/RATIO,0), New b2Vec2(550/RATIO,10/RATIO), New b2Vec2(0,10/RATIO)])

    fd.friction = 0.5
    fd.restitution = 0.3
    fd.density = 0.0
    fd.shape = sd

    bd.position.Set(0,560/RATIO)

    Local b:b2Body = _world.CreateBody(bd)
    b.CreateFixture(fd)

    Local sdwall:b2PolygonShape = New b2PolygonShape()
    Local fdwall:b2FixtureDef = New b2FixtureDef()
    Local bdwall:b2BodyDef = New b2BodyDef()   
    bd.type = b2Body.b2_staticBody

    fdwall.friction =  0.5
    fdwall.restitution = 0.3
    fdwall.density = 0
    fdwall.shape = sdwall
    sdwall.SetAsBox(5/RATIO,390/RATIO)

    bdwall.position.Set(5/RATIO,195/RATIO)

    Local leftwall:b2Body = _world.CreateBody(bdwall)
    leftwall.CreateFixture(fdwall)

    bdwall.position.Set(545/RATIO,195/RATIO)

    Local rightwall:b2Body = _world.CreateBody(bdwall)
    rightwall.CreateFixture(fdwall)

  End
End Class

 

Monkey: box2d simple join example

#rem
  In this demo I create two bodies and then join them with a Joint.
  one body is a static body.
  Please take this demo and expend it with explanations so we can all learn. (keep it simple..)
#End

'----Imports----'
Import box2d.collision
Import box2d.collision.shapes
Import box2d.common.math
Import box2d.dynamics.contacts
Import box2d.dynamics
Import box2d.flash.flashtypes
Import box2d.common.math.b2vec2

'----Test Zone----'
Function Main()
  New Box2DLoop  
End Function

'----Main Loop----'

Class Box2DLoop Extends App

  'Box 2D World Definitions 
  Field BXworld        : b2World          'Box2D physical World Object
  Field m_velocityIterations  : Int   = 10        'Dont know whats this yet.
    Field m_positionIterations  : Int   = 10        'Either that.
    Field m_timeStep      : Float = 1.0/60      'Hmm, I know whats this but no changes accured when presetting.
    Field m_physScale      : Float = 1 ' 30           'I Change its value but same results.
  Field m_debugdrawscale    : Float  = 10         'This Affects the size of the physical Body Display

  'A Box2D Object Definition
  Field ABody:b2Body      'The Actual Body
  Field BBody:b2Body      'The Actual Body
  Field BodyDef:b2BodyDef         
  Field BodyShape:b2PolygonShape 
  Field BodyFixture:b2FixtureDef

  Method OnCreate()

    'Display Setup
    SetUpdateRate(60)

    '--Box2D Section--'

    'World Setups
    BXworld = New b2World(New b2Vec2(0,9.7),True)     

    'General Body Definitions
     BodyDef  =New b2BodyDef
     BodyShape  =New b2PolygonShape()
     BodyFixture=New b2FixtureDef

     BodyDef.type=b2Body.b2_Body  'A dynamic body set
     BodyFixture.density     =1.0
     BodyFixture.friction     =0.5
     BodyFixture.restitution   =0.1
     BodyShape.SetAsBox(5,5)
     BodyFixture.shape=BodyShape

     'Create Body 1
     ABody=BXworld.CreateBody(BodyDef)
     ABody.CreateFixture(BodyFixture)
     ABody.SetPosition(New b2Vec2(20,20))

     'Create Body 2
     BBody=BXworld.CreateBody(BodyDef)
     BBody.CreateFixture(BodyFixture)
     BBody.SetPosition(New b2Vec2(45,20))
     BBody.SetType(True) 'Setting the Body as Static

     '------------------------------------------------------------'
     'Basic Creation of Joint type revolute..
       Local NewJoint:b2RevoluteJointDef=New b2RevoluteJointDef
       NewJoint.Initialize(ABody,BBody,New b2Vec2(30.0,25.0))
       BXworld.CreateJoint(NewJoint)
     '------------------------------------------------------------'

    'Debug Settings  'Delete this section if you dont need to see the physical process.
    Local dbgDraw :b2DebugDraw = New b2DebugDraw()        
      dbgDraw.SetDrawScale(m_debugdrawscale)
    dbgDraw.SetFillAlpha(0.3)
    dbgDraw.SetLineThickness(1.0)
    dbgDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit)'| b2DebugDraw.e_pairBit)

    BXworld.SetDebugDraw(dbgDraw)

  End Method

  Method OnRender()
    Cls    
    'Box2D Display Section
     BXworld.DrawDebugData() 'Delete this line if you dont need to see the physical process in graphics. (must also delete 'Box2D Debug Settings section above)
  End Method

  Method OnUpdate()
    'The Stepping of Box2D Engine
    BXworld.TimeStep(m_timeStep,m_velocityIterations,m_positionIterations)
    BXworld.ClearForces()                          'Dont know why you need this..  
  End Method

End Class

 

Monkey: simple box2d box

#rem

'Im still very new at box2d but im starting to understand its principle.
'its not an easy to understand engine since the tutorials are not dealing with explaning the core principle of this engine.
'I will try to do that with what ive figured out till now.

'In box2d you First define things and then create them.
'First you define the your 2D world.

'Example:
  Field BXworld        : b2World          'Box2D physical World Object
  Field m_velocityIterations  : int   = 10        'Dont know whats this yet.
    Field m_positionIterations  : int   = 10        'Either that.
    Field m_timeStep      : Float = 1.0/60      'Hmm, I know whats this but no changes accured when presetting.
    Field m_physScale      : Float = 1 ' 30           'I Change its value but same results.
  Field m_debugdrawscale    : Float  = 10  

Then you create it.
  BXworld = New b2World(New b2Vec2(0,9.7),True) 

Now that you have created your world you can create objects.
Same here, first you need to define the object and then create it.

Example:
  Field ABody:b2Body        'The Actual Body
  Field BodyDef:b2BodyDef         
  Field BodyShape:b2PolygonShape 
  Field BodyFixture:b2FixtureDef

  BodyDef.type=b2Body.b2_Body  'A dynamic body set
  BodyFixture.density     =1.0
  BodyFixture.friction     =0.5
  BodyFixture.restitution   =0.1
  BodyShape.SetAsBox(10,10)
  BodyFixture.shape=BodyShape

You create the object using the World...

   ABody=BXworld.CreateBody(BodyDef)
   ABody.CreateFixture(BodyFixture) 

I still not totaly understand this engine but you can run the demo and check stuff out.
My next demo will be a joint demo.

#End

'----Imports----'
Import box2d.collision
Import box2d.collision.shapes
Import box2d.common.math
Import box2d.dynamics.contacts
Import box2d.dynamics
Import box2d.flash.flashtypes
Import box2d.common.math.b2vec2

'----Test Zone----'
Function Main()
  New Box2DLoop  
End Function

'----Main Loop----'

Class Box2DLoop Extends App

  'Box 2D World Definitions 
  Field BXworld        : b2World          'Box2D physical World Object
  Field m_velocityIterations  : Int   = 10        'Dont know whats this yet.
    Field m_positionIterations  : Int   = 10        'Either that.
    Field m_timeStep      : Float = 1.0/60      'Hmm, I know whats this but no changes accured when presetting.
    Field m_physScale      : Float = 1 ' 30           'I Change its value but same results.
  Field m_debugdrawscale    : Float  = 10         'This Affects the size of the physical Body Display

  'A Box2D Object Definition
  Field ABody:b2Body      'The Actual Body
  Field BodyDef:b2BodyDef         
  Field BodyShape:b2PolygonShape 
  Field BodyFixture:b2FixtureDef

  Method OnCreate()

    'Display Setup
    SetUpdateRate(60)

    '--Box2D Section--'

    'World Setups
    BXworld = New b2World(New b2Vec2(0,9.7),True)     

    'Creating a Simple Box (simple.. right..)
     BodyDef  =New b2BodyDef
     BodyShape  =New b2PolygonShape()
     BodyFixture=New b2FixtureDef

     BodyDef.type=b2Body.b2_Body  'A dynamic body set
     BodyFixture.density     =1.0
     BodyFixture.friction     =0.5
     BodyFixture.restitution   =0.1
     BodyShape.SetAsBox(10,10)
     BodyFixture.shape=BodyShape

     ABody=BXworld.CreateBody(BodyDef)
     ABody.CreateFixture(BodyFixture)
     ABody.SetPosition(New b2Vec2(20,20))

    'Debug Settings  'Delete this section if you dont need to see the physical process.
    Local dbgDraw :b2DebugDraw = New b2DebugDraw()        
      dbgDraw.SetDrawScale(m_debugdrawscale)
    dbgDraw.SetFillAlpha(0.3)
    dbgDraw.SetLineThickness(1.0)
    dbgDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit)'| b2DebugDraw.e_pairBit)

    BXworld.SetDebugDraw(dbgDraw)

  End Method

  Method OnRender()
    Cls    
    'Box2D Display Section
     BXworld.DrawDebugData() 'Delete this line if you dont need to see the physical process in graphics. (must also delete 'Box2D Debug Settings section above)
  End Method

  Method OnUpdate()
    'The Stepping of Box2D Engine
    BXworld.TimeStep(m_timeStep,m_velocityIterations,m_positionIterations)
    BXworld.ClearForces()                          'Dont know why you need this..  
  End Method

End Class

 

Monkey: minimum Box2d with diddy example

Strict
Import diddy 
Import box2d.collision
Import box2d.collision.shapes
Import box2d.collision.shapes
Import box2d.dynamics.joints
Import box2d.common.math
Import box2d.dynamics.contacts
Import box2d.dynamics
Import box2d.flash.flashtypes
Import box2d.common.math.b2vec2

Global gameScreen:Screen

Function Main:Int()
        game=New MyGame()
        Return 0
End Function

Class MyGame Extends DiddyApp

        Method OnCreate:Int()
               Super.OnCreate()
               SetUpdateRate(60)     
               gameScreen = New Box2dscreen  
               gameScreen.PreStart()         
               Return 0
        End

End

Class Box2dscreen Extends Screen
        '
        Field world:b2World 
        Field contactlistener:ContactListener 
        '
    Field m_velocityIterations:Int = 10
    Field m_positionIterations:Int = 10
    Field m_timeStep:Float = 1.0/60     ' set this to your SetUpdateRate()
    Field m_physScale:Float = 1' 30       ' Not in use, but you should not use pixels as your units, an object of length 200 pixels would be seen by Box2D as the size of a 45 story building.
        Field m_debugdrawscale:Float=1          ' set this to m_physScale if you are scaling your world.

        Method New()
               Local doSleep:Bool = True

               Self.world = New b2World(New b2Vec2(0,0), doSleep)    ' no need for AABB in newer versions of box2d, the world is infinite
               Self.SetGravity(1.0,20) '
               world.SetWarmStarting(True)   
               '
                '
               '// set debug draw
               Local dbgDraw :b2DebugDraw = New b2DebugDraw()      

               dbgDraw.SetDrawScale(m_debugdrawscale) ' was 30
               dbgDraw.SetFillAlpha(0.3)
               dbgDraw.SetLineThickness(1.0)
               dbgDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit)'| b2DebugDraw.e_pairBit)
               world.SetDebugDraw(dbgDraw)
               Self.contactlistener=New ContactListener()
               world.SetContactListener(Self.contactlistener)' for collision detection, if you need information which objects collide                           
        End Method

        Method Start:Void()
               Self.CreateDemo()     
        End

        Method Render:Void()
               Cls
               Self.world.DrawDebugData()
        End

        Method Update:Void()
               world.TimeStep(m_timeStep, m_velocityIterations, m_positionIterations)
               world.ClearForces()
        End Method

        Method SetGravity:Void(x:Float,y:Float)
               Self.world.SetGravity(New b2Vec2(x,y))

        End Method

        Method CreateDemo:Void()
               Local b:b2Body 
               ' a box for ground
               b=Self.CreateBox(340,420,480,30,True)
               b.SetUserData(New StringObject("ground")) ' give object a name for collision detection in contactlistener
               ' a sphere
               b=Self.CreateSphere(350,220,40)      
               b.SetUserData(New StringObject("sphere"))
               ' create a polygon from an array of b2d Vectors
               Local tri:b2Vec2[]= [New b2Vec2(0, 0), New b2Vec2(0, -100),   New b2Vec2(200 ,0)]
               b=Self.CreatePolybody(200,20,tri)
               b.SetUserData(New StringObject("triangle1"))                               
'              ' create a polygon from an array with floats
               Local triangle:Float[]=[0.000000000,-49.000000,99.000000,59.0000000,-77.000000,79.0000000]
               b=Self.CreatePolybody(200,100,Self.ArrayToVectorarray(triangle))
               b.SetUserData(New StringObject("triangle2")) 
        End Method

        Method CreateBox:b2Body (xpos:Float,ypos:Float,width:Float,height:Float,static:Bool=True)
               Local fd :b2FixtureDef = New b2FixtureDef()
               Local sd :b2PolygonShape = New b2PolygonShape()
               Local bd :b2BodyDef = New b2BodyDef()
               If static=True
                       bd.type = b2Body.b2_staticBody
               Else
                       bd.type = b2Body.b2_Body
               Endif          
               fd.density = 1.0
               fd.friction = 0.5
               fd.restitution = 0.1
               fd.shape = sd
               sd.SetAsBox(width,height)
               bd.position.Set(xpos,ypos)
               Local b :b2Body
               b = Self.world.CreateBody(bd)        
               ' Recall that shapes don’t know about bodies and may be used independently of the physics simulation. Therefore Box2D provides the b2Fixture class to attach shapes to bodies.
               b.CreateFixture(fd)   
               '
               Return b       
        End Method

        Method CreateSphere:b2Body (xpos:Float,ypos:Float,radius:Float,static:Bool=False)
               Local fd :b2FixtureDef = New b2FixtureDef()
               Local bd :b2BodyDef = New b2BodyDef()
               Local cd :b2CircleShape = New b2CircleShape()  
               '              
               cd.m_radius  = radius
               fd.density = 2
               fd.restitution = 0.2
               fd.friction = 0.5
               fd.shape=cd
               If static=True
                       bd.type = b2Body.b2_staticBody ' a static body
               Else
                       bd.type = b2Body.b2_Body 'a dynamic body
               Endif
               bd.position.Set(xpos,ypos)
               Local b :b2Body
               b = Self.world.CreateBody(bd)
               b=Self.world.CreateBody(bd)
               b.CreateFixture(fd)                  
               Return b       
        End Method

        Method CreatePolybody:b2Body(xpos:Float,ypos:Float,verts:b2Vec2[],static:Bool=False,bullet:Bool=False)
               ' polys must be  defined vertices from left to right or their collision will not work. They must be convex.
               ' A polygon is convex when all line segments connecting two points in the interior do not cross any edge
               ' of the polygon. 
               ' Polygons are solid and never hollow. A polygon must have 3 or more vertices.

               Local b :b2Body
               Local fd :b2FixtureDef = New b2FixtureDef()
               Local sd :b2PolygonShape = New b2PolygonShape()
               Local bd :b2BodyDef = New b2BodyDef()
               '
               sd.SetAsArray(verts,verts.Length)
               fd.shape=sd
               bd.type = b2Body.b2_Body              
               '
               bd.position.Set(xpos,ypos)
               bd.bullet=bullet
               b=Self.world.CreateBody(bd)
               '
               fd.density = 1.0
               fd.friction = 0.5
               fd.restitution = 0.1
               b.CreateFixture(fd)
               '              
               Return b               
        End Method

        Method ArrayToVectorarray:b2Vec2[](arr:Float[])
               ' converts a normal array with floats to an array of b2Vec2
               Local vecs:b2Vec2[1]
               vecs=vecs.Resize(arr.Length/2)
               Local count:Int
                For Local f:Float=0 To arr.Length-2 Step 2
                       vecs[count]=New b2Vec2(arr[f],arr[f+1])
                       count+=1
               Next
               Return vecs
        End Method

        Method Cleanup:Void()
               ' When a world leaves scope or is deleted by calling delete on a pointer, all the memory reserved for bodies, fixtures, and joints is freed.
               ' This is done to improve performance and make your life easier. However, you will need to nullify any body, fixture, or joint pointers you have because they will become invalid.

        End Method
End Class

Class ContactListener Extends b2ContactListener
    ' to gather information about collided objects.
        ' http://www.box2dflash.org/docs/2.1a/reference/Box2D/Dynamics/b2ContactListener.html
        ' You cannot create/destroy Box2D entities inside these callbacks.

    Method New()
        Super.New()
    End

    Method PreSolve : Void (contact:b2Contact, oldManifold:b2Manifold)

    End

        Method BeginContact:Void(contact:b2Contact)
'              Print "objects did collide.."
               '
               ' get the fixtures involved in collision
               Local fixA:b2Fixture=contact.GetFixtureA()' Instead of telling you which b2Body collided, the b2Contact tells you which fixture collided. 
               Local fixB:b2Fixture=contact.GetFixtureB()' To know which b2Body was involved in the collision you can retrieve a reference to the fixture.
               Local userdata1:Object=Object(fixA.GetBody().GetUserData())
               Local userdata2:Object=Object(fixB.GetBody().GetUserData())
               If userdata1<>Null
                       Local name:String=StringObject(userdata1).ToString()
'                      Print "involved in collision:"+ name
               Endif
               If userdata2<>Null
                       Local name:String=StringObject(userdata2).ToString()
'                      Print "involved in collision:"+ name
               Endif          
        End Method

End

 

ASObjC: NSURLConnection – http get and post

--
--  pgURLAppDelegate.applescript
--  pgURL
--
--  Created by goodtime on 4/10/11.
--  Copyright 2011 NiceMac. All rights reserved.

-- demonstrates doing a GET or POST Request using NSURLConnection.  Runs in the Background (not in main thread)
-- contains no UI... might add one later, for now it just logs or displays alerts
-- see console log and feel free to change the URL
-- reference material: http://cocoawithlove.com/2008/09/cocoa-application-driven-by-http-data.html

script pgURLAppDelegate
    property parent : class "NSObject"
    property self : current application's pgURLAppDelegate -- should match the script delegate name above

    property myURL : "http://www.heise.de"  -- URL of your request
    property postMethod : "POST"  -- use POST for POST
    property myBody : ""  -- PUT YOUR POST MESSAGE HERE if trying to do a POST

    -- URL Request Encoding
    property myEncoding : NSUTF8StringEncoding of current application --code for UTF8

    property getMethod : "GET"  -- use GET for any other Requests
    property intermediateMsg : "" --  Text String returned from the request (may not be complete for long downloads)
    property entireMsg : "" --  All the Text String returned from the request

    on pgURL_(myURL, myBody, myMethod)
        -- String to NSURL
        tell class "NSURL" of current application
            set myURL to URLWithString_(myURL)
        end tell

        -- String 
        tell class "NSString" of current application
            set myBody to stringWithString_(myBody)
        end

        set myBody to myBody's dataUsingEncoding_(myEncoding)

        tell class "NSString" of current application
            set myMethod to myMethod
        end

        tell NSMutableURLRequest of current application
            set myRequest to requestWithURL_(myURL)
        end

        tell myRequest
            setHTTPMethod_(myMethod)
        end

        -- add the Message Body when sending a POST Method
        if myMethod = "POST" then
            tell myRequest
                setHTTPBody_(myBody)
            end
        end

        -- form the connection
        set myConnection to (((current application's class "NSURLConnection")'s alloc)'s initWithRequest_delegate_(myRequest, self))
    end

    -- handle the connection in the background (not in main thread)
    -- this is controlled by the next four threads
    on connection_didReceiveResponse_(myConnection, response)

        tell class "NSHTTPURLResponse" of current application
            set statusText to (localizedStringForStatusCode_(statusCode of response)) as text
            set statusCode to (statusCode of response) as string
        end

        -- if it fails to do anything, show what it didn't do here (the error)
        if statustext = "no error" then
            -- I am not really sure if this does anything or if it is reseting the returnData properly
            tell current application's returnData
                setLength_(0)
            end
            else
            display alert "HTTP Error: " & statusCode & return & "Error Message: " & statusText & "." 
        end
    end

    on connection_didReceiveData_(myConnection, returnData)

        -- convert Data returned to String (Don't ever forget how to do this, it is a pain when do forget)
        set my intermediateMsg to (((current application's class "NSString")'s alloc)'s initWithData_encoding_(returnData, current application's NSUTF8StringEncoding)) as string
        log "didReceivedData:"

        log intermediateMsg & return & return

        set my entireMsg to my entireMsg & intermediateMsg

    end

    on connection_didFailWithError_(myConnection,trpErr)
        -- display alert trpErr as string
        log trpErr

        set EM to ""
        try
            set newError to (NSLocalizedDescription of userInfo of (trpErr)) as string
                on error EM
            -- if AppleScript can't do this, so what else is wrong
            set errorMore to EM
        end

        display alert newError & return & return & errorMore
    end

    on connectionDidFinishLoading_(myConnection)
        log "connection Finished."

        -- here you can do what you want to do with the intermediateMsg
        log "here is your entire message returned:"
        log entireMsg

        log "end of line."
    end

    on applicationWillFinishLaunching_(aNotification)
        -- Insert code here to initialize your application before any files are opened 

        -- run the request here for demonstration purposes
        pgURL_(myURL, myBody, getMethod)

    end applicationWillFinishLaunching_

    on applicationShouldTerminate_(sender)
        -- Insert code here to do any housekeeping before your application quits 
        return current application's NSTerminateNow
    end applicationShouldTerminate_

end script

ASObjC: NSImage – open, crop and save image

--Cocoa crop
set srcImage to NSImage's alloc()'s initWithContentsOfFile_(picPath)
srcView's setImage_(srcImage)

set w to _width's stringValue() as string as number
set h to _height's stringValue() as string as number
set t to _top's stringValue() as string as number
set l to _left's stringValue() as string as number

set destImage to NSImage's alloc()'s initWithSize_({|width|:w, height:h})

set destRect to {|size|:{w, h}, origin:{0, 0}}
set srcRect to {|size|:{w, h}, origin:{l, t}}

destImage's lockFocus()
srcImage's drawInRect_fromRect_operation_fraction_(destRect, srcRect, current application's NSCompositeSourceOver, 1.0)
destImage's unlockFocus()

destView's setImage_(destImage)

--save as png
set theData to destImage's TIFFRepresentation()
set myNsBitmapImageRepObj to NSBitmapImageRep's imageRepWithData_(theData)
set myNewImageData to (myNsBitmapImageRepObj's representationUsingType_properties_(current application's NSPNGFileType, missing value))
if not (myNewImageData's writeToFile_atomically_(picPath, true)) as boolean then
    set messageText to "There was an error writing to file"
    display dialog messageText buttons {"Ok"}
end if

AppleScript: System Events – versteckte Fenster anzeigen/anpassen

(*
A little script to gather any application windows that are partially offscreen in some way and shift them back to the desktop.
This is particularly useful if you use a MacBook with an external display.
*)
tell application "Finder"
	-- get desktop dimensions (dw = desktop width; dh = desktop height)
	set db to bounds of window of desktop
	set {dw, dh} to {item 3 of db, item 4 of db}
end tell

tell application "System Events"
	repeat with proc in application processes
		tell proc
			repeat with win in windows
				-- get window dimensions (w = width; h = height)
				set {w, h} to size of win

				-- get window postion (l = left of window; t = top of window)
				set {l, t} to position of win

				-- nh = new window height; nw = new window width
				set {nh, nw} to {h, w}

				-- window width is bigger than desktop size,
				-- so set new window width to match the desktop
				if (w > dw) then set nw to dw

				-- window height is bigger than the desktop size (minus menu bar),
				-- so set new window height to be desktop height - 22 pixels
				if (h > dh - 22) then set nh to dh - 22

				-- r = right coordinate of window; b = bottom coordinate of window
				set {r, b} to {l + nw, t + nh}

				-- nl = new left coordinate; nt = new top coordinate
				set {nl, nt} to {l, t}

				-- left coordinate is off screen, so set new left coordinate
				-- to be 0 (at the left edge of the desktop)
				if (l < 0) then set nl to 0

				-- top coordinate is above bottom of menu bar (22 pixels tall),
				-- so set new top coordinate to be 22
				if (t < 22) then set nt to 22

				-- right coordinate extends beyond desktop width,
				-- so set new left coordinate to be desktop width - window width
				if (r > dw) then set nl to dw - nw

				-- bottom coordinate extends beyond desktop height,
				-- so set new top coordinate to be desktop height - window height
				if (b > dh) then set nt to dh - nh

				-- if we have calculated a new top or left coordinate, reposition window
				if (l > nl or t > nt) then set position of win to {nl, nt}

				-- if we have calculated a new height or width, resize window
				if (h > nh or w > nw) then set size of win to {nw, nh}
			end repeat
		end tell
	end repeat
end tell