ActionScript 3 coding error - properties

I need a little bit of help with some code issue. I am trying to connect to the server from a click of a button. When I execute the code I receive this error in my output: 1120: Access of undefined property nc.close
Which is strange because I already declared the nc property in the btnStart function. I have been tweaking around with the code but I keep getting the same annoying error. If you have any suggestions how to resolve this that be great!
Thanks
Code is below:
btn_One.addEventListener(MouseEvent.CLICK, btnStart);
btn_Two.addEventListener(MouseEvent.CLICK, btnClose);
function btnStart(event:MouseEvent):void{
trace("Connecting...");
var nc:NetConnection = new NetConnection();
nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
nc.connect("rtmfp://localhost/streamingLive");
}
//// ERROR LINE NC.CLOSE();
function btnClose(event:MouseEvent):void{
trace("Closing time");
nc.close();
}
function netStatusHandler(event:NetStatusEvent):void{
switch(event.info.code){
case "NetConnection.Connect.Success":
trace("Awesome connection");
break;
case "NetConnection.Connect.Failed":
trace("Unable to connect");
break;
case "NetConnection.Connect.Rejected":
trace("WHoooops");
break;
case "NetGroup.Connect.Success":
trace("GroupConnection");
break;
case "NetGroup.Connect.Failed":
trace("Group failed");
break;
case "NetGroup.Connect.Rejected":
trace("Ouch!!!");
break;
var ns:NetStream = new NetStream();
ns.publish("live", "streaming");
ns.attachCamera();
ns.attachAudio();
ns.connect(nc);
var ng:NetGroup = new NetGroup(nc, groupspec.groupspecWithAuthorizations());
ng.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
}
}
var cam:Camera = Camera.getCamera();
cam.setMode(420, 320, 15);
cam.setQuality(0, 85);
cam.addEventListener(StatusEvent.STATUS, statusHandler);
var vid:Video = new Video();
vid.width = cam.width;
vid.height = cam.height;
vid.x = 100;
vid.y = 100;
vid.attachCamera(cam);
addChild(vid);
var mic:Microphone = Microphone.getMicrophone();
mic.gain = 50;
mic.framesPerPacket = 1;
mic.setSilenceLevel(0, 2000);
mic.codec = SoundCodec.SPEEX;
//camera access permissions
function statusHandler(event:StatusEvent):void
{
switch (event.code)
{
case "Camera.Muted":
trace("User clicked Deny.");
break;
case "Camera.Unmuted":
trace("User clicked Accept.");
break;
}
}
//audio access permissions
function micStatus(event:StatusEvent):void
{
if (event.code == "Microphone.Unmuted")
{
trace("Microphone access was allowed.");
}
else if (event.code == "Microphone.Muted")
{
trace("Microphone access was denied.");
}
}
//array of camera names
var cameraA:Array = Camera.names;
for ( var i : int = 0; i < cameraA.length; i++){
trace ( "Camera: ", cameraA[i] );
}
var groupspec:GroupSpecifier = new GroupSpecifier("groupone");
groupspec.multicastEnabled = true;
//group postings
groupspec.postingEnabled = true;
//specific peer posting
groupspec.routingEnabled = true;
//automatic peer discovery
groupspec.serverChannelEnabled = true;

nc is declared inside one function, but you're trying to use it inside of another function. Sometimes you can just pass the variable around as an argument, but in this case, that won't really work out too well. So in this case, do the following:
var nc:NetConnection = new NetConnection();
function btnStart(event:MouseEvent):void{
trace("Connecting...");
// var nc:NetConnection = new NetConnection(); // removed
nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
nc.connect("rtmfp://localhost/streamingLive");
}
//// ERROR LINE NC.CLOSE();
function btnClose(event:MouseEvent):void{
trace("Closing time");
nc.close();
}

Related

Photoshop Scripting: Relink Smart Object

