text:
package be.objectify.deadbolt.java.filters;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletionStage;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Singleton;
import akka.stream.Materializer;
import be.objectify.deadbolt.java.DeadboltHandler;
import be.objectify.deadbolt.java.cache.HandlerCache;
import be.objectify.deadbolt.java.models.PatternType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import play.api.routing.HandlerDef;
import play.libs.F;
import play.mvc.Http;
import play.mvc.Result;
import play.routing.Router;

/**
 * Filters all incoming HTTP requests and applies constraints based on the routes' modifier tags.  If deadbolt modifier tags are present, the constraints
 * for that route will be applied.  If access is allowed, the next filter in the chain is invoked; if access is not allowed,
 * {@link DeadboltHandler#onAuthFailure(Http.RequestHeader, Optional)} is invoked.
 *

 * The format of a modifier tag is deadbolt:constraintType:config.  Individual configurations have the form :label[value] - to omit an optional config,
 * remove :label[value],
 *

 *

 *
deadbolt:subjectPresent:handler[handler name]
 *

 *
handler - optional.  The name of a handler in the HandlerCache

 *

 *

 *
deadbolt:subjectNotPresent:handler[handler name]
 *

 *
name - required.  This is the name passed to DeadboltHandler#isAllowed

 *

 *

 *
deadbolt:dynamic:name[constraint name]:handler[handler name]
 *

 *
name - required.  This is the name passed to DeadboltHandler#isAllowed

 *
handler - optional.  The name of a handler in the HandlerCache

 *

 *

 *
deadbolt:pattern:value[constraint value]:type[EQUALITY|REGEX|CUSTOM]:invert[true|false]:handler[handler name]
 *

 *
value - required.  Used to test the permissions of a subject.

 *
type - required.  The pattern type, case sensitive.

 *
invert - optional.  Defines if the result should be flipped, i.e. a matching permission mean unauthorized.  Defaults to false.

 *
handler - optional.  The name of a handler in the HandlerCache

 *

 *

 *
deadbolt:composite:name[constraint name]:handler[handler name]
 *

 *
name - required.  The name of a constraint in CompositeCache.

 *
handler - optional.  The name of a handler in the HandlerCache

 *

 *

 *
deadbolt:restrict:name[constraint name]:handler[handler name]
 *

 *
name - required.  The name of a constraint in the CompositeCache

 *
handler - optional.  The name of a handler in the HandlerCache

 *

 *

 *
deadbolt:rbp:name[role name]:handler[handler name]
 *

 *
name - required.  The name of a role, which will be used to resolve permissions from {@link DeadboltHandler#getPermissionsForRole(String)}

 *
handler - optional.  The name of a handler in the HandlerCache

 *

 *

 *

 *

 * Restrict is a tricky one, because the possible combinations of roles leads to a nightmare to parse.  Instead, define your role constraints within the
 * composite cache and use the named constraint instead.  deadbolt:restrict is actually a synonym for deadbolt:composite.
 *
 * @author Steve Chaloner (steve@objectify.be)
 * @since 2.5.1
 */
@Singleton
public class DeadboltRouteModifierTagsFilter extends AbstractDeadboltFilter
{
    private static final Logger LOGGER = LoggerFactory.getLogger(DeadboltRouteModifierTagsFilter.class);

    final Pattern subjectPresentModifierTag = Pattern.compile("deadbolt\\:(subjectPresent)(?:\\:content\\[(?<content>.+?)\\]){0,1}(?:\\:handler\\[(?<handler>.+?)\\]){0,1}");
    final Pattern subjectNotPresentModifierTag = Pattern.compile("deadbolt\\:(subjectNotPresent)(?:\\:content\\[(?<content>.+?)\\]){0,1}(?:\\:handler\\[(?<handler>.+?)\\]){0,1}");
    final Pattern dynamicModifierTag = Pattern.compile("deadbolt\\:(dynamic)\\:name\\[(?<name>.+?)\\](?:\\:meta\\[(?<meta>.+?)\\]){0,1}(?:\\:content\\[(?<content>.+?)\\]){0,1}(?:\\:handler\\[(?<handler>.+?)\\]){0,1}");
    final Pattern patternModifierTag = Pattern.compile("deadbolt\\:(pattern)\\:value\\[(?<value>.+?)\\]\\:type\\[(?<type>EQUALITY|REGEX|CUSTOM)\\](?:\\:meta\\[(?<meta>.+?)\\]){0,1}(?:\\:invert\\[(?<invert>true|false)\\]){0,1}(?:\\:content\\[(?<content>.+?)\\]){0,1}(?:\\:handler\\[(?<handler>.+?)\\]){0,1}");
    final Pattern compositeModifierTag = Pattern.compile("deadbolt\\:(composite)\\:name\\[(?<name>.+?)\\](?:\\:content\\[(?<content>.+?)\\]){0,1}(?:\\:handler\\[(?<handler>.+?)\\]){0,1}");
    final Pattern restrictModifierTag = Pattern.compile("deadbolt\\:(restrict)\\:name\\[(?<name>.+?)\\](?:\\:content\\[(?<content>.+?)\\]){0,1}(?:\\:handler\\[(?<handler>.+?)\\]){0,1}");
    final Pattern roleBasedPermissionsModifierTag = Pattern.compile("deadbolt\\:(rbp)\\:name\\[(?<name>.+?)\\](?:\\:content\\[(?<content>.+?)\\]){0,1}(?:\\:handler\\[(?<handler>.+?)\\]){0,1}");

    private final HandlerCache handlerCache;
    private final DeadboltHandler handler;
    private final FilterConstraints filterConstraints;

    private final F.Tuple<FilterFunction, DeadboltHandler> unknownDeadboltModifierTag;

    @Inject
    public DeadboltRouteModifierTagsFilter(final Materializer mat,
                                           final HandlerCache handlerCache,
                                           final FilterConstraints filterConstraints)
    {
        super(mat);
        this.handlerCache = handlerCache;
        this.handler = handlerCache.get();
        this.filterConstraints = filterConstraints;

        this.unknownDeadboltModifierTag = new F.Tuple<>((requestHeader, dh, onSuccess) ->
                                                    {
                                                        LOGGER.error("Unknown Deadbolt route modifier tag in [{}], denying access with default handler",
                                                                     requestHeader.attrs().get(Router.Attrs.HANDLER_DEF)
                                                                             .getModifiers().stream().collect(Collectors.joining(" ")));
                                                        return dh.onAuthFailure(requestHeader, Optional.empty());
                                                    }, handler);
    }

    /**
     * If a constraint is defined for a given route, test that constraint before allowing the request to proceed.
     *
     * @param next          the next step in the filter chain
     * @param requestHeader the request header
     * @return a future for the result
     */
    @Override
    public CompletionStage<Result> apply(final Function<Http.RequestHeader, CompletionStage<Result>> next,
                                         final Http.RequestHeader requestHeader)
    {
        final HandlerDef handlerDef = requestHeader.attrs().get(Router.Attrs.HANDLER_DEF);
        final List<String> deadboltModifierTags = handlerDef.getModifiers().stream().filter(mt -> mt != null && mt.startsWith("deadbolt:")).collect(Collectors.toList());
        return processModifierTags(deadboltModifierTags, 0, requestHeader, next);
    }

    private CompletionStage<Result> processModifierTags(final List<String> deadboltModifierTags, int index, final Http.RequestHeader requestHeader, final Function<Http.RequestHeader, CompletionStage<Result>> lastNext)
    {
        if(index < deadboltModifierTags.size())
        {
            final String modifierTag = deadboltModifierTags.get(index);
            // this is horrible
            final F.Tuple<FilterFunction, DeadboltHandler> tuple = subjectPresent(modifierTag).orElseGet(() -> subjectNotPresent(modifierTag)
                    .orElseGet(() -> dynamic(modifierTag)
                            .orElseGet(() -> composite(modifierTag)
                                    .orElseGet(() -> restrict(modifierTag)
                                            .orElseGet(() -> pattern(modifierTag)
                                                    .orElseGet(() -> roleBasedPermissions(modifierTag)
                                                            .orElse(unknownDeadboltModifierTag)))))));
            return tuple._1.apply(requestHeader,
                                  tuple._2,
                                  rh -> processModifierTags(deadboltModifierTags, index + 1, rh, lastNext));
        }
        else
        {
            return lastNext.apply(requestHeader);
        }
    }

    private Optional<F.Tuple<FilterFunction, DeadboltHandler>> subjectPresent(final String modifierTag)
    {
        final Matcher matcher = subjectPresentModifierTag.matcher(modifierTag);
        return matcher.matches() ? Optional.of(new F.Tuple<>(filterConstraints.subjectPresent(Optional.ofNullable(matcher.group("content"))),
                                                             handler(matcher)))
                                 : Optional.empty();
    }

    private Optional<F.Tuple<FilterFunction, DeadboltHandler>> subjectNotPresent(final String modifierTag)
    {
        final Matcher matcher = subjectNotPresentModifierTag.matcher(modifierTag);
        return matcher.matches() ? Optional.of(new F.Tuple<>(filterConstraints.subjectNotPresent(Optional.ofNullable(matcher.group("content"))),
                                                             handler(matcher)))
                                 : Optional.empty();
    }

    private Optional<F.Tuple<FilterFunction, DeadboltHandler>> dynamic(final String modifierTag)
    {
        final Matcher matcher = dynamicModifierTag.matcher(modifierTag);
        return matcher.matches() ? Optional.of(new F.Tuple<>(filterConstraints.dynamic(matcher.group("name"),
                                                                                Optional.ofNullable(matcher.group("meta")),
                                                                                Optional.ofNullable(matcher.group("content"))),
                                                             handler(matcher)))
                                 : Optional.empty();
    }

    private Optional<F.Tuple<FilterFunction, DeadboltHandler>> composite(final String modifierTag)
    {
        final Matcher matcher = compositeModifierTag.matcher(modifierTag);
        return matcher.matches() ? Optional.of(new F.Tuple<>(filterConstraints.composite(matcher.group("name"),
                                                                                Optional.ofNullable(matcher.group("content"))),
                                                             handler(matcher)))
                                 : Optional.empty();
    }

