Not producing the textfield output - actionscript-3

This code produces no errors but the TextField gives no output.
I tried this with a simpler code and the valuelocal has a value and gives an output however I need a smaller font size and anyway I need another Textfield with much bigger font so I determined that I needed to preload the font
I was referring.
http://krasimirtsonev.com/blog/article/AS3-flash-runtime-font-loading-embedding
So what is going wrong here?
Correction- I thought output was results- I get a dozen panels loading other than output. Cut out a few lines. The numbers are trace from Main.as
Building New Project
mxmlc -load-config+=obj\NewProjectConfig.xml -debug=true -incremental=true -o obj\NewProject635574676017466150
Starting java as: java.exe -Xmx384m -Dsun.io.useCanonCaches=false -Duser.language=en -Duser.region=US -
INITIALIZING: Adobe Flex Compiler SHell (fcsh)
Starting new compile.
Loading configuration file ...\frameworks\flex-config.xml
Loading configuration file ...\NewProjectConfig.xml
obj\NewProject635574676017466150 (5264 bytes)
(fcsh)Build succeeded
Done(0)
[Starting debug session with FDB]
0
1
2
3
4
5
6
Successfully loaded FontArial (../bin/js/Arial.swf)
Successfully loaded FontArial (../bin/js/Arial.swf)
Successfully loaded FontArial (../bin/js/Arial.swf)
Successfully loaded FontArial (../bin/js/Arial.swf)
Successfully loaded FontArial (../bin/js/Arial.swf)
Successfully loaded FontArial (../bin/js/Arial.swf)
Successfully loaded FontArial (../bin/js/Arial.swf
This is my code :
package {
import flash.display.Bitmap;
import flash.display.Sprite;
import flash.events.Event;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.text.TextFormatAlign;
import flash.text.AntiAliasType;
import flash.display.Loader;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.net.URLRequest;
import flash.text.Font;
import flash.text.TextFieldAutoSize;
/**
* ...
* #author Michael
*/
public class tile extends Sprite {
public static const FONT_NAME:String = "Arial";
public static const FONT_EXPORT_NAME:String = "FontArial";
public static const FONT_FILE_NAME:String = "../bin/js/Arial.swf";
private function onFontLoaded(e:Event):void {
trace("Successfully loaded " + FONT_EXPORT_NAME + " (" + FONT_FILE_NAME + ")");
if (e.target.applicationDomain.hasDefinition(FONT_EXPORT_NAME))
{
var FontClass:Class = e.target.applicationDomain.getDefinition(FONT_EXPORT_NAME) as Class;
Font.registerFont(FontClass);
init();
}
else
{
trace("Missing " + FONT_EXPORT_NAME + "!");
}
}
private function onFontLoadingFailed(e:IOErrorEvent):void {
trace("Missing " + FONT_FILE_NAME);
}
[Embed(source = "C:/my_absolute_local_path/Games/New Project/bin/js/blank.png")]
private var blank:Class;
private var b1:Bitmap;
private var valuelocal:int;
public function tile(value:int):void {
valuelocal = value;
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onFontLoaded);
loader.addEventListener(IOErrorEvent.IO_ERROR, onFontLoadingFailed);
loader.addEventListener(IOErrorEvent.NETWORK_ERROR, onFontLoadingFailed);
loader.addEventListener(IOErrorEvent.VERIFY_ERROR, onFontLoadingFailed);
loader.addEventListener(IOErrorEvent.DISK_ERROR, onFontLoadingFailed);
loader.load(new URLRequest(FONT_FILE_NAME));
}
private function init():void {
b1 = new blank ;
this.addChild(b1);
/* var myText:TextField = new TextField();*/
/*myText.antiAliasType = AntiAliasType.ADVANCED;
myText.text = valuelocal.toString();
myText.x = 17;
myText.y = 17;*/
var format:TextFormat = new TextFormat();
format.font = FONT_NAME;
format.size = 20;
format.color = 0x000000;
var field:TextField = new TextField();
field.defaultTextFormat = format;
field.text = valuelocal.toString();
field.x = field.y = 10;
field.embedFonts = true;
field.autoSize = TextFieldAutoSize.LEFT;
this.addChild(field);
}
}
}