I'm working on a script that should go through a photoshop document and relink all visible linked objects to a new specified file. I've gotten the loop working so that it cycles through every layer and collects only the visible layers, but for the life of me I can't find if there's a method available to relink a smart object. The closest I've found is this script:
https://gist.github.com/laryn/0a1f6bf0dab5b713395a835f9bfa805c
but when it gets to desc3.putPath(idnull, new File(newFile));, it spits out an error indicating that the functionality may not be present in the current Photoshop version. The script itself is 4 years old so it may be out of date.
Any help would be appreciated!
MY script as it stands is below:
// SELECT FILE //
var files = File.openDialog("Please select new linked file");
var selectedFile = files[0];
// GET ALL LAYERS //
var doc = app.activeDocument;
var allLayers = [];
var allLayers = collectAllLayers(doc, allLayers);
function collectAllLayers (doc, allLayers)
{
for (var m = 0; m < doc.layers.length; m++)
{
var theLayer = doc.layers[m];
if (theLayer.typename === "ArtLayer")
{
allLayers.push(theLayer);
}
else
{
collectAllLayers(theLayer, allLayers);
}
}
return allLayers;
}
// GET VISIBLE LAYERS //
var visibleLayers = [];
for (i = 0; i < allLayers.length; i++)
{
var layer = allLayers[i];
if (layer.visible && layer.kind == LayerKind.SMARTOBJECT)
{
visibleLayers.push(layer);
}
}
// REPLACE LAYERS
for (i = 0; i < visibleLayers.length; i++)
{
var layer = visibleLayers[i];
//--> REPLACE THE FILE HERE
}
Note: I am aware that this script currently may be error-prone if you don't know exactly how it works; I'm not intending to publish it at this time so I'm not super concerned with that at the moment. Mostly I just need the core functionality to work.
I used an AM function for getting visible smart objects — it works much faster. But if you want you can use yours. The important bit is relinkSO(path);: it'll also work in your script (just don't forget to select a layer: activeDocument.activeLayer = visibleLayers[i];)
Note that it works similar to Photoshop Relink to File command — if used on one instance of Smart Object all the instances are going to be relinked. If you want to relink only specific layers you'll have to break instancing first (probably using the New Smart Object via Copy command)
function main() {
var myFile = Folder.myDocuments.openDlg('Load file', undefined, false);
if (myFile == null) return false;
// gets IDs of all smart objects
var lyrs = getLyrs();
for (var i = 0; i < lyrs.length; i++) {
// for each SO id...
// select it
selectById(lyrs[i]);
// relink SO to file
relinkSO(myFile);
// embed linked if you want
embedLinked()
}
function getLyrs() {
var ids = [];
var layers, desc, vis, type, id;
try
{
activeDocument.backgroundLayer;
layers = 0;
}
catch (e)
{
layers = 1;
}
while (true)
{
ref = new ActionReference();
ref.putIndex(charIDToTypeID('Lyr '), layers);
try
{
desc = executeActionGet(ref);
}
catch (err)
{
break;
}
vis = desc.getBoolean(charIDToTypeID("Vsbl"));
type = desc.getInteger(stringIDToTypeID("layerKind"));
id = desc.getInteger(stringIDToTypeID("layerID"));
if (type == 5 && vis) ids.push(id);
layers++;
}
return ids;
} // end of getLyrs()
function selectById(id) {
var desc = new ActionDescriptor();
var ref = new ActionReference();
ref.putIdentifier(charIDToTypeID('Lyr '), id);
desc.putReference(charIDToTypeID('null'), ref);
executeAction(charIDToTypeID('slct'), desc, DialogModes.NO);
} // end of selectById()
function relinkSO(path) {
var desc = new ActionDescriptor();
desc.putPath( charIDToTypeID('null'), new File( path ) );
executeAction( stringIDToTypeID('placedLayerRelinkToFile'), desc, DialogModes.NO );
} // end of relinkSO()
function embedLinked() {
executeAction( stringIDToTypeID('placedLayerConvertToEmbedded'), undefined, DialogModes.NO );
} // end of embedLinked()
}
app.activeDocument.suspendHistory("relink SOs", "main()");

ActionScript 2.0 Random Boolean Function not working

I have the below code which show be randomly true and randomly false. But in my case its always being false. Any help is appreciated. Thanks.
In the below code tail and heads are the tow buttons.
on(release)
{
var guess:Boolean = Boolean(Math.round(Math.random()));
var input:Boolean;
if (event.target.name == "tail"){
input = true;
}
else if (event.target.name == "heads"){
input = false;
}
if (guess == input){
var newresult = Number(income.text) + Number(amount.text);
income.text = Number(newresult);
}
else{
var newresult = Number(income.text) - Number(amount.text);
income.text = Number(newresult);
}
}
This will also work:
on(release)
{
var guess:Boolean = Boolean(Math.floor(Math.random()*2));
if (guess){
result.text = "Your Guess is corrent";
var newresult = Number(income.text) + Number(amount.text);
income.text = Number(newresult);
}
else{
result.text = "Your Guess is wrong";
var newresult = Number(income.text) - Number(amount.text);
income.text = Number(newresult);
}
}
You dont need the event.target.name because the function is within the event handler of each button. So you can just use a random boolean. Event.target.name also doesnt work in AS2.0