    private Optional<F.Tuple<FilterFunction, DeadboltHandler>> restrict(final String modifierTag)
    {
        final Matcher matcher = restrictModifierTag.matcher(modifierTag);
        return matcher.matches() ? Optional.of(new F.Tuple<>(filterConstraints.composite(matcher.group("name"),
                                                                                Optional.ofNullable(matcher.group("content"))),
                                                             handler(matcher)))
                                 : Optional.empty();
    }

    private Optional<F.Tuple<FilterFunction, DeadboltHandler>> roleBasedPermissions(final String modifierTag)
    {
        final Matcher matcher = roleBasedPermissionsModifierTag.matcher(modifierTag);
        return matcher.matches() ? Optional.of(new F.Tuple<>(filterConstraints.roleBasedPermissions(matcher.group("name"),
                                                                                Optional.ofNullable(matcher.group("content"))),
                                                             handler(matcher)))
                                 : Optional.empty();
    }

    private Optional<F.Tuple<FilterFunction, DeadboltHandler>> pattern(final String modifierTag)
    {
        final Matcher matcher = patternModifierTag.matcher(modifierTag);
        if (matcher.matches())
        {
            final String invertStr = matcher.group("invert");
            final boolean invert = invertStr != null && Boolean.parseBoolean(invertStr);
            return Optional.of(new F.Tuple<>(filterConstraints.pattern(matcher.group("value"),
                                                                       PatternType.valueOf(matcher.group("type")),
                                                                       Optional.ofNullable(matcher.group("meta")),
                                                                       invert,
                                                                       Optional.ofNullable(matcher.group("content"))),
                                             handler(matcher)));
        }
        else
        {
            return Optional.empty();
        }
    }

    private DeadboltHandler handler(final Matcher matcher)
    {
        final String namedHandler = matcher.group("handler");
        return namedHandler == null ? handler
                                    : handlerCache.apply(namedHandler);
    }
}


text:
namespace performance_manager {
namespace v8_memory {

namespace {

bool IsSynchronousIframeAttributionDataExpected(
    const execution_context::ExecutionContext* ec) {
  DCHECK(ec);
  auto* frame = ec->GetFrameNode();
  // We only expect iframe data for frames...
  if (!frame)
    return false;
  // ... that aren't main frames (have a parent) ...
  if (frame->IsMainFrame())
    return false;
  auto* parent = frame->GetParentFrameNode();
  DCHECK(parent);
  // ... where the parent is hosted in the same process ...
  if (frame->GetProcessNode() != parent->GetProcessNode())
    return false;
  // ... and where they are both in the same site instance (implying they are
  // both in the same frame-tree and know directly of each other's LocalFrame
  // rather then communicating via a RemoteFrame and a RenderFrameProxy).
  return frame->GetSiteInstanceId() == parent->GetSiteInstanceId();
}

}  // namespace

blink::ExecutionContextToken ToExecutionContextToken(
    const blink::WorkerToken& token) {
  if (token.Is<blink::DedicatedWorkerToken>()) {
    return blink::ExecutionContextToken(
        token.GetAs<blink::DedicatedWorkerToken>());
  }
  if (token.Is<blink::ServiceWorkerToken>()) {
    return blink::ExecutionContextToken(
        token.GetAs<blink::ServiceWorkerToken>());
  }
  // This will DCHECK for us if the token isn't a SharedWorkerToken.
  return blink::ExecutionContextToken(token.GetAs<blink::SharedWorkerToken>());
}

bool HasCrossProcessParent(const FrameNode* frame_node) {
  DCHECK(frame_node);
  if (frame_node->IsMainFrame())
    return false;
  const ProcessNode* process = frame_node->GetProcessNode();
  const ProcessNode* parent_process =
      frame_node->GetParentFrameNode()->GetProcessNode();
  return process != parent_process;
}

bool IsValidExtensionId(const std::string& s) {
  // Must be a 32-character string with lowercase letters between a and p,
  // inclusive.
  if (s.size() != 32u)
    return false;
  for (char c : s) {
    if (c < 'a' || c > 'p')
      return false;
  }
  return true;
}

bool IsWorkletToken(const blink::ExecutionContextToken& token) {
  return token.Is<blink::AnimationWorkletToken>() ||
         token.Is<blink::AudioWorkletToken>() ||
         token.Is<blink::LayoutWorkletToken>() ||
         token.Is<blink::PaintWorkletToken>();
}

bool IsWorkerToken(const blink::ExecutionContextToken& token) {
  return token.Is<blink::DedicatedWorkerToken>() ||
         token.Is<blink::ServiceWorkerToken>() ||
         token.Is<blink::SharedWorkerToken>();
}

const execution_context::ExecutionContext* GetExecutionContext(
    const blink::ExecutionContextToken& token,
    Graph* graph) {
  auto* registry =
      execution_context::ExecutionContextRegistry::GetFromGraph(graph);
  DCHECK(registry);
  return registry->GetExecutionContextByToken(token);
}

V8ContextDescriptionStatus ValidateV8ContextDescription(
    const mojom::V8ContextDescription& description) {
  switch (description.world_type) {
    case mojom::V8ContextWorldType::kMain: {
      if (description.world_name)
        return V8ContextDescriptionStatus::kUnexpectedWorldName;
      if (!description.execution_context_token)
        return V8ContextDescriptionStatus::kMissingExecutionContextToken;
      if (!description.execution_context_token->Is<blink::LocalFrameToken>())
        return V8ContextDescriptionStatus::kMissingLocalFrameToken;
    } break;

    case mojom::V8ContextWorldType::kWorkerOrWorklet: {
      if (description.world_name)
        return V8ContextDescriptionStatus::kUnexpectedWorldName;
      if (!description.execution_context_token)
        return V8ContextDescriptionStatus::kMissingExecutionContextToken;
      if (description.execution_context_token->Is<blink::LocalFrameToken>())
        return V8ContextDescriptionStatus::kUnexpectedLocalFrameToken;
    } break;

    case mojom::V8ContextWorldType::kExtension: {
      if (!description.world_name)
        return V8ContextDescriptionStatus::kMissingWorldName;
      if (!IsValidExtensionId(description.world_name.value()))
        return V8ContextDescriptionStatus::kInvalidExtensionWorldName;
      // Extensions can only inject into frames and workers, *not* worklets.
      if (!description.execution_context_token)
        return V8ContextDescriptionStatus::kMissingExecutionContextToken;
      if (IsWorkletToken(description.execution_context_token.value()))
        return V8ContextDescriptionStatus::kUnexpectedWorkletToken;
    } break;

    case mojom::V8ContextWorldType::kIsolated: {
      // World names are optional in isolated worlds.
      // Only frame and workers can have isolated worlds, *not* worklets.
      if (!description.execution_context_token)
        return V8ContextDescriptionStatus::kMissingExecutionContextToken;
      if (IsWorkletToken(description.execution_context_token.value()))
        return V8ContextDescriptionStatus::kUnexpectedWorkletToken;
    } break;

    case mojom::V8ContextWorldType::kInspector: {
      if (description.world_name)
        return V8ContextDescriptionStatus::kUnexpectedWorldName;
      // Devtools can only inject into frames and workers, *not* worklets.
      if (!description.execution_context_token)
        return V8ContextDescriptionStatus::kMissingExecutionContextToken;
      if (IsWorkletToken(description.execution_context_token.value()))
        return V8ContextDescriptionStatus::kUnexpectedWorkletToken;
    } break;

    case mojom::V8ContextWorldType::kRegExp: {
      // Regexp worlds have no additional data.
      if (description.world_name)
        return V8ContextDescriptionStatus::kUnexpectedWorldName;
      if (description.execution_context_token)
        return V8ContextDescriptionStatus::kUnexpectedExecutionContextToken;
    } break;
  }

  return V8ContextDescriptionStatus::kValid;
}

absl::optional<bool> ExpectIframeAttributionDataForV8ContextDescription(
    const mojom::V8ContextDescription& description,
    Graph* graph) {
  switch (description.world_type) {
    case mojom::V8ContextWorldType::kMain: {
      // There's no guarantee that the actual ExecutionContext has yet been
      // created from our POV as there's a race between V8Context creation
      // notifications and node creations. But if it does exist, we sanity check
      // that we should in fact be receiving iframe data for this frame.
      if (auto* ec = GetExecutionContext(*description.execution_context_token,
                                         graph)) {
        return IsSynchronousIframeAttributionDataExpected(ec);
      }
      // Unable to be determined.
      return absl::nullopt;
    }

    case mojom::V8ContextWorldType::kWorkerOrWorklet:
    case mojom::V8ContextWorldType::kExtension:
    case mojom::V8ContextWorldType::kIsolated:
    case mojom::V8ContextWorldType::kInspector:
    case mojom::V8ContextWorldType::kRegExp:
      break;
  }

  return false;
}

void MarkedObjectCount::Mark() {
  DCHECK_LT(marked_count_, count_);
  ++marked_count_;
}

void MarkedObjectCount::Decrement(bool marked) {
  DCHECK_LT(0u, count_);
  if (marked) {
    DCHECK_LT(0u, marked_count_);
    --marked_count_;
  } else {
    DCHECK_LT(marked_count_, count_);
  }
  --count_;
}

}  // namespace v8_memory
}  // namespace performance_manager

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using UnityEngine.Rendering;
using UnityEngine.Serialization;

namespace UnityEngine.Experimental.Rendering.HDPipeline
{
    public enum ShadowMapType
    {
        CascadedDirectional,
        PunctualAtlas,
        AreaLightAtlas
    }

    [GenerateHLSL]
    public struct HDShadowData
    {
        public Vector3      rot0;
        public Vector3      rot1;
        public Vector3      rot2;
        public Vector3      pos;
        public Vector4      proj;

        public Vector2      atlasOffset;
        public float        edgeTolerance;
        public int          flags;

        public Vector4      zBufferParam;
        public Vector4      shadowMapSize;