Related

Audio upload not working on server

I have an app which records and upload mic input encoding in mp3.
When I test locally, in Flash IDE, it works fine, my audio file is uploaded.
What I have tried:
All my files are on swf_dir (see in the code below)
My embed tag already have allowScriptAcess set to always;
Already put a generic crossdomain.xml in my host root and in swf_dir;
My main class already load a policy file and allow all domains (even this being unnecessary, because it's in the same server): system.security.loadPolicyFile("http://www.host.com/swf_dir/crossdomain.xml") and system.Security.allowDomain("*")
Here is the upload/encode class.
package
{
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.net.URLRequestHeader;
import flash.net.URLRequestMethod;
import flash.utils.ByteArray;
import org.bytearray.micrecorder.encoder.WaveEncoder;
import fr.kikko.lab.ShineMP3Encoder;
/**
* ...
* #author Marcelo de Assis
*/
public class Mp3Helper extends EventDispatcher
{
var loader:URLLoader = new URLLoader();
var LOCAL_PATH:String = "http://www.host.com/swf_dir/upload.php"; // URL used to test on Flash IDE
var PRODUCTION_PATH:String = "upload.php"; // URL used to test on server
var mp3Encoder:ShineMP3Encoder;
var urlRequest:URLRequest = new URLRequest();
var urlLoader:URLLoader = new URLLoader();
public function Mp3Helper()
{
urlRequest.url = PRODUCTION_PATH;
urlRequest.contentType = 'multipart/form-data; boundary=' + UploadPostHelper.getBoundary();
urlRequest.method = URLRequestMethod.POST;
urlRequest.requestHeaders.push( new URLRequestHeader( 'Cache-Control', 'no-cache' ) );
var urlLoader:URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
}
function upload_s(soundByteArray: ByteArray)
{
var waveEncoder:WaveEncoder = new WaveEncoder();
var wavData:ByteArray = waveEncoder.encode(soundByteArray, 1);
mp3Encoder = new ShineMP3Encoder(wavData);
mp3Encoder.addEventListener(Event.COMPLETE, mp3EncodeComplete);
mp3Encoder.start();
}
function mp3EncodeComplete(event: Event) : void
{
urlRequest.data = UploadPostHelper.getPostData("audio.mp3", mp3Encoder.mp3Data);
urlLoader.load(urlRequest);
urlLoader.addEventListener(Event.COMPLETE, loaderCompleted);
}
private function loaderCompleted(event: Event):void
{
dispatchEvent(event);
var fileLoader: URLLoader = URLLoader(event.target);
trace("loaderCompleted: ", fileLoader.data);
}
}
}
In case of URLLoader security error try to turn on policy logging (PolicyFileLog = 1) in mm.cfg file (check out this article where to locate mm.cfg file in your OS http://jpauclair.net/2010/02/10/mmcfg-treasure/, for win7 the default log location is C:\Users\user\AppData\Roaming\Macromedia\Flash Player\Logs\policyfiles.txt), it will helps in case of Socket as well.

Showing main menu over objects / movieclips?

I am creating a game in Flash and I am creating a main menu for the game (With buttons like 'Play', 'How to Play', 'Hiscores' etc.) and was wondering what is the best way to go about it?
All of my Actionscript code is in external .as files and I've used classes throughout but I was having trouble figuring out how to get it so that the menu will be shown as soon as the game is ran. The main problem is that there are timers in my game that have event handlers attached to them and I was trying to think of the best way to essentially stop these timers until the user actually clicks 'Play', otherwise the objects spawn over the top of the menu and the timer ticks down.
Would stopping the timers but then adding an event handler to the play button to start the timers be a good idea? I am trying to figure out the best way to do this for future reference.
Thank you for any assistance.
Edit: Tried Cherniv's advice, getting some errors.
Main.as:
package {
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.display.DisplayObject;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.ui.Mouse;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.text.TextFormat;
import flash.text.TextField;
import flash.display.Loader;
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.system.LoaderContext;
import flash.display.Sprite;
import flash.net.Socket;
public class Main extends MovieClip {
public static var gameLayer:Sprite = new Sprite;
public static var endGameLayer:Sprite = new Sprite;
public static var menuLayer:Sprite = new Sprite;
public var gameTime:int;
public var levelDuration:int;
public var crosshair:crosshair_mc;
static var score:Number;
var enemyShipTimer:Timer;
var enemyShipTimerMed:Timer;
var enemyShipTimerSmall:Timer;
static var scoreHeader:TextField = new TextField();
static var scoreText:TextField = new TextField();
static var timeHeader:TextField = new TextField();
static var timeText:TextField = new TextField();
public function Main()
{
var mainMenu:myMenu = new myMenu;
addChild(gameLayer);
addChild(endGameLayer);
addChild(menuLayer);
playBtn.addEventListener(MouseEvent.CLICK, startButtonPressed);
}
function startButtonPressed(e:Event)
{
levelDuration = 30;
gameTime = levelDuration;
var gameTimer:Timer = new Timer(1000,levelDuration);
gameTimer.addEventListener(TimerEvent.TIMER, updateTime);
gameTimer.addEventListener(TimerEvent.TIMER_COMPLETE, timeExpired)
gameTimer.start();
scoreHeader = new TextField();
scoreHeader.x = 5;
scoreHeader.text = String("Score: ");
gameLayer.addChild(scoreHeader);
scoreText = new TextField();
scoreText.x = 75;
scoreText.y = 0;
scoreText.text = String(0);
gameLayer.addChild(scoreText);
timeHeader = new TextField();
timeHeader.x = 490;
timeHeader.y = 0;
timeHeader.text = String("Time: ");
gameLayer.addChild(timeHeader);
timeText = new TextField();
timeText.x = 550;
timeText.y = 0;
timeText.text = gameTime.toString();
gameLayer.addChild(timeText);
var scoreFormat = new TextFormat("Arial Rounded MT Bold", 20, 0xFFFFFF);
scoreHeader.setTextFormat(scoreFormat);
scoreText.setTextFormat(scoreFormat);
timeHeader.setTextFormat(scoreFormat);
timeText.setTextFormat(scoreFormat);
enemyShipTimer = new Timer(2000);
enemyShipTimer.addEventListener("timer", sendEnemy);
enemyShipTimer.start();
enemyShipTimerMed = new Timer(2500);
enemyShipTimerMed.addEventListener("timer", sendEnemyMed);
enemyShipTimerMed.start();
enemyShipTimerSmall = new Timer(2750);
enemyShipTimerSmall.addEventListener("timer", sendEnemySmall);
enemyShipTimerSmall.start();
crosshair = new crosshair_mc();
gameLayer.addChild(crosshair);
crosshair.mouseEnabled = crosshair.mouseChildren = false;
Mouse.hide();
gameLayer.addEventListener(Event.ENTER_FRAME, moveCursor);
resetScore();
}
function sendEnemy(e:Event)
{
var enemy = new EnemyShip();
gameLayer.addChild(enemy);
gameLayer.addChild(crosshair);
}
function sendEnemyMed(e:Event)
{
var enemymed = new EnemyShipMed();
gameLayer.addChild(enemymed);
gameLayer.addChild(crosshair);
}
function sendEnemySmall(e:Event)
{
var enemysmall = new EnemyShipSmall();
gameLayer.addChild(enemysmall);
gameLayer.addChild(crosshair);
}
static function updateScore(points)
{
score += points;
scoreText.text = String(score);
var scoreFormat = new TextFormat("Arial Rounded MT Bold", 20, 0xFFFFFF);
scoreHeader.setTextFormat(scoreFormat);
scoreText.setTextFormat(scoreFormat);
}
static function resetScore()
{
score = 0;
scoreText.text = String(score);
}
function updateTime(e:TimerEvent):void
{
trace(gameTime);
// your class variable tracking each second,
gameTime--;
//update your user interface as needed
var scoreFormat = new TextFormat("Arial Rounded MT Bold", 20, 0xFFFFFF);
timeText.defaultTextFormat = scoreFormat;
timeText.text = String(gameTime);
}
function timeExpired(e:TimerEvent):void
{
var gameTimer:Timer = e.target as Timer;
gameTimer.removeEventListener(TimerEvent.TIMER, updateTime)
gameTimer.removeEventListener(TimerEvent.TIMER, timeExpired)
// do whatever you need to do for game over
}
function moveCursor(event:Event)
{
crosshair.x=mouseX;
crosshair.y=mouseY;
}
}
}
Menu.as:
package {
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.display.DisplayObject;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.ui.Mouse;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.text.TextFormat;
import flash.text.TextField;
import flash.display.Loader;
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.system.LoaderContext;
import flash.display.Sprite;
import flash.net.Socket;
public class Menu extends MovieClip
{
var mainMenu:Menu = new Menu();
Main.menuLayer.addChild(myMenu);
playBtn.addEventListener(MouseEvent.CLICK, playBtnPressed);
function playBtnPressed()
{
Main.menuLayer.removeChild(myMenu);
dispatchEvent(new Event("playButtonPressed"))
}
}
My menu is a movieclip named myMenu and the class is set as Menu but I get errors such as:
Main.as, Line 50 1120: Access of undefined property playBtn
I gave the button an instance name of playBtn before I converted the menu to a movieclip so not sure what's going on there. I'm probably missing something really easy but it's a bit confusing for me after typing all day.
If you have all of your initialization stuff (including timers initializations) in Main constructor function , so you need to split it to two functions , Main constructor will show the menu , and "start" button will fire the second function , that will include all the initialization stuff

local storage of images to re-use them again in flash application

I have a flash applcation which has two things
1.Browse for new image component
2.Build scroller image gallery component- has 10 recently uploaded images only
How do I save the new images as and when the user browses it and store it locally and then reuse it again for later sessions (load the images from the saved location and build the scroller again when user visits next time)
Please help me know how to save images locally and then reuse it later as well, more like a history application
Here you go :
This piece of code save images in shared object and restore them when you restart.
package{
import flash.display.Loader;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.net.FileFilter;
import flash.net.FileReference;
import flash.net.SharedObject;
import flash.text.TextField;
import flash.utils.ByteArray;
[SWF(width="100",height="800")]
public class TestSO extends Sprite{
private var _soFileIndex : SharedObject = SharedObject.getLocal("fileIndex");
private var _addBtn : Sprite = new Sprite;
private var _fr : FileReference = new FileReference;
public function TestSO(){
// Add a button
var tf : TextField = new TextField;
tf.text = "Add image";
tf.width = 100;
tf.height = 20;
tf.selectable = false;
_addBtn.addChild(tf);
_addBtn.graphics.beginFill(0xDDDDDD);
_addBtn.graphics.drawRect(0,0,_addBtn.width, _addBtn.height);
_addBtn.graphics.endFill();
addChild(_addBtn);
// If file index is empty
if(!_soFileIndex.data.index)
_soFileIndex.data.index = [];
else{
// Display stored images
for each(var fileName : String in _soFileIndex.data.index)
displayImage(fileName, SharedObject.getLocal(fileName).data.bytes)
}
// Listeners
_addBtn.addEventListener(MouseEvent.CLICK, onAddClick);
_fr.addEventListener(Event.SELECT, onFileSelected);
_fr.addEventListener(Event.COMPLETE, onFileLoaded);
}
// Ask for a file
private function onAddClick(e : Event) : void{
_fr.browse([new FileFilter("Images", "*.jpg;*.jpeg;*.png")]);
}
// open file
private function onFileSelected(e : Event) : void{
_fr.load();
}
// save file
private function onFileLoaded(e : Event) : void{
var fileName : String = _fr.name.split(" ").join("_");
// Save a reference to filename
if(_soFileIndex.data.index.indexOf(fileName) == -1)
_soFileIndex.data.index.push(fileName);
else return;
var fileSo : SharedObject = SharedObject.getLocal(fileName);
fileSo.data.bytes = _fr.data;
fileSo.flush();
displayImage(fileName, _fr.data);
}
// Display an image
private function displayImage(name : String, data : ByteArray):void{
var item : Sprite = new Sprite;
// Load image
var imgLoader : Loader = new Loader;
imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,onImageLoaded);
imgLoader.loadBytes(data);
item.addChild(imgLoader);
var label : TextField = new TextField;
label.text = name;
label.y = 100;
label.height = 20;
item.addChild(label);
item.y = height;
addChild(item);
}
// Resize image when loaded
private function onImageLoaded(e : Event) : void{
e.target.content.width = e.target.content.height = 100;
e.target.removeEventListener(Event.COMPLETE,onImageLoaded);
}
}
}

AIR: how to use FileReference.upload() with POST-based web services (AS3)

I can't seem to get this little AIR app I'm making to work right. There is a single button on the stage, and when the user presses it they are presented with a file browser (FileReference.browse() function). When they select an image file, I want the image to be uploaded to the site imgur.com (http://www.api.imgur.com for those interested).
I'm getting a response from imgur, so I know my app is connecting, but it's returning an error, "No image data was sent to the upload API". Any help is greatly appreciated! (Also I do have an API key, just removed it from this post for obvious reasons :) )
package
{
import flash.display.MovieClip;
import flash.events.*;
import flash.net.*;
import flash.utils.ByteArray;
public class Document extends MovieClip
{
//file browser var
var myFileReference:FileReference = new FileReference();
//file loader var
private var loader:URLLoader;
//string constants
private const API_KEY:String = "******REMOVED*******";
private const UPLOAD_URL:String = "http://api.imgur.com/2/upload.xml";
public function Document()
{
// constructor code
browse_btn.addEventListener(MouseEvent.CLICK, browse);
}
function browse(e:MouseEvent)
{
var imagesFilter:FileFilter = new FileFilter("Images", "*.jpg;*.gif;*.png");
myFileReference.browse([imagesFilter]);
myFileReference.addEventListener(Event.SELECT, selectHandler);
myFileReference.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, responseHandler);
}
function selectHandler(e:Event):void
{
var vars:String = "?key=" + API_KEY + "&name=name&title=title";
var params:URLVariables = new URLVariables();
params.date = new Date();
var request:URLRequest = new URLRequest(UPLOAD_URL + vars);
//request.contentType = "application/octet-stream";
request.contentType = "multipart/form-data";
request.method = URLRequestMethod.POST;
request.data = params;
myFileReference.upload(request);
try
{
myFileReference.upload(request);
}
catch (error:Error)
{
trace("Unable to upload file.");
}
}
function responseHandler(e:DataEvent):void
{
trace("responseHandler() initaialized");
var res:XML = XML(e.data);
trace(res);
}
}
}
there's actually an example for AS3 on their site:
package
{
import com.adobe.images.PNGEncoder;
import flash.display.BitmapData;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.SecurityErrorEvent;
import flash.events.IOErrorEvent
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.utils.ByteArray;
public class ImgurExample
{
private var loader:URLLoader;
private const API_KEY:String = "<api key>";
private const UPLOAD_URL:String = "http://api.imgur.com/2/upload.xml";
public function ImgurExample() {
loader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE, onCookieSent);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
// Create a bitmapdata instance of a movieclip on the stage.
var mc:MovieClip;
var b:BitmapData = new BitmapData(mc.width, mc.height, true);
b.draw(mc);
var png:ByteArray = PNGEncoder.encode(b);
var vars:String = "?key=" + API_KEY + "&name=name&title=title";
var request:URLRequest = new URLRequest(UPLOAD_URL + vars);
request.contentType = "application/octet-stream";
request.method = URLRequestMethod.POST;
request.data = png; // set the data object of the request to your image.
loader.load(request);
}
// privates
private function onSend(e:Event):void {
var res:XML = new XML(unescape(loader.data));
trace(res);
}
private function onIOError(e:IOErrorEvent):void {
trace("ioErrorHandler: " + e);
// Handle error
}
private function onSecurityError(e:SecurityErrorEvent):void {
trace("securityErrorHandler: " + e);
// handle error
}
}
}
http://api.imgur.com/examples