InDesign copy layer to another document

I am trying to write a script that copies a layer from one document into another.
var srcDocName = 0;
var destDocName = 1;
var layerNameOriginal = "Original";
var layerNameCopyTo = "Destination";
var destDoc = app.documents.item(destDocName);
var layerSrc = app.documents.item(srcDocName).layers.item(layerNameOriginal);
try {
layerSrc.duplicate(destDoc, ElementPlacement.INSIDE);
}
catch(e) {
alert(e)
}
Apparently this works in Photoshop but not in InDesign. I have been trying for ages to find some decent documentation for InDesign scripting. But all I can find is the CS scripting guide, which isn't of much use.
http://wwwimages.adobe.com/www.adobe.com/content/dam/Adobe/en/products/indesign/pdfs/InDesignCS5_ScriptingGuide_JS.pdf
If someone can point me to a good reference to the object model I would be grateful.
After some more googling I finally found the answer:
var sourceLayer = app.documents[0].layers.itemByName("Layer1");
var destLayer = app.documents[1].layers[0];
sourceLayer.pageItems.everyItem().duplicate(destLayer);
I also came across jongware which seems to be a complete Object reference extracted directly out of Adobe CS.
You can use this script: https://redokun.com/blog/indesign-copy-entire-layer-one-file-another
The underlying implementation is basically the same, but we've added a UI so it's not necessary to edit the script every time the layer name changes.
Edit: We've been told that the solution above doesn't work with threaded text frames, so I re-wrote the script. The new implementation is way more complex but it now supports threaded TFs.
To expand on the solution offered by Loopo and offer you the ability to copy all layers from 1 document to another...
main();
function main()
{
var source = GetSourceDocument();
if(source == -1)
{
return;
}
var target = GetTargetDocument ();
if(target == -1)
{
return;
}
if(target == source)
{
return;
}
copyLayersOver(source, target);
}
function GetSourceDocument()
{
var returnVal = -1;
var oldPrefs = app.scriptPreferences.userInteractionLevel;
app.scriptPreferences.userInteractionLevel=UserInteractionLevels.INTERACT_WITH_ALL;
var dialog = app.dialogs.add({name:"Document to Copy From", canCanel: true, label:"DocumentToCopyFrom"});
var col1 = dialog.dialogColumns.add();
var StringList= [];
for(var i = 0; i<app.documents.length; i++)
{
StringList.push("[" + app.documents[i].index + "] " + app.documents[i].name);
}
var ddl = col1.dropdowns.add({id:"SourceDocDDL", stringList: StringList});
if(dialog.show() == true)
{
returnVal = ddl.stringList[ddl.selectedIndex].split("]")[0].substr(1);
}
else
{
returnVal -1;
}
dialog.destroy();
app.scriptPreferences.userInteractionLevel = oldPrefs;
return returnVal;
}
function GetTargetDocument()
{
var returnVal = -1;
var oldPrefs = app.scriptPreferences.userInteractionLevel;
app.scriptPreferences.userInteractionLevel=UserInteractionLevels.INTERACT_WITH_ALL;
var dialog = app.dialogs.add({name:"Document to Copy To", canCanel: true, label:"DocumentToCopyTo"});
var col1 = dialog.dialogColumns.add();
var StringList= [];
for(var i = 0; i<app.documents.length; i++)
{
StringList.push("[" + app.documents[i].index + "] " + app.documents[i].name);
}
var ddl = col1.dropdowns.add({id:"SourceDocDDL", stringList: StringList});
if(dialog.show() == true)
{
returnVal = ddl.stringList[ddl.selectedIndex].split("]")[0].substr(1);
}
else
{
returnVal -1;
}
dialog.destroy();
app.scriptPreferences.userInteractionLevel = oldPrefs;
return returnVal;
}
function copyLayersOver(source, target)
{
var sourceDocument = app.documents[source];
var targetDocument = app.documents[target];
var sourceLayers = sourceDocument.layers;
//Match the number of pages
while(targetDocument.pages.length < sourceDocument.pages.length)
{
targetDocument.pages.add();
}
//copy the layers over
for(var i= 0; i < sourceLayers.length; i++)
{
var names = targetDocument.layers.everyItem().name;
var merge = false;
for(var y = 0; y < names.length; y++)
{
if(names[y] == sourceLayers[i].name)
{
merge = true;
break;
}
}
if(merge)
{
var targetLayer = targetDocument.layers.add();
targetLayer.name = "temp";
sourceLayers[i].pageItems.everyItem().duplicate(targetLayer);
targetDocument.layers.itemByName(sourceLayers[i].name).merge(targetLayer);
}
else
{
var targetLayer = targetDocument.layers.add();
targetLayer.name = sourceLayers[i].name;
targetLayer.layerColor = sourceLayers[i].layerColor;
sourceLayers[i].pageItems.everyItem().duplicate(targetLayer);
}
}
}