        public Vector4      viewBias;
        public Vector3      normalBias;
        public float        _padding;

        public Vector4      shadowFilterParams0;

        public Matrix4x4    shadowToWorld;
    }

    // We use a different structure for directional light because these is a lot of data there
    // and it will add too much useless stuff for other lights
    // Note: In order to support HLSL array generation, we need to use fixed arrays and so a unsafe context for this struct
    [GenerateHLSL]
    public unsafe struct HDDirectionalShadowData
    {
        // We can't use Vector4 here because the vector4[] makes this struct non blittable
        [HLSLArray(4, typeof(Vector4))]
        public fixed float      sphereCascades[4 * 4];

        public Vector4          cascadeDirection;

        [HLSLArray(4, typeof(float))]
        public fixed float      cascadeBorders[4];
    }

    [GenerateHLSL]
    public enum HDShadowFlag
    {
        SampleBiasScale     = (1 << 0),
        EdgeLeakFixup       = (1 << 1),
        EdgeToleranceNormal = (1 << 2),
    }

    public class HDShadowRequest
    {
        public Matrix4x4            view;
        // Use the y flipped device projection matrix as light projection matrix
        public Matrix4x4            deviceProjectionYFlip;
        public Matrix4x4            deviceProjection;
        public Matrix4x4            shadowToWorld;
        public Vector3              position;
        public Vector4              zBufferParam;
        // Warning: this field is updated by ProcessShadowRequests and is invalid before
        public Rect                 atlasViewport;
        public bool                 zClip;
        public Vector4[]            frustumPlanes;

        // Store the final shadow indice in the shadow data array
        // Warning: the index is computed during ProcessShadowRequest and so is invalid before calling this function
        public int                  shadowIndex;
        public int                  lightType;

        // Determine in which atlas the shadow will be rendered
        public ShadowMapType        shadowMapType = ShadowMapType.PunctualAtlas;

        // TODO: Remove these field once scriptable culling is here (currently required by ScriptableRenderContext.DrawShadows)
        public int                  lightIndex;
        public ShadowSplitData      splitData;
        // end

        public Vector4              viewBias;
        public Vector3              normalBias;
        public float                edgeTolerance;
        public int                  flags;

        // PCSS parameters
        public float                shadowSoftness;
        public int                  blockerSampleCount;
        public int                  filterSampleCount;
        public float                minFilterSize;

        // IMS parameters
        public float                kernelSize;
        public float                lightAngle;
        public float                maxDepthBias;

        public Vector4              evsmParams;
    }

    public enum HDShadowQuality
    {
        Low = 0,
        Medium = 1,
        High = 2,
        VeryHigh = 3,
    }

    public enum DirectionalShadowAlgorithm
    {
        PCF5x5,
        PCF7x7,
        PCSS,
        IMS
    }

    [Serializable]
    public struct HDShadowInitParameters
    {
        [Serializable]
        public struct HDShadowAtlasInitParams
        {
            public int shadowAtlasResolution;
            public DepthBits shadowAtlasDepthBits;
            public bool useDynamicViewportRescale;

            public static HDShadowAtlasInitParams GetDefault()
            {
                return new HDShadowAtlasInitParams()
                {
                    shadowAtlasResolution = k_DefaultShadowAtlasResolution,
                    shadowAtlasDepthBits = k_DefaultShadowMapDepthBits,
                    useDynamicViewportRescale = true
                };
            }
        }

        /// <summary>Default HDShadowInitParameters</summary>
        public static readonly HDShadowInitParameters @default = new HDShadowInitParameters()
        {
            maxShadowRequests           = k_DefaultMaxShadowRequests,
            directionalShadowsDepthBits = k_DefaultShadowMapDepthBits,
            punctualLightShadowAtlas    = HDShadowAtlasInitParams.GetDefault(),
            areaLightShadowAtlas        = HDShadowAtlasInitParams.GetDefault(),
			shadowQuality               = HDShadowQuality.Low
        };

        public const int k_DefaultShadowAtlasResolution = 4096;
        public const int k_DefaultMaxShadowRequests = 128;
        public const DepthBits k_DefaultShadowMapDepthBits = DepthBits.Depth32;

        public int maxShadowRequests;
        public DepthBits directionalShadowsDepthBits;

        public HDShadowQuality shadowQuality;

        public HDShadowAtlasInitParams punctualLightShadowAtlas;
        public HDShadowAtlasInitParams areaLightShadowAtlas;
    }

    public class HDShadowResolutionRequest
    {
        public Rect             atlasViewport;
        public Vector2          resolution;
        public ShadowMapType    shadowMapType;
    }

    public class HDShadowManager : IDisposable
    {
        public const int            k_DirectionalShadowCascadeCount = 4;

        List<HDShadowData>          m_ShadowDatas = new List<HDShadowData>();
        HDShadowRequest[]           m_ShadowRequests;
        List<HDShadowResolutionRequest> m_ShadowResolutionRequests = new List<HDShadowResolutionRequest>();

        HDDirectionalShadowData     m_DirectionalShadowData;

        // Structured buffer of shadow datas
        ComputeBuffer               m_ShadowDataBuffer;
        ComputeBuffer               m_DirectionalShadowDataBuffer;

        // The two shadowmaps atlases we uses, one for directional cascade (without resize) and the second for the rest of the shadows
        HDShadowAtlas               m_CascadeAtlas;
        HDShadowAtlas               m_Atlas;
        HDShadowAtlas               m_AreaLightShadowAtlas;

        int m_MaxShadowRequests;
        int                         m_ShadowRequestCount;
        int                         m_CascadeCount;

        public HDShadowManager(RenderPipelineResources renderPipelineResources, DepthBits directionalShadowDepthBits,
                            HDShadowInitParameters.HDShadowAtlasInitParams punctualLightAtlasInfo, HDShadowInitParameters.HDShadowAtlasInitParams areaLightAtlasInfo, int maxShadowRequests, Shader clearShader)
        {
            Material clearMaterial = CoreUtils.CreateEngineMaterial(clearShader);

            // Prevent the list from resizing their internal container when we add shadow requests
            m_ShadowDatas.Capacity = maxShadowRequests;
            m_ShadowResolutionRequests.Capacity = maxShadowRequests;
            m_ShadowRequests = new HDShadowRequest[maxShadowRequests];

            // The cascade atlas will be allocated only if there is a directional light
            m_Atlas = new HDShadowAtlas(renderPipelineResources, punctualLightAtlasInfo.shadowAtlasResolution, punctualLightAtlasInfo.shadowAtlasResolution, HDShaderIDs._ShadowAtlasSize, clearMaterial, false, depthBufferBits: punctualLightAtlasInfo.shadowAtlasDepthBits, name: "Shadow Map Atlas");
            // Cascade atlas render texture will only be allocated if there is a shadow casting directional light
            bool useMomentShadows = GetDirectionalShadowAlgorithm() == DirectionalShadowAlgorithm.IMS;
            m_CascadeAtlas = new HDShadowAtlas(renderPipelineResources, 1, 1, HDShaderIDs._CascadeShadowAtlasSize, clearMaterial, useMomentShadows, depthBufferBits: directionalShadowDepthBits, name: "Cascade Shadow Map Atlas");

            m_AreaLightShadowAtlas = new HDShadowAtlas(renderPipelineResources, areaLightAtlasInfo.shadowAtlasResolution, areaLightAtlasInfo.shadowAtlasResolution, HDShaderIDs._AreaShadowAtlasSize, clearMaterial, false, BlurredEVSM: true, depthBufferBits: areaLightAtlasInfo.shadowAtlasDepthBits, name: "Area Light Shadow Map Atlas");

            m_ShadowDataBuffer = new ComputeBuffer(maxShadowRequests, System.Runtime.InteropServices.Marshal.SizeOf(typeof(HDShadowData)));
            m_DirectionalShadowDataBuffer = new ComputeBuffer(1, System.Runtime.InteropServices.Marshal.SizeOf(typeof(HDDirectionalShadowData)));

            m_MaxShadowRequests = maxShadowRequests;
        }

        public static DirectionalShadowAlgorithm GetDirectionalShadowAlgorithm()
        {
            var hdAsset = (GraphicsSettings.renderPipelineAsset as HDRenderPipelineAsset);
            switch (hdAsset.currentPlatformRenderPipelineSettings.hdShadowInitParams.shadowQuality)
            {
                case HDShadowQuality.Low:
                {
                    return DirectionalShadowAlgorithm.PCF5x5;
                }
                case HDShadowQuality.Medium:
                {
                    return DirectionalShadowAlgorithm.PCF7x7;
                }
                case HDShadowQuality.High:
                {
                    return DirectionalShadowAlgorithm.PCSS;
                }
                case HDShadowQuality.VeryHigh:
                {
                    return DirectionalShadowAlgorithm.IMS;
                }
            };
            return DirectionalShadowAlgorithm.PCF5x5;
        }

        public void UpdateDirectionalShadowResolution(int resolution, int cascadeCount)
        {
            Vector2Int atlasResolution = new Vector2Int(resolution, resolution);

            if (cascadeCount > 1)
                atlasResolution.x *= 2;
            if (cascadeCount > 2)
                atlasResolution.y *= 2;

            m_CascadeAtlas.UpdateSize(atlasResolution);
        }

        public int ReserveShadowResolutions(Vector2 resolution, ShadowMapType shadowMapType)
        {
            if (m_ShadowRequestCount >= m_MaxShadowRequests)
            {
                Debug.LogWarning("Max shadow requests count reached, dropping all exceeding requests. You can increase this limit by changing the max requests in the HDRP asset");
                return -1;
            }

            HDShadowResolutionRequest   resolutionRequest = new HDShadowResolutionRequest{
                resolution = resolution,
                shadowMapType = shadowMapType,
            };

            switch (shadowMapType)
            {
                case ShadowMapType.PunctualAtlas:
                    m_Atlas.ReserveResolution(resolutionRequest);
                    break;
                case ShadowMapType.AreaLightAtlas:
                    m_AreaLightShadowAtlas.ReserveResolution(resolutionRequest);
                    break;
                case ShadowMapType.CascadedDirectional:
                    m_CascadeAtlas.ReserveResolution(resolutionRequest);
                    break;
            }

            m_ShadowResolutionRequests.Add(resolutionRequest);
            m_ShadowRequestCount = m_ShadowResolutionRequests.Count;

            return m_ShadowResolutionRequests.Count - 1;
        }