adding noise to a video in actionscript

Before I begin, I would like to apologize if what I'm going to ask is to be considered as super newbie question.
so I was trying out Lee Brimelow's tutorial on creating a simple AR scene using actionscript3. (http://blog.theflashblog.com/?p=901)
It worked out pretty well, considering I have never created something out of Adobe Flex Builder before. (I installed Flex Builder right after I saw those tutorial)
here is the source code
package {
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.events.Event;
import flash.media.Camera;
import flash.media.Video;
import flash.utils.ByteArray;
import org.libspark.flartoolkit.core.FLARCode;
import org.libspark.flartoolkit.core.param.FLARParam;
import org.libspark.flartoolkit.core.raster.rgb.FLARRgbRaster_BitmapData;
import org.libspark.flartoolkit.core.transmat.FLARTransMatResult;
import org.libspark.flartoolkit.detector.FLARSingleMarkerDetector;
import org.libspark.flartoolkit.support.pv3d.FLARBaseNode;
import org.libspark.flartoolkit.support.pv3d.FLARCamera3D;
import org.papervision3d.lights.PointLight3D;
import org.papervision3d.materials.shadematerials.FlatShadeMaterial;
import org.papervision3d.materials.utils.MaterialsList;
import org.papervision3d.objects.primitives.Cube;
import org.papervision3d.render.BasicRenderEngine;
import org.papervision3d.scenes.Scene3D;
import org.papervision3d.view.Viewport3D;
[SWF(width="640", height="480", frameRate="30", backgroundColor="#FFFFFF")]
public class FLARdemo extends Sprite
{
[Embed(source="pat1.pat", mimeType="application/octet-stream")]
private var pattern:Class;
[Embed(source="camera_para.dat", mimeType="application/octet-stream")]
private var params:Class;
private var fparams:FLARParam;
private var mpattern:FLARCode;
private var vid:Video;
private var cam:Camera;
private var bmd:BitmapData;
private var raster:FLARRgbRaster_BitmapData;
private var detector:FLARSingleMarkerDetector;
private var scene:Scene3D;
private var camera:FLARCamera3D;
private var container:FLARBaseNode;
private var vp:Viewport3D;
private var bre:BasicRenderEngine;
private var trans:FLARTransMatResult;
public function FLARdemo()
{
setupFLAR();
setupCamera();
setupBitmap();
setupPV3D();
addEventListener(Event.ENTER_FRAME, loop);
}
private function setupFLAR():void
{
fparams = new FLARParam();
fparams.loadARParam(new params() as ByteArray);
mpattern = new FLARCode(16, 16);
mpattern.loadARPatt(new pattern());
}
private function setupCamera():void
{
vid = new Video(640, 480);
cam = Camera.getCamera();
cam.setMode(640, 480, 30);
vid.attachCamera(cam);
addChild(vid);
}
private function setupBitmap():void
{
bmd = new BitmapData(640, 480);
bmd.draw(vid);
raster = new FLARRgbRaster_BitmapData(bmd);
detector = new FLARSingleMarkerDetector(fparams, mpattern, 80);
}
private function setupPV3D():void
{
scene = new Scene3D();
camera = new FLARCamera3D(fparams);
container = new FLARBaseNode();
scene.addChild(container);
var pl:PointLight3D = new PointLight3D();
pl.x = 1000;
pl.y = 1000;
pl.z = -1000;
var ml:MaterialsList = new MaterialsList({all: new FlatShadeMaterial(pl)});
var Cube1:Cube = new Cube(ml, 30, 30, 30);
var Cube2:Cube = new Cube(ml, 30, 30, 30);
Cube2.z = 50
var Cube3:Cube = new Cube(ml, 30, 30, 30);
Cube3.z = 100
container.addChild(Cube1);
container.addChild(Cube2);
container.addChild(Cube3);
bre = new BasicRenderEngine();
trans = new FLARTransMatResult();
vp = new Viewport3D;
addChild(vp);
}
private function loop(e:Event):void
{
bmd.draw(vid);
try
{
if(detector.detectMarkerLite(raster, 80) && detector.getConfidence() > 0.5)
{
detector.getTransformMatrix(trans);
container.setTransformMatrix(trans);
bre.renderScene(scene, camera, vp);
}
}
catch(e:Error){}
}
}
}
what I am asking is :
is it possible for us to add some noise in the final video output? I'm trying to find out the PSNR by adding noises respectively.
can I do some convolution between the noise and the video?
oh btw I'm doing this for my assignment in college. My prof wanted me to explain how exactly the FlarToolKit works. (details such as Matrix Projections, Obtaining Errors by doing Iterative Method, etc.)
Thank you.
Prama
Creating fine-grained noise dynamically is computationally expensive, so I generate low-res noise and scale it up. In your project, simply add the bitmap setup code after the addEventListener call and then add the single line to generate the noise to your activity loop.
package
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.BlendMode;
import flash.display.Sprite;
import flash.events.Event;
import flash.geom.Matrix;
import flash.media.Camera;
import flash.media.Video;
import flash.utils.getTimer;
public class NoiseMain extends Sprite
{
protected static const VID_WIDTH : uint = 640;
protected static const VID_HEIGHT : uint = 480;
protected static const NOISE_SCALE_X : Number = 4;
protected static const NOISE_SCALE_Y : Number = 2;
protected var _vid : Video;
protected var _noise : BitmapData;
protected var _composite : BitmapData;
protected var _matrix : Matrix;
public function NoiseMain()
{
// We're creating a webcam outlet, but not adding it to the stage since we want to post-process the image.
_vid = new Video(VID_WIDTH, VID_HEIGHT);
var cam : Camera = Camera.getCamera();
cam.setMode(VID_WIDTH, VID_HEIGHT, 30);
_vid.attachCamera(cam);
var w : uint = Math.ceil(VID_WIDTH / NOISE_SCALE_X);
var h : uint = Math.ceil(VID_HEIGHT / NOISE_SCALE_Y);
_noise = new BitmapData(w, h, false, 0xFFFFFF);
_composite = new BitmapData(VID_WIDTH, VID_HEIGHT, false, 0x000000);
var bmp : Bitmap = new Bitmap(_composite);
addChild(bmp);
_matrix = new Matrix(NOISE_SCALE_X, 0, 0, NOISE_SCALE_Y);
stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
}
protected function enterFrameHandler(evt : Event) : void
{
_noise.noise(getTimer(), 204, 255, 7, true);
_composite.lock();
_composite.draw(_vid);
_composite.draw(_noise, _matrix, null, BlendMode.MULTIPLY);
_composite.unlock();
}
}
}
EDIT: I've revised my example to be more in line with what you're trying to do. You can tweak the noise scale constants to change the "texture" of the noise as well as messing with the strength of the noise (the 2nd and 3rd arguments to the noise() method) and the visual appearance of the noise by changing the BlendMode in the 2nd draw() call).