DirectX Application Causes Computer Crash

I have written a DirectX11 Application that is running on an Alienware Laptop with a GeForce GT 555m graphics card, so I know the computer supports it.
I have come across this weird thing were my laptop will turn of without any warning if it isn't plugged into power, however the application runs fine if it is plugged into power.
I have tried to replicate this with other DirectX11 Applications, including the Samples that come with DirectX however my application is the only one that does it, but I use very similar code to the Samples. I must be missing something but I don't know what.
This is my code to setup the SwapChain and the RenderTargetView
ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));
swapChainDesc.BufferCount = 1;
swapChainDesc.BufferDesc.Width = width;
swapChainDesc.BufferDesc.Height = height;
swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
if(vsync) {
swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator;
swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator;
}
else {
swapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
}
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.OutputWindow = hwnd;
swapChainDesc.SampleDesc.Count = 1;
swapChainDesc.SampleDesc.Quality = 0;
if(fullscreen) {
swapChainDesc.Windowed = false;
}
else {
swapChainDesc.Windowed = true;
}
swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
swapChainDesc.Flags = 0;
D3D_FEATURE_LEVEL featureLevels[4] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, D3D_FEATURE_LEVEL_9_3, };
if (FAILED(D3D11CreateDeviceAndSwapChain(0, D3D_DRIVER_TYPE_HARDWARE, 0, 0, featureLevels, 4, D3D11_SDK_VERSION, &swapChainDesc, &swapChain, &device, &featureLevel, &deviceContext))) {
if (!device) {
printf("Insanity Error: Failed To Create Direct3D Device\n");
}
if (!swapChain) {
printf("Insanity Error: Failed To Create Swap Chain\n");
}
return false;
}
else {
switch (featureLevel) {
case D3D_FEATURE_LEVEL_11_0:
printf("Insanity Info: Currently Using DirectX 11.0\n");
break;
case D3D_FEATURE_LEVEL_10_1:
printf("Insanity Info: Currently Using DirectX 10.1\n");
break;
case D3D_FEATURE_LEVEL_10_0:
printf("Insanity Info: Currently Using DirectX 10.0\n");
break;
case D3D_FEATURE_LEVEL_9_3:
printf("Insanity Info: Currently Using DirectX 9.3\n");
break;
default:
printf("Insanity Info: Graphics System Unknown\n");
break;
}
}
if (FAILED(swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr))) {
printf("Insanity Error: Faield To Find Back Buffer\n");
return false;
}
if (FAILED(device->CreateRenderTargetView(backBufferPtr, 0, &renderTargetView))) {
printf("Insanity Error: Failed To Create Render View Target\n");
return false;
}
backBufferPtr->Release();
backBufferPtr = 0;
And then this is my code to set up the DepthStencilState and the RasterState
ZeroMemory(&depthStencilDesc, sizeof(D3D11_DEPTH_STENCIL_DESC));
depthStencilDesc.DepthEnable = false;
depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
depthStencilDesc.StencilEnable = true;
depthStencilDesc.StencilReadMask = 0xFF;
depthStencilDesc.StencilWriteMask = 0xFF;
depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
if (FAILED(device->CreateDepthStencilState(&depthStencilDesc, &depthDisableStencilState))) {
printf("Insanity Error: Failed To Create Depth State\n");
return false;
}
deviceContext->OMSetDepthStencilState(depthEnableStencilState, 1);
this->enableDepthTesting = true;
ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));
depthStencilViewDesc.Format = depthBufferDesc.Format;
depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
depthStencilViewDesc.Texture2D.MipSlice = 0;
if (FAILED(device->CreateDepthStencilView(depthStencilBuffer, &depthStencilViewDesc, &depthStencilView))) {
printf("Insanity Error: Failed To Create Depth View\n");
return false;
}
rasterDesc.AntialiasedLineEnable = false;
rasterDesc.CullMode = D3D11_CULL_NONE;
rasterDesc.DepthBias = 0;
rasterDesc.DepthBiasClamp = 0.0f;
rasterDesc.DepthClipEnable = true;
rasterDesc.FillMode = D3D11_FILL_SOLID;
rasterDesc.FrontCounterClockwise = false;
rasterDesc.MultisampleEnable = false;
rasterDesc.ScissorEnable = true;
rasterDesc.SlopeScaledDepthBias = 0.0f;
if (FAILED(device->CreateRasterizerState(&rasterDesc, &rasterState))) {
printf("Insanity Error: Failed To Create Rasterizer State\n");
return false;
}
deviceContext->RSSetState(rasterState);
If any one has any ideas as to what could be going on please help!
Try using the reference device instead of your hardware device and see if the problem recurs. This should help isolate the driver from the code. When you create your device, instead use D3D_DRIVER_TYPE_REFERENCE.