        public Vector2 GetReservedResolution(int index)
        {
            if (index < 0 || index >= m_ShadowRequestCount)
                return Vector2.zero;

            return m_ShadowResolutionRequests[index].resolution;
        }

        public void UpdateShadowRequest(int index, HDShadowRequest shadowRequest)
        {
            if (index >= m_ShadowRequestCount)
                return;

            shadowRequest.atlasViewport = m_ShadowResolutionRequests[index].atlasViewport;
            m_ShadowRequests[index] = shadowRequest;

            switch (shadowRequest.shadowMapType)
            {
                case ShadowMapType.PunctualAtlas:
                {
                    m_Atlas.AddShadowRequest(shadowRequest);
                    break;
                }
                case ShadowMapType.CascadedDirectional:
                {
                    m_CascadeAtlas.AddShadowRequest(shadowRequest);
                    break;
                }
                case ShadowMapType.AreaLightAtlas:
                {
                    m_AreaLightShadowAtlas.AddShadowRequest(shadowRequest);
                    break;
                }
            };
        }

        public void UpdateCascade(int cascadeIndex, Vector4 cullingSphere, float border)
        {
            if (cullingSphere.w != float.NegativeInfinity)
            {
                cullingSphere.w *= cullingSphere.w;
            }

            m_CascadeCount = Mathf.Max(m_CascadeCount, cascadeIndex);

            unsafe
            {
                fixed (float * sphereCascadesBuffer = m_DirectionalShadowData.sphereCascades)
                    ((Vector4 *)sphereCascadesBuffer)[cascadeIndex] = cullingSphere;
                fixed (float * cascadeBorders = m_DirectionalShadowData.cascadeBorders)
                    cascadeBorders[cascadeIndex] = border;
            }
        }

        HDShadowData CreateShadowData(HDShadowRequest shadowRequest, HDShadowAtlas atlas)
        {
            HDShadowData data = new HDShadowData();

            var devProj = shadowRequest.deviceProjection;
            var view = shadowRequest.view;
            data.proj = new Vector4(devProj.m00, devProj.m11, devProj.m22, devProj.m23);
            data.pos = shadowRequest.position;
            data.rot0 = new Vector3(view.m00, view.m01, view.m02);
            data.rot1 = new Vector3(view.m10, view.m11, view.m12);
            data.rot2 = new Vector3(view.m20, view.m21, view.m22);
            data.shadowToWorld = shadowRequest.shadowToWorld;

            // Compute the scale and offset (between 0 and 1) for the atlas coordinates
            float rWidth = 1.0f / atlas.width;
            float rHeight = 1.0f / atlas.height;
            data.atlasOffset = Vector2.Scale(new Vector2(rWidth, rHeight), new Vector2(shadowRequest.atlasViewport.x, shadowRequest.atlasViewport.y));

            data.shadowMapSize = new Vector4(shadowRequest.atlasViewport.width, shadowRequest.atlasViewport.height, 1.0f / shadowRequest.atlasViewport.width, 1.0f / shadowRequest.atlasViewport.height);

            data.viewBias = shadowRequest.viewBias;
            data.normalBias = shadowRequest.normalBias;
            data.flags = shadowRequest.flags;
            data.edgeTolerance = shadowRequest.edgeTolerance;

            data.shadowFilterParams0.x = shadowRequest.shadowSoftness;
            data.shadowFilterParams0.y = HDShadowUtils.Asfloat(shadowRequest.blockerSampleCount);
            data.shadowFilterParams0.z = HDShadowUtils.Asfloat(shadowRequest.filterSampleCount);
            data.shadowFilterParams0.w = shadowRequest.minFilterSize;

            var hdAsset = (GraphicsSettings.renderPipelineAsset as HDRenderPipelineAsset);
            if (hdAsset.currentPlatformRenderPipelineSettings.hdShadowInitParams.shadowQuality == HDShadowQuality.VeryHigh && shadowRequest.lightType == (int)LightType.Directional)
            {
                data.shadowFilterParams0.x = shadowRequest.kernelSize;
                data.shadowFilterParams0.y = shadowRequest.lightAngle;
                data.shadowFilterParams0.z = shadowRequest.maxDepthBias;
            }

            if (atlas.HasBlurredEVSM())
            {
                data.shadowFilterParams0 = shadowRequest.evsmParams;
            }

            return data;
        }

        unsafe Vector4 GetCascadeSphereAtIndex(int index)
        {
            fixed (float * sphereCascadesBuffer = m_DirectionalShadowData.sphereCascades)
            {
                return ((Vector4 *)sphereCascadesBuffer)[index];
            }
        }

        public void UpdateCullingParameters(ref ScriptableCullingParameters cullingParams)
        {
            cullingParams.shadowDistance = Mathf.Min(VolumeManager.instance.stack.GetComponent<HDShadowSettings>().maxShadowDistance.value, cullingParams.shadowDistance);
        }

        public void LayoutShadowMaps(LightingDebugSettings lightingDebugSettings)
        {
            m_Atlas.UpdateDebugSettings(lightingDebugSettings);

            if (m_CascadeAtlas != null)
                m_CascadeAtlas.UpdateDebugSettings(lightingDebugSettings);

            m_AreaLightShadowAtlas.UpdateDebugSettings(lightingDebugSettings);

            if (lightingDebugSettings.shadowResolutionScaleFactor != 1.0f)
            {
                foreach (var shadowResolutionRequest in m_ShadowResolutionRequests)
                {
                    // We don't rescale the directional shadows with the global shadow scale factor
                    // because there is no dynamic atlas rescale when it overflow.
                    if (shadowResolutionRequest.shadowMapType != ShadowMapType.CascadedDirectional)
                        shadowResolutionRequest.resolution *= lightingDebugSettings.shadowResolutionScaleFactor;
                }
            }

            // Assign a position to all the shadows in the atlas, and scale shadows if needed
            if (m_CascadeAtlas != null && !m_CascadeAtlas.Layout(false))
                Debug.LogError("Cascade Shadow atlasing has failed, only one directional light can cast shadows at a time");
            m_Atlas.Layout();
            m_AreaLightShadowAtlas.Layout();
        }

        unsafe public void PrepareGPUShadowDatas(CullingResults cullResults, Camera camera)
        {
            int shadowIndex = 0;

            m_ShadowDatas.Clear();

            // Create all HDShadowDatas and update them with shadow request datas
            for (int i = 0; i < m_ShadowRequestCount; i++)
            {
                HDShadowAtlas atlas = m_Atlas;
                if (m_ShadowRequests[i].shadowMapType == ShadowMapType.CascadedDirectional)
                {
                    atlas = m_CascadeAtlas;
                }
                else if (m_ShadowRequests[i].shadowMapType == ShadowMapType.AreaLightAtlas)
                {
                    atlas = m_AreaLightShadowAtlas;
                }
                m_ShadowDatas.Add(CreateShadowData(m_ShadowRequests[i], atlas));
                m_ShadowRequests[i].shadowIndex = shadowIndex++;
            }

            int first = k_DirectionalShadowCascadeCount, second = k_DirectionalShadowCascadeCount;

            fixed (float *sphereBuffer = m_DirectionalShadowData.sphereCascades)
            {
                Vector4 * sphere = (Vector4 *)sphereBuffer;
                for (int i = 0; i < k_DirectionalShadowCascadeCount; i++)
                {
                    first  = (first  == k_DirectionalShadowCascadeCount                       && sphere[i].w > 0.0f) ? i : first;
                    second = ((second == k_DirectionalShadowCascadeCount || second == first)  && sphere[i].w > 0.0f) ? i : second;
                }
            }

            // Update directional datas:
            if (second != k_DirectionalShadowCascadeCount)
                m_DirectionalShadowData.cascadeDirection = (GetCascadeSphereAtIndex(second) - GetCascadeSphereAtIndex(first)).normalized;
            else
                m_DirectionalShadowData.cascadeDirection = Vector4.zero;

            m_DirectionalShadowData.cascadeDirection.w = VolumeManager.instance.stack.GetComponent<HDShadowSettings>().cascadeShadowSplitCount.value;
        }

        public void RenderShadows(ScriptableRenderContext renderContext, CommandBuffer cmd, CullingResults cullResults, HDCamera hdCamera)
        {
            // Avoid to do any commands if there is no shadow to draw
            if (m_ShadowRequestCount == 0)
                return ;

            // TODO remove DrawShadowSettings, lightIndex and splitData when scriptable culling is available
            ShadowDrawingSettings dss = new ShadowDrawingSettings(cullResults, 0);
            dss.useRenderingLayerMaskTest = hdCamera.frameSettings.IsEnabled(FrameSettingsField.LightLayers);

            // Clear atlas render targets and draw shadows
            using (new ProfilingSample(cmd, "Punctual Lights Shadows rendering", CustomSamplerId.RenderShadows.GetSampler()))
            {
                m_Atlas.RenderShadows(renderContext, cmd, dss);
            }

            using (new ProfilingSample(cmd, "Directional Light Shadows rendering", CustomSamplerId.RenderShadows.GetSampler()))
            {
                m_CascadeAtlas.RenderShadows(renderContext, cmd, dss);
            }

            using (new ProfilingSample(cmd, "Area Light Shadows rendering", CustomSamplerId.RenderShadows.GetSampler()))
            {
                m_AreaLightShadowAtlas.RenderShadows(renderContext, cmd, dss);
                if (m_AreaLightShadowAtlas.HasBlurredEVSM())
                {
                    m_AreaLightShadowAtlas.AreaShadowBlurMoments(cmd, hdCamera);
                }
            }

            // If the shadow algorithm is the improved moment shadow
            if (GetDirectionalShadowAlgorithm() == DirectionalShadowAlgorithm.IMS)
            {
                m_CascadeAtlas.ComputeMomentShadows(cmd, hdCamera);
            }
        }

