Archive

Archive for March 6, 2015

The Zen of Smart Pascal

March 6, 2015 Leave a comment
The Zen of Smart Pascal

The Zen of Smart Pascal

Something so elegant with memory management in place under Smart Mobile Studio. Moving pixels used to be so mind-numbingly slow compared to pointers. Now it’s a one-liner and faster than Embarcadero¬†Delphi (only FreePascal is keeping pace).

The method ToBuffer() used to be over 200 lines long, as was LoadFromBuffer(). With the advent of TMemory, TMarshal and various low-level kick-ass to-the-bone methods now in place, such are things of the past. Now Smart Mobile Studio coders can enjoy the full power of modern OOP development under HTML5 using all the tools they are used to from FreePascal and Delphi.

function TW3Image.ToBuffer:TMemory;
begin
  if Ready then
  result:=TMemory.Create(toImageData.Handle.data);
end;

procedure TW3Image.LoadFromBuffer(const Memory:TMemory);
var
  mContext: TW3GraphicContext;
  mCanvas:  TW3Canvas;
  mData:  JImageData;
begin
  if Ready then
  begin
    mContext := TW3GraphicContext.Create(Null);
    try
      mContext.Allocate(PixelWidth,PixelHeight);
      mCanvas := TW3Canvas.Create(mContext);
      try
        (* Get pixel buffer *)
        mData:=mCanvas.Handle.getImageData(0,0,PixelWidth,PixelHeight);

        (* over-write pixel buffer with our data *)
        TMemory.Move(memory.Handle,0,Variant(mData.data),0,mData.data.length);

        (* put pixel buffer back *)
        mCanvas.Handle.putImageData(mData,0,0);

        (* And force a re-load via Base64 *)
        LoadFromUrl(mCanvas.ToDataURL("png"));
      finally
        mCanvas.Free;
      end;
    finally
      mContext.Free;
    end;
  end else
  Raise Exception.Create
  ('Loading image from memory failed, surface must be allocated first');
end;