JScript.NET private variables

I'm wondering about JScript.NET private variables. Please take a look on the following code:
import System;
import System.Windows.Forms;
import System.Drawing;
var jsPDF = function(){
var state = 0;
var beginPage = function(){
state = 2;
out('beginPage');
}
var out = function(text){
if(state == 2){
var st = 3;
}
MessageBox.Show(text + ' ' + state);
}
var addHeader = function(){
out('header');
}
return {
endDocument: function(){
state = 1;
addHeader();
out('endDocument');
},
beginDocument: function(){
beginPage();
}
}
}
var j = new jsPDF();
j.beginDocument();
j.endDocument();
Output:
beginPage 2
header 2
endDocument 2
if I run the same script in any browser, the output is:
beginPage 2
header 1
endDocument 1
Why it is so??
Thanks,
Paul.
Just a guess, but it appears that JScript.NET doesn't support closures the same way as EMCAScript, so the state variable in endDocument() isn't referencing the private member of the outer function, but rather an local variable (undeclared). Odd.
You don't have to use new when calling jsPDF here since you're using a singleton pattern. jsPDF is returning an object literal so even without new you'll have access to the beginPage and endDocument methods. To be perfectly honest I don't know what the specifications call for when using new on a function that returns an object literal so I'm not sure if JScript.NET is getting it wrong or the browser. But for now try either getting rid of the new before jsPDF() or change your function to this:
var jsPDF = function(){
var state = 0;
var beginPage = function(){
state = 2;
out('beginPage');
};
var out = function(text){
if(state == 2){
var st = 3;
}
MessageBox.Show(text + ' ' + state);
};
var addHeader = function(){
out('header');
};
this.endDocument = function(){
state = 1;
addHeader();
out('endDocument');
};
this.beginDocument: function(){
beginPage();
};
}
That will allow you to use the new keyword and create more than one jsPDF object.
I've come across the same problem. In the following code, the closure bound to fun should contain only one variable called result. As the code stands, the variable result in the function with one parameter seems to be different to the result variable in the closure.
If in this function the line
result = [];
is removed, then the result in the line
return result;
refers to the result in the closure.
var fun = function() {
var result = [];
// recursive descent, collects property names of obj
// dummy parameter does nothing
var funAux = function(obj, pathToObj, dummy) {
if (typeof obj === "object") {
for (var propName in obj) {
if (obj.hasOwnProperty(propName)) {
funAux(obj[propName], pathToObj.concat(propName), dummy);
}
}
}
else {
// at leaf property, save path to leaf
result.push(pathToObj);
}
}
return function(obj) {
// remove line below and `result' 3 lines below is `result' in closure
result = []; // does not appear to be bound to `result' above
funAux(obj, [], "dummy");
return result; // if result 2 lines above is set, result is closure is a different variable
};
}();