        public void SyncData()
        {
            // Avoid to upload datas which will not be used
            if (m_ShadowRequestCount == 0)
                return;

            // Upload the shadow buffers to GPU
            m_ShadowDataBuffer.SetData(m_ShadowDatas);
            m_DirectionalShadowDataBuffer.SetData(new HDDirectionalShadowData[]{ m_DirectionalShadowData });
        }

        public void BindResources(CommandBuffer cmd)
        {
            // This code must be in sync with HDShadowContext.hlsl
            cmd.SetGlobalBuffer(HDShaderIDs._HDShadowDatas, m_ShadowDataBuffer);
            cmd.SetGlobalBuffer(HDShaderIDs._HDDirectionalShadowData, m_DirectionalShadowDataBuffer);

            cmd.SetGlobalTexture(HDShaderIDs._ShadowmapAtlas, m_Atlas.identifier);
            cmd.SetGlobalTexture(HDShaderIDs._ShadowmapCascadeAtlas, m_CascadeAtlas.identifier);
            cmd.SetGlobalTexture(HDShaderIDs._AreaLightShadowmapAtlas, m_AreaLightShadowAtlas.identifier);
            if (m_AreaLightShadowAtlas.HasBlurredEVSM())
            {
                cmd.SetGlobalTexture(HDShaderIDs._AreaShadowmapMomentAtlas, m_AreaLightShadowAtlas.GetMomentRT());
            }

            cmd.SetGlobalInt(HDShaderIDs._CascadeShadowCount, m_CascadeCount + 1);
        }

        public int GetShadowRequestCount()
        {
            return m_ShadowRequestCount;
        }

        public void Clear()
        {
            // Clear the shadows atlas infos and requests
            m_Atlas.Clear();
            m_CascadeAtlas.Clear();
            m_AreaLightShadowAtlas.Clear();
            m_ShadowResolutionRequests.Clear();

            m_ShadowRequestCount = 0;
            m_CascadeCount = 0;
        }

        // Warning: must be called after ProcessShadowRequests and RenderShadows to have valid informations
        public void DisplayShadowAtlas(CommandBuffer cmd, Material debugMaterial, float screenX, float screenY, float screenSizeX, float screenSizeY, float minValue, float maxValue)
        {
            m_Atlas.DisplayAtlas(cmd, debugMaterial, new Rect(0, 0, m_Atlas.width, m_Atlas.height), screenX, screenY, screenSizeX, screenSizeY, minValue, maxValue);
        }

        // Warning: must be called after ProcessShadowRequests and RenderShadows to have valid informations
        public void DisplayShadowCascadeAtlas(CommandBuffer cmd, Material debugMaterial, float screenX, float screenY, float screenSizeX, float screenSizeY, float minValue, float maxValue)
        {
            m_CascadeAtlas.DisplayAtlas(cmd, debugMaterial, new Rect(0, 0, m_CascadeAtlas.width, m_CascadeAtlas.height), screenX, screenY, screenSizeX, screenSizeY, minValue, maxValue);
        }

        // Warning: must be called after ProcessShadowRequests and RenderShadows to have valid informations
        public void DisplayAreaLightShadowAtlas(CommandBuffer cmd, Material debugMaterial, float screenX, float screenY, float screenSizeX, float screenSizeY, float minValue, float maxValue)
        {
            m_AreaLightShadowAtlas.DisplayAtlas(cmd, debugMaterial, new Rect(0, 0, m_AreaLightShadowAtlas.width, m_AreaLightShadowAtlas.height), screenX, screenY, screenSizeX, screenSizeY, minValue, maxValue);
        }

        // Warning: must be called after ProcessShadowRequests and RenderShadows to have valid informations
        public void DisplayShadowMap(int shadowIndex, CommandBuffer cmd, Material debugMaterial, float screenX, float screenY, float screenSizeX, float screenSizeY, float minValue, float maxValue)
        {
            if (shadowIndex >= m_ShadowRequestCount)
                return;

            HDShadowRequest   shadowRequest = m_ShadowRequests[shadowIndex];

            switch (shadowRequest.shadowMapType)
            {
                case ShadowMapType.PunctualAtlas:
                {
                    m_Atlas.DisplayAtlas(cmd, debugMaterial, shadowRequest.atlasViewport, screenX, screenY, screenSizeX, screenSizeY, minValue, maxValue);
                    break;
                }
                case ShadowMapType.CascadedDirectional:
                {
                    m_CascadeAtlas.DisplayAtlas(cmd, debugMaterial, shadowRequest.atlasViewport, screenX, screenY, screenSizeX, screenSizeY, minValue, maxValue);
                    break;
                }
                case ShadowMapType.AreaLightAtlas:
                {
                    m_AreaLightShadowAtlas.DisplayAtlas(cmd, debugMaterial, shadowRequest.atlasViewport, screenX, screenY, screenSizeX, screenSizeY, minValue, maxValue);
                    break;
                }
            };
        }

        public void Dispose()
        {
            m_ShadowDataBuffer.Dispose();
            m_DirectionalShadowDataBuffer.Dispose();
            m_Atlas.Release();
            m_AreaLightShadowAtlas.Release();
            m_CascadeAtlas.Release();
        }
    }
}


text:
layout: page
title: "ANTH 4120: Advanced Biological Anthropology Statistics"
comments: true
description: "blanks"
keywords: "ANTH,4120,CU,Boulder"
---

#### GRADE AND WORKLOAD STATISTICS

**Percent withdrawn**: 4.23%

**Percent incomplete**: 1.54%

**Average grade** (4.0 scale): 3.52

**Standard deviation in grades** (4.0 scale): 0.17

**Average workload** (raw): 2.77

**Standard deviation in workload** (raw): 0.51

#### COURSE AND INSTRUCTOR RATINGS/INFORMATION

**Average course rating** (6 point scale): 4.99

**Standard deviation in course rating** (6 point scale): 0.54

**Average instructor rating** (6 point scale): 5.38

**Standard deviation in instructor rating** (6 point scale): 0.43

**Instructors**: Robin Miriam Bernstein, Herbert Covert, Joanna Lambert, Steven Robert Leigh, Michelle Linda Sauther, Matthew James Sponheimer

#### GENERAL CLASS INFORMATION

**Years provided**: Fall 2006, Fall 2007, Spring 2008, Fall 2008, Fall 2009, Spring 2010, Fall 2010, Spring 2012, Fall 2013, Fall 2014, Spring 2015, Fall 2015, Spring 2016, Fall 2016, Spring 2017

**Credits**: 3

**RAP/Honors class?** Neither

**Number of Sections**: 18

**Department**: ANTH

**College**: College of Arts and Sciences

**A&S Division**: Social Sciences

**Level**: Upper

**Activity**: LEC - Lecture


text:
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using MS.Core;

namespace System.Runtime.InteropServices
{
    public static class __COMException
    {
        public static IObservable<System.String> ToString(
            this IObservable<System.Runtime.InteropServices.COMException> COMExceptionValue)
        {
            return Observable.Select(COMExceptionValue, (COMExceptionValueLambda) => COMExceptionValueLambda.ToString());
        }
    }
}


text:
package net.bytebuddy.implementation;

import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.bind.annotation.Argument;
import net.bytebuddy.implementation.bind.annotation.FieldProxy;
import org.junit.Before;
import org.junit.Test;

import java.io.Serializable;

import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;

public class MethodDelegationFieldProxyTest extends AbstractImplementationTest {

    private static final String FOO = "foo", BAR = "bar", QUX = "qux";

    @Before
    public void setUp() throws Exception {
        ExplicitStatic.foo = FOO;
    }

    @Test
    public void testExplicitFieldAccess() throws Exception {
        DynamicType.Loaded<Explicit> loaded = implement(Explicit.class, MethodDelegation.to(Swap.class)
                .appendParameterBinder(FieldProxy.Binder.install(Get.class, Set.class)));
        Explicit explicit = loaded.getLoaded().newInstance();
        assertThat(explicit.foo, is(FOO));
        explicit.swap();
        assertThat(explicit.foo, is(FOO + BAR));
    }

    @Test
    public void testExplicitFieldAccessSerializable() throws Exception {
        DynamicType.Loaded<Explicit> loaded = implement(Explicit.class, MethodDelegation.to(SwapSerializable.class)
                .appendParameterBinder(FieldProxy.Binder.install(Get.class, Set.class)));
        Explicit explicit = loaded.getLoaded().newInstance();
        assertThat(explicit.foo, is(FOO));
        explicit.swap();
        assertThat(explicit.foo, is(FOO + BAR));
    }

    @Test
    public void testExplicitFieldAccessStatic() throws Exception {
        DynamicType.Loaded<ExplicitStatic> loaded = implement(ExplicitStatic.class, MethodDelegation.to(Swap.class)
                .appendParameterBinder(FieldProxy.Binder.install(Get.class, Set.class)));
        ExplicitStatic explicit = loaded.getLoaded().newInstance();
        assertThat(ExplicitStatic.foo, is(FOO));
        explicit.swap();
        assertThat(ExplicitStatic.foo, is(FOO + BAR));
    }

    @Test
    public void testImplicitFieldGetterAccess() throws Exception {
        DynamicType.Loaded<ImplicitGetter> loaded = implement(ImplicitGetter.class, MethodDelegation.to(GetInterceptor.class)
                .appendParameterBinder(FieldProxy.Binder.install(Get.class, Set.class)));
        ImplicitGetter implicitGetter = loaded.getLoaded().newInstance();
        assertThat(implicitGetter.foo, is(FOO));
        assertThat(implicitGetter.getFoo(), is(FOO + BAR));
        assertThat(implicitGetter.foo, is(FOO + BAR));
    }

