avtDataRepresentation * avtNeighborExpression::ExecuteData(avtDataRepresentation *in_dr) { // // Get the VTK data set. // vtkDataSet *in_ds = in_dr->GetDataVTK(); // Let's get the points from the input dataset. vtkPoints *pts = NULL; switch (in_ds->GetDataObjectType()) { // Easily done, just grab them. case VTK_UNSTRUCTURED_GRID: case VTK_POLY_DATA: case VTK_STRUCTURED_GRID: pts = ((vtkPointSet *) in_ds)->GetPoints(); break; // If they're any other type of grid, this filter shouldn't be used default: EXCEPTION0(ImproperUseException); } vtkIdType nPoints = pts->GetNumberOfPoints(); // A neighbor filter would require the existance of neighbors if (nPoints < 2) EXCEPTION0(ImproperUseException); // Now that we've done all of our checks for improper use, // let's allocate for our needs vtkPolyData *results = vtkPolyData::New(); vtkCellArray *verts = vtkCellArray::New(); vtkDataArray *data = CreateArrayFromMesh(in_ds); results->SetPoints(pts); data->SetNumberOfComponents(1); data->SetNumberOfTuples(nPoints); double bounds[6]; in_ds->GetBounds(bounds); // Create the point locator vtkPointLocator *ptLoc = vtkPointLocator::New(); ptLoc->SetDataSet(in_ds); ptLoc->BuildLocator(); for (vtkIdType id = 0; id < nPoints; id++) { // Build the vertex list vtkVertex *v = vtkVertex::New(); v->Initialize( 1, &id, pts); verts->InsertNextCell(v); v->Delete(); // And at the same time, set the distance data double coords[3]; pts->GetPoint(id, coords); // Find the closest 2 points, since the closest is itself of course. vtkIdList *closeId = vtkIdList::New(); ptLoc->FindClosestNPoints(2, coords, closeId); double nearCoords[3]; pts->GetPoint(closeId->GetId(1), nearCoords); double distance = (coords[0]-nearCoords[0])*(coords[0]-nearCoords[0]) + (coords[1]-nearCoords[1])*(coords[1]-nearCoords[1]) + (coords[2]-nearCoords[2])*(coords[2]-nearCoords[2]); distance=sqrt(distance); data->SetTuple1(id, distance); closeId->Delete(); } data->SetName("neighbor"); results->GetPointData()->AddArray(data); results->GetPointData()->SetActiveScalars("neighbor"); results->SetVerts(verts); // // Make our best attempt at maintaining our extents. // double exts[2]; double range[2]; data->GetRange(range, 0); exts[0] = range[0]; exts[1] = range[1]; GetOutput()->GetInfo().GetAttributes().GetOriginalDataExtents()->Merge(exts); data->Delete(); verts->Delete(); pts->Delete(); avtDataRepresentation *out_dr = new avtDataRepresentation(results, in_dr->GetDomain(), in_dr->GetLabel()); results->Delete(); return out_dr; }
avtDataRequest_p avtOriginatingSource::BalanceLoad(avtContract_p contract) { bool usesAllDomains =contract->GetDataRequest()->GetSIL().UsesAllDomains(); // // If it shouldn't use load balancing, then it has to do with auxiliary // data coming through our meta-data mechanism. Calling InitPipeline // would change the data attributes and it also causes an unnecessary // callback to our progress mechanism. // if (contract->ShouldUseLoadBalancing()) { InitPipeline(contract); } else if (contract->DoingOnDemandStreaming()) { GetOutput()->GetInfo().GetValidity().SetWhetherStreaming(true); } // // Allow the load balancer to split the load across processors. // bool dataReplicationOccurred = false; avtDataRequest_p rv = NULL; if (!UseLoadBalancer()) { debug5 << "This source should not load balance the data." << endl; rv = contract->GetDataRequest(); } else if (! contract->ShouldUseLoadBalancing()) { debug5 << "This pipeline has indicated that no load balancing should " << "be used." << endl; rv = contract->GetDataRequest(); } else if (loadBalanceFunction != NULL) { debug5 << "Using load balancer to reduce data." << endl; rv = loadBalanceFunction(loadBalanceFunctionArgs, contract); dataReplicationOccurred = contract->ReplicateSingleDomainOnAllProcessors(); } else { debug1 << "No load balancer exists to reduce data." << endl; rv = contract->GetDataRequest(); } // // Return the portion for this processor. // rv->SetUsesAllDomains(usesAllDomains); // // Tell the output if we are doing data replication. // if (dataReplicationOccurred) GetOutput()->GetInfo().GetAttributes().SetDataIsReplicatedOnAllProcessors(true); return rv; }
IResultPtr result() const { auto output = join(GetOutput()); auto errors = join(GetErrors()); return IResultPtr(new PerforceResult(output.c_str(), errors.c_str(), fileResults())); }
Float64 AUEffectBase::GetSampleRate() { return GetOutput(0)->GetStreamFormat().mSampleRate; }
//_____________________________________________________________________________ // OSStatus AUEffectBase::Initialize() { // get our current numChannels for input and output SInt16 auNumInputs = (SInt16) GetInput(0)->GetStreamFormat().mChannelsPerFrame; SInt16 auNumOutputs = (SInt16) GetOutput(0)->GetStreamFormat().mChannelsPerFrame; // does the unit publish specific information about channel configurations? const AUChannelInfo *auChannelConfigs = NULL; UInt32 numIOconfigs = SupportedNumChannels(&auChannelConfigs); if ((numIOconfigs > 0) && (auChannelConfigs != NULL)) { bool foundMatch = false; for (UInt32 i = 0; (i < numIOconfigs) && !foundMatch; ++i) { SInt16 configNumInputs = auChannelConfigs[i].inChannels; SInt16 configNumOutputs = auChannelConfigs[i].outChannels; if ((configNumInputs < 0) && (configNumOutputs < 0)) { // unit accepts any number of channels on input and output if (((configNumInputs == -1) && (configNumOutputs == -2)) || ((configNumInputs == -2) && (configNumOutputs == -1))) { foundMatch = true; // unit accepts any number of channels on input and output IFF they are the same number on both scopes } else if (((configNumInputs == -1) && (configNumOutputs == -1)) && (auNumInputs == auNumOutputs)) { foundMatch = true; // unit has specified a particular number of channels on both scopes } else continue; } else { // the -1 case on either scope is saying that the unit doesn't care about the // number of channels on that scope bool inputMatch = (auNumInputs == configNumInputs) || (configNumInputs == -1); bool outputMatch = (auNumOutputs == configNumOutputs) || (configNumOutputs == -1); if (inputMatch && outputMatch) foundMatch = true; } } if (!foundMatch) return kAudioUnitErr_FormatNotSupported; } else { // there is no specifically published channel info // so for those kinds of effects, the assumption is that the channels (whatever their number) // should match on both scopes if ((auNumOutputs != auNumInputs) || (auNumOutputs == 0)) { return kAudioUnitErr_FormatNotSupported; } } MaintainKernels(); mMainOutput = GetOutput(0); mMainInput = GetInput(0); const CAStreamBasicDescription& format = GetStreamFormat(kAudioUnitScope_Output, 0); format.IdentifyCommonPCMFormat(mCommonPCMFormat, NULL); mBytesPerFrame = format.mBytesPerFrame; return noErr; }
void avtLinearTransformFilter::PostExecute() { GetOutput()->GetInfo().GetAttributes().SetInvTransform((*invM)[0]); GetOutput()->GetInfo().GetAttributes().SetTransform((*M)[0]); }
Float64 GetSampleRate() { return GetOutput(0)->GetStreamFormat().mSampleRate; }
void vtkSlicer::UnstructuredGridExecute(void) { // The routine here is a bit trickier than for the Rectilinear or // Structured grids. We want to slice an unstructured grid -- but that // could mean any cell type. We only have triangulation tables for // the finite element zoo. So the gameplan is to slice any of the // elements of the finite element zoo. If there are more elements left // over, slice them using the conventional VTK filters. Finally, // append together the slices from the zoo with the slices from the // non-zoo elements. If all the elements are from the zoo, then just // slice them with no appending. vtkUnstructuredGrid *ug = (vtkUnstructuredGrid *) GetInput(); vtkIdType nCells = ug->GetNumberOfCells(); vtkPoints *inPts = ug->GetPoints(); vtkCellData *inCD = ug->GetCellData(); vtkPointData *inPD = ug->GetPointData(); vtkPolyData *output = GetOutput(); vtkIdType ptSizeGuess = (this->CellList == NULL ? (int) pow(float(nCells), 0.6667f) * 5 + 100 : CellListSize*5 + 100); vtkSurfaceFromVolume sfv(ptSizeGuess); vtkUnstructuredGrid *stuff_I_cant_slice = vtkUnstructuredGrid::New(); vtkPolyData *vertices_on_slice = vtkPolyData::New(); double D = Origin[0]*Normal[0] + Origin[1]*Normal[1] + Origin[2]*Normal[2]; vtkIdType nToProcess = (CellList != NULL ? CellListSize : nCells); vtkIdType numIcantSlice = 0; vtkIdType numVertices = 0; for (vtkIdType i = 0 ; i < nToProcess ; i++) { vtkIdType cellId = (CellList != NULL ? CellList[i] : i); int cellType = ug->GetCellType(cellId); vtkIdType npts; vtkIdType *pts; ug->GetCellPoints(cellId, npts, pts); const int *triangulation_table = NULL; const int *vertices_from_edges = NULL; int tt_step = 0; bool canSlice = false; bool isVertex = false; switch (cellType) { case VTK_TETRA: triangulation_table = (const int *) tetTriangulationTable; vertices_from_edges = (const int *) tetVerticesFromEdges; tt_step = 7; canSlice = true; break; case VTK_PYRAMID: triangulation_table = (const int *) pyramidTriangulationTable; vertices_from_edges = (const int *) pyramidVerticesFromEdges; tt_step = 13; canSlice = true; break; case VTK_WEDGE: triangulation_table = (const int *) wedgeTriangulationTable; vertices_from_edges = (const int *) wedgeVerticesFromEdges; tt_step = 13; canSlice = true; break; case VTK_HEXAHEDRON: triangulation_table = (const int *) hexTriangulationTable; vertices_from_edges = (const int *) hexVerticesFromEdges; tt_step = 16; canSlice = true; break; case VTK_VERTEX: isVertex = true; break; default: canSlice = false; break; } if (canSlice) { int tmp[3] = {0,0,0}; if(inPts->GetDataType() == VTK_FLOAT) { vtkUnstructuredCreateTriangles<float, SliceFunction<float> >( sfv, cellId, pts, npts, triangulation_table, vertices_from_edges, tt_step, SliceFunction<float>(tmp, inPts, this->Origin, this->Normal) ); } else if(inPts->GetDataType() == VTK_DOUBLE) { vtkUnstructuredCreateTriangles<double, SliceFunction<double> >( sfv, cellId, pts, npts, triangulation_table, vertices_from_edges, tt_step, SliceFunction<double>(tmp, inPts, this->Origin, this->Normal) ); } else { vtkUnstructuredCreateTriangles<double, GeneralSliceFunction >( sfv, cellId, pts, npts, triangulation_table, vertices_from_edges, tt_step, GeneralSliceFunction(tmp, inPts, this->Origin, this->Normal) ); } } else if (isVertex) { // // Determine if the vertex is even on the plane. // const double *pt = inPts->GetPoint(pts[0]); double dist_from_plane = Normal[0]*pt[0] + Normal[1]*pt[1] + Normal[2]*pt[2] - D; if (fabs(dist_from_plane) < 1e-12) { if (numVertices == 0) { vertices_on_slice->SetPoints(ug->GetPoints()); vertices_on_slice->GetPointData()->ShallowCopy( ug->GetPointData()); vertices_on_slice->Allocate(nCells); vertices_on_slice->GetCellData()-> CopyAllocate(ug->GetCellData(), nCells); } vertices_on_slice->InsertNextCell(VTK_VERTEX, 1, pts); vertices_on_slice->GetCellData()-> CopyData(ug->GetCellData(), cellId, numVertices); numVertices++; } } else { if (numIcantSlice == 0) { stuff_I_cant_slice->SetPoints(ug->GetPoints()); stuff_I_cant_slice->GetPointData()->ShallowCopy( ug->GetPointData()); stuff_I_cant_slice->Allocate(nCells); stuff_I_cant_slice->GetCellData()-> CopyAllocate(ug->GetCellData(), nCells); } if(cellType == VTK_POLYHEDRON) { vtkIdType nFaces, *facePtIds; ug->GetFaceStream(cellId, nFaces, facePtIds); stuff_I_cant_slice->InsertNextCell(cellType, npts, pts, nFaces, facePtIds); } else stuff_I_cant_slice->InsertNextCell(cellType, npts, pts); stuff_I_cant_slice->GetCellData()-> CopyData(ug->GetCellData(), cellId, numIcantSlice); numIcantSlice++; } } if ((numIcantSlice > 0) || (numVertices > 0)) { vtkAppendPolyData *appender = vtkAppendPolyData::New(); if (numIcantSlice > 0) { vtkPolyData *not_from_zoo = vtkPolyData::New(); SliceDataset(stuff_I_cant_slice, not_from_zoo, true); appender->AddInput(not_from_zoo); not_from_zoo->Delete(); } if (numVertices > 0) { appender->AddInput(vertices_on_slice); } vtkPolyData *just_from_zoo = vtkPolyData::New(); sfv.ConstructPolyData(inPD, inCD, just_from_zoo, inPts); appender->AddInput(just_from_zoo); just_from_zoo->Delete(); appender->GetOutput()->Update(); output->ShallowCopy(appender->GetOutput()); appender->Delete(); } else { sfv.ConstructPolyData(inPD, inCD, output, inPts); } stuff_I_cant_slice->Delete(); vertices_on_slice->Delete(); }
void vtkSlicer::GeneralExecute(void) { SliceDataset(GetInput(), GetOutput(), false); }
XnStatus XnPacked12DepthProcessor::Unpack12to16(const XnUInt8* pcInput, const XnUInt32 nInputSize, XnUInt32* pnActualRead) { const XnUInt8* pOrigInput = pcInput; XnUInt32 nElements = nInputSize / XN_INPUT_ELEMENT_SIZE; // floored XnUInt32 nNeededOutput = nElements * XN_OUTPUT_ELEMENT_SIZE; *pnActualRead = 0; XnBuffer* pWriteBuffer = GetWriteBuffer(); if (!CheckDepthBufferForOverflow(nNeededOutput)) { return XN_STATUS_OUTPUT_BUFFER_OVERFLOW; } XnUInt16* pnOutput = GetDepthOutputBuffer(); XnUInt16* pShiftOut = GetShiftsOutputBuffer(); XnUInt16 shift[16]; #ifdef XN_NEON XnUInt16 depth[16]; uint8x8x3_t inD3; uint8x8_t rshft4D, lshft4D; uint16x8_t rshft4Q, lshft4Q; uint16x8_t depthQ; uint16x8x2_t shiftQ2; #endif // Convert the 11bit packed data into 16bit shorts for (XnUInt32 nElem = 0; nElem < nElements; ++nElem) { #ifndef XN_NEON // input: 0, 1,2,3, 4,5,6, 7,8,9, 10,11,12, 13,14,15, 16,17,18, 19,20,21, 22,23 // -,---,-,-,---,-,-,---,-,-,---,--,--,---,--,--,---,--,--,---,--,--,---,-- // bits: 8,4,4,8,8,4,4,8,8,4,4,8,8,4,4, 8, 8,4,4, 8, 8,4,4, 8, 8,4,4, 8, 8,4,4, 8 // ---,---,---,---,---,---,---,----,----,----,----,----,----,----,----,---- // output: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 shift[0] = (XN_TAKE_BITS(pcInput[0],8,0) << 4) | XN_TAKE_BITS(pcInput[1],4,4); shift[1] = (XN_TAKE_BITS(pcInput[1],4,0) << 8) | XN_TAKE_BITS(pcInput[2],8,0); shift[2] = (XN_TAKE_BITS(pcInput[3],8,0) << 4) | XN_TAKE_BITS(pcInput[4],4,4); shift[3] = (XN_TAKE_BITS(pcInput[4],4,0) << 8) | XN_TAKE_BITS(pcInput[5],8,0); shift[4] = (XN_TAKE_BITS(pcInput[6],8,0) << 4) | XN_TAKE_BITS(pcInput[7],4,4); shift[5] = (XN_TAKE_BITS(pcInput[7],4,0) << 8) | XN_TAKE_BITS(pcInput[8],8,0); shift[6] = (XN_TAKE_BITS(pcInput[9],8,0) << 4) | XN_TAKE_BITS(pcInput[10],4,4); shift[7] = (XN_TAKE_BITS(pcInput[10],4,0) << 8) | XN_TAKE_BITS(pcInput[11],8,0); shift[8] = (XN_TAKE_BITS(pcInput[12],8,0) << 4) | XN_TAKE_BITS(pcInput[13],4,4); shift[9] = (XN_TAKE_BITS(pcInput[13],4,0) << 8) | XN_TAKE_BITS(pcInput[14],8,0); shift[10] = (XN_TAKE_BITS(pcInput[15],8,0) << 4) | XN_TAKE_BITS(pcInput[16],4,4); shift[11] = (XN_TAKE_BITS(pcInput[16],4,0) << 8) | XN_TAKE_BITS(pcInput[17],8,0); shift[12] = (XN_TAKE_BITS(pcInput[18],8,0) << 4) | XN_TAKE_BITS(pcInput[19],4,4); shift[13] = (XN_TAKE_BITS(pcInput[19],4,0) << 8) | XN_TAKE_BITS(pcInput[20],8,0); shift[14] = (XN_TAKE_BITS(pcInput[21],8,0) << 4) | XN_TAKE_BITS(pcInput[22],4,4); shift[15] = (XN_TAKE_BITS(pcInput[22],4,0) << 8) | XN_TAKE_BITS(pcInput[23],8,0); pShiftOut[0] = (((shift[0]) < (XN_DEVICE_SENSOR_MAX_SHIFT_VALUE-1)) ? (shift[0]) : 0); pShiftOut[1] = (((shift[1]) < (XN_DEVICE_SENSOR_MAX_SHIFT_VALUE-1)) ? (shift[1]) : 0); pShiftOut[2] = (((shift[2]) < (XN_DEVICE_SENSOR_MAX_SHIFT_VALUE-1)) ? (shift[2]) : 0); pShiftOut[3] = (((shift[3]) < (XN_DEVICE_SENSOR_MAX_SHIFT_VALUE-1)) ? (shift[3]) : 0); pShiftOut[4] = (((shift[4]) < (XN_DEVICE_SENSOR_MAX_SHIFT_VALUE-1)) ? (shift[4]) : 0); pShiftOut[5] = (((shift[5]) < (XN_DEVICE_SENSOR_MAX_SHIFT_VALUE-1)) ? (shift[5]) : 0); pShiftOut[6] = (((shift[6]) < (XN_DEVICE_SENSOR_MAX_SHIFT_VALUE-1)) ? (shift[6]) : 0); pShiftOut[7] = (((shift[7]) < (XN_DEVICE_SENSOR_MAX_SHIFT_VALUE-1)) ? (shift[7]) : 0); pShiftOut[8] = (((shift[8]) < (XN_DEVICE_SENSOR_MAX_SHIFT_VALUE-1)) ? (shift[8]) : 0); pShiftOut[9] = (((shift[9]) < (XN_DEVICE_SENSOR_MAX_SHIFT_VALUE-1)) ? (shift[9]) : 0); pShiftOut[10] = (((shift[10]) < (XN_DEVICE_SENSOR_MAX_SHIFT_VALUE-1)) ? (shift[10]) : 0); pShiftOut[11] = (((shift[11]) < (XN_DEVICE_SENSOR_MAX_SHIFT_VALUE-1)) ? (shift[11]) : 0); pShiftOut[12] = (((shift[12]) < (XN_DEVICE_SENSOR_MAX_SHIFT_VALUE-1)) ? (shift[12]) : 0); pShiftOut[13] = (((shift[13]) < (XN_DEVICE_SENSOR_MAX_SHIFT_VALUE-1)) ? (shift[13]) : 0); pShiftOut[14] = (((shift[14]) < (XN_DEVICE_SENSOR_MAX_SHIFT_VALUE-1)) ? (shift[14]) : 0); pShiftOut[15] = (((shift[15]) < (XN_DEVICE_SENSOR_MAX_SHIFT_VALUE-1)) ? (shift[15]) : 0); pnOutput[0] = GetOutput(pShiftOut[0]); pnOutput[1] = GetOutput(pShiftOut[1]); pnOutput[2] = GetOutput(pShiftOut[2]); pnOutput[3] = GetOutput(pShiftOut[3]); pnOutput[4] = GetOutput(pShiftOut[4]); pnOutput[5] = GetOutput(pShiftOut[5]); pnOutput[6] = GetOutput(pShiftOut[6]); pnOutput[7] = GetOutput(pShiftOut[7]); pnOutput[8] = GetOutput(pShiftOut[8]); pnOutput[9] = GetOutput(pShiftOut[9]); pnOutput[10] = GetOutput(pShiftOut[10]); pnOutput[11] = GetOutput(pShiftOut[11]); pnOutput[12] = GetOutput(pShiftOut[12]); pnOutput[13] = GetOutput(pShiftOut[13]); pnOutput[14] = GetOutput(pShiftOut[14]); pnOutput[15] = GetOutput(pShiftOut[15]); #else // input: 0, 1,2 (X8) // -,---,- // bits: 8,4,4,8 (X8) // ---,--- // output: 0, 1 (X8) // Split 24 bytes into 3 vectors (64 bit each) inD3 = vld3_u8(pcInput); // rshft4D0 contains 4 MSB of second vector (placed at offset 0) rshft4D = vshr_n_u8(inD3.val[1], 4); // lshft4D0 contains 4 LSB of second vector (placed at offset 4) lshft4D = vshl_n_u8(inD3.val[1], 4); // Expand 64 bit vectors to 128 bit (8 values of 16 bits) shiftQ2.val[0] = vmovl_u8(inD3.val[0]); shiftQ2.val[1] = vmovl_u8(inD3.val[2]); rshft4Q = vmovl_u8(rshft4D); lshft4Q = vmovl_u8(lshft4D); // Even indexed shift = 8 bits from first vector + 4 MSB bits of second vector shiftQ2.val[0] = vshlq_n_u16(shiftQ2.val[0], 4); shiftQ2.val[0] = vorrq_u16(shiftQ2.val[0], rshft4Q); // Odd indexed shift = 4 LSB bits of second vector + 8 bits from third vector lshft4Q = vshlq_n_u16(lshft4Q, 4); shiftQ2.val[1] = vorrq_u16(shiftQ2.val[1], lshft4Q); // Interleave shift values to a single vector vst2q_u16(shift, shiftQ2); shift[0] = (((shift[0]) < (XN_DEVICE_SENSOR_MAX_SHIFT_VALUE-1)) ? (shift[0]) : 0); shift[1] = (((shift[1]) < (XN_DEVICE_SENSOR_MAX_SHIFT_VALUE-1)) ? (shift[1]) : 0); shift[2] = (((shift[2]) < (XN_DEVICE_SENSOR_MAX_SHIFT_VALUE-1)) ? (shift[2]) : 0); shift[3] = (((shift[3]) < (XN_DEVICE_SENSOR_MAX_SHIFT_VALUE-1)) ? (shift[3]) : 0); shift[4] = (((shift[4]) < (XN_DEVICE_SENSOR_MAX_SHIFT_VALUE-1)) ? (shift[4]) : 0); shift[5] = (((shift[5]) < (XN_DEVICE_SENSOR_MAX_SHIFT_VALUE-1)) ? (shift[5]) : 0); shift[6] = (((shift[6]) < (XN_DEVICE_SENSOR_MAX_SHIFT_VALUE-1)) ? (shift[6]) : 0); shift[7] = (((shift[7]) < (XN_DEVICE_SENSOR_MAX_SHIFT_VALUE-1)) ? (shift[7]) : 0); shift[8] = (((shift[8]) < (XN_DEVICE_SENSOR_MAX_SHIFT_VALUE-1)) ? (shift[8]) : 0); shift[9] = (((shift[9]) < (XN_DEVICE_SENSOR_MAX_SHIFT_VALUE-1)) ? (shift[9]) : 0); shift[10] = (((shift[10]) < (XN_DEVICE_SENSOR_MAX_SHIFT_VALUE-1)) ? (shift[10]) : 0); shift[11] = (((shift[11]) < (XN_DEVICE_SENSOR_MAX_SHIFT_VALUE-1)) ? (shift[11]) : 0); shift[12] = (((shift[12]) < (XN_DEVICE_SENSOR_MAX_SHIFT_VALUE-1)) ? (shift[12]) : 0); shift[13] = (((shift[13]) < (XN_DEVICE_SENSOR_MAX_SHIFT_VALUE-1)) ? (shift[13]) : 0); shift[14] = (((shift[14]) < (XN_DEVICE_SENSOR_MAX_SHIFT_VALUE-1)) ? (shift[14]) : 0); shift[15] = (((shift[15]) < (XN_DEVICE_SENSOR_MAX_SHIFT_VALUE-1)) ? (shift[15]) : 0); depth[0] = GetOutput(shift[0]); depth[1] = GetOutput(shift[1]); depth[2] = GetOutput(shift[2]); depth[3] = GetOutput(shift[3]); depth[4] = GetOutput(shift[4]); depth[5] = GetOutput(shift[5]); depth[6] = GetOutput(shift[6]); depth[7] = GetOutput(shift[7]); // Load depthQ = vld1q_u16(depth); //Store vst1q_u16(pnOutput, depthQ); // Load depthQ = vld1q_u16(shift); // Store vst1q_u16(pShiftOut, depthQ); depth[8] = GetOutput(shift[8]); depth[9] = GetOutput(shift[9]); depth[10] = GetOutput(shift[10]); depth[11] = GetOutput(shift[11]); depth[12] = GetOutput(shift[12]); depth[13] = GetOutput(shift[13]); depth[14] = GetOutput(shift[14]); depth[15] = GetOutput(shift[15]); // Load depthQ = vld1q_u16(depth + 8); // Store vst1q_u16(pnOutput + 8, depthQ); // Load depthQ = vld1q_u16(shift + 8); // Store vst1q_u16(pShiftOut + 8, depthQ); #endif pcInput += XN_INPUT_ELEMENT_SIZE; pnOutput += 16; pShiftOut += 16; } *pnActualRead = (XnUInt32)(pcInput - pOrigInput); pWriteBuffer->UnsafeUpdateSize(nNeededOutput); return XN_STATUS_OK; }
//---------------------------------------------------------------------------- bool FxCompiler::Process (const Program& program, InputArray& inputs, OutputArray& outputs, ConstantArray& constants, SamplerArray& samplers) { // Variable lines are one of the following: // var TYPE NAME : $vin.SEMANTIC : inputType : index : 1 // var TYPE NAME : $vout.SEMANTIC : outputType : index : 1 // var TYPE NAME : : c[REGISTER] : index : 1 // var TYPE NAME : : c[REGISTER], NUMREG : index : 1 // var TYPE NAME : : texunit UNITNUMBER : -1 : 1 // The last field is "used", a value of "0" or "1". However, the parser // stored in 'program' only those variables with a used value "1". The // all-capitals identifiers are needed by the Wild Magic FX system. TokenArrays::const_iterator iter = program.Variables.begin(); TokenArrays::const_iterator end = program.Variables.end(); for (/**/; iter != end; ++iter) { const TokenArray& tokens = *iter; // The token array has 10 or 11 tokens. if (tokens.size() < 10 || tokens.size() > 11) { ReportError("Invalid number of tokens", &tokens); return false; } // Get the variable type. Shader::VariableType vartype = Shader::VT_NONE; Shader::SamplerType samtype = Shader::ST_NONE; std::string::size_type begin = tokens[1].find("sampler", 0); if (begin != std::string::npos) { SamplerTypeMap::iterator iter = mSamplerTypes.find(tokens[1]); if (iter == mSamplerTypes.end()) { ReportError("Invalid sampler type", &tokens); return false; } samtype = iter->second; } else { VariableTypeMap::iterator iter = mVariableTypes.find(tokens[1]); if (iter == mVariableTypes.end()) { ReportError("Invalid variable type", &tokens); return false; } vartype = iter->second; } // Get the variable name. std::string name = tokens[2]; // Test whether the variable is a singleton or was declared as an // array. If it is an array, we need to determine how many registers // it uses. This requires processing variable lines with the same // variable index. bool varArray; begin = name.find("[", 0); if (begin != std::string::npos) { varArray = true; name = name.substr(0, begin); // strip off "[register]" } else { varArray = false; } // Get the separator before the classifier. if (tokens[3] != ":") { ReportError("Expecting separator character at index 3", &tokens); return false; } // Get the classifier. begin = tokens[4].find("$vin.", 0); if (begin != std::string::npos) { // The variable is a shader input. if (!GetInput(tokens, name, vartype, inputs)) { return false; } continue; } begin = tokens[4].find("$vout.", 0); if (begin != std::string::npos) { // The variable is a shader output. if (!GetOutput(tokens, name, vartype, outputs)) { return false; } continue; } if (tokens[4] == ":") { begin = tokens[1].find("sampler", 0); if (begin != std::string::npos) { // The variable is a shader sampler. if (!GetSampler(tokens, name, samtype, samplers)) { return false; } } else { // The variable is a shader constant. if (varArray) { if (constants.size() > 0 && name == constants.back().Name) { // This is another occurrence of the array variable. // Just increment the register count. ++constants.back().NumRegistersUsed; } else { // Create the constant with the first occurrence of // the array variable. if (!GetConstant(tokens, name, vartype, constants)) { return false; } } } else { if (!GetConstant(tokens, name, vartype, constants)) { return false; } } } continue; } ReportError("Failed to find classifier", &tokens); return false; } return true; }
PhraseDictionary* PhraseDictionaryFeature::LoadPhraseTable(const TranslationSystem* system) { const StaticData& staticData = StaticData::Instance(); if (m_implementation == Memory) { // memory phrase table VERBOSE(2,"using standard phrase tables" << std::endl); if (!FileExists(m_filePath) && FileExists(m_filePath + ".gz")) { m_filePath += ".gz"; VERBOSE(2,"Using gzipped file" << std::endl); } if (staticData.GetInputType() != SentenceInput) { UserMessage::Add("Must use binary phrase table for this input type"); CHECK(false); } PhraseDictionaryMemory* pdm = new PhraseDictionaryMemory(m_numScoreComponent,this); bool ret = pdm->Load(GetInput(), GetOutput() , m_filePath , m_weight , m_tableLimit , system->GetLanguageModels() , system->GetWeightWordPenalty()); CHECK(ret); return pdm; } else if (m_implementation == Binary) { PhraseDictionaryTreeAdaptor* pdta = new PhraseDictionaryTreeAdaptor(m_numScoreComponent, m_numInputScores,this); bool ret = pdta->Load( GetInput() , GetOutput() , m_filePath , m_weight , m_tableLimit , system->GetLanguageModels() , system->GetWeightWordPenalty()); CHECK(ret); return pdta; } else if (m_implementation == SCFG || m_implementation == Hiero) { // memory phrase table if (m_implementation == Hiero) { VERBOSE(2,"using Hiero format phrase tables" << std::endl); } else { VERBOSE(2,"using Moses-formatted SCFG phrase tables" << std::endl); } if (!FileExists(m_filePath) && FileExists(m_filePath + ".gz")) { m_filePath += ".gz"; VERBOSE(2,"Using gzipped file" << std::endl); } RuleTableTrie *dict; if (staticData.GetParsingAlgorithm() == ParseScope3) { dict = new RuleTableUTrie(m_numScoreComponent, this); } else { dict = new PhraseDictionarySCFG(m_numScoreComponent, this); } bool ret = dict->Load(GetInput() , GetOutput() , m_filePath , m_weight , m_tableLimit , system->GetLanguageModels() , system->GetWordPenaltyProducer()); assert(ret); return dict; } else if (m_implementation == ALSuffixArray) { // memory phrase table VERBOSE(2,"using Hiero format phrase tables" << std::endl); if (!FileExists(m_filePath) && FileExists(m_filePath + ".gz")) { m_filePath += ".gz"; VERBOSE(2,"Using gzipped file" << std::endl); } PhraseDictionaryALSuffixArray* pdm = new PhraseDictionaryALSuffixArray(m_numScoreComponent,this); bool ret = pdm->Load(GetInput() , GetOutput() , m_filePath , m_weight , m_tableLimit , system->GetLanguageModels() , system->GetWordPenaltyProducer()); CHECK(ret); return pdm; } else if (m_implementation == OnDisk) { PhraseDictionaryOnDisk* pdta = new PhraseDictionaryOnDisk(m_numScoreComponent, this); bool ret = pdta->Load(GetInput() , GetOutput() , m_filePath , m_weight , m_tableLimit , system->GetLanguageModels() , system->GetWordPenaltyProducer()); CHECK(ret); return pdta; } else if (m_implementation == SuffixArray) { #ifndef WIN32 PhraseDictionaryDynSuffixArray *pd = new PhraseDictionaryDynSuffixArray(m_numScoreComponent, this); if(!(pd->Load( GetInput() ,GetOutput() ,m_filePath ,m_targetFile , m_alignmentsFile , m_weight, m_tableLimit , system->GetLanguageModels() , system->GetWeightWordPenalty()))) { std::cerr << "FAILED TO LOAD\n" << endl; delete pd; pd = NULL; } std::cerr << "Suffix array phrase table loaded" << std::endl; return pd; #else CHECK(false); #endif } else if (m_implementation == FuzzyMatch) { PhraseDictionaryFuzzyMatch *dict = new PhraseDictionaryFuzzyMatch(m_numScoreComponent, this); bool ret = dict->Load(GetInput() , GetOutput() , m_filePath , m_weight , m_tableLimit , system->GetLanguageModels() , system->GetWordPenaltyProducer()); assert(ret); return dict; } else if (m_implementation == Compact) { #ifndef WIN32 VERBOSE(2,"Using compact phrase table" << std::endl); PhraseDictionaryCompact* pd = new PhraseDictionaryCompact(m_numScoreComponent, m_implementation, this); bool ret = pd->Load(GetInput(), GetOutput() , m_filePath , m_weight , m_tableLimit , system->GetLanguageModels() , system->GetWeightWordPenalty()); assert(ret); return pd; #else CHECK(false); #endif } else { std::cerr << "Unknown phrase table type " << m_implementation << endl; CHECK(false); } }
void avtOriginatingDatasetSource::MergeExtents(vtkDataSet *ds) { if (ds == NULL) { return; } avtDataAttributes &atts = GetOutput()->GetInfo().GetAttributes(); if (atts.GetTrueSpatialExtents()->HasExtents() == false) { double bounds[6]; if (ds->GetFieldData()->GetArray("avtOriginalBounds") != NULL) { vtkDataArray *arr = ds->GetFieldData()->GetArray("avtOriginalBounds"); for (int i = 0 ; i < 6 ; i++) bounds[i] = arr->GetTuple1(i); } else { ds->GetBounds(bounds); } double dbounds[6]; dbounds[0] = bounds[0]; dbounds[1] = bounds[1]; dbounds[2] = bounds[2]; dbounds[3] = bounds[3]; dbounds[4] = bounds[4]; dbounds[5] = bounds[5]; atts.GetCumulativeTrueSpatialExtents()->Merge(dbounds); } int nvars = atts.GetNumberOfVariables(); // We will probably use only 2 of the 6. But this avoids a UMR where // the avtExtents object copies 6 values for vectors (even though it only // uses the first 2 -- but that's a bigger battle.) double dextents[6] = { FLT_MAX, -FLT_MAX, FLT_MAX, -FLT_MAX, FLT_MAX, -FLT_MAX }; for (int i = 0 ; i < nvars ; i++) { const char *vname = atts.GetVariableName(i).c_str(); if (atts.GetTrueDataExtents(vname)->HasExtents()) { // // There is no point in walking through the data and determining // what the cumulative extents are -- we know them already. // continue; } bool ignoreGhost = true; GetDataRange(ds, dextents, vname, true); atts.GetCumulativeTrueDataExtents(vname)->Merge(dextents); if (atts.GetVariableType(vname) == AVT_ARRAY_VAR) { double *compExt = new double[atts.GetVariableDimension(vname)*2]; GetDataAllComponentsRange(ds, compExt, vname, true); atts.GetVariableComponentExtents(vname)->Merge(compExt); delete[] compExt; } } }
void CCommandLineDisplay::Update (void) // Update // // Update the buffer { if (!m_bInvalid || m_pFonts == NULL || m_pFonts->Console.GetHeight() == 0 || m_pFonts->Console.GetAverageWidth() == 0) return; // If we don't yet have a buffer, create one if (m_Buffer.IsEmpty()) { m_Buffer.Create(RectWidth(m_rcRect), RectHeight(m_rcRect)); //m_Buffer.SetBlending(220); } // Clear int cxWidth = RectWidth(m_rcRect); int cyHeight = RectHeight(m_rcRect); m_Buffer.Set(BACK_COLOR); CG32bitPixel rgbColor = CG32bitPixel(0, 160, 221); CG32bitPixel rgbFadeColor = CG32bitPixel(0, 80, 110); // Outline the box m_Buffer.DrawLine(0, 0, cxWidth - 1, 0, 1, rgbColor); CGDraw::LineGradient(m_Buffer, 0, 0, 0, cyHeight - 1, 1, rgbColor, rgbFadeColor); CGDraw::LineGradient(m_Buffer, cxWidth - 1, 0, cxWidth - 1, cyHeight - 1, 1, rgbColor, rgbFadeColor); m_Buffer.DrawLine(0, cyHeight - 1, cxWidth, cyHeight - 1, 1, rgbFadeColor); // Figure out how many lines and columns we can display int cyLine = m_pFonts->Console.GetHeight(); int iLines = (cyHeight - (TOP_SPACING + BOTTOM_SPACING)) / cyLine; iLines = Max(1, iLines); int cxCol = m_pFonts->Console.GetAverageWidth(); int iCols = (cxWidth - (LEFT_SPACING + RIGHT_SPACING)) / cxCol; iCols = Max(1, iCols); // Figure out how many lines we need for input int iInputCols = m_sInput.GetLength() + 1; int iInputLines = (iInputCols / iCols) + ((iInputCols % iCols) ? 1 : 0); // Figure out how many lines we need for the hint TArray<CString> HintLines; m_pFonts->Console.BreakText(m_sHint, (RectWidth(m_rcRect) - (LEFT_SPACING + RIGHT_SPACING)), &HintLines); int iHintLines = HintLines.GetCount(); // Figure out how many lines in the output int iOutputLines = GetOutputCount(); // Paint from the bottom up int iTotalLines = Min(iLines, iInputLines + iHintLines + iOutputLines); int x = LEFT_SPACING; int yMin = TOP_SPACING; int y = yMin + (iTotalLines - 1) * cyLine; // Paint the input line int iRemainder = iInputCols % iCols; int iRemainderText = (iRemainder == 0 ? iCols : iRemainder) - 1; int iStart = m_sInput.GetLength() - iRemainderText; while (y >= yMin && iStart >= 0) { CString sLine(m_sInput.GetASCIIZPointer() + iStart, iRemainderText); m_Buffer.DrawText(x, y, m_pFonts->Console, INPUT_COLOR, sLine); // Work out where the cursor should be if (m_iCursorPos >= iStart && (m_iCursorPos - iStart) < iCols) { m_rcCursor.left = x + (m_iCursorPos-iStart) * cxCol; m_rcCursor.top = y; m_rcCursor.right = m_rcCursor.left + cxCol; m_rcCursor.bottom = m_rcCursor.top + cyLine; } y -= cyLine; iStart -= iCols; iRemainderText = iCols; } // Work out how much we can scroll the display m_iScrollPos = Min(m_iScrollPos, iInputLines+iHintLines+iOutputLines - iTotalLines); int iScroll = m_iScrollPos; // Paint the hint line while (y >= yMin && iHintLines > 0) { if (iScroll <= 0) { m_Buffer.DrawText(x, y, m_pFonts->Console, HINT_COLOR, HintLines[iHintLines - 1]); y -= cyLine; } else iScroll--; iHintLines--; } // Paint each line of output int iLine = 0; while (y >= yMin && iLine < GetOutputCount()) { if (iScroll <= 0) { m_Buffer.DrawText(x, y, m_pFonts->Console, GetOutputColor(iLine), GetOutput(iLine)); y -= cyLine; } else iScroll--; iLine++; } m_bInvalid = false; }
TEST_F(ProjectionTests, TwoColumnTest) { MockExecutor child_executor; EXPECT_CALL(child_executor, DInit()).WillOnce(Return(true)); EXPECT_CALL(child_executor, DExecute()) .WillOnce(Return(true)) .WillOnce(Return(false)); size_t tile_size = 5; // Create a table and wrap it in logical tile auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(); auto txn = txn_manager.BeginTransaction(); std::unique_ptr<storage::DataTable> data_table( ExecutorTestsUtil::CreateTable(tile_size)); ExecutorTestsUtil::PopulateTable(data_table.get(), tile_size, false, false, false, txn); txn_manager.CommitTransaction(txn); std::unique_ptr<executor::LogicalTile> source_logical_tile1( executor::LogicalTileFactory::WrapTileGroup(data_table->GetTileGroup(0))); EXPECT_CALL(child_executor, GetOutput()) .WillOnce(Return(source_logical_tile1.release())); // Create the plan node TargetList target_list; DirectMapList direct_map_list; ///////////////////////////////////////////////////////// // PROJECTION 3, 1, 3 ///////////////////////////////////////////////////////// // construct schema std::vector<catalog::Column> columns; auto orig_schema = data_table.get()->GetSchema(); columns.push_back(orig_schema->GetColumn(3)); columns.push_back(orig_schema->GetColumn(1)); columns.push_back(orig_schema->GetColumn(3)); std::shared_ptr<const catalog::Schema> schema(new catalog::Schema(columns)); // direct map DirectMap map0 = std::make_pair(0, std::make_pair(0, 3)); DirectMap map1 = std::make_pair(1, std::make_pair(0, 1)); DirectMap map2 = std::make_pair(2, std::make_pair(0, 3)); direct_map_list.push_back(map0); direct_map_list.push_back(map1); direct_map_list.push_back(map2); std::unique_ptr<const planner::ProjectInfo> project_info( new planner::ProjectInfo(std::move(target_list), std::move(direct_map_list))); planner::ProjectionPlan node(std::move(project_info), schema); // Create and set up executor executor::ExecutorContext context(txn); executor::ProjectionExecutor executor(&node, &context); executor.AddChild(&child_executor); RunTest(executor, 1); }
void avtCoordSystemConvert::UpdateDataObjectInfo(void) { avtDataAttributes &inAtts = GetInput()->GetInfo().GetAttributes(); avtDataAttributes &outAtts = GetOutput()->GetInfo().GetAttributes(); if (inputSys == CARTESIAN) { if (outputSys == SPHERICAL) { if (inAtts.GetXLabel() == "X-Axis" || inAtts.GetXLabel() == "X Axis") outAtts.SetXLabel("Radius"); else outAtts.SetXLabel(std::string("Radius / ") + inAtts.GetXLabel()); if (inAtts.GetYLabel() == "Y-Axis" || inAtts.GetYLabel() == "Y Axis") outAtts.SetYLabel("Theta"); else outAtts.SetYLabel(std::string("Theta / ") + inAtts.GetYLabel()); if (inAtts.GetZLabel() == "Z-Axis" || inAtts.GetZLabel() == "Z Axis") outAtts.SetZLabel("Phi"); else outAtts.SetZLabel(std::string("Phi / ") + inAtts.GetZLabel()); } else if (outputSys == CYLINDRICAL) { if (inAtts.GetXLabel() == "X-Axis" || inAtts.GetXLabel() == "X Axis") outAtts.SetXLabel("Radius"); else outAtts.SetXLabel(std::string("Radius / ") + inAtts.GetXLabel()); if (inAtts.GetYLabel() == "Y-Axis" || inAtts.GetYLabel() == "Y Axis") outAtts.SetYLabel("Theta"); else outAtts.SetYLabel(std::string("Theta / ") + inAtts.GetYLabel()); if (inAtts.GetZLabel() == "Z-Axis" || inAtts.GetZLabel() == "Z Axis") outAtts.SetZLabel("Height"); else outAtts.SetZLabel(std::string("Height / ") + inAtts.GetZLabel()); } } if (outputSys == SPHERICAL) { outAtts.SetYUnits("radians"); outAtts.SetZUnits("radians"); } else if (outputSys == CYLINDRICAL) { outAtts.SetYUnits("radians"); } GetOutput()->GetInfo().GetValidity().SetPointsWereTransformed(true); GetOutput()->GetInfo().GetValidity().InvalidateSpatialMetaData(); }
TEST_F(ProjectionTests, BasicTargetTest) { MockExecutor child_executor; EXPECT_CALL(child_executor, DInit()).WillOnce(Return(true)); EXPECT_CALL(child_executor, DExecute()) .WillOnce(Return(true)) .WillOnce(Return(false)); size_t tile_size = 5; // Create a table and wrap it in logical tile auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(); auto txn = txn_manager.BeginTransaction(); std::unique_ptr<storage::DataTable> data_table( ExecutorTestsUtil::CreateTable(tile_size)); ExecutorTestsUtil::PopulateTable(data_table.get(), tile_size, false, false, false, txn); txn_manager.CommitTransaction(txn); std::unique_ptr<executor::LogicalTile> source_logical_tile1( executor::LogicalTileFactory::WrapTileGroup(data_table->GetTileGroup(0))); EXPECT_CALL(child_executor, GetOutput()) .WillOnce(Return(source_logical_tile1.release())); // Create the plan node TargetList target_list; DirectMapList direct_map_list; ///////////////////////////////////////////////////////// // PROJECTION 0, TARGET 0 + 20 ///////////////////////////////////////////////////////// // construct schema std::vector<catalog::Column> columns; auto orig_schema = data_table.get()->GetSchema(); columns.push_back(orig_schema->GetColumn(0)); columns.push_back(orig_schema->GetColumn(0)); std::shared_ptr<const catalog::Schema> schema(new catalog::Schema(columns)); // direct map DirectMap direct_map = std::make_pair(0, std::make_pair(0, 0)); direct_map_list.push_back(direct_map); // target list auto const_val = new expression::ConstantValueExpression( type::ValueFactory::GetIntegerValue(20)); auto tuple_value_expr = expression::ExpressionUtil::TupleValueFactory(type::Type::INTEGER, 0, 0); expression::AbstractExpression *expr = expression::ExpressionUtil::OperatorFactory(EXPRESSION_TYPE_OPERATOR_PLUS, type::Type::INTEGER, tuple_value_expr, const_val); Target target = std::make_pair(1, expr); target_list.push_back(target); std::unique_ptr<const planner::ProjectInfo> project_info( new planner::ProjectInfo(std::move(target_list), std::move(direct_map_list))); planner::ProjectionPlan node(std::move(project_info), schema); // Create and set up executor executor::ProjectionExecutor executor(&node, nullptr); executor.AddChild(&child_executor); RunTest(executor, 1); }
void AwesomeView::ProcessSelectedImage() { // Before we even think about processing something, we need to make sure // that we have valid input. Don't be sloppy, this is a main reason // for application crashes if neglected. auto selectedDataNodes = this->GetDataManagerSelection(); if (selectedDataNodes.empty()) return; auto firstSelectedDataNode = selectedDataNodes.front(); if (firstSelectedDataNode.IsNull()) { QMessageBox::information(nullptr, "Awesome View", "Please load and select an image before starting image processing."); return; } auto data = firstSelectedDataNode->GetData(); // Something is selected, but does it contain data? if (data != nullptr) { // We don't use the auto keyword here, which would evaluate to a native // image pointer. Instead, we want a smart pointer in order to ensure that // the image isn't deleted somewhere else while we're using it. mitk::Image::Pointer image = dynamic_cast<mitk::Image*>(data); // Something is selected and it contains data, but is it an image? if (image.IsNotNull()) { auto imageName = firstSelectedDataNode->GetName(); auto offset = m_Controls.offsetSpinBox->value(); MITK_INFO << "Process image \"" << imageName << "\" ..."; // We're finally using the AwesomeImageFilter from our AwesomeLib module. auto filter = AwesomeImageFilter::New(); filter->SetInput(image); filter->SetOffset(offset); filter->Update(); mitk::Image::Pointer processedImage = filter->GetOutput(); if (processedImage.IsNull() || !processedImage->IsInitialized()) return; MITK_INFO << " done"; // Stuff the resulting image into a data node, set some properties, // and add it to the data storage, which will eventually display the // image in the application. auto processedImageDataNode = mitk::DataNode::New(); processedImageDataNode->SetData(processedImage); QString name = QString("%1 (Offset: %2)").arg(imageName.c_str()).arg(offset); processedImageDataNode->SetName(name.toStdString()); // We don't really need to copy the level window, but if we wouldn't // do it, the new level window would be initialized to display the image // with optimal contrast in order to capture the whole range of pixel // values. This is also true for the input image as long as one didn't // modify its level window manually. Thus, the images would appear // identical unless you compare the level window widget for both images. mitk::LevelWindow levelWindow; if (firstSelectedDataNode->GetLevelWindow(levelWindow)) processedImageDataNode->SetLevelWindow(levelWindow); // We also attach our AwesomeImageInteractor, which allows us to paint // on the resulting images by using the mouse as long as the CTRL key // is pressed. auto interactor = CreateAwesomeImageInteractor(); if (interactor.IsNotNull()) interactor->SetDataNode(processedImageDataNode); this->GetDataStorage()->Add(processedImageDataNode); } } // Now it's your turn. This class/method has lots of room for improvements, // for example: // // - What happens when multiple items are selected but the first one isn't // an image? - There isn't any feedback for the user at all. // - What's the front item of a selection? Does it depend on the order // of selection or the position in the Data Manager? - Isn't it // better to process all selected images? Don't forget to adjust the // titles of the UI widgets. // - In addition to the the displayed label, it's probably a good idea to // enable or disable the button depending on the selection. }
int main(int argc, char **argv) { args::ArgumentParser parser("Generates masks in stages.\n" "Stage 1 - Otsu thresholding to generate binary mask\n" "Stage 2 - RATs (optional)\n" "Stage 3 - Hole filling (optional)\n" "http://github.com/spinicist/QUIT"); args::Positional<std::string> input_path(parser, "INPUT_FILE", "Input file"); args::HelpFlag help(parser, "HELP", "Show this help menu", {'h', "help"}); args::Flag verbose(parser, "VERBOSE", "Print more information", {'v', "verbose"}); args::ValueFlag<std::string> outarg( parser, "OUTPUT FILE", "Set output filename, default is input + _mask", {'o', "out"}); args::ValueFlag<int> volume( parser, "VOLUME", "Choose volume to mask in multi-volume file. Default 1, -1 selects last volume", {'v', "volume"}, 0); args::Flag is_complex(parser, "COMPLEX", "Input data is complex, take magnitude first", {'x', "complex"}); args::ValueFlag<float> lower_threshold( parser, "LOWER THRESHOLD", "Specify lower intensity threshold for 1st stage, otherwise Otsu's method is used", {'l', "lower"}, 0.); args::ValueFlag<float> upper_threshold( parser, "UPPER THRESHOLD", "Specify upper intensity threshold for 1st stage, otherwise Otsu's method is used", {'u', "upper"}, std::numeric_limits<float>::infinity()); args::ValueFlag<float> rats( parser, "RATS", "Perform the RATS step, argument is size threshold for connected component", {'r', "rats"}, 0.); args::ValueFlag<int> fillh_radius( parser, "FILL HOLES", "Fill holes in thresholded mask with radius N", {'F', "fillh"}, 0); QI::ParseArgs(parser, argc, argv, verbose); QI::SeriesF::Pointer vols = ITK_NULLPTR; if (is_complex) { vols = QI::ReadMagnitudeImage<QI::SeriesF>(QI::CheckPos(input_path), verbose); } else { vols = QI::ReadImage<QI::SeriesF>(QI::CheckPos(input_path), verbose); } std::string out_path; if (outarg.Get() == "") { out_path = QI::StripExt(input_path.Get()) + "_mask" + QI::OutExt(); } else { out_path = outarg.Get(); } // Extract one volume to process auto region = vols->GetLargestPossibleRegion(); if (static_cast<size_t>(std::abs(volume.Get())) < region.GetSize()[3]) { int volume_to_get = (region.GetSize()[3] + volume.Get()) % region.GetSize()[3]; QI::Log(verbose, "Masking volume {}...", volume_to_get); region.GetModifiableIndex()[3] = volume_to_get; } else { QI::Fail("Specified mask volume was invalid {} ", volume.Get()); } region.GetModifiableSize()[3] = 0; auto vol = itk::ExtractImageFilter<QI::SeriesF, QI::VolumeF>::New(); vol->SetExtractionRegion(region); vol->SetInput(vols); vol->SetDirectionCollapseToSubmatrix(); vol->Update(); QI::VolumeF::Pointer intensity_image = vol->GetOutput(); intensity_image->DisconnectPipeline(); /* * Stage 1 - Otsu or Threshold */ QI::VolumeI::Pointer mask_image = ITK_NULLPTR; if (lower_threshold || upper_threshold) { QI::Log(verbose, "Thresholding range: {}-{}", lower_threshold.Get(), upper_threshold.Get()); mask_image = QI::ThresholdMask(intensity_image, lower_threshold.Get(), upper_threshold.Get()); } else { QI::Log(verbose, "Generating Otsu mask"); mask_image = QI::OtsuMask(intensity_image); } /* * Stage 2 - RATS */ if (rats) { typedef itk::BinaryBallStructuringElement<int, 3> TBall; typedef itk::BinaryErodeImageFilter<QI::VolumeI, QI::VolumeI, TBall> TErode; typedef itk::BinaryDilateImageFilter<QI::VolumeI, QI::VolumeI, TBall> TDilate; float mask_volume = std::numeric_limits<float>::infinity(); float voxel_volume = QI::VoxelVolume(mask_image); QI::Log(verbose, "Voxel volume: {}", voxel_volume); int radius = 0; QI::VolumeI::Pointer mask_rats; while (mask_volume > rats.Get()) { radius++; TBall ball; TBall::SizeType radii; radii.Fill(radius); ball.SetRadius(radii); ball.CreateStructuringElement(); TErode::Pointer erode = TErode::New(); erode->SetInput(mask_image); erode->SetForegroundValue(1); erode->SetBackgroundValue(0); erode->SetKernel(ball); erode->Update(); std::vector<float> kept_sizes = QI::FindLabels(erode->GetOutput(), 0, 1, mask_rats); mask_volume = kept_sizes[0] * voxel_volume; auto dilate = TDilate::New(); dilate->SetKernel(ball); dilate->SetInput(mask_rats); dilate->SetForegroundValue(1); dilate->SetBackgroundValue(0); dilate->Update(); mask_rats = dilate->GetOutput(); mask_rats->DisconnectPipeline(); QI::Log(verbose, "Ran RATS iteration, radius = {} volume = {}", radius, mask_volume); } mask_image = mask_rats; } /* * Stage 3 - Hole Filling */ QI::VolumeI::Pointer finalMask = ITK_NULLPTR; if (fillh_radius) { QI::Log(verbose, "Filling holes"); auto fillHoles = itk::VotingBinaryIterativeHoleFillingImageFilter<QI::VolumeI>::New(); itk::VotingBinaryIterativeHoleFillingImageFilter<QI::VolumeI>::InputSizeType radius; radius.Fill(fillh_radius.Get()); fillHoles->SetInput(mask_image); fillHoles->SetRadius(radius); fillHoles->SetMajorityThreshold(2); // Corresponds to (rad^3-1)/2 + 2 threshold fillHoles->SetBackgroundValue(0); fillHoles->SetForegroundValue(1); fillHoles->SetMaximumNumberOfIterations(3); fillHoles->Update(); mask_image = fillHoles->GetOutput(); mask_image->DisconnectPipeline(); } QI::WriteImage(mask_image, out_path, verbose); QI::Log(verbose, "Finished."); return EXIT_SUCCESS; }
void avtResampleFilter::ResampleInput(void) { int i, j, k; avtDataset_p output = GetTypedOutput(); double bounds[6] = { 0, 0, 0, 0, 0, 0 }; bool is3D = GetBounds(bounds); debug4 << "Resampling over space: " << bounds[0] << ", " << bounds[1] << ": " << bounds[2] << ", " << bounds[3] << ": " << bounds[4] << ", " << bounds[5] << endl; // // Our resampling leaves some invalid values in the data range. The // easiest way to bypass this is to get the data range from the input and // pass it along (since resampling does not change it in theory). // double range[2]; if (GetInput()->GetInfo().GetAttributes().ValidActiveVariable()) { GetDataExtents(range); output->GetInfo().GetAttributes().GetDesiredDataExtents()->Set(range); } avtViewInfo view; double scale[3]; CreateViewFromBounds(view, bounds, scale); // // What we want the width, height, and depth to be depends on the // attributes. // int width, height, depth; GetDimensions(width, height, depth, bounds, is3D); // // If there are no variables, then just create the mesh and exit. // bool thereAreNoVariables = (GetInput()->GetInfo().GetAttributes().GetNumberOfVariables() <= 0); if (thereAreNoVariables) { if (PAR_Rank() == 0) { vtkRectilinearGrid *rg = CreateGrid(bounds, width, height, depth, 0, width, 0, height, cellCenteredOutput, is3D); avtDataTree_p tree = new avtDataTree(rg, 0); rg->Delete(); SetOutputDataTree(tree); } else { // // Putting in a NULL data tree can lead to seg faults, etc. // avtDataTree_p dummy = new avtDataTree(); SetOutputDataTree(dummy); } return; } // // World space is a right-handed coordinate system. Image space (as used // in the sample point extractor) is a left-handed coordinate system. // This is because large X is at the right and large Y is at the top. // The z-buffer has the closest points at z=0, so Z is going away from the // screen ===> left handed coordinate system. If we reflect across X, // then this will account for the difference between the coordinate // systems. // scale[0] *= -1.; // // We don't want an Update to go all the way up the pipeline, so make // a terminating source corresponding to our input. // avtDataset_p ds; avtDataObject_p dObj = GetInput(); CopyTo(ds, dObj); avtSourceFromAVTDataset termsrc(ds); // // The sample point extractor expects everything to be in image space. // avtWorldSpaceToImageSpaceTransform trans(view, scale); trans.SetInput(termsrc.GetOutput()); bool doKernel = (GetInput()->GetInfo().GetAttributes().GetTopologicalDimension() == 0); avtSamplePointExtractor extractor(width, height, depth); extractor.SendCellsMode(false); extractor.Set3DMode(is3D); extractor.SetInput(trans.GetOutput()); if (doKernel) extractor.SetKernelBasedSampling(true); avtSamplePoints_p samples = extractor.GetTypedOutput(); // // If the selection this filter exists to create has already been handled, // or if there are no pieces for this processor to process, then we can skip // execution. But, take care to emulate the same collective // calls other processors may make before returning. // if (GetInput()->GetInfo().GetAttributes().GetSelectionApplied(selID)) { debug1 << "Bypassing Resample operator because database plugin " "claims to have applied the selection already" << endl; SetOutputDataTree(GetInputDataTree()); // we can save a lot of time if we know everyone can bypass if (UnifyMaximumValue(0) == 0) return; // here is some dummied up code to match collective calls below int effectiveVars = samples->GetNumberOfRealVariables(); double *ptrtmp = new double[width*height*depth]; for (int jj = 0; jj < width*height*depth; jj++) ptrtmp[jj] = -FLT_MAX; for (i = 0 ; i < effectiveVars ; i++) Collect(ptrtmp, width*height*depth); delete [] ptrtmp; return; } else { UnifyMaximumValue(1); } // // // PROBLEM SIZED WORK OCCURS BEYOND THIS POINT // If you add (or remove) collective calls below this point, make sure to // put matching sequence into bypass code above // // avtSamplePointCommunicator communicator; avtImagePartition partition(width, height, PAR_Size(), PAR_Rank()); communicator.SetImagePartition(&partition); bool doDistributedResample = false; #ifdef PARALLEL doDistributedResample = atts.GetDistributedResample(); #endif if (doDistributedResample) { partition.SetShouldProduceOverlaps(true); avtDataObject_p dob; CopyTo(dob, samples); communicator.SetInput(dob); samples = communicator.GetTypedOutput(); } // Always set up an arbitrator, even if user selected random. bool arbLessThan = !atts.GetUseArbitrator() || atts.GetArbitratorLessThan(); std::string arbName = atts.GetArbitratorVarName(); if (arbName == "default") arbName = primaryVariable; extractor.SetUpArbitrator(arbName, arbLessThan); // // Since this is Execute, forcing an update is okay... // samples->Update(GetGeneralContract()); if (samples->GetInfo().GetValidity().HasErrorOccurred()) { GetOutput()->GetInfo().GetValidity().ErrorOccurred(); GetOutput()->GetInfo().GetValidity().SetErrorMessage( samples->GetInfo().GetValidity().GetErrorMessage()); } // // Create a rectilinear dataset that is stretched according to the // original bounds. // int width_start = 0; int width_end = width; int height_start = 0; int height_end = height; if (doDistributedResample) { partition.GetThisPartition(width_start, width_end, height_start, height_end); width_end += 1; height_end += 1; } // // If we have more processors than domains, we have to handle that // gracefully. Communicate how many variables there are so that those // that don't have data can play well. // int realVars = samples->GetNumberOfRealVariables(); int numArrays = realVars; if (doKernel) numArrays++; vtkDataArray **vars = new vtkDataArray*[numArrays]; for (i = 0 ; i < numArrays ; i++) { vars[i] = vtkDoubleArray::New(); if (doKernel && (i == numArrays-1)) vars[i]->SetNumberOfComponents(1); else { vars[i]->SetNumberOfComponents(samples->GetVariableSize(i)); vars[i]->SetName(samples->GetVariableName(i).c_str()); } } if (doKernel) samples->GetVolume()->SetUseKernel(true); avtImagePartition *ip = NULL; if (doDistributedResample) ip = &partition; // We want all uncovered regions to get the default value. That is // what the first argument of GetVariables is for. But if the // default value is large, then it will screw up the collect call below, // which uses MPI_MAX for an all reduce. So give uncovered regions very // small values now (-FLT_MAX) and then replace them later. double defaultPlaceholder = -FLT_MAX; samples->GetVolume()->GetVariables(defaultPlaceholder, vars, numArrays, ip); if (!doDistributedResample) { // // Collect will perform the parallel collection. Does nothing in // serial. This will only be valid on processor 0. // for (i = 0 ; i < numArrays ; i++) { double *ptr = (double *) vars[i]->GetVoidPointer(0); Collect(ptr, vars[i]->GetNumberOfComponents()*width*height*depth); } } // Now replace the -FLT_MAX's with the default value. (See comment above.) for (i = 0 ; i < numArrays ; i++) { int numTups = vars[i]->GetNumberOfComponents() * vars[i]->GetNumberOfTuples(); if (numTups > 0) { double *ptr = (double *) vars[i]->GetVoidPointer(0); for (j = 0 ; j < numTups ; j++) ptr[j] = (ptr[j] == defaultPlaceholder ? atts.GetDefaultVal() : ptr[j]); } } bool iHaveData = false; if (doDistributedResample) iHaveData = true; if (PAR_Rank() == 0) iHaveData = true; if (height_end > height) iHaveData = false; if (iHaveData) { vtkRectilinearGrid *rg = CreateGrid(bounds, width, height, depth, width_start, width_end, height_start, height_end, cellCenteredOutput, is3D); if (doKernel) { double min_weight = avtPointExtractor::GetMinimumWeightCutoff(); vtkDataArray *weights = vars[numArrays-1]; int numVals = weights->GetNumberOfTuples(); for (i = 0 ; i < realVars ; i++) { for (j = 0 ; j < vars[i]->GetNumberOfComponents() ; j++) { for (k = 0 ; k < numVals ; k++) { double weight = weights->GetTuple1(k); if (weight <= min_weight) vars[i]->SetComponent(k, j, atts.GetDefaultVal()); else vars[i]->SetComponent(k, j, vars[i]->GetComponent(k, j) / weight); } } } } // // Attach these variables to our rectilinear grid. // for (i = 0 ; i < realVars ; i++) { const char *varname = vars[i]->GetName(); if (strcmp(varname, primaryVariable) == 0) { if (vars[i]->GetNumberOfComponents() == 3) if (cellCenteredOutput) rg->GetCellData()->SetVectors(vars[i]); else rg->GetPointData()->SetVectors(vars[i]); else if (vars[i]->GetNumberOfComponents() == 1) { if (cellCenteredOutput) { rg->GetCellData()->AddArray(vars[i]); rg->GetCellData()->SetScalars(vars[i]); } else { rg->GetPointData()->AddArray(vars[i]); rg->GetPointData()->SetScalars(vars[i]); } } else { if (cellCenteredOutput) rg->GetCellData()->AddArray(vars[i]); else rg->GetPointData()->AddArray(vars[i]); } } else { if (cellCenteredOutput) rg->GetCellData()->AddArray(vars[i]); else rg->GetPointData()->AddArray(vars[i]); } } avtDataTree_p tree = new avtDataTree(rg, 0); rg->Delete(); SetOutputDataTree(tree); } else { // // Putting in a NULL data tree can lead to seg faults, etc. // avtDataTree_p dummy = new avtDataTree(); SetOutputDataTree(dummy); } for (i = 0 ; i < numArrays ; i++) { vars[i]->Delete(); } delete [] vars; }
void FRCPassPostProcessVisualizeLPV::Process(FRenderingCompositePassContext& Context) { SCOPED_DRAW_EVENT(Context.RHICmdList, VisualizeLPV); const FSceneView& View = Context.View; const FSceneViewFamily& ViewFamily = *(View.Family); // const FSceneRenderTargetItem& DestRenderTarget = PassOutputs[0].RequestSurface(Context); const TRefCountPtr<IPooledRenderTarget> RenderTarget = GetInput(ePId_Input0)->GetOutput()->PooledRenderTarget; const FSceneRenderTargetItem& DestRenderTarget = RenderTarget->GetRenderTargetItem(); // Set the view family's render target/viewport. SetRenderTarget(Context.RHICmdList, DestRenderTarget.TargetableTexture, FTextureRHIRef()); { // this is a helper class for FCanvas to be able to get screen size class FRenderTargetTemp : public FRenderTarget { public: const FSceneView& View; const FTexture2DRHIRef Texture; FRenderTargetTemp(const FSceneView& InView, const FTexture2DRHIRef InTexture) : View(InView), Texture(InTexture) { } virtual FIntPoint GetSizeXY() const { return View.ViewRect.Size(); }; virtual const FTexture2DRHIRef& GetRenderTargetTexture() const { return Texture; } } TempRenderTarget(View, (const FTexture2DRHIRef&)DestRenderTarget.TargetableTexture); FCanvas Canvas(&TempRenderTarget, NULL, ViewFamily.CurrentRealTime, ViewFamily.CurrentWorldTime, ViewFamily.DeltaWorldTime, View.GetFeatureLevel()); float X = 30; float Y = 28; const float YStep = 14; const float ColumnWidth = 250; Canvas.DrawShadowedString( X, Y += YStep, TEXT("VisualizeLightPropagationVolume"), GetStatsFont(), FLinearColor(0.2f, 0.2f, 1)); Y += YStep; const FLightPropagationVolumeSettings& Dest = View.FinalPostProcessSettings.BlendableManager.GetSingleFinalDataConst<FLightPropagationVolumeSettings>(); #define ENTRY(name)\ Canvas.DrawShadowedString( X, Y += YStep, TEXT(#name) TEXT(":"), GetStatsFont(), FLinearColor(1, 1, 1));\ Canvas.DrawShadowedString( X + ColumnWidth, Y, *FString::Printf(TEXT("%g"), Dest.name), GetStatsFont(), FLinearColor(1, 1, 1)); ENTRY(LPVIntensity) ENTRY(LPVVplInjectionBias) ENTRY(LPVSize) ENTRY(LPVSecondaryOcclusionIntensity) ENTRY(LPVSecondaryBounceIntensity) ENTRY(LPVGeometryVolumeBias) ENTRY(LPVEmissiveInjectionIntensity) ENTRY(LPVDirectionalOcclusionIntensity) ENTRY(LPVDirectionalOcclusionRadius) ENTRY(LPVDiffuseOcclusionExponent) ENTRY(LPVSpecularOcclusionExponent) ENTRY(LPVDiffuseOcclusionIntensity) ENTRY(LPVSpecularOcclusionIntensity) #undef ENTRY Canvas.Flush_RenderThread(Context.RHICmdList); } Context.RHICmdList.CopyToResolveTarget(DestRenderTarget.TargetableTexture, DestRenderTarget.ShaderResourceTexture, false, FResolveParams()); // to satify following passws FRenderingCompositeOutput* Output = GetOutput(ePId_Output0); Output->PooledRenderTarget = RenderTarget; }
void GenerationDictionary::Load() { FactorCollection &factorCollection = FactorCollection::Instance(); const size_t numFeatureValuesInConfig = this->GetNumScoreComponents(); // data from file InputFileStream inFile(m_filePath); UTIL_THROW_IF2(!inFile.good(), "Couldn't read " << m_filePath); string line; size_t lineNum = 0; while(getline(inFile, line)) { ++lineNum; vector<string> token = Tokenize( line ); // add each line in generation file into class Word *inputWord = new Word(); // deleted in destructor Word outputWord; // create word with certain factors filled out // inputs vector<string> factorString = Tokenize( token[0], "|" ); for (size_t i = 0 ; i < GetInput().size() ; i++) { FactorType factorType = GetInput()[i]; const Factor *factor = factorCollection.AddFactor( Output, factorType, factorString[i]); inputWord->SetFactor(factorType, factor); } factorString = Tokenize( token[1], "|" ); for (size_t i = 0 ; i < GetOutput().size() ; i++) { FactorType factorType = GetOutput()[i]; const Factor *factor = factorCollection.AddFactor( Output, factorType, factorString[i]); outputWord.SetFactor(factorType, factor); } size_t numFeaturesInFile = token.size() - 2; if (numFeaturesInFile < numFeatureValuesInConfig) { stringstream strme; strme << m_filePath << ":" << lineNum << ": expected " << numFeatureValuesInConfig << " feature values, but found " << numFeaturesInFile << std::endl; throw strme.str(); } std::vector<float> scores(numFeatureValuesInConfig, 0.0f); for (size_t i = 0; i < numFeatureValuesInConfig; i++) scores[i] = FloorScore(TransformScore(Scan<float>(token[2+i]))); Collection::iterator iterWord = m_collection.find(inputWord); if (iterWord == m_collection.end()) { m_collection[inputWord][outputWord].Assign(this, scores); } else { // source word already in there. delete input word to avoid mem leak (iterWord->second)[outputWord].Assign(this, scores); delete inputWord; } } inFile.Close(); }
UInt32 AUEffectBase::GetNumberOfChannels() { return GetOutput(0)->GetStreamFormat().mChannelsPerFrame; }
void Output::Data( data_type* vec, data_type scale ) { for ( int i = 0; i < mLayerSize; i++ ) vec[i] = scale * GetOutput( i ); }
int main(int argc, char* argv[]) { mitkCommandLineParser parser; // Set general information about your command-line app parser.setCategory("Example Cmd App Category"); parser.setTitle("Example Cmd App"); parser.setContributor("CAMIC"); parser.setDescription( "This command-line app takes the given image and adds the provided offset to each voxel."); // How should arguments be prefixed parser.setArgumentPrefix("--", "-"); // Add arguments. Unless specified otherwise, each argument is optional. // See mitkCommandLineParser::addArgument() for more information. parser.addArgument( "input", "i", mitkCommandLineParser::InputFile, "Input Image", "Any image format known to MITK.", us::Any(), false); parser.addArgument( "output", "o", mitkCommandLineParser::OutputFile, "Output file", "Where to save the output.", us::Any(), false); parser.addArgument( "offset", "f", mitkCommandLineParser::Int, "Offset", "the offset integer to add to each voxel.", us::Any(), false); parser.addArgument( // optional "verbose", "v", mitkCommandLineParser::Bool, "Verbose Output", "Whether to produce verbose output"); // Parse arguments. This method returns a mapping of long argument names to // their values. auto parsedArgs = parser.parseArguments(argc, argv); if (parsedArgs.empty()) return EXIT_FAILURE; // Just exit, usage information was already printed. if (parsedArgs["input"].Empty() || parsedArgs["output"].Empty() || parsedArgs["offset"].Empty()) { MITK_INFO << parser.helpText(); return EXIT_FAILURE; } // Parse, cast and set required arguments auto inFilename = us::any_cast<std::string>(parsedArgs["input"]); auto outFilename = us::any_cast<std::string>(parsedArgs["output"]); auto offset = us::any_cast<int>(parsedArgs["offset"]); // Default values for optional arguments auto verbose = false; // Parse, cast and set optional arguments if (parsedArgs.end() != parsedArgs.find("verbose")) verbose = us::any_cast<bool>(parsedArgs["verbose"]); try { if (verbose) MITK_INFO << "Read input file"; auto inImage = mitk::IOUtil::Load<mitk::Image>(inFilename); if (inImage.IsNull()) { MITK_ERROR << "Could not read \"" << inFilename << "\"!"; return EXIT_FAILURE; } if (verbose) MITK_INFO << "Add offset to image"; auto exampleFilter = ExampleImageFilter::New(); exampleFilter->SetInput(inImage); exampleFilter->SetOffset(offset); exampleFilter->Update(); auto outImage = exampleFilter->GetOutput(); if (nullptr == outImage) { MITK_ERROR << "Image processing failed!"; return EXIT_FAILURE; } if (verbose) MITK_INFO << "Write output file"; mitk::IOUtil::Save(outImage, outFilename); return EXIT_SUCCESS; } catch (const std::exception &e) { MITK_ERROR << e.what(); return EXIT_FAILURE; } catch (...) { MITK_ERROR << "Unexpected error!"; return EXIT_FAILURE; } }
bool GSRenderer::Merge(int field) { bool en[2]; GSVector4i fr[2]; GSVector4i dr[2]; int baseline = INT_MAX; for(int i = 0; i < 2; i++) { en[i] = IsEnabled(i); if(en[i]) { fr[i] = GetFrameRect(i); dr[i] = GetDisplayRect(i); baseline = min(dr[i].top, baseline); //printf("[%d]: %d %d %d %d, %d %d %d %d\n", i, fr[i].x,fr[i].y,fr[i].z,fr[i].w , dr[i].x,dr[i].y,dr[i].z,dr[i].w); } } if(!en[0] && !en[1]) { return false; } // try to avoid fullscreen blur, could be nice on tv but on a monitor it's like double vision, hurts my eyes (persona 4, guitar hero) // // NOTE: probably the technique explained in graphtip.pdf (Antialiasing by Supersampling / 4. Reading Odd/Even Scan Lines Separately with the PCRTC then Blending) bool samesrc = en[0] && en[1] && m_regs->DISP[0].DISPFB.FBP == m_regs->DISP[1].DISPFB.FBP && m_regs->DISP[0].DISPFB.FBW == m_regs->DISP[1].DISPFB.FBW && m_regs->DISP[0].DISPFB.PSM == m_regs->DISP[1].DISPFB.PSM; // bool blurdetected = false; if(samesrc /*&& m_regs->PMODE.SLBG == 0 && m_regs->PMODE.MMOD == 1 && m_regs->PMODE.ALP == 0x80*/) { if(fr[0].eq(fr[1] + GSVector4i(0, -1, 0, 0)) && dr[0].eq(dr[1] + GSVector4i(0, 0, 0, 1)) || fr[1].eq(fr[0] + GSVector4i(0, -1, 0, 0)) && dr[1].eq(dr[0] + GSVector4i(0, 0, 0, 1))) { // persona 4: // // fr[0] = 0 0 640 448 // fr[1] = 0 1 640 448 // dr[0] = 159 50 779 498 // dr[1] = 159 50 779 497 // // second image shifted up by 1 pixel and blended over itself // // god of war: // // fr[0] = 0 1 512 448 // fr[1] = 0 0 512 448 // dr[0] = 127 50 639 497 // dr[1] = 127 50 639 498 // // same just the first image shifted int top = min(fr[0].top, fr[1].top); int bottom = max(dr[0].bottom, dr[1].bottom); fr[0].top = top; fr[1].top = top; dr[0].bottom = bottom; dr[1].bottom = bottom; // blurdetected = true; } else if(dr[0].eq(dr[1]) && (fr[0].eq(fr[1] + GSVector4i(0, 1, 0, 1)) || fr[1].eq(fr[0] + GSVector4i(0, 1, 0, 1)))) { // dq5: // // fr[0] = 0 1 512 445 // fr[1] = 0 0 512 444 // dr[0] = 127 50 639 494 // dr[1] = 127 50 639 494 int top = min(fr[0].top, fr[1].top); int bottom = min(fr[0].bottom, fr[1].bottom); fr[0].top = fr[1].top = top; fr[0].bottom = fr[1].bottom = bottom; // blurdetected = true; } //printf("samesrc = %d blurdetected = %d\n",samesrc,blurdetected); } GSVector2i fs(0, 0); GSVector2i ds(0, 0); GSTexture* tex[2] = {NULL, NULL}; if(samesrc && fr[0].bottom == fr[1].bottom) { tex[0] = GetOutput(0); tex[1] = tex[0]; // saves one texture fetch } else { if(en[0]) tex[0] = GetOutput(0); if(en[1]) tex[1] = GetOutput(1); } GSVector4 src[2]; GSVector4 dst[2]; for(int i = 0; i < 2; i++) { if(!en[i] || !tex[i]) continue; GSVector4i r = fr[i]; // overscan hack if(dr[i].height() > 512) // hmm { int y = GetDeviceSize(i).y; if(m_regs->SMODE2.INT && m_regs->SMODE2.FFMD) y /= 2; r.bottom = r.top + y; } GSVector4 scale = GSVector4(tex[i]->GetScale()).xyxy(); src[i] = GSVector4(r) * scale / GSVector4(tex[i]->GetSize()).xyxy(); GSVector2 o(0, 0); if(dr[i].top - baseline >= 4) // 2? { o.y = tex[i]->GetScale().y * (dr[i].top - baseline); if(m_regs->SMODE2.INT && m_regs->SMODE2.FFMD) { o.y /= 2; } } dst[i] = GSVector4(o).xyxy() + scale * GSVector4(r.rsize()); fs.x = max(fs.x, (int)(dst[i].z + 0.5f)); fs.y = max(fs.y, (int)(dst[i].w + 0.5f)); } ds = fs; if(m_regs->SMODE2.INT && m_regs->SMODE2.FFMD) { ds.y *= 2; } bool slbg = m_regs->PMODE.SLBG; bool mmod = m_regs->PMODE.MMOD; if(tex[0] || tex[1]) { if(tex[0] == tex[1] && !slbg && (src[0] == src[1] & dst[0] == dst[1]).alltrue()) { // the two outputs are identical, skip drawing one of them (the one that is alpha blended) tex[0] = NULL; } GSVector4 c = GSVector4((int)m_regs->BGCOLOR.R, (int)m_regs->BGCOLOR.G, (int)m_regs->BGCOLOR.B, (int)m_regs->PMODE.ALP) / 255; m_dev->Merge(tex, src, dst, fs, slbg, mmod, c); if(m_regs->SMODE2.INT && m_interlace > 0) { if (m_interlace == 7 && m_regs->SMODE2.FFMD == 1) // Auto interlace enabled / Odd frame interlace setting { int field2 = 0; int mode = 2; m_dev->Interlace(ds, field ^ field2, mode, tex[1] ? tex[1]->GetScale().y : tex[0]->GetScale().y); } else { int field2 = 1 - ((m_interlace - 1) & 1); int mode = (m_interlace - 1) >> 1; m_dev->Interlace(ds, field ^ field2, mode, tex[1] ? tex[1]->GetScale().y : tex[0]->GetScale().y); } } if(m_shadeboost) { m_dev->ShadeBoost(); } if (m_shaderfx) { m_dev->ExternalFX(); } if(m_fxaa) { m_dev->FXAA(); } } return true; }
void DataManager::Initialize(itk::SmartPointer<LabelMapType> labelMap, std::shared_ptr<Coordinates> coordinates, std::shared_ptr<Metadata> metadata) { m_orientationData = coordinates; auto spacing = m_orientationData->GetImageSpacing(); auto imageorigin = m_orientationData->GetImageOrigin(); auto imagesize = m_orientationData->GetImageSize(); // insert background label info, initially all voxels are background, we'll subtract later auto object = std::make_shared<ObjectInformation>(); object->scalar = 0; object->centroid = Vector3d((imagesize[0] / 2.0) * spacing[0], (imagesize[1] / 2.0) * spacing[1], (imagesize[2] / 2.0) / spacing[2]); object->size = imagesize[0] * imagesize[1] * imagesize[2]; object->min = Vector3ui(0, 0, 0); object->max = Vector3ui(imagesize[0], imagesize[1], imagesize[2]); ObjectVector.insert(std::pair<unsigned short, std::shared_ptr<ObjectInformation>>(0, object)); // evaluate shapelabelobjects to get the centroid of the object auto evaluator = itk::ShapeLabelMapFilter<LabelMapType>::New(); evaluator->SetInput(labelMap); evaluator->ComputePerimeterOff(); evaluator->ComputeFeretDiameterOff(); evaluator->SetInPlace(true); evaluator->Update(); // get voxel count for each label for statistics and "flatten" the labelmap (make all labels consecutive starting from 1) auto labelChanger = ChangeType::New(); labelChanger->SetInput(evaluator->GetOutput()); labelChanger->SetInPlace(true); ImageRegionType region; unsigned short i = 1; itk::Point<double, 3> centroid; for (int i = 0; i < evaluator->GetOutput()->GetNumberOfLabelObjects(); ++i) { auto labelObject = evaluator->GetOutput()->GetNthLabelObject(i); auto scalar = labelObject->GetLabel(); centroid = labelObject->GetCentroid(); region = labelObject->GetBoundingBox(); auto regionOrigin = region.GetIndex(); auto regionSize = region.GetSize(); object = std::make_shared<ObjectInformation>(); object->scalar = scalar; object->centroid = Vector3d(centroid[0] / spacing[0], centroid[1] / spacing[1], centroid[2] / spacing[2]); object->size = labelObject->Size(); object->min = Vector3ui(regionOrigin[0], regionOrigin[1], regionOrigin[2]); object->max = Vector3ui(regionSize[0] + regionOrigin[0], regionSize[1] + regionOrigin[1], regionSize[2] + regionOrigin[2]) - Vector3ui(1, 1, 1); ObjectVector.insert(std::pair<unsigned short, std::shared_ptr<ObjectInformation>>(i, object)); // substract the voxels of this object from the background label ObjectVector[0]->size -= labelObject->Size(); // need to mark object label as used to correct errors in the segmha metadata (defined labels but empty objects) metadata->markAsUsed(scalar); // flatten label labelChanger->SetChange(scalar, i); } // start entering new labels at the end of the scalar range m_firstFreeValue = GetScalarForLabel(GetNumberOfLabels() - 1) + 1; // apply all the changes made to labels labelChanger->Update(); m_labelMap = LabelMapType::New(); m_labelMap = labelChanger->GetOutput(); m_labelMap->Optimize(); m_labelMap->Update(); // generate the initial vtkLookupTable m_lookupTable = vtkSmartPointer<vtkLookupTable>::New(); GenerateLookupTable(); m_lookupTable->Modified(); }
void avtLineToPolylineFilter::UpdateDataObjectInfo(void) { if (GetInput()->GetInfo().GetAttributes().GetTopologicalDimension() == 1) GetOutput()->GetInfo().GetValidity().InvalidateZones(); }
void avtCracksClipperFilter::Execute(void) { #ifdef ENGINE // // Create an artificial pipeline. // avtDataObject_p dObj = GetInput(); avtDataset_p ds; CopyTo(ds, dObj); avtSourceFromAVTDataset termsrc(ds); avtDataObject_p data = termsrc.GetOutput(); // // Do the work of removing cracks // avtRemoveCracksFilter removeCracks; removeCracks.SetAtts(&atts); removeCracks.SetInput(data); if (calculateDensity) { // // Calculate volume for the new cells // avtVMetricVolume volume; volume.SetOutputVariableName("ccvol"); volume.SetInput(removeCracks.GetOutput()); volume.UseVerdictHex(false); // // Calculate density // avtCracksDensityFilter density; density.SetInput(volume.GetOutput()); density.SetVarName(varname); // // Force the network to execute // density.Update(GetGeneralContract()); // // Copy output of the exectuion to the output of this fitler. // GetOutput()->Copy(*(density.GetOutput())); } else { // // Force the network to execute // removeCracks.Update(GetGeneralContract()); // // Copy output of the exectuion to the output of this fitler. // GetOutput()->Copy(*(removeCracks.GetOutput())); } #endif }
// Compress data and send it to the connected computer BOOL CNeighbour::OnWrite() { // If we're not sending compressed data to the remote computer, just call CConnection::OnWrite to send the output buffer if ( m_pZOutput == NULL ) return CConnection::OnWrite(); // Return the result and leave now // Start or continue using zlib with m_pZSInput and pStream pointers BOOL bNew = ( m_pZSOutput == NULL ); // Make bNew true if zlib compression isn't setup yet if ( bNew ) m_pZSOutput = new z_stream; // Create a new z_stream structure and point m_pZSOutput and pStream at it z_streamp pStream = (z_streamp)m_pZSOutput; // If we are starting to use zlib now if ( bNew ) { // Zero the z_stream structure and set it up for compression ZeroMemory( pStream, sizeof( z_stream ) ); if ( deflateInit( pStream, Settings.Connection.ZLibCompressionLevel ) != Z_OK ) { // There was an error setting up zlib, clean up and leave now delete pStream; delete m_pZOutput; m_pZOutput = NULL; m_pZSOutput = NULL; return TRUE; // Report success anyway } } CLockedBuffer pOutput( GetOutput() ); // If there is data in the output buffer already if ( pOutput->m_nLength ) { // Send it to the other computer CConnection::OnWrite(); if ( pOutput->m_nLength ) return TRUE; // Return true if there is still more to send after this (do) } // If it's been more than 2 seconds since we've flushed the compressed output buffer to the remote computer, set the flag to do it next const DWORD tNow = GetTickCount(); if ( tNow >= m_tZOutput + Z_TIMER ) m_bZFlush = TRUE; // Loop until all the data in ZOutput has been compressed into Output while ( ( m_pZOutput->m_nLength && ! pOutput->m_nLength ) // ZOutput has data to compress and Output is empty || pStream->avail_out == 0 ) // Or, zlib says it has no more room left (do) { // Make sure the output buffer is 1 KB (do) if ( ! pOutput->EnsureBuffer( 1024u ) ) return FALSE; // Tell zlib where the data to compress is, and where it should put the compressed data pStream->next_in = m_pZOutput->m_pBuffer; // Start next_in and avail_in on the data in ZOutput pStream->avail_in = m_pZOutput->m_nLength; pStream->next_out = pOutput->m_pBuffer + pOutput->m_nLength; // Start next_out and avail_out on the empty space in Output pStream->avail_out = pOutput->GetBufferSize() - pOutput->m_nLength; // Call zlib inflate to decompress the contents of m_pInput into the end of m_pZInput deflate( pStream, m_bZFlush ? Z_SYNC_FLUSH : Z_NO_FLUSH ); // Zlib adjusts next in, avail in, next out, and avail out to record what it did // Add the number of uncompressed bytes that zlib compressed to the m_nZOutput count m_nZOutput += m_pZOutput->m_nLength - pStream->avail_in; // Remove the chunk that zlib compressed from the start of ZOutput m_pZOutput->Remove( m_pZOutput->m_nLength - pStream->avail_in ); // Set nOutput to the size of the new compressed block in the output buffer between the data already there, and the empty space afterwards int nOutput = ( pOutput->GetBufferSize() - pOutput->m_nLength ) - pStream->avail_out; // Zlib compressed something if ( nOutput ) { // Add the new block to the length, and record when this happened pOutput->m_nLength += nOutput; m_tZOutput = tNow; } else if ( m_bZFlush ) { // Zlib didn't compress anything, and the flush flag is true m_bZFlush = FALSE; // Make the flush flag false } // Send the contents of the output buffer to the remote computer CConnection::OnWrite(); } return TRUE; }