    @Test
    public void testImplicitFieldSetterAccess() throws Exception {
        DynamicType.Loaded<ImplicitSetter> loaded = implement(ImplicitSetter.class, MethodDelegation.to(SetInterceptor.class)
                .appendParameterBinder(FieldProxy.Binder.install(Get.class, Set.class)));
        ImplicitSetter implicitSetter = loaded.getLoaded().newInstance();
        assertThat(implicitSetter.foo, is(FOO));
        implicitSetter.setFoo(BAR);
        assertThat(implicitSetter.foo, is(FOO + BAR));
    }

    @Test
    public void testExplicitFieldAccessImplicitTarget() throws Exception {
        DynamicType.Loaded<ExplicitInherited> loaded = implement(ExplicitInherited.class, MethodDelegation.to(Swap.class)
                .appendParameterBinder(FieldProxy.Binder.install(Get.class, Set.class)));
        ExplicitInherited explicitInherited = loaded.getLoaded().newInstance();
        assertThat(((Explicit) explicitInherited).foo, is(FOO));
        assertThat(explicitInherited.foo, is(QUX));
        explicitInherited.swap();
        assertThat(((Explicit) explicitInherited).foo, is(FOO));
        assertThat(explicitInherited.foo, is(QUX + BAR));
    }

    @Test
    public void testExplicitFieldAccessExplicitTarget() throws Exception {
        DynamicType.Loaded<ExplicitInherited> loaded = implement(ExplicitInherited.class, MethodDelegation.to(SwapInherited.class)
                .appendParameterBinder(FieldProxy.Binder.install(Get.class, Set.class)));
        ExplicitInherited explicitInherited = loaded.getLoaded().newInstance();
        assertThat(((Explicit) explicitInherited).foo, is(FOO));
        assertThat(explicitInherited.foo, is(QUX));
        explicitInherited.swap();
        assertThat(((Explicit) explicitInherited).foo, is(FOO + BAR));
        assertThat(explicitInherited.foo, is(QUX));
    }

    @Test(expected = ClassCastException.class)
    public void testIncompatibleGetterTypeThrowsException() throws Exception {
        DynamicType.Loaded<Explicit> loaded = implement(Explicit.class, MethodDelegation.to(GetterIncompatible.class)
                .appendParameterBinder(FieldProxy.Binder.install(Get.class, Set.class)));
        Explicit explicit = loaded.getLoaded().newInstance();
        explicit.swap();
    }

    @Test(expected = ClassCastException.class)
    public void testIncompatibleSetterTypeThrowsException() throws Exception {
        DynamicType.Loaded<Explicit> loaded = implement(Explicit.class, MethodDelegation.to(SetterIncompatible.class)
                .appendParameterBinder(FieldProxy.Binder.install(Get.class, Set.class)));
        Explicit explicit = loaded.getLoaded().newInstance();
        explicit.swap();
    }

    @Test(expected = IllegalArgumentException.class)
    public void testGetterTypeDoesNotDeclareCorrectMethodThrowsException() throws Exception {
        MethodDelegation.to(GetterIncompatible.class).appendParameterBinder(FieldProxy.Binder.install(Serializable.class, Set.class));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testSetterTypeDoesNotDeclareCorrectMethodThrowsException() throws Exception {
        MethodDelegation.to(GetterIncompatible.class).appendParameterBinder(FieldProxy.Binder.install(Get.class, Serializable.class));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testGetterTypeDoesInheritFromOtherTypeThrowsException() throws Exception {
        MethodDelegation.to(GetterIncompatible.class).appendParameterBinder(FieldProxy.Binder.install(GetInherited.class, Set.class));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testSetterTypeDoesInheritFromOtherTypeThrowsException() throws Exception {
        MethodDelegation.to(GetterIncompatible.class).appendParameterBinder(FieldProxy.Binder.install(Get.class, SetInherited.class));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testGetterTypeNonPublicThrowsException() throws Exception {
        MethodDelegation.to(GetterIncompatible.class).appendParameterBinder(FieldProxy.Binder.install(GetPrivate.class, Set.class));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testSetterTypeNonPublicThrowsException() throws Exception {
        MethodDelegation.to(GetterIncompatible.class).appendParameterBinder(FieldProxy.Binder.install(Get.class, SetPrivate.class));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testSetterTypeIncorrectSignatureThrowsException() throws Exception {
        MethodDelegation.to(GetterIncompatible.class).appendParameterBinder(FieldProxy.Binder.install(GetIncorrect.class, Set.class));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testGetterTypeIncorrectSignatureThrowsException() throws Exception {
        MethodDelegation.to(GetterIncompatible.class).appendParameterBinder(FieldProxy.Binder.install(Get.class, SetIncorrect.class));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testGetterTypeNotInterfaceThrowsException() throws Exception {
        MethodDelegation.to(GetterIncompatible.class).appendParameterBinder(FieldProxy.Binder.install(Object.class, Set.class));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testSetterTypeNotInterfaceThrowsException() throws Exception {
        MethodDelegation.to(GetterIncompatible.class).appendParameterBinder(FieldProxy.Binder.install(Get.class, Object.class));
    }

    public interface Get<T> {

        T get();
    }

    public interface Set<T> {

        void set(T value);
    }

    public interface GetInherited<T> extends Get<T> {
        /* empty */
    }

    public interface SetInherited<T> extends Set<T> {
        /* empty */
    }

    private interface GetPrivate<T> {

        T get();
    }

    private interface SetPrivate<T> {

        void set(T value);
    }

    public interface GetIncorrect<T> {

        T get(Object value);
    }

    public interface SetIncorrect<T> {

        Object set(T value);
    }

    public static class Swap {

        public static void swap(@FieldProxy(FOO) Get<String> getter, @FieldProxy(FOO) Set<String> setter) {
            assertThat(getter, not(instanceOf(Serializable.class)));
            assertThat(setter, not(instanceOf(Serializable.class)));
            setter.set(getter.get() + BAR);
        }
    }

    public static class Explicit {

        protected String foo = FOO;

        public void swap() {
            /* do nothing */
        }
    }

    public static class ExplicitInherited extends Explicit {

        protected String foo = QUX;

        @Override
        public void swap() {
            /* do nothing */
        }
    }

    public static class SwapInherited {

        public static void swap(@FieldProxy(value = FOO, definingType = Explicit.class) Get<String> getter,
                                @FieldProxy(value = FOO, definingType = Explicit.class) Set<String> setter) {
            assertThat(getter, not(instanceOf(Serializable.class)));
            assertThat(setter, not(instanceOf(Serializable.class)));
            setter.set(getter.get() + BAR);
        }
    }

    public static class ExplicitStatic {

        protected static String foo;

        public void swap() {
            /* do nothing */
        }
    }

    public static class ImplicitGetter {

        protected String foo = FOO;

        public String getFoo() {
            return null;
        }

    }

    public static class GetInterceptor {

        public static String get(@FieldProxy Get<String> getter, @FieldProxy Set<String> setter) {
            setter.set(getter.get() + BAR);
            return getter.get();
        }
    }

    public static class ImplicitSetter {

        protected String foo = FOO;

        public void setFoo(String value) {
            /* do nothing */
        }

    }

    public static class SetInterceptor {

        public static void set(@Argument(0) String value, @FieldProxy Get<String> getter, @FieldProxy Set<String> setter) {
            setter.set(getter.get() + value);
        }
    }

    public static class SwapSerializable {

        public static void swap(@FieldProxy(value = FOO, serializableProxy = true) Get<String> getter,
                                @FieldProxy(value = FOO, serializableProxy = true) Set<String> setter) {
            assertThat(getter, instanceOf(Serializable.class));
            assertThat(setter, instanceOf(Serializable.class));
            setter.set(getter.get() + BAR);
        }
    }

    public static class GetterIncompatible {

        public static void swap(@FieldProxy(FOO) Get<Integer> getter, @FieldProxy(FOO) Set<String> setter) {
            Integer value = getter.get();
        }
    }

    public static class SetterIncompatible {

        public static void swap(@FieldProxy(FOO) Get<String> getter, @FieldProxy(FOO) Set<Integer> setter) {
            setter.set(0);
        }
    }
}


text:
Introduction to the [TypeScript](http://www.typescriptlang.org/) Language

## Why TypeScript?

* JavaScript is great because of its reach
  * JavaScript is everywhere
* JavaScript is great because of available libraries
  * For server and client
* JavaScript (sometimes) sucks because of missing types
  * Limited editor support (IntelliSense, refactoring)
  * Runtime errors instead of compile-time errors
> Our wish: Productivity of robustness of typed languages like C# or Java with reach of JavaScript

## What is TypeScript?

* Superset of JavaScript
  * Valid JavaScript is (mostly) valid TypeScript
  * TypeScript defines add-ons to ECMAScript (primarily type information)
* Existing JavaScript code works perfectly with TypeScript
  * TypeScript compiles into JavaScript
  * Use it where you can use JavaScript
  * Compile-time error checking base on type information
* Generated code follows usual JavaScript patterns (e.g. pseudo-classes)
  * Built-in transpiler similar to [*babel*](https://babeljs.io/)
* Great tool support
  * e.g. [Visual Studio Code](https://code.visualstudio.com)

## Install TypeScript

* Install locally: `npm install typescript --save-dev`
  * Run compiler `tsc` from NPM script
  * Run compiler from `node_modules`: `./node_modules/.bin/tsc`
* Install globally: `npm install --global typescript`
  * Run compiler from every folder with `tsc`
* Install TypeScript with [development tools](http://www.typescriptlang.org/#download-links)
* Tip: Consider [*ts-node*](https://github.com/TypeStrong/ts-node) to execute TypeScript files directly without compiling

## Type Fundamentals

```
let n: number;      // typed variable
let a;              // no type -> any
const s = "Max";    // contextual typing -> string

n = 5;              // valid because 5 is a number
a = 5;              // valid because a is of type any
a = "Hello";        // valid because a is of type any
n = "Hello";        // compile time error because  "Hello" is not a number
```

* Try it in [TypeScript Playground](http://www.typescriptlang.org/play/index.html)
  * Try code navigation (right-click)
  * Try IntelliSense

## Type Fundamentals (cont.)

* Types are used during editing and compiling
  * No type information in resulting JavaScript code
* Contextual Typing: Determine result type from expressions automatically
* Copy the following code into [TypeScript Playground](http://www.typescriptlang.org/play/index.html)
  * Watch the transpiler work
  * Try IntelliSense

```
class Person {
    get firstName(): string { return "Tom"; }

    async doSomethingAsync(): Promise<number> {
        const result: number = await Promise.resolve(42);
        return result;
    }

    doSometing(callback: (result: number) => void) { callback(42); }
}

const p = new Person();
p.doSometing(result => console.log(result));
```

## Basic Types

* TypeScript Handbook: [Basic Types](http://www.typescriptlang.org/docs/handbook/basic-types.html)
* Important basic types:
  * `boolean`, `number`, `string`, `array`, `tuple`
  * `enum` = [enumerations](http://www.typescriptlang.org/docs/handbook/enums.html)
  * `any` = type not known at compile time
  * `void` = no type at all
* Type assertions
* Advanced topics (not in scope for exams):
  * `never`

> Important rule: Forget `var`, always use [`const` or `let`](http://www.typescriptlang.org/docs/handbook/variable-declarations.html)

## Basic Types (cont.)

```
<!--#include file="typescript-fundamentals/0010-Basic-Types/bool-number-string.ts" -->
```

## Basic Types (cont.)

```
<!--#include file="typescript-fundamentals/0010-Basic-Types/any-array.ts" -->
```

## Basic Types (cont.)

```
<!--#include file="typescript-fundamentals/0010-Basic-Types/tuple-enum.ts" -->
```

## Basic Types (cont.)

Note problems of `var` --> avoid it!
```
<!--#include file="typescript-fundamentals/0010-Basic-Types/var.ts" -->
```

## Basic Types (cont.)

```
<!--#include file="typescript-fundamentals/0010-Basic-Types/let.ts" -->
```

## Objects

```
<!--#include file="typescript-fundamentals/0020-Objects-and-Functions/objects.ts" -->
```

## Functions

* TypeScript Handbook: [Functions](http://www.typescriptlang.org/docs/handbook/functions.html)
* `function` keyword vs. arrow functions
* Type inferrence
* Parameters (required, optional, default parameters)
* Advanced topics (not in scope for exams):
  * Rest parameters, details of `this`, overloads

## Functions (cont.)

```
<!--#include file="typescript-fundamentals/0020-Objects-and-Functions/functions.ts" -->
```

## Interfaces

* TypeScript Handbook: [Interfaces](http://www.typescriptlang.org/docs/handbook/interfaces.html)
* Works differently compared to many other languages like C#
* "Duck Typing" aka *Structural Subtyping*
* Interfaces can *extend* each other
* Advanced topics (not in scope for exams):
  * Function types, indexable types, class types, hybrid types

## Interfaces (cont.)

```
<!--#include file="typescript-fundamentals/0030-Interfaces-and-Classes/interface.ts" -->
```

## Interfaces (cont.)

```
<!--#include file="typescript-fundamentals/0030-Interfaces-and-Classes/class-with-interface.ts" -->
```

## Duck Typing (cont.)

```
<!--#include file="typescript-fundamentals/0030-Interfaces-and-Classes/duck-typing.ts" -->
```

## Classes

* TypeScript Handbook: [Classes](http://www.typescriptlang.org/docs/handbook/classes.html)
* Constructors
* Accessibility of members: `public`, `private`, `protected`
* Static members vs. instance members
* Inheritance
* Abstract classes
* `readonly` properties
* Accessors

## Generics

* TypeScript Handbook: [Generics](http://www.typescriptlang.org/docs/handbook/generics.html)
* Generic functions
* Generic classes
* Generic interfaces
* Advanced topics (not in scope for exams):
  * Generic Constraints

## Generics (cont.)

```
<!--#include file="typescript-fundamentals/0030-Interfaces-and-Classes/generics.ts" -->
```

## `for..of` and `for..in`

* TypeScript Handbook: [Iterators and Generators](http://www.typescriptlang.org/docs/handbook/iterators-and-generators.html)
* `for..of` = iterate over iterable object (e.g. array)
* `for..in` = iterate over all keys of an object (see also [*Object.keys()*](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys))

## Modules

* TypeScript Handbook: [Modules](http://www.typescriptlang.org/docs/handbook/modules.html)
* Conceptually similar to ECMAScript modules
* `export`/`import`
* Ambient modules
  * [`@types`](https://www.npmjs.com/~types) on NPM
* Advanced topics (not in scope for exams):
  * Code generation for modules, optional module loading

## Modules (cont.)

`module.ts`
```
<!--#include file="typescript-fundamentals/0050-Modules/module.ts" -->
```
`anotherModule.ts`
```
<!--#include file="typescript-fundamentals/0050-Modules/anotherModule.ts" -->
```

## Modules (cont.)

```
<!--#include file="typescript-fundamentals/0050-Modules/app.ts" -->
```
Exercise: Try this sample with different module systems (e.g. `--module commonjs`)

## Declaration Files

* TypeScript Handbook: [Declaration Files - Consumption](http://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html)
* Many libraries are written in JavaScript, not TypeScript
  * Black box for TypeScript compiler
* External declarations for globals (e.g. `$` in [jQuery](https://jquery.com/)), interfaces, etc. necessary
* TypeScript declaration files (`.d.ts`)
  * Similar to C++ header files
  * `npm install @types/...` (e.g. `npm install @types/chalk` for `chalk`)

## Project Configuration

* TypeScript Handbook: [*tsconfig.json*](http://www.typescriptlang.org/docs/handbook/tsconfig-json.html)
* Compiler has a [large number of compiler options](http://www.typescriptlang.org/docs/handbook/compiler-options.html)
* Options can be passed...
  * ...on the command line (`tsc --help`)
  * ...in `tsconfig.json` (preferred)
* Tip: Generate basic `tsconfig.json` file with `tsc --init`

## Important Compiler Options

* *lib*: List of library files to be included in the compilation

  (e.g. ES2015, DOM)
* *module*: Specify module code generation (e.g. *CommonJS*, *AMD*, *UMD*;

  see also [What Is AMD, CommonJS, and UMD?](http://davidbcalhoun.com/2014/what-is-amd-commonjs-and-umd/))
* *moduleResolution*: Rule of thumb: Set it to *Node* if you include packages from NPM
* *outFile*, *outDir*: File and directory ouput structure
* *sourceMap*: Generate [source map files](https://developers.google.com/web/tools/chrome-devtools/javascript/source-maps) for debugging
* *target*: ECMAScript target version (e.g. *ES2015*, *ES2016*)
* *--watch*: Run the compiler in *watch mode*: Watch input files and trigger recompilation on changes.
* *--version*: Print the compiler's version

## Advanced Topics

* Not in scope for exams
* Symbols
* Namespaces
* JSX
* Decorators
* Mixins

## Summary: TypeScript Goals

* TypeScript offers you the *reach* of JavaScript
* TypeScript makes you *more productive* (e.g. IntelliSense)
  * Ready for larger projects and larger teams
* TypeScript produces *less runtime errors*
  * Because of compile-time type checking

## Further Readings and Exercises

* Exercises
  * [*Game of Life* exercise](https://github.com/rstropek/htl-mobile-computing/blob/master/typescript-fundamentals/9010-game-of-life/readme.md)
  * [*Deezer Search* exercise](https://github.com/rstropek/htl-mobile-computing/blob/master/typescript-fundamentals/9015-deezer-search/readme.md)
  * [*Fractal Tree* exercise](https://github.com/rstropek/htl-mobile-computing/blob/master/typescript-fundamentals/9020-fractal-tree/readme.md)
  * [*Form validation* exercise](https://github.com/rstropek/htl-mobile-computing/blob/master/typescript-fundamentals/9025-form-validation/readme.md)
  * [*Chart* exercise (covering *webpack*)](https://github.com/rstropek/htl-mobile-computing/tree/master/typescript-fundamentals/9040-chart)


text:
<ons-page id="d_birthday.html" ng-controller="BirthdayController as bid">
  <ons-dialog  cancelable>
      <ons-toolbar inline>

        誕生日の変更

      </ons-toolbar>

  </ons-dialog>
</ons-page>


text:
'use strict'
import React from 'React';
import {
  AppRegistry,
  Component,
  StyleSheet,
  Text,
  View,
  TouchableHighlight,
} from 'react-native';

const styles = StyleSheet.create({
  button:{
    backgroundColor:'white',
    padding:15,
    borderBottomWidth:StyleSheet.hairlineWidth,
    borderBottomColor:'#CDCDCD'
  },
  buttonText:{
    fontSize:16,
    paddingTop:100,
  },
});

class NavButton extends React.Component {
  render(){
    return(
      <TouchableHighlight underlayColor="#B5B5B5" onPress={this.props.onPress}
        style={styles.button}>
        <Text style={styles.buttonText}>
          {this.props.btnText}
        </Text>
      </TouchableHighlight>
    );
  }
}

module.exports = NavButton;


text:
using XSharp.Assembler;
using Cosmos.IL2CPU.API;
using Cosmos.IL2CPU.API.Attribs;
using XSharp;

namespace Cosmos.Debug.Kernel.Plugs.Asm
{
  [Plug(Target = typeof(Cosmos.Debug.Kernel.Debugger))]
  public static class Debugger
  {
    [PlugMethod(Assembler = typeof(DebugBreak))]
    public static void Break(Cosmos.Debug.Kernel.Debugger aThis) { }

    //[PlugMethod(Assembler = typeof(DebugActualSend))]
    //public static unsafe void ActualSend(int aLength, char* aText) { }

    [PlugMethod(Assembler = typeof(DebugDoSend))]
    public static void DoSend(string aText) { }

    [PlugMethod(Assembler = typeof(DebugDoSendNumber))]
    public static void DoSendNumber(int aNumber) { }

    [PlugMethod(Assembler = typeof(DebugDoSendNumber))]
    public static void DoSendNumber(uint aNumber) { }

    [PlugMethod(Assembler = typeof(DebugDoSendLongNumber))]
    public static void DoSendNumber(long aNumber) { }

    [PlugMethod(Assembler = typeof(DebugDoSendLongNumber))]
    public static void DoSendNumber(ulong aNumber) { }

    [PlugMethod(Assembler = typeof(DebugDoSendComplexNumber))]
    public static void DoSendNumber(float aNumber) { }

    [PlugMethod(Assembler = typeof(DebugDoSendComplexLongNumber))]
    public static void DoSendNumber(double aNumber) { }

    [PlugMethod(Assembler = typeof(DebugSendMessageBox))]
    public static unsafe void SendMessageBox(Kernel.Debugger aThis, int aLength, char* aText) { }

    [PlugMethod(Assembler = typeof(DebugSendPtr))]
    public static unsafe void SendPtr(Kernel.Debugger aThis, object aPtr) { }

    [PlugMethod(Assembler = typeof(DebugSendChannelCommand))]
    public static unsafe void SendChannelCommand(byte aChannel, byte aCommand, int aByteCount, byte* aData) { }

    [PlugMethod(Assembler = typeof(DebugSendChannelCommandNoData))]
    public static unsafe void SendChannelCommand(byte aChannel, byte aCommand) { }

    [PlugMethod(Assembler = typeof(DoBochsBreak))]
    public static void DoBochsBreak()
    {
    }

    [Inline]
    public static void SendKernelPanic(uint id)
    {
      new LiteralAssemblerCode("%ifdef DEBUGSTUB");
      new LiteralAssemblerCode("push dword [EBP + 8]");
      new LiteralAssemblerCode("Call DebugStub_SendKernelPanic");
      new LiteralAssemblerCode("add ESP, 4");
      new LiteralAssemblerCode("%endif");
    }

    [PlugMethod(Assembler = typeof(DoRealHalt))]
    public static void DoRealHalt()
    {
    }
    //[PlugMethod(Assembler = typeof(DebugTraceOff))]
    //public static void TraceOff() { }

    //[PlugMethod(Assembler = typeof(DebugTraceOn))]
    //public static void TraceOn() { }
  }

  //TODO: Make a new plug attrib that assembly plug methods dont need
  // an empty stub also, its just extra fluff - although they allow signature matching
  // Maybe could merge this into the same unit as the plug
  public class DebugTraceOff : AssemblerMethod
  {
    public override void AssembleNew(XSharp.Assembler.Assembler aAssembler, object aMethodInfo)
    {
      new LiteralAssemblerCode("%ifdef DEBUGSTUB");
      new LiteralAssemblerCode("pushad");
      new LiteralAssemblerCode("Call DebugStub_TraceOff");
      new LiteralAssemblerCode("popad");
      new LiteralAssemblerCode("%endif");
    }
  }

  public class DebugTraceOn : AssemblerMethod
  {
    public override void AssembleNew(XSharp.Assembler.Assembler aAssembler, object aMethodInfo)
    {
      new LiteralAssemblerCode("%ifdef DEBUGSTUB");
      new LiteralAssemblerCode("pushad");
      new LiteralAssemblerCode("Call DebugStub_TraceOn");
      new LiteralAssemblerCode("popad");
      new LiteralAssemblerCode("%endif");
    }
  }

  /// <summary>
  /// Assembler for SendChannelCommand
  /// </summary>
  /// <remarks>
  /// AL contains channel
  /// BL contains command
  /// ECX contains number of bytes to send as command data
  /// ESI contains data start pointer
  /// </remarks>
  public class DebugSendChannelCommand : AssemblerMethod
  {
    public override void AssembleNew(XSharp.Assembler.Assembler aAssembler, object aMethodInfo)
    {
      new LiteralAssemblerCode("%ifdef DEBUGSTUB");
      new LiteralAssemblerCode("mov AL, [EBP + 20]");
      new LiteralAssemblerCode("mov BL, [EBP + 16]");
      new LiteralAssemblerCode("mov ECX, [EBP + 12]");
      new LiteralAssemblerCode("mov ESI, [EBP + 8]");
      new LiteralAssemblerCode("call DebugStub_SendCommandOnChannel");
      new LiteralAssemblerCode("%endif");
    }
  }

  /// <summary>
  /// Assembler for SendChannelCommandNoData
  /// </summary>
  /// <remarks>
  /// AL contains channel
  /// BL contains command
  /// ECX contains number of bytes to send as command data
  /// ESI contains data start pointer
  /// </remarks>
  public class DebugSendChannelCommandNoData : AssemblerMethod
  {
    public override void AssembleNew(XSharp.Assembler.Assembler aAssembler, object aMethodInfo)
    {
      new LiteralAssemblerCode("%ifdef DEBUGSTUB");
      new LiteralAssemblerCode("mov AL, [EBP + 12]");
      new LiteralAssemblerCode("mov BL, [EBP + 8]");
      new LiteralAssemblerCode("mov ECX, 0");
      new LiteralAssemblerCode("mov ESI, EBP");
      new LiteralAssemblerCode("call DebugStub_SendCommandOnChannel");
      new LiteralAssemblerCode("%endif");
    }
  }

  public class DebugBreak : AssemblerMethod
  {
    public override void AssembleNew(XSharp.Assembler.Assembler aAssembler, object aMethodInfo)
    {
      new LiteralAssemblerCode("%ifdef DEBUGSTUB");
      new LiteralAssemblerCode("mov dword [DebugStub_DebugBreakOnNextTrace], 1");
      new LiteralAssemblerCode("%endif");
    }
  }

  /// <summary>
  /// Assembler for DoSend
  /// </summary>
  /// <remarks>
  /// EBP + 12 contains length
  /// EBP + 8 contains first char pointer
  /// </remarks>
  public class DebugDoSend : AssemblerMethod
  {
    public override void AssembleNew(XSharp.Assembler.Assembler aAssembler, object aMethodInfo)
    {
      new LiteralAssemblerCode("%ifdef DEBUGSTUB");
      XS.Label(".BeforeArgumentsPrepare");
      new LiteralAssemblerCode("mov EBX, [EBP + 12]");
      new LiteralAssemblerCode("push dword [EBX + 12]");
      new LiteralAssemblerCode("add EBX, 16");
      new LiteralAssemblerCode("push dword EBX");
      XS.Label(".BeforeCall");
      new LiteralAssemblerCode("Call DebugStub_SendText");
      new LiteralAssemblerCode("add ESP, 8");
      new LiteralAssemblerCode("%endif");
    }
  }

  public class DebugDoSendNumber : AssemblerMethod
  {
    public override void AssembleNew(XSharp.Assembler.Assembler aAssembler, object aMethodInfo)
    {
      new LiteralAssemblerCode("%ifdef DEBUGSTUB");
      new LiteralAssemblerCode("push dword [EBP + 8]");
      new LiteralAssemblerCode("Call DebugStub_SendSimpleNumber");
      new LiteralAssemblerCode("add ESP, 4");
      new LiteralAssemblerCode("%endif");
    }
  }

  public class DebugDoSendLongNumber : AssemblerMethod
  {
    public override void AssembleNew(XSharp.Assembler.Assembler aAssembler, object aMethodInfo)
    {
      new LiteralAssemblerCode("%ifdef DEBUGSTUB");
      new LiteralAssemblerCode("push dword [EBP + 12]");
      new LiteralAssemblerCode("push dword [EBP + 8]");
      new LiteralAssemblerCode("Call DebugStub_SendSimpleLongNumber");
      new LiteralAssemblerCode("add ESP, 8");
      new LiteralAssemblerCode("%endif");
    }
  }

  public class DebugDoSendComplexNumber : AssemblerMethod
  {
    public override void AssembleNew(XSharp.Assembler.Assembler aAssembler, object aMethodInfo)
    {
      new LiteralAssemblerCode("%ifdef DEBUGSTUB");
      new LiteralAssemblerCode("push dword [EBP + 8]");
      new LiteralAssemblerCode("Call DebugStub_SendComplexNumber");
      new LiteralAssemblerCode("add ESP, 4");
      new LiteralAssemblerCode("%endif");
    }
  }

  public class DebugDoSendComplexLongNumber : AssemblerMethod
  {
    public override void AssembleNew(XSharp.Assembler.Assembler aAssembler, object aMethodInfo)
    {
      new LiteralAssemblerCode("%ifdef DEBUGSTUB");
      new LiteralAssemblerCode("push dword [EBP + 12]");
      new LiteralAssemblerCode("push dword [EBP + 8]");
      new LiteralAssemblerCode("Call DebugStub_SendComplexLongNumber");
      new LiteralAssemblerCode("add ESP, 8");
      new LiteralAssemblerCode("%endif");
    }
  }

  public class DebugSendMessageBox : AssemblerMethod
  {
    public override void AssembleNew(XSharp.Assembler.Assembler aAssembler, object aMethodInfo)
    {
      new LiteralAssemblerCode("%ifdef DEBUGSTUB");
      new LiteralAssemblerCode("pushad");
      new LiteralAssemblerCode("Call DebugStub_SendMessageBox");
      new LiteralAssemblerCode("popad");
      new LiteralAssemblerCode("%endif");
    }
  }

  public class DebugSendPtr : AssemblerMethod
  {
    public override void AssembleNew(XSharp.Assembler.Assembler aAssembler, object aMethodInfo)
    {
      new LiteralAssemblerCode("%ifdef DEBUGSTUB");
      new LiteralAssemblerCode("pushad");
      new LiteralAssemblerCode("Call DebugStub_SendPtr");
      new LiteralAssemblerCode("popad");
      new LiteralAssemblerCode("%endif");
    }
  }

  public class DoBochsBreak : AssemblerMethod
  {
    public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
    {
      XS.Exchange(XSRegisters.BX, XSRegisters.BX);
    }
  }

  public class DoRealHalt : AssemblerMethod
  {
    public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
    {
      XS.DisableInterrupts();
      // bochs magic break
      //Exchange(BX, BX);
      XS.Halt();
    }
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycotaxon 51: 215 (1994)

#### Original name
Sphaeria minutella Peck

### Remarks
null